2 个版本

0.1.1 2023 年 5 月 3 日
0.1.0 2023 年 5 月 3 日

#2163编码

Download history 109/week @ 2024-03-11 77/week @ 2024-03-18 40/week @ 2024-03-25 73/week @ 2024-04-01 38/week @ 2024-04-08 37/week @ 2024-04-15 29/week @ 2024-04-22 65/week @ 2024-04-29 30/week @ 2024-05-06 28/week @ 2024-05-13 30/week @ 2024-05-20 57/week @ 2024-05-27 344/week @ 2024-06-03 348/week @ 2024-06-10 70/week @ 2024-06-17 188/week @ 2024-06-24

953 每月下载量
3 个包中使用 (通过 value-bag-serde1)

Apache-2.0 OR MIT

59KB
1.5K SLoC

serde_buf

rust Latest version Documentation Latest

类似于 serde_json::Value,但不可见、可借用且格式无关。

请参阅文档获取更多详细信息。


lib.rs:

serde 提供泛型缓冲。

该库提供 OwnedRef 类型作为格式无关的 serde 缓冲区。缓冲区将保证以与原始来源完全相同的方式序列化。

获取拥有的缓冲区

任何实现了 serde::Serialize 的类型都可以缓冲到一个 Owned 缓冲区

use serde_buf::Owned;

// Imagine we have some owned resource...
thread_local! {
static SOME_THREAD_STATIC: RefCell<Option<Owned>> = RefCell::new(None);
}

// ...and some short-lived data
let short_lived: &'_ str = "A string";

// We can create an owned buffer from it...
let buffer = Owned::buffer(short_lived)?;

// ...and stash it in our owned resource
SOME_THREAD_STATIC.with(|ts| *ts.borrow_mut() = Some(buffer));

获取借用的缓冲区

借用的 Ref 缓冲区可能内部借用了字符串,这使得它们与 serde::Serialize 不兼容。您可以从任何底层源手动构建 [Ref]

use serde_buf::Ref;

// Imagine we have some borrowed datatype
struct MyData<'a> {
id: u64,
content: &'a str,
}

// We can buffer it into a partially owned buffer manually
fn buffer_my_data<'a>(data: &'_ MyData<'a>) -> Ref<'a> {
Ref::record_struct("MyData", [
("id", Ref::u64(data.id)),
("content", Ref::str(data.content)),
])
}

序列化缓冲区

一旦您有了 OwnedRef 缓冲区,您就可以使用它们自己的 serde::Serialize 实现来以某种格式进行编码

#[derive(Serialize)]
struct MyData<'a> {
id: u64,
content: &'a str,
}

let data = MyData {
id: 42,
content: "Some content",
};

let buffer = Owned::buffer(&data)?;

let data_json = serde_json::to_string(&data)?;
let buffer_json = serde_json::to_string(&buffer)?;

assert_eq!(data_json, buffer_json);

从缓冲区反序列化

值也可以通过它们的 serde::de::IntoDeserializer 实现将直接从 OwnedRef 缓冲区反序列化

#[derive(Deserialize, Debug, PartialEq)]
struct MyData<'a> {
id: u64,
content: &'a str,
}

let data = MyData {
id: 42,
content: "Some content",
};

let buffer: Ref = buffer_my_data(&data);

let deserialized = MyData::deserialize(buffer.into_deserializer())?;

assert_eq!(data, deserialized);

直接到缓冲区的反序列化

类型 [Ref] 和 Owned 未实现 serde::Deserialize,因此不能直接反序列化。这是因为 serde 依赖于目标类型的提示来了解如何解释枚举变体。如果类型实现了 serde::Serializeserde::Deserialize,则可以先反序列化为该具体类型,然后再缓冲它

#[derive(Serialize, Deserialize)]
enum MyData<'a> {
Short(&'a str),
Full { id: u64, content: &'a str },
}

let json = data_json();

let buffer = Owned::buffer(&serde_json::from_str::<MyData>(&json)?)?;

依赖项

~110–355KB