Trait cuprate_database::Storable

source ·
pub trait Storable: Debug {
    const BYTE_LENGTH: Option<usize>;

    // Required methods
    fn as_bytes(&self) -> &[u8] ;
    fn from_bytes(bytes: &[u8]) -> Self;
}
Expand description

A type that can be stored in the database.

All keys and values in the database must be able to be (de)serialized into/from raw bytes ([u8]).

This trait represents types that can be perfectly casted/represented as raw bytes.

§bytemuck

Any type that implements:

will automatically implement Storable.

See StorableVec & StorableBytes for storing slices of T: Storable.

let number: u64 = 0;

// Into bytes.
let into = Storable::as_bytes(&number);
assert_eq!(into, &[0; 8]);

// From bytes.
let from: u64 = Storable::from_bytes(&into);
assert_eq!(from, number);

§Invariants

No function in this trait is expected to panic.

The byte conversions must execute flawlessly.

§Endianness

This trait doesn’t currently care about endianness.

Bytes are (de)serialized as-is, and bytemuck types are architecture-dependant.

Most likely, the bytes are little-endian, however that cannot be relied upon when using this trait.

Required Associated Constants§

source

const BYTE_LENGTH: Option<usize>

Is this type fixed width in byte length?

I.e., when converting Self to bytes, is it represented with a fixed length array of bytes?

§Some

This should be Some(usize) on types like:

  • u8
  • u64
  • i32

where the byte length is known.

§None

This should be None on any variable-length type like:

  • str
  • [u8]
  • Vec<u8>
§Examples
assert_eq!(<()>::BYTE_LENGTH, Some(0));
assert_eq!(u8::BYTE_LENGTH, Some(1));
assert_eq!(u16::BYTE_LENGTH, Some(2));
assert_eq!(u32::BYTE_LENGTH, Some(4));
assert_eq!(u64::BYTE_LENGTH, Some(8));
assert_eq!(i8::BYTE_LENGTH, Some(1));
assert_eq!(i16::BYTE_LENGTH, Some(2));
assert_eq!(i32::BYTE_LENGTH, Some(4));
assert_eq!(i64::BYTE_LENGTH, Some(8));
assert_eq!(StorableVec::<u8>::BYTE_LENGTH, None);
assert_eq!(StorableVec::<u64>::BYTE_LENGTH, None);

Required Methods§

source

fn as_bytes(&self) -> &[u8]

Return self in byte form.

source

fn from_bytes(bytes: &[u8]) -> Self

Create an owned Self from bytes.

§Blanket implementation

The blanket implementation that covers all types used by cuprate_database will simply bitwise copy bytes into Self.

The bytes do not have be correctly aligned.

Object Safety§

This trait is not object safe.

Implementors§