8 个版本
0.3.1 | 2021 年 6 月 11 日 |
---|---|
0.3.0 | 2021 年 2 月 18 日 |
0.2.0 | 2019 年 12 月 28 日 |
0.1.5 | 2019 年 11 月 16 日 |
0.1.2 | 2019 年 8 月 15 日 |
#5 in #framing
每月 32 次下载
23KB
363 行
futures_cbor_codec
将 futures 库中的 AsyncRead/AsyncWrite 封装成 serde-cbor 的编解码器
这个 Rust 包将 serde-cbor
集成到 future-codec
的编解码器(Decoder
和 Encoder
)中。这使得可以将 AsyncRead/AsyncWrite 转换为实现了 serde Serialize/Deserialize 的 Rust 对象的流和接收器。
这是一个从 tokio-serde-cbor 分支出来的版本。经过测试,这个版本对 futures-codec 也是适用的。所有这个功能应该归功于 @vorner。
目录
安装
使用 cargo add: cargo add futures_cbor_codec
使用 cargo yaml
dependencies:
futures_cbor_codec: ^0.2
使用原始 Cargo.toml
[dependencies]
futures_cbor_codec = "0.2"
升级
升级时请查看 变更日志。
依赖
这个包的依赖项很少。Cargo 将自动为您处理其依赖项。
没有可选功能。
使用
此包提供了一种编解码器,用于将信息封装为 CBOR 编码的消息。它允许编码和解码任意 serde 准备的类型。它可以通过将编解码器插入连接的 framed
方法来使用,以获取所需项的流和接收器。
编码和解码的项是独立的(您可能希望编码引用并解码所有者数据,或者协议可能是不对称的)。如果您只需要一个方向,可以使用 Decoder
或 Encoder
。如果您需要两个方向,最好使用 Codec
。
请注意,如果 CBOR 本身定义了帧,这非常有用。如果消息以某种方式(例如长度前缀编码)分隔,而 CBOR 仅作为有效负载,则应使用其他封装的编解码器,并在接收到的流和接收器上使用 .map
转换消息。
请查看仓库中的示例目录。
此crate支持WASM。
基本示例
#![feature(async_await)]
use
{
futures_ringbuf :: { * } ,
futures :: { SinkExt, StreamExt, executor::block_on } ,
asynchronous_codec :: { Framed } ,
futures_cbor_codec :: { Codec } ,
std :: { collections::HashMap } ,
};
// We create some test data to serialize. This works because Serde implements
// Serialize and Deserialize for HashMap, so the codec can frame this type.
//
type TestData = HashMap<String, usize>;
/// Something to test with. It doesn't really matter what it is.
//
fn test_data() -> TestData
{
let mut data = HashMap::new();
data.insert( "hello".to_string(), 42 );
data.insert( "world".to_string(), 0 );
data
}
// In a real life scenario the sending and receiving end usually are in different processes.
// We could simulate that somewhat by putting them in separate async blocks and spawning those,
// but since we only send in one direction, I chose to keep it simple.
//
// Obviously in production code you should do some real error handling rather than using
// `expect`. However for this example, almost any error would fatal, so we might as well.
//
fn main()
{
let program = async
{
let mock = RingBuffer::new(32);
// Type annotations are needed unfortunately.
//
let (mut writer, mut reader) = Framed::new( mock , Codec::<TestData, TestData>::new() ).split();
writer.send( test_data() ).await.expect( "send message1" );
writer.send( test_data() ).await.expect( "send message2" );
writer.close().await.expect( "close sender" );
while let Some(msg) = reader.next().await.transpose().expect( "receive message" )
{
println!( "Received: {:#?}", msg );
}
};
block_on( program );
}
API
API文档可以在docs.rs上找到。
贡献
请查阅贡献指南。
测试
cargotest
在wasm上,安装wasm-pack之后
wasm-pack test--firefox--无头
或
wasm-pack test--chrome--无头
行为准则
任何在公民行为准则第4点“不可接受的行为”中描述的行为都不受欢迎,可能会被禁止。如果任何人都未能尊重这些/您的限制,包括项目的维护者和管理员,您有权指出。
许可证
以下任一许可证下授权
- Apache License,版本2.0,LICENSE-APACHE
- MIT许可证LICENSE-MIT,任选其一。
依赖
~1.4–2MB
~39K SLoC