#serialization #deserialize #serde #typename #derive-debug

serde_typename

方便地将Rust类型序列化/反序列化为/从其serde名称

1个不稳定版本

0.1.0 2022年7月9日

#1486编码

Download history • Rust 包仓库 45/week @ 2024-03-13 • Rust 包仓库 40/week @ 2024-03-20 • Rust 包仓库 75/week @ 2024-03-27 • Rust 包仓库 78/week @ 2024-04-03 • Rust 包仓库 81/week @ 2024-04-10 • Rust 包仓库 185/week @ 2024-04-17 • Rust 包仓库 117/week @ 2024-04-24 • Rust 包仓库 99/week @ 2024-05-01 • Rust 包仓库 47/week @ 2024-05-08 • Rust 包仓库 33/week @ 2024-05-15 • Rust 包仓库 46/week @ 2024-05-22 • Rust 包仓库 81/week @ 2024-05-29 • Rust 包仓库 154/week @ 2024-06-05 • Rust 包仓库 67/week @ 2024-06-12 • Rust 包仓库 111/week @ 2024-06-19 • Rust 包仓库 37/week @ 2024-06-26 • Rust 包仓库

377 每月下载次数

GPL-3.0 许可证

36KB
887

crates.io docs

serde_typename

方便地将Rust类型序列化/反序列化为/从其serde名称。

用法

use serde::{Serialize, Deserialize};
use serde_typename::{to_str, from_str};

/// Enums

#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Enum {
    UnitVariant,
    #[serde(rename = "RENAMED")]
    Renamed,
    HoldsData(u8),
    HoldsDataAsTuple(u8, u8),
    HoldsDataAsStruct { field: u8 }
}

// Safe to serialize, held data gets discarded
assert_eq!(to_str(&Enum::UnitVariant).unwrap(), "UnitVariant");
assert_eq!(to_str(&Enum::Renamed).unwrap(), "RENAMED");
assert_eq!(to_str(&Enum::HoldsData(0)).unwrap(), "HoldsData");
assert_eq!(to_str(&Enum::HoldsDataAsTuple(0, 0)).unwrap(), "HoldsDataAsTuple");
assert_eq!(to_str(&Enum::HoldsDataAsStruct { field: 0 }).unwrap(), "HoldsDataAsStruct");

// Safe to deserialize since no data is held
assert_eq!(from_str::<Enum>("UnitVariant").unwrap(), Enum::UnitVariant);
assert_eq!(from_str::<Enum>("RENAMED").unwrap(), Enum::Renamed);
// Cant be deserialized since their data was lost during serialization
assert!(from_str::<Enum>("HoldsData").is_err());
assert!(from_str::<Enum>("HoldsDataAsTuple").is_err());
assert!(from_str::<Enum>("HoldsDataAsStruct").is_err());

/// Structs

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct UnitStruct;
assert_eq!(to_str(&UnitStruct).unwrap(), "UnitStruct");
assert_eq!(from_str::<UnitStruct>("UnitStruct").unwrap(), UnitStruct);

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct TupleStruct(u64, u64);
assert_eq!(to_str(&TupleStruct(0, 0)).unwrap(), "TupleStruct");
assert!(from_str::<TupleStruct>("TupleStruct").is_err());

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Struct {
    field: u8
}
assert_eq!(to_str(&Struct { field: 123 }).unwrap(), "Struct");
assert!(from_str::<Struct>("Struct").is_err());

致谢

此crate最初是Daniel Mueller维护的 serde_variant 的分支,Daniel Mueller的邮箱是 deso@posteo.net

依赖项

~110–350KB