serde_versioned
A Rust library built on top of the Serde crate for handling versioned serialization and deserialization of structs with backward compatibility support.
Features
- Version Management: Easily manage multiple versions of your data structures
- Backward Compatibility: Automatically convert older versions to the current version
- Type Safety: Compile-time guarantees for version conversions
- Serde Integration: Seamless integration with serde for serialization/deserialization
- Flexible Format Support: Works with any format supported by serde (JSON, YAML, TOML, etc.)
Installation
Add this to your Cargo.toml:
[]
= "0.2.0"
= { = "1.0", = ["derive"] }
= "1.0" # Optional, for JSON support
Quick Start
Basic Usage
use ;
use ;
// Define your current struct
// Define version 1 (older version)
// Define version 2 (current version)
// Implement conversion from version 1 to current
// Implement conversion from version 2 to current
Converting Between Versions
// Convert current struct to versioned enum
let user = User ;
let version = user.to_version;
// Convert versioned enum back to current struct
let restored = from_version.unwrap;
assert_eq!;
Serialization and Deserialization
use serde_json;
// Serialize to JSON
let user = User ;
let version = user.to_version;
let json = to_string.unwrap;
// json: {"version":"2","name":"David","age":35}
// Deserialize from JSON
let version_restored: UserVersion = from_str.unwrap;
let user_restored = from_version.unwrap;
assert_eq!;
Working with Older Versions
// Deserialize an older version (v1) and convert to current
let v1_json = r#"{"version":"1","name":"Eve"}"#;
let user = from_format.unwrap;
assert_eq!;
assert_eq!; // default value from conversion
Convenience Methods
// Serialize using convenience method
let user = User ;
let json = user.to_format.unwrap;
// Deserialize using convenience method
let user = from_format.unwrap;
Requirements
- The struct must have named fields (tuple structs and unit structs are not supported)
- Each version struct must implement:
SerializeandDeserialize(from serde)CloneFromVersion<CurrentStruct>trait
Examples
See the tests/test.rs file for more comprehensive examples including:
- Version conversion
- JSON serialization/deserialization
- Handling multiple versions
- Default value handling for missing fields
License
This project is licensed under the MIT License - see the LICENSE.md file for details.