Crate decoder

Source
Expand description

A decoder library for your types.

When using serde, your types become entangled with serialization logic due to the Serialize and Deserialize traits.

This crate lets you decouple serialization logic by leveraging simple functions, at some performance cost:

use decoder::{Map, Result, Value};

struct Person {
    name: String,
    projects: Vec<Project>
}

struct Project {
    name: String,
    url: String,
}

impl Person {
    fn decode(value: Value) -> Result<Self> {
        use decoder::decode::{map, sequence, string};

        let mut person = map(value)?;

        Ok(Self {
            name: person.required("name", string)?,
            projects: person.required("projects", sequence(Project::decode))?,
        })
    }

    fn encode(&self) -> Value {
        use decoder::encode::{map, sequence, string};

        map([
            ("name", string(&self.name)),
            ("projects", sequence(Project::encode, &self.projects)),
        ])
        .into()
    }
}

impl Project {
    fn decode(value: Value) -> Result<Self> {
        use decoder::decode::{map, string};

        let mut project = map(value)?;

        Ok(Project {
            name: project.required("name", string)?,
            url: project.required("url", string)?
        })
    }

    fn encode(&self) -> Value {
        use decoder::encode::{map, string};

        map([
            ("name", string(&self.name)),
            ("url", string(&self.url)),
        ])
        .into()
    }
}

let person =
   decoder::run(serde_json::from_str, Person::decode, "{ ... }").expect("Decode person");

let _ = serde_json::to_string(&person.encode());

You can try this crate if the serde way™ has become painful or it does not resonate with you.

Modules§

decode
Decode your types.
encode
Encode your types.

Structs§

Map
A map of fields and their values, sorted by order of insertion.
Value
A generic value.

Enums§

Error
A decoder error.

Traits§

Decoder
Some logic that turns a Value into some Output.

Functions§

run
Runs a Decoder using the given function to deserialize a Value from the given input.

Type Aliases§

Result
A decoding result.