13个版本 (3个稳定版)
| 2.0.0 | 2024年5月7日 |
|---|---|
| 1.1.3 | 2024年5月7日 |
| 1.0.0-rc1 | 2022年4月15日 |
| 0.3.8 | 2022年1月27日 |
| 0.1.0 |
|
#342 在 编码
每月33次下载
在 2 crates 中使用
75KB
1.5K SLoC
Simple Serde
Simple serde正如其名,是对多个序列化和反序列化存储库的简化实现。
简而言之,目标是拥有一个用于序列化和反序列化的单一工具,具有通用接口。
用法
Simple Serde使用 .encode 和 .decode 进行编码和解码。解码可以应用于任何 Vec<u8> 或 &[u8],这使得实现最为简洁。对于任何需要序列化/编码的内容也是如此。任何实现了 #[derive(Serialize)] 的类型都可以轻松使用 .encode 进行编码
编码/解码
.encode 和 .decode 都接受一个 ContentType,它定义了你要编码/解码的内容。例如,可以是 [some Vec<u8>].decode("bson") 或 my_struct.encode("bson")。这是可能的,因为 ContentType 为 &str 和 String 实现了 TryFrom 特性。如果实现无法从您尝试编码/解码的类型中解码,编码器/解码器将返回包含 Error::UnknownContentTypeMatchFromStr 的 Err 结果
编码器输出的内容类型将为 Vec<u8> 类型,进一步地,这个 Vec<u8> 被一个名为 Encoded 的结构体包装,这使得实现进一步简化,例如,TryToString 将自动尝试将 Encoded 转换为 String,此外,Encoded 实现了 Deref 和 DerefMut 特性,使得获取封装数据更加容易。
支持的格式
- Bson
- Cbor
- FlexBuffers
- Json
- Json5
- Lexpr
- MessagePack
- Pickle
- Postcard
- Ron
- Toml
- Url
- Yaml
- Xml (等待 serde-xml-rs v. >0.51)
所有 ContentType 的字符串定义均不区分大小写,并且有备选的
application/[格式]application/x-[格式]
序列化/编码示例
use std::ops::Deref;
use serde::Serialize;
#[macro_use]
use serde_derive;
use simple_serde::{Encoded, SimpleEncoder, TryToString};
#[derive(Serialize)]
struct Foo {
bar: String,
}
let my_foo = Foo {
bar: "foobar".to_string(),
};
let encoded: Encoded = my_foo
.encode("yaml")
.expect("Should have been encoded in yaml");
assert_eq!(
&vec![45, 45, 45, 10, 98, 97, 114, 58, 32, 102, 111, 111, 98, 97, 114, 10],
encoded.deref()
);
assert_eq!(r#"---
bar: foobar
"#, encoded.try_to_string().unwrap())
反序列化/解码示例
use std::ops::Deref;
use serde::Deserialize;
#[macro_use]
use serde_derive;
use simple_serde::{Decoded, SimpleDecoder};
#[derive(Deserialize, Debug, PartialEq)]
struct Foo {
bar: String,
}
let my_foo = Foo {
bar: "foobar".to_string(),
};
let v_u8_data = &vec![45, 45, 45, 10, 98, 97, 114, 58, 32, 102, 111, 111, 98, 97, 114, 10];
let string_data = r#"---
bar: foobar
"#;
let decoded_from_v_u8: Decoded<Foo> = v_u8_data.decode("yaml").expect("Should have decoded the Vec<u8>");
let decoded_from_string: Decoded<Foo> = string_data.decode("yaml").expect("Should have decoded the String");
assert_eq!(
Foo{bar: "foobar".to_string()},
decoded_from_v_u8.into()
);
assert_eq!(
Foo{bar: "foobar".to_string()},
decoded_from_string.into()
);
贡献
欢迎任何合并请求!
许可
MIT
依赖
~8–19MB
~288K SLoC