Borsh
https://crates.io/crates/borsh
Borsh (short for Binary Object Representation Serializer for Hashing) is a deterministic, binary serialization format often used in Rust (and other languages) to encode and decode data in a consistent, unambiguous way
It was originally developed by the NEAR Protocol team for use in smart contracts, but you can use it in any Rust project that needs a fast, predictable serialization layer.
cargo add borsh
Update Cargo.toml
[dependencies]borsh = { version = "1.5", features = ["derive"]}
Try to serialize and deserialize a struct
use borsh::{BorshSerialize, BorshDeserialize};
#[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq)]struct MyStruct { id: u64, data: String, v: Vec<u32>}
fn main() { let original = MyStruct { id: 42, data: "Hello, Borsh!".into(), v: vec![1, 2, 3] };
let mut buffer: Vec<u8> = Vec::new();
original.serialize(&mut buffer).unwrap();
// Deserialize let deserialized = MyStruct::try_from_slice(&mut buffer).unwrap();
assert_eq!(original, deserialized); println!("Successfully serialized and deserialized: {:?}", deserialized);}
Assignment -
- Write the same code in JS, log the values and confirm they are indeed the sam
- Create a function called
increment
anddecrement
that reads bytes from a file (a.bin), update the value of aCounter
variable inside and re-write it to the file