2个版本
0.1.1 | 2023年6月19日 |
---|---|
0.1.0 | 2023年6月17日 |
#2139 in 解析器实现
每月35次下载
用于 asimov
12KB
108 行
json-stream
一个从字节流中解析换行分隔JSON值的库。
这个crate的驱动用例是从Axum的BodyStream中解析换行分隔的JSON值,但也适用于任何Stream<Item = Result<B, E>>
,其中B: Deref<Target = [u8]>
。
内存使用
JsonStream
被设计成最小化内存使用,以便能够处理任何大小的流。当JSON值被反序列化时,字节将从底层缓冲区中删除。这是为了为读取的下一个字节块腾出空间。
示例
use json_stream::JsonStream;
use futures::stream::once;
use futures::StreamExt;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Foo {
bar: String,
}
#[tokio::main]
async fn main() {
// This could be any stream that yields bytes, such as a file stream or a network stream.
let pinned_bytes_future = Box::pin(async {
Ok::<_, std::io::Error>(r#"{"bar": "foo"}\n{"bar": "qux"}\n{"bar": "baz"}"#.as_bytes())
});
let mut json_stream = JsonStream::<Foo, _>::new(once(pinned_bytes_future));
while let Some(Ok(foo)) = json_stream.next().await {
println!("{:?}", foo);
}
}
依赖项
~1.7–2.9MB
~55K SLoC