nanoserde

repository·master·Indexed 21 days ago

https://github.com/not-fl3/nanoserde

A lightweight serialization and deserialization library for Rust and a fork of makepad-tinyserde. It is optimized to remove heavy build-time dependencies such as syn, proc_macro2, and quote. nanoserde supports JSON, Binary, RON, and TOML formats via specialized derive macros (e.g., SerJson, DeJson, SerBin, DeBin, SerRon, DeRon) and provides customization through #[nserde(...)] attributes.

Tokens
4.9K
Snippets
19
Records
26
Agent score
75%

What's inside nanoserde

  1. Use nanoserde for serialization and deserialization

    master

    nanoserde is a lightweight serialization framework designed to avoid heavy dependencies like syn, proc_macro2, or quote in your build tree. You can use it by deriving SerJson and DeJson traits on your data structures.

    To use the derive macros, you will need both nanoserde and nanoserde-derive in your dependency tree.

    use nanoserde::{DeJson, SerJson};
    
    #[derive(Clone, Debug, Default, DeJson, SerJson)]
    pub struct Property {
        pub name: String,
        #[nserde(default)]
        pub value: String,
        #[nserde(rename = "type")]
        pub ty: String,
    }
  2. Configure nanoserde crate features

    master

    By default, all features are enabled. If you want to reduce your dependency footprint, you can disable default features and enable only the specific formats you need.

    Add the following to your Cargo.toml to select specific formats:

    nanoserde = { version = "*", default-features = false, features = ["std", "json"] }

    Available format features:

    • binary for Binary format
    • json for JSON format
    • ron for RON format
    • toml for TOML format
  3. Configure nanoserde macros with nserde attributes

    master
    The nanoserde derive macros (SerBin, DeBin, SerRon, DeRon, SerJson, DeJson) support the nserde attribute to customize serialization behavior. Additionally, you can specify a custom crate name via attributes if you are not using the default nanoserde crate.
  4. How SerRon and DeRon work together

    master

    The RON implementation in nanoserde follows a state-based approach for both serialization and deserialization:

    1. Serialization (SerRon): Uses SerRonState to maintain an internal String buffer. The ser_ron method is called recursively on nested structures, using the indent and field methods to manage formatting.
    2. Deserialization (DeRon): Uses DeRonState to track the current character, the current token (DeRonTok), and buffer strings for identifiers, numbers, and strings. The de_ron method consumes tokens from a Chars iterator provided by the input string.
  5. Supported types for JSON serialization and deserialization

    master

    Nanoserde provides built-in implementations for several common Rust types. Note that some collection types require the std feature.

    Primitives:

    • Unsigned integers (u8, u16, u32, u64, usize)
    • Signed integers (i8, i16, i32, i64)
    • Floating point (f32, f64)
    • Booleans (bool)
    • Strings (String, str)
    • Null/Unit ((), Option<T>)

    Collections (requires std feature for some):

    • Vec<T>
    • [T; N] (Fixed-size arrays)
    • (A, B, ...) (Tuples up to 4 elements)
    • LinkedList<T>
    • BTreeSet<T>
    • BTreeMap<K, V> (via std)
    • HashMap<K, V> (via std)
    • HashSet<T> (via std)
  6. Understand the Toml data model

    master

    The Toml enum supports the following data types:

    • Str(String): A string value.
    • Bool(bool): A boolean value.
    • Num(f64): A numeric value (handles integers, floats, NaN, and Infinity).
    • Date(String): A date string.
    • Array(Vec<BTreeMap<String, Toml>>): A table array (an array of tables).
    • SimpleArray(Vec<Toml>): A standard array of values.
  7. Customize serialization with #[nserde()] attributes

    master

    You can customize how your data is serialized or deserialized using the #[nserde()] attribute. The specific attributes supported depend on the format you are using (JSON, Binary, or RON). Refer to the Features support matrix in the repository for a complete list of supported attributes per format.

    #[derive(SerJson, DeJson)]
    #[nserde(..)]
    struct MyData {
        // attributes go here
    }
  8. Reference nanoserde field and container attributes

    master

    nanoserde provides several attributes via the #[nserde(...)] syntax to control how data is serialized and deserialized. Note that support for these attributes varies depending on the chosen format (JSON, Binary, RON, or TOML).

    ### Field Attributes
    - `#[nserde(default)]`: Uses the type's default value if the field is missing.
    - `#[nserde(rename = "...")]`: Renames the field in the serialized output.
    - `#[nserde(proxy = "...")]`: Uses a proxy type for serialization/deserialization.
    - `#[nserde(serialize_none_as_null)]`: Serializes `None` as a null value.
    
    ### Container Attributes
    - `#[nserde(default)]`: Uses default values for missing fields.
    - `#[nserde(default = "...")]`: Uses a specific function for default values.
    - `#[nserde(default_with = "...")]`: Uses a specific function for default values.
    - `#[nserde(skip)]`: Skips the field (implies `default`).
    - `#[nserde(serialize_none_as_null)]`: Serializes `None` as a null value.
    - `#[nserde(rename = "...")]`: Renames the container.
    - `#[nserde(proxy = "...")]`: Uses a proxy type.
    - `#[nserde(transparent)]`: Treats the container as its single field.
    - `#[nserde(crate = "...")]`: Specifies the crate path for nanoserde.
  9. Serialize data to RON format with SerRon

    master

    The SerRon trait allows types to be serialized into the RON (Rusty Object Notation) format.

    To perform a simple serialization to a String, use the serialize_ron() method. For more granular control, implement ser_ron(indent_level: usize, state: &mut SerRonState), where SerRonState manages the output buffer.

    Supported types include primitives (integers, floats, bools, strings, chars), Option<T>, Vec<T>, tuples, arrays, and various collections like LinkedList, BTreeSet, and HashMap (when the std feature is enabled).

    # use nanoserde::SerRon;
    // Assuming a type implements SerRon
    let value = 42u32;
    let ron_string = value.serialize_ron();
    assert_eq!(ron_string, "42");
  10. Deserialize objects from binary with DeBin

    master

    The DeBin trait allows objects to be parsed from a byte slice.

    • deserialize_bin(d: &[u8]): A convenience method that starts parsing from the beginning (offset 0) of the provided slice.
    • de_bin(offset: &mut usize, bytes: &[u8]): A low-level method that parses data starting at the provided offset. After successful deserialization, the offset is updated to point to the byte immediately following the consumed data.
    # use nanoserde::DeBin;
    let bytes = [1, 0, 0, 0, 2, 0, 0, 0];
    let mut offset = 4;
    let two = u32::de_bin(&mut offset, &bytes).unwrap();
    assert_eq!(two, 2);
    assert_eq!(offset, 8);
  11. Derive serialization and deserialization for RON format

    master

    Use the SerRon and DeRon derive macros to implement RON (Rusty Object Notation) serialization and deserialization for structs and enums. These macros support the nserde attribute for configuration.

    Note: This requires the ron feature to be enabled in your Cargo.toml.

    #[derive(SerRon, DeRon)]
    struct MyStruct {
        field: u32,
    }
  12. Derive serialization and deserialization for Binary format

    master

    Use the SerBin and DeBin derive macros to implement binary serialization and deserialization for structs and enums. These macros support the nserde attribute for configuration.

    Note: This requires the binary feature to be enabled in your Cargo.toml.

    #[derive(SerBin, DeBin)]
    struct MyStruct {
        field: u32,
    }