serde_rson

Crates.ioserde_rson
lib.rsserde_rson
version1.0.0
created_at2025-05-31 21:13:19.04619+00
updated_at2025-05-31 21:24:11.115418+00
descriptionSerde integration for RSON
homepagehttps://rson.dev
repositoryhttps://github.com/RSON-Rust-Serialized-Object-Notation/RSON-core
max_upload_size
id1696647
size14,060
Okware (okwareddevnest)

documentation

README

๐Ÿฆ€ serde_rson

Serde integration for RSON (Rust Serialized Object Notation)

Crates.io Documentation License


๐ŸŽฏ What is serde_rson?

serde_rson provides seamless Serde integration for RSON, allowing you to serialize and deserialize Rust structs and enums to/from RSON format with zero boilerplate.

Key Features:

  • Drop-in replacement for serde_json
  • Rich type support - Structs, enums, options, tuples
  • Comments and trailing commas - Developer-friendly format
  • JSON compatibility - Every JSON is valid RSON
  • High performance - Built on efficient Rust parsing

๐Ÿš€ Quick Start

Installation

[dependencies]
serde_rson = "1.0.0"
serde = { version = "1.0", features = ["derive"] }

Basic Usage

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    name: String,
    version: String,
    database: DatabaseConfig,
    features: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug)]
struct DatabaseConfig {
    host: String,
    port: Option<u16>,
    ssl: bool,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Parse RSON with comments and rich types
    let rson_text = r#"
        // Application configuration
        Config(
            name: "My App",
            version: "1.0.0",
            database: DatabaseConfig(
                host: "localhost",
                port: Some(5432), // Optional port
                ssl: true,
            ),
            features: ["auth", "logging"], // Trailing comma OK
        )
    "#;
    
    // Deserialize from RSON
    let config: Config = serde_rson::from_str(rson_text)?;
    println!("Config: {:#?}", config);
    
    // Serialize to RSON
    let rson_output = serde_rson::to_string(&config)?;
    println!("RSON output:\n{}", rson_output);
    
    Ok(())
}

๐Ÿ“š API Reference

Deserialization

use serde_rson;

// From string
let value: MyStruct = serde_rson::from_str(rson_text)?;

// From reader (file, network, etc.)
let value: MyStruct = serde_rson::from_reader(reader)?;

// From bytes
let value: MyStruct = serde_rson::from_slice(rson_bytes)?;

Serialization

use serde_rson;

// To string
let rson_text = serde_rson::to_string(&my_struct)?;

// To string with pretty printing
let rson_text = serde_rson::to_string_pretty(&my_struct)?;

// To writer (file, network, etc.)
serde_rson::to_writer(writer, &my_struct)?;

// To bytes
let rson_bytes = serde_rson::to_vec(&my_struct)?;

๐ŸŽจ RSON vs JSON Examples

Rich Enums

#[derive(Serialize, Deserialize)]
enum Message {
    Text(String),
    Image { url: String, width: u32, height: u32 },
    Video { url: String, duration: f64 },
}

// RSON representation
let rson = r#"
Message::Image(
    url: "https://example.com/image.jpg",
    width: 800,
    height: 600,
)
"#;

// JSON would need workarounds like:
// {"Image": {"url": "...", "width": 800, "height": 600}}

Optional Fields

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    email: Option<String>,
    phone: Option<String>,
}

// RSON with explicit optionals
let rson = r#"
User(
    name: "John Doe",
    email: Some("john@example.com"),
    phone: None, // Explicit null
)
"#;

Comments in Configuration

#[derive(Serialize, Deserialize)]
struct ServerConfig {
    host: String,
    port: u16,
    workers: u8,
    timeout: u64,
}

// RSON with documentation
let rson = r#"
// Production server configuration
ServerConfig(
    host: "0.0.0.0",         // Bind to all interfaces
    port: 8080,              // HTTP port
    workers: 4,              // Number of worker threads
    timeout: 30,             // Request timeout in seconds
)
"#;

๐Ÿ”ง Advanced Features

Custom Serialization

use serde_rson::Serializer;
use serde::Serialize;

let mut serializer = Serializer::new();
serializer.pretty(true);
serializer.comments(true);

my_struct.serialize(&mut serializer)?;
let rson_text = serializer.into_string();

Custom Deserialization

use serde_rson::Deserializer;
use serde::Deserialize;

let mut deserializer = Deserializer::new(rson_text);
deserializer.strict_mode(false); // Allow trailing commas

let value = MyStruct::deserialize(&mut deserializer)?;

Streaming

use serde_rson::StreamDeserializer;

// Parse multiple RSON values from a stream
let stream = StreamDeserializer::new(reader);
for value in stream {
    let config: Config = value?;
    // Process each config...
}

๐ŸŽฏ Migration from serde_json

1. Update Dependencies

# Before
[dependencies]
serde_json = "1.0"

# After  
[dependencies]
serde_rson = "0.1.0"

2. Update Imports

// Before
use serde_json;

// After
use serde_rson;

3. Replace Function Calls

// Before
let value: MyStruct = serde_json::from_str(json_text)?;
let json_text = serde_json::to_string(&value)?;

// After
let value: MyStruct = serde_rson::from_str(rson_text)?;
let rson_text = serde_rson::to_string(&value)?;

4. Enjoy RSON Features

// Now you can use RSON-specific features
let rson_with_comments = r#"
    // This is a comment!
    Config(
        name: "My App",
        debug: true, // Trailing comma
    )
"#;

let config: Config = serde_rson::from_str(rson_with_comments)?;

๐Ÿ“Š Performance

RSON performance is comparable to JSON for typical use cases:

Operation serde_json serde_rson Notes
Parse Baseline ~95% Slightly slower due to richer parsing
Serialize Baseline ~100% Same performance
File Size Baseline ~95% More compact with unquoted keys

Benchmarks on typical configuration files


๐Ÿ› ๏ธ Configuration

Serializer Options

use serde_rson::ser::{Serializer, Config};

let config = Config {
    pretty: true,           // Pretty-print output
    indent: "  ".to_string(), // Indentation string
    comments: false,        // Include comments in output
    trailing_commas: true,  // Add trailing commas
};

let serializer = Serializer::with_config(config);

Deserializer Options

use serde_rson::de::{Deserializer, Config};

let config = Config {
    strict_mode: false,     // Allow RSON extensions
    max_depth: 128,         // Maximum nesting depth
    allow_comments: true,   // Parse comments
    allow_trailing_commas: true, // Allow trailing commas
};

let deserializer = Deserializer::with_config(rson_text, config);

๐Ÿงช Testing

#[cfg(test)]
mod tests {
    use super::*;
    use serde_rson;

    #[test]
    fn test_roundtrip() {
        let original = Config {
            name: "Test".to_string(),
            version: "1.0".to_string(),
            // ... other fields
        };
        
        // Serialize to RSON
        let rson_text = serde_rson::to_string(&original).unwrap();
        
        // Deserialize back
        let parsed: Config = serde_rson::from_str(&rson_text).unwrap();
        
        // Should be identical
        assert_eq!(original, parsed);
    }
}

๐Ÿ“– Documentation


๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide.

Areas we need help with:

  • Performance optimizations
  • Additional Serde features
  • Better error messages
  • Documentation and examples

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ”— Related Projects


Made with ๐Ÿฆ€ by the RSON community

Commit count: 7

cargo fmt