U8Pool
Uses preallocated memory to store byte slices. The interface is stack-based, with Vec and Map iterators. The code is no_std, with thiserror as the only dependency.
Example
use U8Pool;
let mut buffer = ;
let mut u8pool = with_default_max_slices?;
// Add key-value pairs
u8pool.push?;
u8pool.push?;
u8pool.push?;
u8pool.push?;
// Iterate over all elements
for element in &u8pool
// Output:
// "name"
// "Alice"
// "age"
// "30"
// Iterate over pairs
for in u8pool.pairs
// Output:
// "name" = "Alice"
// "age" = "30"
Memory Layout
Memory layout for the example above:
┌─────────────────────────────────────────────────────────────────────────┐
│ Buffer (1000 bytes) │
├─────────────────────────────────┬───────────────────────────────────────┤
│ Metadata Section │ Data Section │
│ (4 * 32 = 128) │ (872 bytes) │
├─────────────────────────────────┼───────────────────────────────────────┤
│ Slice 0: [0,4) len=4 →→→→→┼→→ nameAliceage30 │
│ Slice 1: [4,9) len=5 →→→→→┼→→→→→→→┘ ↑ ↑ │
│ Slice 2: [9,12) len=3 →→→→→┼→→→→→→→→→→→→┘ ↑ │
│ Slice 3: [12,14) len=2 →→→→→┼→→→→→→→→→→→→→→→┘ │
│ ... (28 unused slots) │ ... (858 unused bytes) │
└─────────────────────────────────┴───────────────────────────────────────┘
Each slice descriptor is stored as 4 bytes, with 2 bytes for the offset and 2 bytes for the length.
API Summary
Construction:
U8Pool::new(buffer: &mut [u8], max_slices: usize)- Creates a pool with custom slice limitU8Pool::with_default_max_slices(buffer: &mut [u8])- Creates a pool with default limit (32 slices)
Stack Operations:
push(&mut self, data: &[u8])- Adds a slice to the poolpop(&mut self) -> Option<&[u8]>- Removes and returns the last sliceget(&self, index: usize) -> Option<&[u8]>- Accesses a slice by indexclear(&mut self)- Removes all slices
Information:
len(&self) -> usize- Returns the number of slices storedis_empty(&self) -> bool- Checks if the pool is empty
Iteration:
iter(&self)- Returns a forward iterator over slicesiter_rev(&self)- Returns a reverse iterator over slicespairs(&self)- Returns an iterator over key-value pairs (even/odd slices). If there is an odd number of slices, the last slice is ignored
Error Handling:
All operations that can fail return Result<T, U8PoolError> with these error types:
InvalidInitialization- Invalid buffer ormax_slicesparameterSliceLimitExceeded- Too many slices have been addedBufferOverflow- Insufficient space for dataValueTooLarge- Slice position or length exceedsu16::MAX
Colophon
License: MIT
Author: Oleg Parashchenko, olpa@ https://uucode.com/
Contact: via email or Ailets Discord
u8pool is a part of the streaming json project, with other crates rjiter and scan_json.