#byte #hex #serde #hash #serde-json #serde-yaml #json

macro stdto_derive

Stdto provides a set of functional traits for conversion between various data representations

13 breaking releases

0.14.0 Mar 1, 2023
0.13.0 Dec 26, 2022
0.12.0 Dec 22, 2022

#28 in #serde-yaml


Used in stdto

MIT/Apache

17KB
322 lines

Stdto

stdto provides a set of functional traits for conversion between various data representations.

CI Crates.io Licensed Twitter

| Examples | Docs | Latest Note |

stdto = "0.14.0"

Goal

As a blockchain developer who specializes in Rust, I often find it challenging to work with bytes, hashes, and JSON. The Rust ecosystem is decentralized and many popular crates are old and complex. This makes it difficult to find simple, well-abstracted solutions that are easy to understand. I created the Stdto crate to address this need. The goal of Stdto is to provide a standard library-like interface that makes it easy for users to work with and understand primitive data structures.

Features

default = ["derive", "serde", "bytes", "hash", "json", "yaml", "toml", "file", "hex"]
cargo add stdto  # [derive, serde, bytes, hash, json, yaml, toml, file, hex]
cargo add stdto --features "derive bytes" # [derive, serde, bytes]
cargo add stdto --features "derive hash" # [derive, serde, bytes, hash]
cargo add stdto --features "derive json" # [derive, serde, json]
cargo add stdto --features "derive yaml" # [derive, serde, yaml]
cargo add stdto --features "derive toml" # [derive, serde, toml]
cargo add stdto --features "derive file" # [derive, serde, json, yaml, toml]
cargo add stdto --features "derive hex" # [derive, hex]

Examples

use stdto::prelude::*;
// #[stdto::bytes(endian = "little")]
#[stdto::bytes]
struct Test {
    a: u32,
    b: String,
    c: [u8; 32],
    d: Vec<u8>,
    e: BTreeMap<String, f64>,
}

let bytes = Test { .. }.to_bytes();
let test = Test::from_bytes(bytes);
// Test::try_from_bytes(bytes).unwrap();
#[stdto::bytes]
#[stdto::hash]
struct Test {
    ...
}

let hash = test.to_hash::<sha2::Sha256>();
// Any digest crate implemented hasher type
#[stdto::json]
// #[stdto::yaml]
// #[stdto::toml]
struct Test {
    ...
}

let json = test.to_json();
let test = Test::from_json(json);
// Test::try_from_json(json).unwrap();

// let yaml = test.to_yaml();
// let test = Test::from_yaml(yaml);
// let toml = test.to_toml();
// let test = Test::from_toml(toml);
// Any AsRef<[u8]> or AsBytes implemented to hex

let hex = bytes.to_hex();
let hex = hash.to_hex();
let bytes = Vec::<u8>::from_hex(hex);
// Vec::<u8>::try_from_hex(hex).unwrap();

let mut arr = [0u8; 32];
arr.copy_from_hex(hex);
// Any AsRef<[u8]> or AsBytes implemented <-> String, &str

let arr = [72, 105, 77, 111, 109];
let s1 = arr.into_string(); // .try_into_string().unwrap();
let bytes = s1.to_bytes();
let s2 = bytes.as_str(); // .try_as_str().unwrap();

assert_eq!(s1, s2);

Dependencies

~1.5MB
~38K SLoC