Skip to main content

deserialize_version

Function deserialize_version 

Source
pub fn deserialize_version<T: VerCodable>(
    version: u32,
    buf: &[u8],
) -> Result<T, InvalidEncoding>
Expand description

Deserialize a value from a specific version. Only fields with version less than or equal to the specified version will be deserialized; higher-version fields will be initialized with default values.

⚠️ For Testing Only: This function is almost never useful except for testing purposes. In production code, use deserialize instead.

This function can be useful in tests to simulate an older version of code reading newer serialized data, or to verify that default values are correctly applied to fields that weren’t present in older versions.

§Examples

use vercode::{Vercode, serialize, deserialize_version};

#[derive(Vercode, Default, Debug, PartialEq, Clone)]
struct Config {
    host: String,
    #[version(1)]
    port: u16,
    #[version(2)]
    timeout_ms: u32,
}

let config = Config {
    host: "localhost".to_string(),
    port: 8080,
    timeout_ms: 5000,
};

// Serialize with all fields
let mut buf = vec![0u8; 1024];
let serialized = serialize(&config, &mut buf);

// Simulate old code (version 1) reading new data
let old_config: Config = deserialize_version(1, serialized)
    .expect("deserialize failed");

// Version 1 can see host and port, but timeout_ms gets default value
assert_eq!(old_config.host, "localhost");
assert_eq!(old_config.port, 8080);
assert_eq!(old_config.timeout_ms, 0); // Default for u32