Skip to content

Commit

Permalink
Merge pull request #6 from jfrimmel/realworld-allocations
Browse files Browse the repository at this point in the history
Add a real-world allocation test case
  • Loading branch information
jfrimmel authored Aug 20, 2022
2 parents f5ddf97 + 6f116e0 commit c3662ca
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ static ALLOCATOR: emballoc::Allocator<4096> = emballoc::Allocator::new();
extern crate alloc;
```

Now the crate can use the `std` collections such as `Vec<T>`, `HashMap<K, V>`, etc. together with important types like `Box<T>` and `Rc<T>`.
Now the crate can use the `std` collections such as `Vec<T>`, `BTreeMap<K, V>`, etc. together with important types like `Box<T>` and `Rc<T>`.
Note, that things in the `std`-prelude (e.g. `Vec<T>`, `Box<T>`, ...) have to be imported explicitly.
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
//! The usage is simple: just copy and paste the following code snipped into
//! your binary crate and potentially adjust the number of bytes of the heap
//! (here 4K):
//! ```no_run
//! ```
//! #[global_allocator]
//! static ALLOCATOR: emballoc::Allocator<4096> = emballoc::Allocator::new();
//!
//! extern crate alloc;
//! ```
//! Afterwards you don't need to interact with the crate or the variable
//! `ALLOCATOR` anymore. Now you can just `use alloc::vec::Vec` or even
//! `use alloc::collections::HashMap`, i.e. every fancy collection which is
//! `use alloc::collections::BTreeMap`, i.e. every fancy collection which is
//! normally provided by the `std`.
//!
//! The minimal buffer size is `8`, which would allow exactly one allocation of
Expand Down
32 changes: 32 additions & 0 deletions tests/allocation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#![no_std]

const HEAP_SIZE: usize = 4 * 1024 * 1024;

#[global_allocator]
static ALLOCATOR: emballoc::Allocator<HEAP_SIZE> = emballoc::Allocator::new();

extern crate alloc;

#[test]
fn vec() {
let mut v = alloc::vec![1, 2, 3];
v.push(4);

assert_eq!((1..=4).collect::<alloc::vec::Vec<_>>(), v);
}

#[test]
fn map_and_formatting() {
let mut map = alloc::collections::BTreeMap::new();
map.insert(10, "Hello");
map.insert(11, "world");
map.insert(20, "Hallo");
map.insert(21, "Welt");
map.insert(-1, "english");
map.insert(-2, "german");

let english = alloc::format!("[{}]: {}, {}!", map[&-1], map[&10], map[&11]);
let german = alloc::format!("[{}]: {}, {}!", map[&-2], map[&20], map[&21]);
assert_eq!(english, "[english]: Hello, world!");
assert_eq!(german, "[german]: Hallo, Welt!");
}

0 comments on commit c3662ca

Please sign in to comment.