16 unstable releases (3 breaking)

new 0.4.3 Sep 19, 2020
0.4.2 Sep 17, 2020
0.3.7 Sep 13, 2020
0.3.1 Aug 26, 2020
0.1.2 Aug 16, 2020

#77 in Procedural macros

Download history 38/week @ 2020-08-15 31/week @ 2020-08-22 22/week @ 2020-08-29 120/week @ 2020-09-05 708/week @ 2020-09-12

347 downloads per month
Used in 2 crates

LGPL-3.0

13KB
243 lines

edn-derive

Edn derive procedural macros for (De)Serialization.

This library still is pre-alpha.

Usage

[dependencies]
edn-derive = "0.4.3"

Example

Serialization

use edn_derive::Serialize;

#[derive(Serialize)]
enum Kind {
    Cool,
    Chill,
    Pirate,
}

#[derive(Serialize)]
pub struct Person {
    name: String,
    age: usize,
    kind: Kind,
}

fn main() {
    let person = Person {
        name: "joana".to_string(),
        age: 290000,
        kind: Kind::Chill,
    };
    assert_eq!(
        edn_rs::to_string(person),
        "{ :name \"joana\", :age 290000, :kind :kind/chill, }"
    );
}

Deserialization

use edn_derive::Deserialize;
use edn_rs::EdnError;

// The `Debug` and `PartialEq` are only necessary because of `assert_eq`, you don't need them
#[derive(Deserialize, Debug, PartialEq)]
enum Kind {
    Cool,
    Chill,
    Pirate,
}

// The `Debug` and `PartialEq` are only necessary because of `assert_eq`, you don't need them
#[derive(Deserialize, Debug, PartialEq)]
pub struct Person {
    name: String,
    age: usize,
    kind: Kind,
}

fn main() -> Result<(), EdnError> {
    let edn_person = "{ :name \"joana\", :age 290000, :kind :kind/pirate, }";

    let person: Person = edn_rs::from_str(edn_person)?;

    assert_eq!(
        person,
        Person {
            name: "joana".to_string(),
            age: 290000,
            kind: Kind::Pirate,
        }
    );

    Ok(())
}

With more complexity using ., - and / on EDN conversions:

use edn_derive::{Deserialize, Serialize};
use edn_rs::EdnError;

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
enum AccountType {
    Basic,
    Premium,
    PremiumPlus,
}

#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
struct Account {
    crux__db___id: String,
    account___amount: usize,
    account_type: AccountType,
}

fn main() -> Result<(), EdnError> {
    let account = Account {
        crux__db___id: "123".to_string(),
        account___amount: 42,
        account_type: AccountType::PremiumPlus,
    };

    let account_edn_str =
        "{ :crux.db/id \"123\", :account/amount 42, :account-type :account-type/premium-plus, }";

    assert_eq!(edn_rs::to_string(account), account_edn_str);

    let account: Account = edn_rs::from_str(account_edn_str)?;

    assert_eq!(
        account,
        Account {
            crux__db___id: "123".to_string(),
            account___amount: 42,
            account_type: AccountType::PremiumPlus,
        }
    );

    Ok(())
}

Dependencies

~0.5–1MB
~23K SLoC