Skip to main content

AsyncWriteJsonLines

Trait AsyncWriteJsonLines 

Source
pub trait AsyncWriteJsonLines: AsyncWrite {
    // Provided method
    fn into_json_lines_sink<T>(self) -> JsonLinesSink<Self, T>
       where Self: Sized { ... }
}
Available on crate feature async only.
Expand description

An extension trait for the tokio::io::AsyncWrite trait that adds an into_json_lines_sink() method

§Example

use futures_util::SinkExt;
use serde::Serialize;
use serde_jsonlines::AsyncWriteJsonLines;
use tokio::fs::{read_to_string, File};

#[derive(Serialize)]
pub struct Structure {
    pub name: String,
    pub size: i32,
    pub on: bool,
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    {
        let fp = File::create("example.jsonl").await?;
        let mut sink = fp.into_json_lines_sink();
        sink.send(Structure {
            name: "Foo Bar".into(),
            size: 42,
            on: true,
        })
        .await?;
        sink.send(Structure {
            name: "Quux".into(),
            size: 23,
            on: false,
        })
        .await?;
        sink.send(Structure {
            name: "Gnusto Cleesh".into(),
            size: 17,
            on: true,
        })
        .await?;
        sink.close().await?;
    }
    assert_eq!(
        read_to_string("example.jsonl").await?,
        concat!(
            "{\"name\":\"Foo Bar\",\"size\":42,\"on\":true}\n",
            "{\"name\":\"Quux\",\"size\":23,\"on\":false}\n",
            "{\"name\":\"Gnusto Cleesh\",\"size\":17,\"on\":true}\n",
        )
    );
    Ok(())
}

Provided Methods§

Source

fn into_json_lines_sink<T>(self) -> JsonLinesSink<Self, T>
where Self: Sized,

Consume the writer and return an asynchronous sink for serializing values as JSON and writing them to the writer.

The returned sink consumes T values and has an Error type of std::io::Error. Each call to send() has the same error conditions as AsyncJsonLinesWriter::write().

Note that all values sent to the sink must be of the same type.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§