borsh-incremental
Incremental Borsh deserialization with defaults for backward-compatible schema evolution.
Example
use borsh::{to_vec, BorshSerialize};
use borsh_incremental::BorshDeserializeIncremental;
#[derive(BorshSerialize, BorshDeserializeIncremental, Debug, PartialEq)]
struct ExampleV1 {
#[incremental(default = "Unnamed".to_string())]
name: String,
count: u32,
}
#[derive(BorshDeserializeIncremental, Debug, PartialEq)]
struct ExampleV2 {
#[incremental(default = "Unnamed".to_string())]
name: String,
count: u32,
#[incremental(default = "active".to_string())]
status: String, }
fn main() {
let old = ExampleV1 {
name: "Alice".into(),
count: 5,
};
let old_bytes = to_vec(&old).unwrap();
let parsed_v2 = ExampleV2::try_from(&old_bytes[..]).unwrap();
println!("Backward-compatible decode: {:?}", parsed_v2);
let truncated_partial = &old_bytes[..(4 + 2)]; match ExampleV2::try_from(truncated_partial) {
Ok(v) => println!("Unexpected success on partial field: {:?}", v),
Err(e) => println!("Partial decode now errors: {}", e),
}
let truncated_after_name = &old_bytes[..old_bytes.len() - 4]; let defaults_applied = ExampleV2::try_from(truncated_after_name).unwrap();
println!(
"Truncated after name (defaults applied): {:?}",
defaults_applied
);
}
Attributes
| Attribute |
Applies To |
Description |
#[incremental(error = <Path>)] |
struct |
Sets the error type for TryFrom<&[u8]>. |
#[incremental(default = <Expr>)] |
field |
Expression or value used if field cannot be deserialized. |
#[incremental(deser_with = <fn>)] |
field |
Uses a custom function fn(&mut &[u8]) -> Result<T, E> to deserialize that field. |
Features
- Implements
TryFrom<&[u8]> for your struct
- Automatically fills missing or invalid fields with defaults
- Supports per-field custom deserializers
- Ideal for forward/backward compatibility or partial account decoding