Memory-Slice
memory_slice
that can alias any kind of data, and provides an API that allow user to read, write and borrow
data of any type.
Features
- Read and write data of any type with alignment check.
- Write data in the buffer and get a smart pointer that will destroy the object in the buffer when the smart pointer is droped.
- Use the static borrow-checker to ensure that no write can be performed on any borrowed data in the buffer.
- Provides an API to create statically sized buffer on the stack with alignment requirement.
- No std.
Example
Any kind of data can be viewed as constant memory slice:
use AsMemory;
let v: = ;
//as_memory return a &memory_slice
assert_eq!;
But only types that do not preserve any invariants are accessible as mutable memory slice:
This will compile:
use AsMutMemory;
let mut v: = ;
//as_memory return a &memory_slice
v.as_mut_memory.write;
This will not compile:
use AsMutMemory;
use String;
let mut v = String new;
//as_memory return a &memory_slice
v.as_mut_memory.write; //compilation failure
Mutable memory slices can be used to write information of any type while preserving borrow rules. The API provide also a smart pointer that will drop value created on the memory slice:
use ;
// creates an array of 64 u8 aligned as 8:
let mut buff = align!;
//the create an int inside the buffer and get a reference to it
let = buff.as_mut_memory.write;
assert!;
//unsafe{buff[0]}; //error => cannot borrow buff as immutable
//use the remaining unitialized buffer to write an u64 in it:
let = remaining_buffer.write;
assert_eq!;
//unsafe{remaing_buffer.read::<u8>()}; //error => cannot borrow remaining_buffer
//v1 and v2 are reference to the i32 and u64 created inside buff
assert_eq!;
//string refered by v3 is dropped
//buff is not anymore borrowed, so it is accessible:
assert_eq!;
//memory slice can be indexed (!!less inoffensive than it looks)
unsafe;
assert_ne!;
A macro named buffer
is provided to create uninitialized
buffer:
use buffer;
// create an uninitialized buffer of 64 bytes aligned as 8.
let mut buff = buffer!;
// buffer are dereferencable as memory_slice
//the create an int inside the buffer and get a reference to it
buff.write;