Skip to content

Instantly share code, notes, and snippets.

@jamesmunns
Created December 19, 2021 18:13
Show Gist options
  • Save jamesmunns/408b2cd532fa8f1b26784e3cc2b5cb56 to your computer and use it in GitHub Desktop.
Save jamesmunns/408b2cd532fa8f1b26784e3cc2b5cb56 to your computer and use it in GitHub Desktop.
// Context to this complaint:
//
// https://twitter.com/bitshiftmask/status/1472624304860839945
//
// What I want:
use byte_slab::{
// https://docs.rs/byte-slab/latest/byte_slab/byte_slab/struct.BSlab.html
Bslab,
// https://docs.rs/byte-slab/latest/byte_slab/managed_arc_slab/enum.ManagedArcStr.html
ManagedArcStr,
// https://docs.rs/byte-slab/latest/byte_slab/managed_arc_slab/enum.ManagedArcSlab.html
ManagedArcSlab
};
// https://docs.rs/postcard/latest/postcard/fn.to_slice.html
use postcard::to_slice;
static SLAB: BSlab<4, 128> = BSlab::new();
#[derive(Deserialize, Serialize)]
struct Example<'a> {
foo: ManagedArcStr<'a, 4, 128>,
bar: ManagedArcSlab<'a, 4, 128>,
}
fn main() {
let _ = SLAB.init().unwrap();
let mut box_data = SLAB.alloc_box().unwrap();
// Pretend these are locals, not statics. Assume this data will be "dropped",
// and we want the later deserialized data to outlive the lifetime of this
// original `data` item.
let data = Example {
foo: ManagedArcStr::Borrowed("Hello,"),
bar: ManagedArcSlab::Borrowed(b"World!"),
};
let used = to_slice(&data, &mut box_data).unwrap().len();
// Totally, definitely gone
drop(data);
// Convert the owned box into a reference counted arc
let arc = box_data.into_arc();
// Take a subslice of the arc, which increments the ref
// count and gives a separate "owned" handle
let subslice = arc.sub_slice_arc(0, used).unwrap();
// imaginary method, should convert all `Managed*` types to their
// "Owned" variants, ensuring that the data lives as long as this `Example`
// instance does. This still re-uses the data allocated by the original
// creation of `box_data`.
//
// I don't know how/where to write this function to allow this to happen
let deser = from_sub_slice_arc::<Example<'static>>(subslice).unwrap();
match deser {
Example { foo: ManagedArcStr::Owned(_), bar: ManagedArcSlab::Owned(_) } => {
// TODO: Something that asserts that the contents of `foo` and `bar`
// are actually stored within the allocation represented by `box_data`/`arc`.
}
_ => panic!()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment