Sled: Storing complex datatypes

Created on 5 Oct 2019  路  2Comments  路  Source: spacejam/sled

Be prepared for a silly question.

I see that sled takes in values of u8, is there a way to get more complex data types like a struct with 30 fields? Or is there a possible way to convert these structs into something more digestible by sled?

Most helpful comment

I think the obvious way to store your struct is to make it Serialize (using serde_derive for example) and serialize it using bincode for example, bincode will produce a Vec<u8> that sled can now understand.

To retrieve it you will need to deserialize it from the bytes (Vec<u8>) that sled will gives you.

#[derive(Default, Serialize, Deserialize)]
struct MySuperStruct {
    field1: String,
    field2: Vec<f64>,
}

let tree = Db::open(path)?;

let my_super_struct = MySuperStruct::default();
let bytes = bincode::serialize(&my_super_struct)?;

tree.insert("my-super-struct", bytes);

match tree.get("my-super-struct")? {
    Some(bytes) => {
        let my_super_struct: MySuperStruct = bincode::deserialize(&bytes)?;
        // play with this struct here
    },
    None => (),
}

All 2 comments

I think the obvious way to store your struct is to make it Serialize (using serde_derive for example) and serialize it using bincode for example, bincode will produce a Vec<u8> that sled can now understand.

To retrieve it you will need to deserialize it from the bytes (Vec<u8>) that sled will gives you.

#[derive(Default, Serialize, Deserialize)]
struct MySuperStruct {
    field1: String,
    field2: Vec<f64>,
}

let tree = Db::open(path)?;

let my_super_struct = MySuperStruct::default();
let bytes = bincode::serialize(&my_super_struct)?;

tree.insert("my-super-struct", bytes);

match tree.get("my-super-struct")? {
    Some(bytes) => {
        let my_super_struct: MySuperStruct = bincode::deserialize(&bytes)?;
        // play with this struct here
    },
    None => (),
}

You are the man!! Thank you so much!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rubdos picture rubdos  路  8Comments

rubdos picture rubdos  路  4Comments

spacejam picture spacejam  路  6Comments

brechtcs picture brechtcs  路  4Comments

thedrow picture thedrow  路  5Comments