Skip to content

Conversation

@scarmuega
Copy link
Member

This PR introduces a new approach for dealing with original CBOR of decoded primitive structs.

Happy path:

// this is the store for cbor bytes. The item size multiplied by the capacity
// defines the pre-allocated memory.
let mut heap = CborHeap::<1024>::new(1);

// lets say that we get some CBOR from the network that we want to decode and
// remember (simplified here using a hardcoded value)
let cbor = hex::decode("a3000101613202f5").unwrap();

// we ask the heap the decode the CBOR. This step will enter the CBOR into the
// heap and decorate the decoded structure with a lightweight pointer to the
// slice in the heap.
//
// The returned tuple has the decoded structure and a guard that is used to
// forget the CBOR from the heap once we are done with it.
let (plain_struct, cbor_guard) = heap.decode::<ExampleStruct>(&cbor).unwrap();

// Let's say we need to access the cbor for one of the fields in the struct, we
// can ask the heap to retrieve that particular CBOR slice. This search is very
// efficient, is just one index lookup in the hep and a range lookup over the
// full bytes of the CBOR.
let cbor_fragment = heap.find_cbor(&plain_struct.hashable_value);

assert_eq!(hex::encode(cbor_fragment.unwrap()), "6132");

// when we're done doing all of the hashing, we can forget the CBOR from the
// heap.
heap.forget(cbor_guard);

// but the plain structure is still valid and doesn't have any lifetimes or
// dependencies. It can be moved as value to other functions or threads.
owning_function(plain_struct);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects
Status: No status

Development

Successfully merging this pull request may close these issues.

2 participants