Skip to main content

memory/
lib.rs

1//! Shared memory allocator for the krypteia cryptographic workspace.
2//!
3//! This crate provides a single `GlobalAlloc` that both `arcana_ffi`
4//! and `quantica_ffi` use when running on targets without an OS
5//! heap.
6//!
7//! # Feature flags
8//!
9//! | Feature      | Behaviour                                              |
10//! |-------------|--------------------------------------------------------|
11//! | `os-alloc`  | The platform provides `malloc`/`free`. Init is a no-op.|
12//! | `self-alloc`| TLSF allocator over a caller-provided RAM block.       |
13//!
14//! Enable **exactly one** of the two features. `os-alloc` is the
15//! default.
16//!
17//! # Usage from C (bare-metal)
18//!
19//! ```c
20//! #include "krypteia.h"
21//!
22//! static uint8_t heap[8192];
23//!
24//! int main(void) {
25//!     krypteia_init(heap, sizeof(heap));
26//!     // … use arcana or quantica APIs …
27//! }
28//! ```
29
30#![cfg_attr(feature = "self-alloc", no_std)]
31
32#[cfg(all(feature = "self-alloc", feature = "os-alloc"))]
33compile_error!("features `os-alloc` and `self-alloc` are mutually exclusive");
34
35// ====================================================================
36// os-alloc: the platform already has malloc/free — nothing to do
37// ====================================================================
38
39#[cfg(feature = "os-alloc")]
40mod os_alloc {
41    /// Memory allocation statistics.
42    #[derive(Clone, Copy, Debug, Default)]
43    pub struct MemStats {
44        /// Bytes currently allocated.
45        pub used: usize,
46        /// Bytes still available.
47        pub free: usize,
48        /// High-water mark since init.
49        pub peak: usize,
50    }
51
52    /// No-op when the OS provides its own allocator.
53    ///
54    /// # Safety
55    ///
56    /// Always safe; arguments are ignored.
57    pub unsafe fn krypteia_init(_base: *mut u8, _size: usize) -> i32 {
58        0
59    }
60
61    /// Returns zeroed stats in `os-alloc` mode (the OS tracks its
62    /// own heap; we have no visibility).
63    pub fn memory_stats() -> MemStats {
64        MemStats::default()
65    }
66}
67
68#[cfg(feature = "os-alloc")]
69pub use os_alloc::*;
70
71// ====================================================================
72// self-alloc: TLSF allocator over a caller-provided RAM block
73// ====================================================================
74
75#[cfg(feature = "self-alloc")]
76mod self_alloc;
77
78#[cfg(feature = "self-alloc")]
79pub use self_alloc::*;