[
  {
    "path": ".cargo/config.toml",
    "content": "[build]\n# Common embedded build targets\ntarget = \"thumbv7em-none-eabihf\"\n# target = \"thumbv6m-none-eabi\"\n\n[target.thumbv7em-none-eabihf]\n# used to run the qemu_test.rs example with QEMU\nrunner = \"./qemu-runner.sh --target thumbv7em-none-eabihf\"\nrustflags = [\n  \"-Clink-arg=-Tlink.x\",\n  \"-Clink-arg=-Tdefmt.x\",\n  # Can be useful for debugging and to inspect where the heap memory is placed/linked.\n  # \"-Clink-args=-Map=app.map\"\n]\n\n[target.thumbv6m-none-eabi]\n# used to run the qemu_test.rs example with QEMU\nrunner = \"./qemu-runner.sh --target thumbv6m-none-eabi\"\nrustflags = [\n  \"-Clink-arg=-Tlink.x\",\n  \"-Clink-arg=-Tdefmt.x\",\n]\n\n[env]\nDEFMT_LOG=\"info\"\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "* @rust-embedded/libs\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "on:\n  pull_request: # Run CI for PRs on any branch\n  merge_group: # Run CI for the GitHub merge queue\n  workflow_dispatch: # Run CI when manually requested\n  schedule:\n    # Run every week at 8am UTC Saturday\n    - cron: '0 8 * * SAT'\n\nname: Continuous integration\n\njobs:\n  check:\n    runs-on: ubuntu-latest\n    env: {\"RUSTFLAGS\": \"-D warnings\"}\n    strategy:\n      matrix:\n        target:\n          - thumbv6m-none-eabi\n          - thumbv7em-none-eabihf\n        toolchain:\n          - stable\n          - nightly\n\n    steps:\n      - uses: actions/checkout@v6\n      - uses: dtolnay/rust-toolchain@master\n        with:\n          targets: ${{ matrix.target }}\n          toolchain: ${{ matrix.toolchain }}\n      - run: cargo check --target=${{ matrix.target }} --example global_alloc\n      - if: ${{ matrix.toolchain == 'nightly' }}\n        run: cargo check --target=${{ matrix.target }} --examples --all-features\n      - uses: imjohnbo/issue-bot@v3\n        if: |\n          failure()\n          && github.event_name == 'schedule'\n        with:\n          title: CI Failure\n          labels: ci\n          body: |\n            Scheduled CI run failed. Details:\n            https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v6\n      - uses: dtolnay/rust-toolchain@master\n        with:\n          targets: thumbv7em-none-eabihf\n          toolchain: nightly\n      - name: Install QEMU\n        run: |\n          sudo apt update\n          sudo apt install qemu-system-arm\n      - run: qemu-system-arm --version\n      - run: cargo +nightly run --target thumbv7em-none-eabihf --example llff_integration_test --all-features\n      - run: cargo +nightly run --target thumbv7em-none-eabihf --example tlsf_integration_test --all-features\n\n  clippy:\n    name: Clippy\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v6\n      - uses: dtolnay/rust-toolchain@nightly\n        with:\n          components: clippy\n          toolchain: nightly\n          targets: thumbv6m-none-eabi\n      - run: cargo clippy --all-features --examples --target=thumbv6m-none-eabi -- --deny warnings\n\n  format:\n    name: Format\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v6\n      - uses: dtolnay/rust-toolchain@nightly\n        with:\n          components: rustfmt\n      - run: cargo fmt -- --check\n\n  rustdoc:\n    name: rustdoc\n    runs-on: ubuntu-latest\n    env: {\"RUSTDOCFLAGS\": \"-D warnings\"}\n    steps:\n      - uses: actions/checkout@v6\n      - uses: dtolnay/rust-toolchain@nightly\n        with:\n          targets: thumbv7em-none-eabihf\n          toolchain: nightly\n      - name: rustdoc\n        run: cargo +nightly rustdoc --all-features\n"
  },
  {
    "path": ".gitignore",
    "content": "target\nCargo.lock\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](http://keepachangelog.com/)\nand this project adheres to [Semantic Versioning](http://semver.org/).\n\n## [Unreleased]\n\n### Fixed\n\n- Fix panic in `tlsf::Heap::used`.\n- Fix panic in `tlsf::Heap::free` in case the value returned from `insert_free_block_ptr`\n  does not cover the full memory range passed in.\n\n## [v0.7.0] - 2026-01-03\n\n### Added\n\n- Added a `init` macro to make initialization easier.\n- Added `Heap::free` and `Heap::used` for the TLSF heap.\n\n### Changed\n\n- The `Heap::init` methods now panic if they're called more than once or with `size == 0`.\n\n## [v0.6.0] - 2024-09-01\n\n### Added\n\n- Added a Two-Level Segregated Fit heap with the `tlsf` feature.\n\n### Changed\n\n- The `Heap` struct has been renamed to `LlffHeap` and requires the `llff` feature.\n- Updated the rust edition from 2018 to 2021.\n\n## [v0.5.1] - 2023-11-04\n\n### Added\n\n- Implemented [`Allocator`] for `Heap` with the `allocator_api` crate feature.\n  This feature requires a nightly toolchain for the unstable [`allocator_api`]\n  compiler feature.\n\n[`Allocator`]: https://doc.rust-lang.org/core/alloc/trait.Allocator.html\n[`allocator_api`]: https://doc.rust-lang.org/beta/unstable-book/library-features/allocator-api.html\n\n### Changed\n\n- Updated `linked_list_allocator` dependency to 0.10.5, which allows\n  compiling with stable rust.\n\n## [v0.5.0] - 2022-12-06\n\n### Changed\n\n- Renamed crate from `alloc-cortex-m` to `embedded-alloc`.\n- Renamed `CortexMHeap` to `Heap`.\n- Use `critical-section` to lock the heap, instead of `cortex_m::interrupt::free()`.\n  This allows using this crate on non-Cortex-M systems, or on\n  Cortex-M systems that require a custom critical section implementation.\n\n## [v0.4.3] - 2022-11-03\n\n### Changed\n\n- Updated `linked_list_allocator` dependency to 0.10.4, which fixes\n  CVE-2022-36086/RUSTSEC-2022-0063.\n\n## [v0.4.2] - 2022-01-04\n\n### Changed\n\n- Updated `cortex-m` dependency to 0.7.2.\n\n## [v0.4.1] - 2021-01-02\n\n### Added\n\n- `const_mut_refs` feature to the dependency `linked_list_allocator` crate.\n\n### Changed\n\n- Bumped the dependency of the `linked_list_allocator` crate to v0.8.11.\n\n## [v0.4.0] - 2020-06-05\n\n- Bumped the `cortex-m` dependency to v0.6.2.\n- Bumped the dependency of the `linked_list_allocator` crate to v0.8.1.\n- Removed `#![feature(alloc)]` to supress compiler warning about stability for alloc.\n\n## [v0.3.5] - 2018-06-19\n\n### Fixed\n\n- To work with recent nightly\n\n## [v0.3.4] - 2018-05-12\n\n### Changed\n\n- Update the example in the crate level documentation to show how to define the new `oom` lang item.\n\n## [v0.3.3] - 2018-04-23\n\n- Bumped the dependency of the `linked_list_allocator` crate to v0.6.0.\n\n## [v0.3.2] - 2018-02-26\n\n### Changed\n\n- Bumped the dependency of the `linked_list_allocator` crate to v0.5.0.\n\n## [v0.3.1] - 2017-10-07\n\n### Fixed\n\n- The example in the documentation.\n\n## [v0.3.0] - 2017-10-07\n\n### Changed\n\n- [breaking-change] Switched to the new allocator system. See documentation for details.\n\n## [v0.2.2] - 2017-04-29\n\n### Added\n\n- a `__rust_allocate_zeroed` symbol as it's needed on recent nightlies.\n\n## [v0.2.1] - 2016-11-27\n\n### Fixed\n\n- The heap size is `end_addr` - `start_addr`. Previously, it was wrongly\n  calculated as `end_addr - start_addr - 1`.\n\n## [v0.2.0] - 2016-11-19\n\n### Changed\n\n- [breaking-change] Hid the HEAP variable. We now only expose an `init` function to\n  initialize the allocator.\n\n## v0.1.0 - 2016-11-19\n\n### Added\n\n- Initial version of the allocator\n\n[Unreleased]: https://github.com/rust-embedded/embedded-alloc/compare/v0.7.0...HEAD\n[v0.7.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.6.0...v0.7.0\n[v0.6.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.1...v0.6.0\n[v0.5.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.0...v0.5.1\n[v0.5.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.3...v0.5.0\n[v0.4.3]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.2...v0.4.3\n[v0.4.2]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.1...v0.4.2\n[v0.4.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.0...v0.4.1\n[v0.4.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.5...v0.4.0\n[v0.3.5]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.4...v0.3.5\n[v0.3.4]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.3...v0.3.4\n[v0.3.3]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.2...v0.3.3\n[v0.3.2]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.1...v0.3.2\n[v0.3.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.0...v0.3.1\n[v0.3.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.2.2...v0.3.0\n[v0.2.2]: https://github.com/rust-embedded/embedded-alloc/compare/v0.2.1...v0.2.2\n[v0.2.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.2.0...v0.2.1\n[v0.2.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.1.0...v0.2.0\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# The Rust Code of Conduct\n\n## Conduct\n\n**Contact**: [Libs team](https://github.com/rust-embedded/wg#the-libs-team)\n\n* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic.\n* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all.\n* Please be kind and courteous. There's no need to be mean or rude.\n* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer.\n* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works.\n* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term \"harassment\" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups.\n* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [Libs team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back.\n* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.\n\n## Moderation\n\nThese are the policies for upholding our community's standards of conduct.\n\n1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.)\n2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed.\n3. Moderators will first respond to such remarks with a warning.\n4. If the warning is unheeded, the user will be \"kicked,\" i.e., kicked out of the communication channel to cool off.\n5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded.\n6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology.\n7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed.\n8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others.\n\nIn the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely.\n\nAnd if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust.\n\nThe enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org).\n\n*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).*\n\n[team]: https://github.com/rust-embedded/wg#the-libs-team\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nauthors = [\n    \"The Cortex-M Team <cortex-m@teams.rust-embedded.org>\",\n    \"Jonathan Pallant <github@thejpster.org.uk>\",\n    \"Jorge Aparicio <jorge@japaric.io>\",\n    \"Sébastien Béchet <sebastien.bechet@osinix.com>\",\n]\n\ndescription = \"A heap allocator for embedded systems\"\nrepository = \"https://github.com/rust-embedded/embedded-alloc\"\ndocumentation = \"https://docs.rs/embedded-alloc\"\nreadme = \"README.md\"\nedition = \"2021\"\n\nkeywords = [\n    \"allocator\",\n    \"embedded\",\n    \"arm\",\n    \"riscv\",\n    \"cortex-m\",\n]\nlicense = \"MIT OR Apache-2.0\"\nname = \"embedded-alloc\"\nversion = \"0.7.0\"\n\n[features]\ndefault = [\"llff\", \"tlsf\"]\nallocator_api = []\n\n# Use the Two-Level Segregated Fit allocator\ntlsf = [\"rlsf\", \"const-default\"]\n# Use the LinkedList first-fit allocator\nllff = [\"linked_list_allocator\"]\n\n[dependencies]\ncritical-section = \"1.0\"\nlinked_list_allocator = { version = \"0.10.5\", default-features = false, optional = true }\nrlsf = { version = \"0.2.1\", default-features = false, features = [\"unstable\"], optional = true }\nconst-default = { version = \"1.0.0\", default-features = false, optional = true }\n\n[dev-dependencies]\ncortex-m = { version = \"0.7.6\", features = [\"critical-section-single-core\"] }\ncortex-m-rt = \"0.7\"\ndefmt = \"1.0\"\ndefmt-semihosting = \"0.3.0\"\nsemihosting = { version = \"0.1.20\", features = [\"stdio\"] }\n\n# thumbv6m-none-eabi only\n[target.thumbv6m-none-eabi.dev-dependencies]\nportable-atomic = { version = \"1\", features = [\"unsafe-assume-single-core\"] }\n\n# every other target gets the crate without the feature\n[target.'cfg(not(target = \"thumbv6m-none-eabi\"))'.dev-dependencies]\nportable-atomic = { version = \"1\" }\n\n[[example]]\nname = \"allocator_api\"\nrequired-features = [\"allocator_api\", \"llff\"]\n\n[[example]]\nname = \"llff_integration_test\"\nrequired-features = [\"allocator_api\", \"llff\"]\n\n[[example]]\nname = \"tlsf_integration_test\"\nrequired-features = [\"allocator_api\", \"tlsf\"]\n\n[[example]]\nname = \"global_alloc\"\nrequired-features = [\"llff\"]\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Copyright (c) 2016-2018 Jorge Aparicio\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "[![crates.io](https://img.shields.io/crates/d/embedded-alloc.svg)](https://crates.io/crates/embedded-alloc)\n[![crates.io](https://img.shields.io/crates/v/embedded-alloc.svg)](https://crates.io/crates/embedded-alloc) -\n [Documentation](https://docs.rs/embedded-alloc) - [Change log](https://github.com/rust-embedded/embedded-alloc/blob/master/CHANGELOG.md)\n\n# `embedded-alloc`\n\n> A heap allocator for embedded systems.\n\nThis project is developed and maintained by the [libs team][team].\n\n## Example\n\n```rust\n#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse cortex_m_rt::entry;\nuse embedded_alloc::LlffHeap as Heap;\n\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\n\n#[entry]\nfn main() -> ! {\n    // Initialize the allocator BEFORE you use it\n    unsafe {\n        embedded_alloc::init!(HEAP, 1024);\n    }\n    // Alternatively, you can write the code directly to meet specific requirements.\n    {\n        use core::mem::MaybeUninit;\n        const HEAP_SIZE: usize = 1024;\n        static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];\n        unsafe { HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }\n    }\n\n    // now the allocator is ready types like Box, Vec can be used.\n\n    loop { /* .. */ }\n}\n```\n\nFor a full usage example, see [`examples/global_alloc.rs`](https://github.com/rust-embedded/embedded-alloc/blob/master/examples/global_alloc.rs).\n\nFor this to work, an implementation of [`critical-section`](https://github.com/rust-embedded/critical-section) must be provided.\n\nFor simple use cases with Cortex-M CPUs you may enable the `critical-section-single-core` feature in the [cortex-m](https://github.com/rust-embedded/cortex-m) crate.\nPlease refer to the documentation of [`critical-section`](https://docs.rs/critical-section) for further guidance.\n\n## Features\n\nThere are two heaps available to use:\n\n* `llff`: Provides `LlffHeap`, a Linked List First Fit heap.\n* `tlsf`: Provides `TlsfHeap`, a Two-Level Segregated Fit heap.\n\nThe best heap to use will depend on your application, see [#78](https://github.com/rust-embedded/embedded-alloc/pull/78) for more discussion.\n\n## License\n\nLicensed under either of\n\n- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or\n  <http://www.apache.org/licenses/LICENSE-2.0>)\n- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)\n\nat your option.\n\n### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\ndual licensed as above, without any additional terms or conditions.\n\n## Code of Conduct\n\nContribution to this crate is organized under the terms of the [Rust Code of\nConduct][CoC], the maintainer of this crate, the [libs team][team], promises\nto intervene to uphold that code of conduct.\n\n[CoC]: CODE_OF_CONDUCT.md\n[team]: https://github.com/rust-embedded/wg#the-libs-team\n"
  },
  {
    "path": "examples/allocator_api.rs",
    "content": "//! This examples requires nightly for the allocator API.\n#![feature(allocator_api)]\n#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse core::{mem::MaybeUninit, panic::PanicInfo};\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt_semihosting as _;\nuse embedded_alloc::LlffHeap as Heap;\n\n// This is not used, but as of 2023-10-29 allocator_api cannot be used without\n// a global heap\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\n\n#[entry]\nfn main() -> ! {\n    const HEAP_SIZE: usize = 16;\n    static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];\n    let heap: Heap = Heap::empty();\n    unsafe { heap.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }\n\n    let mut vec = alloc::vec::Vec::new_in(heap);\n    vec.push(1);\n\n    defmt::info!(\"Allocated vector: {:?}\", vec.as_slice());\n\n    semihosting::process::exit(0);\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    defmt::error!(\"{}\", info);\n    semihosting::process::exit(-1);\n}\n"
  },
  {
    "path": "examples/exhaustion.rs",
    "content": "//! Example which shows behavior on pool exhaustion. It simply panics.\n#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt::Debug2Format;\nuse defmt_semihosting as _;\n\nuse core::panic::PanicInfo;\nuse embedded_alloc::TlsfHeap as Heap;\n\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\n\n#[entry]\nfn main() -> ! {\n    // Initialize the allocator BEFORE you use it\n    unsafe {\n        embedded_alloc::init!(HEAP, 16);\n    }\n\n    let _vec = alloc::vec![0; 16];\n\n    defmt::error!(\"unexpected vector allocation success\");\n\n    // Panic is expected here.\n    semihosting::process::exit(-1);\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    defmt::warn!(\"received expected heap exhaustion panic\");\n    defmt::warn!(\"{}: {}\", info, Debug2Format(&info.message()));\n    semihosting::process::exit(0);\n}\n"
  },
  {
    "path": "examples/global_alloc.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt_semihosting as _;\n\nuse core::panic::PanicInfo;\n// Linked-List First Fit Heap allocator (feature = \"llff\")\nuse embedded_alloc::LlffHeap as Heap;\n// Two-Level Segregated Fit Heap allocator (feature = \"tlsf\")\n// use embedded_alloc::TlsfHeap as Heap;\n\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\n\n#[entry]\nfn main() -> ! {\n    // Initialize the allocator BEFORE you use it\n    unsafe {\n        embedded_alloc::init!(HEAP, 1024);\n    }\n\n    let vec = alloc::vec![1];\n\n    defmt::info!(\"Allocated vector: {:?}\", vec.as_slice());\n\n    let string = alloc::string::String::from(\"Hello, world!\");\n\n    defmt::info!(\"Allocated string: {:?}\", string.as_str());\n\n    semihosting::process::exit(0);\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    defmt::error!(\"{}\", info);\n    semihosting::process::exit(-1);\n}\n"
  },
  {
    "path": "examples/llff_integration_test.rs",
    "content": "//! This is a very basic smoke test that runs in QEMU\n//! Reference the QEMU section of the [Embedded Rust Book] for more information\n//!\n//! This only tests integration of the allocator on an embedded target.\n//! Comprehensive allocator tests are located in the allocator dependency.\n//!\n//! After toolchain installation this test can be run with:\n//!\n//! ```bash\n//! cargo +nightly run --target thumbv7m-none-eabi --example llff_integration_test --all-features\n//! ```\n//!\n//! [Embedded Rust Book]: https://docs.rust-embedded.org/book/intro/index.html\n\n#![feature(allocator_api)]\n#![no_main]\n#![no_std]\n\nextern crate alloc;\n\nuse alloc::vec::Vec;\nuse core::{\n    mem::{size_of, MaybeUninit},\n    panic::PanicInfo,\n};\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt_semihosting as _;\nuse embedded_alloc::LlffHeap as Heap;\n\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\n\nfn test_global_heap() {\n    assert_eq!(HEAP.used(), 0);\n\n    let mut xs: Vec<i32> = alloc::vec![1];\n    xs.push(2);\n    xs.extend(&[3, 4]);\n\n    // do not optimize xs\n    core::hint::black_box(&mut xs);\n\n    assert_eq!(xs.as_slice(), &[1, 2, 3, 4]);\n    assert_eq!(HEAP.used(), size_of::<i32>() * xs.len());\n}\n\nfn test_allocator_api() {\n    // small local heap\n    const HEAP_SIZE: usize = 16;\n    let mut heap_mem: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];\n    let local_heap: Heap = Heap::empty();\n    unsafe { local_heap.init(&raw mut heap_mem as usize, HEAP_SIZE) }\n\n    assert_eq!(local_heap.used(), 0);\n\n    let mut v: Vec<u16, Heap> = Vec::new_in(local_heap);\n    v.push(0xCAFE);\n    v.extend(&[0xDEAD, 0xFEED]);\n\n    // do not optimize v\n    core::hint::black_box(&mut v);\n\n    assert_eq!(v.as_slice(), &[0xCAFE, 0xDEAD, 0xFEED]);\n}\n\npub type TestTable<'a> = &'a [(fn() -> (), &'static str)];\n\n#[entry]\nfn main() -> ! {\n    unsafe {\n        embedded_alloc::init!(HEAP, 1024);\n    }\n\n    let tests: TestTable = &[\n        (test_global_heap, \"test_global_heap\"),\n        (test_allocator_api, \"test_allocator_api\"),\n    ];\n\n    for (test_fn, test_name) in tests {\n        defmt::info!(\"{}: start\", test_name);\n        test_fn();\n        defmt::info!(\"{}: pass\", test_name);\n    }\n\n    // exit QEMU with a success status\n    semihosting::process::exit(0);\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    defmt::error!(\"{}\", info);\n    semihosting::process::exit(-1);\n}\n"
  },
  {
    "path": "examples/tlsf_integration_test.rs",
    "content": "//! This is a very basic smoke test that runs in QEMU\n//! Reference the QEMU section of the [Embedded Rust Book] for more information\n//!\n//! This only tests integration of the allocator on an embedded target.\n//! Comprehensive allocator tests are located in the allocator dependency.\n//!\n//! After toolchain installation this test can be run with:\n//!\n//! ```bash\n//! cargo +nightly run --target thumbv7m-none-eabi --example tlsf_integration_test --all-features\n//! ```\n//!\n//! [Embedded Rust Book]: https://docs.rust-embedded.org/book/intro/index.html\n\n#![feature(allocator_api)]\n#![no_main]\n#![no_std]\n\nextern crate alloc;\nuse defmt_semihosting as _;\n\nuse alloc::collections::LinkedList;\nuse core::{mem::MaybeUninit, panic::PanicInfo};\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse embedded_alloc::TlsfHeap as Heap;\n\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\nconst HEAP_SIZE: usize = 30 * 1024;\n\npub type TestTable<'a> = &'a [(fn() -> (), &'static str)];\n\nfn test_global_heap() {\n    const ELEMS: usize = 250;\n    assert_eq!(HEAP_SIZE, HEAP.free() + HEAP.used());\n    let initial_free = HEAP.free();\n\n    let mut allocated = LinkedList::new();\n    for _ in 0..ELEMS {\n        allocated.push_back(0);\n    }\n    for i in 0..ELEMS {\n        allocated.push_back(i as i32);\n    }\n\n    assert_eq!(allocated.len(), 2 * ELEMS);\n\n    for _ in 0..ELEMS {\n        allocated.pop_front();\n    }\n\n    for i in 0..ELEMS {\n        assert_eq!(allocated.pop_front().unwrap(), i as i32);\n    }\n    assert_eq!(HEAP_SIZE, HEAP.free() + HEAP.used());\n    assert_eq!(initial_free, HEAP.free());\n}\n\nfn test_allocator_api() {\n    // small local heap\n    const HEAP_SIZE: usize = 256;\n    let mut heap_mem: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];\n    let local_heap: Heap = Heap::empty();\n    unsafe { local_heap.init(heap_mem.as_mut_ptr() as usize, HEAP_SIZE) }\n\n    const ELEMS: usize = 2;\n\n    let mut allocated = LinkedList::new_in(local_heap);\n    for _ in 0..ELEMS {\n        allocated.push_back(0);\n    }\n    for i in 0..ELEMS {\n        allocated.push_back(i as i32);\n    }\n\n    assert_eq!(allocated.len(), 2 * ELEMS);\n\n    for _ in 0..ELEMS {\n        allocated.pop_front();\n    }\n\n    for i in 0..ELEMS {\n        assert_eq!(allocated.pop_front().unwrap(), i as i32);\n    }\n}\n\n#[entry]\nfn main() -> ! {\n    unsafe {\n        embedded_alloc::init!(HEAP, HEAP_SIZE);\n    }\n\n    let tests: TestTable = &[\n        (test_global_heap, \"test_global_heap\"),\n        (test_allocator_api, \"test_allocator_api\"),\n    ];\n\n    for (test_fn, test_name) in tests {\n        defmt::info!(\"{}: start\", test_name);\n        test_fn();\n        defmt::info!(\"{}: pass\", test_name);\n    }\n\n    // exit QEMU with a success status\n    semihosting::process::exit(0);\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    defmt::error!(\"{}\", info);\n    semihosting::process::exit(-1);\n}\n"
  },
  {
    "path": "examples/track_usage.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt::Debug2Format;\nuse defmt_semihosting as _;\n\nuse core::{mem::MaybeUninit, panic::PanicInfo};\nuse embedded_alloc::TlsfHeap as Heap;\n//use embedded_alloc::LlffHeap as Heap;\n\n#[global_allocator]\nstatic HEAP: Heap = Heap::empty();\n\n#[entry]\nfn main() -> ! {\n    // Initialize the allocator BEFORE you use it\n    const HEAP_SIZE: usize = 4096;\n    static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];\n    unsafe { HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }\n\n    let mut alloc_vecs = alloc::vec::Vec::new();\n    let mut free_memory = HEAP_SIZE;\n    // Keep allocating until we are getting low on memory. It doesn't have to end in a panic.\n    while free_memory > 512 {\n        defmt::info!(\n            \"{} of {} heap memory allocated so far...\",\n            HEAP_SIZE - free_memory,\n            HEAP_SIZE\n        );\n        let new_vec = alloc::vec![1_u8; 64];\n        alloc_vecs.push(new_vec);\n        free_memory = HEAP.free();\n    }\n\n    drop(alloc_vecs);\n\n    defmt::info!(\n        \"{} of {} heap memory are allocated after drop\",\n        HEAP_SIZE - HEAP.free(),\n        HEAP_SIZE\n    );\n\n    semihosting::process::exit(0);\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    defmt::error!(\"{}: {}\", info, Debug2Format(&info.message()));\n    semihosting::process::exit(-1);\n}\n"
  },
  {
    "path": "memory.x",
    "content": "MEMORY\n{\n  /* These values correspond to the LM3S6965, one of the few devices QEMU can emulate */\n  FLASH : ORIGIN = 0x00000000, LENGTH = 256K\n  RAM : ORIGIN = 0x20000000, LENGTH = 64K\n}\n"
  },
  {
    "path": "qemu-runner.sh",
    "content": "#!/bin/bash\n\n# This requires you to previously run `cargo install defmt-print`\n\n# See https://ferroussystems.hackmd.io/@jonathanpallant/ryA1S6QDJx for a description of all the relevant QEMU machines\nTARGET=\"\"\nELF_BINARY=\"\"\n\n# very small argument parser\nwhile [[ $# -gt 0 ]]; do\n    case \"$1\" in\n        --target)   TARGET=\"$2\"; shift 2 ;;\n        *)          ELF_BINARY=\"$1\"; shift ;;\n    esac\ndone\n\n# default to the target cargo is currently building for\nTARGET=\"${TARGET:-thumbv7em-none-eabihf}\"\n\ncase \"$TARGET\" in\n    thumbv6m-none-eabi)\n        MACHINE=\"-cpu cortex-m3 -machine mps2-an385\" ;;\n    thumbv7em-none-eabihf)\n        # All suitable for thumbv7em-none-eabihf\n        MACHINE=\"-cpu cortex-m4 -machine mps2-an386\" ;;\n        # MACHINE=\"-cpu cortex-m7 -machine mps2-387\" ;;\n        # MACHINE=\"-cpu cortex-m7 -machine mps2-500\"\n    *)\n        echo \"Unsupported target: $TARGET\" >&2\n        exit 1 ;;\nesac\n\nLOG_FORMAT='{[{L}]%bold} {s} {({ff}:{l:1})%dimmed}'\n\necho \"Running on '$MACHINE'...\"\necho \"------------------------------------------------------------------------\"\nqemu-system-arm $MACHINE -semihosting-config enable=on,target=native -nographic -kernel $ELF_BINARY | defmt-print -e $ELF_BINARY --log-format=\"$LOG_FORMAT\"\necho \"------------------------------------------------------------------------\"\n"
  },
  {
    "path": "src/lib.rs",
    "content": "#![doc = include_str!(\"../README.md\")]\n#![no_std]\n#![cfg_attr(feature = \"allocator_api\", feature(allocator_api))]\n#![warn(missing_docs)]\n\n#[cfg(feature = \"llff\")]\nmod llff;\n#[cfg(feature = \"tlsf\")]\nmod tlsf;\n\n#[cfg(feature = \"llff\")]\npub use llff::Heap as LlffHeap;\n#[cfg(feature = \"tlsf\")]\npub use tlsf::Heap as TlsfHeap;\n\n/// Initialize the global heap.\n///\n/// This macro creates a static, uninitialized memory buffer of the specified size and\n/// initializes the heap instance with that buffer.\n///\n/// # Parameters\n///\n/// - `$heap:ident`: The identifier of the global heap instance to initialize.\n/// - `$size:expr`: An expression evaluating to a `usize` that specifies the size of the\n///   static memory buffer in bytes. It must be **greater than zero**.\n///\n/// # Safety\n///\n/// This macro must be called first, before any operations on the heap, and **only once**.\n/// It internally calls `Heap::init(...)` on the heap,\n/// so `Heap::init(...)` should not be called directly if this macro is used.\n///\n/// # Panics\n///\n/// This macro will panic if either of the following are true:\n///\n/// - this function is called more than ONCE.\n/// - `size == 0`.\n///\n/// # Example\n///\n/// ```rust\n/// use cortex_m_rt::entry;\n/// use embedded_alloc::LlffHeap as Heap;\n///\n/// #[global_allocator]\n/// static HEAP: Heap = Heap::empty();\n///\n/// #[entry]\n/// fn main() -> ! {\n///     // Initialize the allocator BEFORE you use it\n///     unsafe {\n///         embedded_alloc::init!(HEAP, 1024);\n///     }\n///     let mut xs = Vec::new();\n///     // ...\n/// }\n/// ```\n#[macro_export]\nmacro_rules! init {\n    ($heap:ident, $size:expr) => {\n        static mut HEAP_MEM: [::core::mem::MaybeUninit<u8>; $size] =\n            [::core::mem::MaybeUninit::uninit(); $size];\n        $heap.init(&raw mut HEAP_MEM as usize, $size)\n    };\n}\n"
  },
  {
    "path": "src/llff.rs",
    "content": "use core::alloc::{GlobalAlloc, Layout};\nuse core::cell::RefCell;\nuse core::ptr::{self, NonNull};\n\nuse critical_section::Mutex;\nuse linked_list_allocator::Heap as LLHeap;\n\n/// A linked list first fit heap.\npub struct Heap {\n    heap: Mutex<RefCell<(LLHeap, bool)>>,\n}\n\nimpl Heap {\n    /// Create a new UNINITIALIZED heap allocator\n    ///\n    /// You must initialize this heap using the\n    /// [`init`](Self::init) method before using the allocator.\n    pub const fn empty() -> Heap {\n        Heap {\n            heap: Mutex::new(RefCell::new((LLHeap::empty(), false))),\n        }\n    }\n\n    /// Initializes the heap\n    ///\n    /// This function must be called BEFORE you run any code that makes use of the\n    /// allocator.\n    ///\n    /// `start_addr` is the address where the heap will be located.\n    ///\n    /// `size` is the size of the heap in bytes.\n    ///\n    /// Note that:\n    ///\n    /// - The heap grows \"upwards\", towards larger addresses. Thus `start_addr` will\n    ///   be the smallest address used.\n    ///\n    /// - The largest address used is `start_addr + size - 1`, so if `start_addr` is\n    ///   `0x1000` and `size` is `0x30000` then the allocator won't use memory at\n    ///   addresses `0x31000` and larger.\n    ///\n    /// # Safety\n    ///\n    /// This function is safe if the following invariants hold:\n    ///\n    /// - `start_addr` points to valid memory.\n    /// - `size` is correct.\n    ///\n    /// # Panics\n    ///\n    /// This function will panic if either of the following are true:\n    ///\n    /// - this function is called more than ONCE.\n    /// - `size == 0`.\n    pub unsafe fn init(&self, start_addr: usize, size: usize) {\n        assert!(size > 0);\n        critical_section::with(|cs| {\n            let mut heap = self.heap.borrow_ref_mut(cs);\n            assert!(!heap.1);\n            heap.1 = true;\n            heap.0.init(start_addr as *mut u8, size);\n        });\n    }\n\n    /// Returns an estimate of the amount of bytes in use.\n    pub fn used(&self) -> usize {\n        critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.used())\n    }\n\n    /// Returns an estimate of the amount of bytes available.\n    pub fn free(&self) -> usize {\n        critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.free())\n    }\n\n    fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {\n        critical_section::with(|cs| {\n            self.heap\n                .borrow_ref_mut(cs)\n                .0\n                .allocate_first_fit(layout)\n                .ok()\n        })\n    }\n\n    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n        critical_section::with(|cs| {\n            self.heap\n                .borrow_ref_mut(cs)\n                .0\n                .deallocate(NonNull::new_unchecked(ptr), layout)\n        });\n    }\n}\n\nunsafe impl GlobalAlloc for Heap {\n    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n        self.alloc(layout)\n            .map_or(ptr::null_mut(), |allocation| allocation.as_ptr())\n    }\n\n    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n        self.dealloc(ptr, layout);\n    }\n}\n\n#[cfg(feature = \"allocator_api\")]\nmod allocator_api {\n    use super::*;\n    use core::alloc::{AllocError, Allocator};\n\n    unsafe impl Allocator for Heap {\n        fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {\n            match layout.size() {\n                0 => Ok(NonNull::slice_from_raw_parts(layout.dangling_ptr(), 0)),\n                size => self.alloc(layout).map_or(Err(AllocError), |allocation| {\n                    Ok(NonNull::slice_from_raw_parts(allocation, size))\n                }),\n            }\n        }\n\n        unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {\n            if layout.size() != 0 {\n                self.dealloc(ptr.as_ptr(), layout);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/tlsf.rs",
    "content": "use core::alloc::{GlobalAlloc, Layout};\nuse core::cell::RefCell;\nuse core::ptr::{self, NonNull};\n\nuse const_default::ConstDefault;\nuse critical_section::Mutex;\nuse rlsf::Tlsf;\n\ntype TlsfHeap = Tlsf<'static, usize, usize, { usize::BITS as usize }, { usize::BITS as usize }>;\n\nstruct Inner {\n    tlsf: TlsfHeap,\n    initialized: bool,\n    raw_block: Option<NonNull<[u8]>>,\n    raw_block_size: usize,\n}\n\n// Safety: The whole inner type is wrapped by a [Mutex].\nunsafe impl Sync for Inner {}\nunsafe impl Send for Inner {}\n\n/// A two-Level segregated fit heap.\npub struct Heap {\n    heap: Mutex<RefCell<Inner>>,\n}\n\nimpl Heap {\n    /// Create a new UNINITIALIZED heap allocator\n    ///\n    /// You must initialize this heap using the\n    /// [`init`](Self::init) method before using the allocator.\n    pub const fn empty() -> Heap {\n        Heap {\n            heap: Mutex::new(RefCell::new(Inner {\n                tlsf: ConstDefault::DEFAULT,\n                initialized: false,\n                raw_block: None,\n                raw_block_size: 0,\n            })),\n        }\n    }\n\n    /// Initializes the heap\n    ///\n    /// This function must be called BEFORE you run any code that makes use of the\n    /// allocator.\n    ///\n    /// `start_addr` is the address where the heap will be located.\n    ///\n    /// `size` is the size of the heap in bytes.\n    ///\n    /// Note that:\n    ///\n    /// - The heap grows \"upwards\", towards larger addresses. Thus `start_addr` will\n    ///   be the smallest address used.\n    ///\n    /// - The largest address used is `start_addr + size - 1`, so if `start_addr` is\n    ///   `0x1000` and `size` is `0x30000` then the allocator won't use memory at\n    ///   addresses `0x31000` and larger.\n    ///\n    /// # Safety\n    ///\n    /// This function is safe if the following invariants hold:\n    ///\n    /// - `start_addr` points to valid memory.\n    /// - `size` is correct.\n    ///\n    /// # Panics\n    ///\n    /// This function will panic if either of the following are true:\n    ///\n    /// - this function is called more than ONCE.\n    /// - `size`, after aligning start and end to `rlsf::GRANULARITY`, is smaller than `rlsf::GRANULARITY * 2`.\n    pub unsafe fn init(&self, start_addr: usize, size: usize) {\n        assert!(size > 0);\n        critical_section::with(|cs| {\n            let mut heap = self.heap.borrow_ref_mut(cs);\n            assert!(!heap.initialized);\n            let block: NonNull<[u8]> =\n                NonNull::slice_from_raw_parts(NonNull::new_unchecked(start_addr as *mut u8), size);\n            let Some(actual_size) = heap.tlsf.insert_free_block_ptr(block) else {\n                panic!(\"Allocation too small for heap\");\n            };\n            let block: NonNull<[u8]> = NonNull::slice_from_raw_parts(\n                NonNull::new_unchecked(start_addr as *mut u8),\n                actual_size.get(),\n            );\n            heap.initialized = true;\n            heap.raw_block = Some(block);\n            heap.raw_block_size = size;\n        });\n    }\n\n    fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {\n        critical_section::with(|cs| self.heap.borrow_ref_mut(cs).tlsf.allocate(layout))\n    }\n\n    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n        critical_section::with(|cs| {\n            self.heap\n                .borrow_ref_mut(cs)\n                .tlsf\n                .deallocate(NonNull::new_unchecked(ptr), layout.align())\n        })\n    }\n\n    unsafe fn realloc(&self, ptr: *mut u8, new_layout: Layout) -> Option<NonNull<u8>> {\n        critical_section::with(|cs| {\n            self.heap\n                .borrow_ref_mut(cs)\n                .tlsf\n                .reallocate(NonNull::new_unchecked(ptr), new_layout)\n        })\n    }\n\n    /// Get the amount of bytes used by the allocator.\n    pub fn used(&self) -> usize {\n        critical_section::with(|cs| {\n            let free = self.free_with_cs(cs);\n            self.heap.borrow_ref_mut(cs).raw_block_size - free\n        })\n    }\n\n    /// Get the amount of free bytes in the allocator.\n    pub fn free(&self) -> usize {\n        critical_section::with(|cs| self.free_with_cs(cs))\n    }\n\n    fn free_with_cs(&self, cs: critical_section::CriticalSection) -> usize {\n        let inner_mut = self.heap.borrow_ref_mut(cs);\n        if !inner_mut.initialized {\n            return 0;\n        }\n        // Safety: We pass the memory block we previously initialized the heap with\n        // to the `iter_blocks` method.\n        unsafe {\n            inner_mut\n                .tlsf\n                .iter_blocks(inner_mut.raw_block.unwrap())\n                .filter(|block_info| !block_info.is_occupied())\n                .map(|block_info| block_info.max_payload_size())\n                .sum::<usize>()\n        }\n    }\n}\n\nunsafe impl GlobalAlloc for Heap {\n    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n        self.alloc(layout)\n            .map_or(ptr::null_mut(), |allocation| allocation.as_ptr())\n    }\n\n    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n        self.dealloc(ptr, layout)\n    }\n\n    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {\n        // SAFETY: `layout.align()` is a power of two, and the size precondition\n        // is upheld by the caller.\n        let new_layout =\n            unsafe { core::alloc::Layout::from_size_align_unchecked(new_size, layout.align()) };\n        self.realloc(ptr, new_layout)\n            .map_or(ptr::null_mut(), |allocation| allocation.as_ptr())\n    }\n}\n\n#[cfg(feature = \"allocator_api\")]\nmod allocator_api {\n    use super::*;\n    use core::alloc::{AllocError, Allocator};\n\n    unsafe impl Allocator for Heap {\n        fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {\n            match layout.size() {\n                0 => Ok(NonNull::slice_from_raw_parts(layout.dangling_ptr(), 0)),\n                size => self.alloc(layout).map_or(Err(AllocError), |allocation| {\n                    Ok(NonNull::slice_from_raw_parts(allocation, size))\n                }),\n            }\n        }\n\n        unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {\n            if layout.size() != 0 {\n                self.dealloc(ptr.as_ptr(), layout);\n            }\n        }\n    }\n}\n"
  }
]