Piece

Crates.io Documentation

Piece is a collection of composable allocators for rust.

Allocators

Currently this crate contains two allocators, piece::LinearAllocator and piece::ChainAllocator.

Linear allocator

piece::LinearAllocator is an allocator that keeps a fixed-sized buffer internally and use it to make allocations. Once the buffer is full, all next allocations fails.

This allocator is useful when you want a "scratch space" for multiple tiny allocations that share the same lifetime.

Usage: ```rust

![feature(allocator_api)]

use core::{alloc::Allocator, mem::size_of}; use std::vec::Vec;

use piece::LinearAllocator;

let linearallocator = LinearAllocator::withcapacity(64 * size_of::());

let mut vec1 = Vec::withcapacityin(32, linearallocator.byref()); let mut vec2 = Vec::withcapacityin(32, linearallocator.byref());

vec1.extendfromslice(&[1, 2, 3, 4, 5]); vec2.extendfromslice(&[6, 7, 8, 9, 10]);

asserteq!(vec1, &[1, 2, 3, 4, 5]); asserteq!(vec2, &[6, 7, 8, 9, 10]); ```

Chain allocator

A piece::ChainAllocator create a new allocator of type A when the existing allocators of this

It can be useful when used with a piece::LinearAllocator for example. When all of its memory is used, the ChainAllocator will create a new one. This is useful when you want to use fixed-sized allocators but you're worried that your program will run out of memory.

Usage: ```rust

![feature(allocator_api)]

use core::{alloc::Allocator, mem::size_of}; use std::vec::Vec;

use piece::LinearAllocator; use piece::ChainAllocator;

// Make room for the allocator pointer let chainallocator = ChainAllocator::new(|| { LinearAllocator::withcapacity(32 * sizeof::() + sizeof::<*const ()>()) });

// Create two vectors that fills the whole LinearAllocator so // each Vec creates a new allocator let mut vec1 = Vec::withcapacityin(32, chainallocator.byref()); let mut vec2 = Vec::withcapacityin(32, chainallocator.byref());

vec1.extendfromslice(&[1, 2, 3, 4, 5]); vec2.extendfromslice(&[6, 7, 8, 9, 10]);

asserteq!(vec1, &[1, 2, 3, 4, 5]); asserteq!(vec2, &[6, 7, 8, 9, 10]);

asserteq!(2, chainallocator.allocator_count()); ```