├── .github └── workflows │ ├── ci.yml │ └── issue_handler.yml ├── .gitignore ├── .vscode └── settings.json ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs └── macros.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | push: 8 | workflow_dispatch: 9 | 10 | env: 11 | CARGO_TERM_COLOR: always 12 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 13 | 14 | # Cancel any currently running workflows from the same PR, branch, or 15 | # tag when a new workflow is triggered. 16 | # 17 | # https://stackoverflow.com/a/66336834 18 | concurrency: 19 | cancel-in-progress: true 20 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 21 | 22 | jobs: 23 | # -------------------------------------------------------------------------- 24 | # Check 25 | 26 | check-riscv: 27 | name: Check RISC-V 28 | runs-on: ubuntu-latest 29 | 30 | steps: 31 | - uses: actions/checkout@v3 32 | - uses: dtolnay/rust-toolchain@v1 33 | with: 34 | target: riscv32imc-unknown-none-elf 35 | toolchain: stable 36 | components: rust-src 37 | - uses: dtolnay/rust-toolchain@v1 38 | with: 39 | target: riscv32imc-unknown-none-elf 40 | toolchain: nightly 41 | components: rust-src 42 | - uses: Swatinem/rust-cache@v2 43 | 44 | - run: cargo +stable check --target=riscv32imc-unknown-none-elf 45 | - run: cargo +nightly check --target=riscv32imc-unknown-none-elf 46 | 47 | check-xtensa: 48 | name: Check Xtensa 49 | runs-on: ubuntu-latest 50 | 51 | strategy: 52 | fail-fast: false 53 | matrix: 54 | chip: [esp32, esp32s2, esp32s3] 55 | 56 | steps: 57 | - uses: actions/checkout@v3 58 | - uses: esp-rs/xtensa-toolchain@v1.5 59 | with: 60 | default: true 61 | ldproxy: false 62 | - uses: Swatinem/rust-cache@v2 63 | 64 | - run: cargo check -Zbuild-std=core --target=xtensa-${{ matrix.chip }}-none-elf 65 | -------------------------------------------------------------------------------- /.github/workflows/issue_handler.yml: -------------------------------------------------------------------------------- 1 | name: Add new issues to project 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | 8 | jobs: 9 | add-to-project: 10 | name: Add issue to project 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/add-to-project@v0.5.0 14 | with: 15 | project-url: https://github.com/orgs/esp-rs/projects/2 16 | github-token: ${{ secrets.PAT }} 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnPaste": true, 3 | "rust-analyzer.checkOnSave.allTargets": false, 4 | 5 | // ESP32 6 | // "rust-analyzer.cargo.target": "xtensa-esp32-none-elf", 7 | // "rust-analyzer.checkOnSave.target": "xtensa-esp32-none-elf", 8 | 9 | // ESP32-C3 10 | "rust-analyzer.cargo.target": "riscv32imc-unknown-none-elf", 11 | "rust-analyzer.checkOnSave.target": "riscv32imc-unknown-none-elf", 12 | 13 | // ESP32-S2 14 | // "rust-analyzer.cargo.target": "xtensa-esp32s2-none-elf", 15 | // "rust-analyzer.checkOnSave.target": "xtensa-esp32s2-none-elf", 16 | 17 | // ESP32-S3 18 | // "rust-analyzer.cargo.target": "xtensa-esp32s3-none-elf", 19 | // "rust-analyzer.checkOnSave.target": "xtensa-esp32s3-none-elf", 20 | } 21 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "esp-alloc" 3 | version = "0.3.0" 4 | authors = [ 5 | "Björn Quentin ", 6 | "Jesse Braham ", 7 | ] 8 | edition = "2021" 9 | rust-version = "1.68" 10 | description = "A heap allocator for Espressif devices" 11 | repository = "https://github.com/esp-rs/esp-alloc" 12 | license = "MIT OR Apache-2.0" 13 | 14 | keywords = [ 15 | "allocator", 16 | "esp32", 17 | "riscv", 18 | "xtensa", 19 | ] 20 | categories = [ 21 | "memory-management", 22 | "no-std", 23 | ] 24 | 25 | [features] 26 | nightly = [] 27 | 28 | [package.metadata.docs.rs] 29 | default-target = "riscv32imc-unknown-none-elf" 30 | 31 | [dependencies] 32 | critical-section = "1.1.1" 33 | linked_list_allocator = { version = "0.10.5", default-features = false, features = ["const_mut_refs"] } 34 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 esp-rs 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2022 esp-rs 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # esp-alloc 2 | 3 | --- 4 | 5 | ## This project has moved! It can now be found in the [esp-rs/esp-hal](https://github.com/esp-rs/esp-hal/tree/main/esp-alloc) repository. 6 | 7 | --- 8 | 9 | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/esp-rs/esp-alloc/ci.yml?label=CI&logo=github&style=flat-square) 10 | [![Crates.io](https://img.shields.io/crates/v/esp-alloc?color=C96329&logo=Rust&style=flat-square)](https://crates.io/crates/esp-alloc) 11 | [![docs.rs](https://img.shields.io/docsrs/esp-alloc?color=C96329&logo=rust&style=flat-square)](https://docs.rs/esp-alloc) 12 | ![MSRV](https://img.shields.io/badge/MSRV-1.68-blue?style=flat-square) 13 | ![Crates.io](https://img.shields.io/crates/l/esp-alloc?style=flat-square) 14 | 15 | A simple `no_std` heap allocator for RISC-V and Xtensa processors from Espressif. Supports all currently available ESP32 devices. 16 | 17 | **NOTE:** using this as your global allocator requires using Rust 1.68 or greater, or the `nightly` release channel. 18 | 19 | ## License 20 | 21 | Licensed under either of: 22 | 23 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 24 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 25 | 26 | at your option. 27 | 28 | ### Contribution 29 | 30 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in 31 | the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without 32 | any additional terms or conditions. 33 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A simple `no_std` heap allocator for RISC-V and Xtensa processors from 2 | //! Espressif. Supports all currently available ESP32 devices. 3 | //! 4 | //! **NOTE:** using this as your global allocator requires using Rust 1.68 or 5 | //! greater, or the `nightly` release channel. 6 | //! 7 | //! # Using this as your Global Allocator 8 | //! To use EspHeap as your global allocator, you need at least Rust 1.68 or nightly. 9 | //! 10 | //! ```rust 11 | //! #[global_allocator] 12 | //! static ALLOCATOR: esp_alloc::EspHeap = esp_alloc::EspHeap::empty(); 13 | //! 14 | //! fn init_heap() { 15 | //! const HEAP_SIZE: usize = 32 * 1024; 16 | //! static mut HEAP: MaybeUninit<[u8; HEAP_SIZE]> = MaybeUninit::uninit(); 17 | //! 18 | //! unsafe { 19 | //! ALLOCATOR.init(HEAP.as_mut_ptr() as *mut u8, HEAP_SIZE); 20 | //! } 21 | //! } 22 | //! ``` 23 | //! 24 | //! # Using this with the nightly `allocator_api`-feature 25 | //! Sometimes you want to have single allocations in PSRAM, instead of an esp's 26 | //! DRAM. For that, it's convenient to use the nightly `allocator_api`-feature, which allows 27 | //! you to specify an allocator for single allocations. 28 | //! 29 | //! **NOTE:** To use this, you have to enable the create's `nightly` feature flag. 30 | //! 31 | //! Create and initialize an allocator to use in single allocations: 32 | //! ```rust 33 | //! static PSRAM_ALLOCATOR: esp_alloc::EspHeap = esp_alloc::EspHeap::empty(); 34 | //! 35 | //! fn init_psram_heap() { 36 | //! unsafe { 37 | //! PSRAM_ALLOCATOR.init(psram::psram_vaddr_start() as *mut u8, psram::PSRAM_BYTES); 38 | //! } 39 | //! } 40 | //! ``` 41 | //! 42 | //! And then use it in an allocation: 43 | //! ```rust 44 | //! let large_buffer: Vec = Vec::with_capacity_in(1048576, &PSRAM_ALLOCATOR); 45 | //! ``` 46 | 47 | #![no_std] 48 | #![cfg_attr(feature = "nightly", feature(allocator_api))] 49 | 50 | pub mod macros; 51 | 52 | use core::{ 53 | alloc::{GlobalAlloc, Layout}, 54 | cell::RefCell, 55 | ptr::{self, NonNull}, 56 | }; 57 | 58 | #[ cfg( feature = "nightly" ) ] 59 | use core::alloc::{AllocError, Allocator}; 60 | 61 | use critical_section::Mutex; 62 | use linked_list_allocator::Heap; 63 | 64 | pub struct EspHeap { 65 | heap: Mutex>, 66 | } 67 | 68 | impl EspHeap { 69 | /// Crate a new UNINITIALIZED heap allocator 70 | /// 71 | /// You must initialize this heap using the 72 | /// [`init`](struct.EspHeap.html#method.init) method before using the 73 | /// allocator. 74 | pub const fn empty() -> EspHeap { 75 | EspHeap { 76 | heap: Mutex::new(RefCell::new(Heap::empty())), 77 | } 78 | } 79 | 80 | /// Initializes the heap 81 | /// 82 | /// This function must be called BEFORE you run any code that makes use of 83 | /// the allocator. 84 | /// 85 | /// `heap_bottom` is a pointer to the location of the bottom of the heap. 86 | /// 87 | /// `size` is the size of the heap in bytes. 88 | /// 89 | /// Note that: 90 | /// 91 | /// - The heap grows "upwards", towards larger addresses. Thus `end_addr` 92 | /// must be larger than `start_addr` 93 | /// 94 | /// - The size of the heap is `(end_addr as usize) - (start_addr as usize)`. 95 | /// The allocator won't use the byte at `end_addr`. 96 | /// 97 | /// # Safety 98 | /// 99 | /// Obey these or Bad Stuff will happen. 100 | /// 101 | /// - This function must be called exactly ONCE. 102 | /// - `size > 0` 103 | pub unsafe fn init(&self, heap_bottom: *mut u8, size: usize) { 104 | critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().init(heap_bottom, size)); 105 | } 106 | 107 | /// Returns an estimate of the amount of bytes in use. 108 | pub fn used(&self) -> usize { 109 | critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().used()) 110 | } 111 | 112 | /// Returns an estimate of the amount of bytes available. 113 | pub fn free(&self) -> usize { 114 | critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().free()) 115 | } 116 | } 117 | 118 | unsafe impl GlobalAlloc for EspHeap { 119 | unsafe fn alloc(&self, layout: Layout) -> *mut u8 { 120 | critical_section::with(|cs| { 121 | self.heap 122 | .borrow(cs) 123 | .borrow_mut() 124 | .allocate_first_fit(layout) 125 | .ok() 126 | .map_or(ptr::null_mut(), |allocation| allocation.as_ptr()) 127 | }) 128 | } 129 | 130 | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { 131 | critical_section::with(|cs| { 132 | self.heap 133 | .borrow(cs) 134 | .borrow_mut() 135 | .deallocate(NonNull::new_unchecked(ptr), layout) 136 | }); 137 | } 138 | } 139 | 140 | 141 | #[ cfg( feature = "nightly" ) ] 142 | unsafe impl Allocator for EspHeap { 143 | fn allocate(&self, layout: Layout) -> Result, AllocError> { 144 | critical_section::with(|cs| { 145 | let raw_ptr = self.heap 146 | .borrow(cs) 147 | .borrow_mut() 148 | .allocate_first_fit(layout) 149 | .map_err(|_| AllocError)? 150 | .as_ptr(); 151 | let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; 152 | Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) 153 | }) 154 | } 155 | 156 | unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { 157 | self.dealloc(ptr.as_ptr(), layout); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | //! Macros provided for convenience 2 | 3 | /// Create a heap allocator providing a heap of the given size in bytes 4 | /// 5 | /// You can only have ONE allocator at most 6 | #[macro_export] 7 | macro_rules! heap_allocator { 8 | ($size:expr) => {{ 9 | #[global_allocator] 10 | static ALLOCATOR: $crate::EspHeap = $crate::EspHeap::empty(); 11 | static mut HEAP: core::mem::MaybeUninit<[u8; $size]> = core::mem::MaybeUninit::uninit(); 12 | 13 | unsafe { 14 | ALLOCATOR.init(HEAP.as_mut_ptr() as *mut u8, $size); 15 | } 16 | }}; 17 | } 18 | 19 | /// Create a heap allocator backed by PSRAM 20 | /// 21 | /// You can only have ONE allocator at most. You need a SoC which supports PSRAM and activate the feature to enable it. 22 | /// You need to pass the PSRAM peripheral and the psram module path. 23 | /// 24 | /// # Usage 25 | /// ```no_run 26 | /// esp_alloc::psram_allocator!(peripherals.PSRAM, hal::psram); 27 | /// ``` 28 | #[macro_export] 29 | macro_rules! psram_allocator { 30 | ($peripheral:expr,$psram_module:path) => {{ 31 | #[global_allocator] 32 | static ALLOCATOR: $crate::EspHeap = $crate::EspHeap::empty(); 33 | 34 | use $psram_module as _psram; 35 | _psram::init_psram($peripheral); 36 | unsafe { 37 | ALLOCATOR.init(_psram::psram_vaddr_start() as *mut u8, _psram::PSRAM_BYTES); 38 | } 39 | }}; 40 | } 41 | --------------------------------------------------------------------------------