2021-11-24 17:56:37 +01:00
|
|
|
// Copyright 2021 System76 <info@system76.com>
|
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
2021-08-30 18:28:50 +02:00
|
|
|
|
2022-03-27 17:38:37 +02:00
|
|
|
use futures::{Stream, StreamExt};
|
2021-08-10 01:04:20 +02:00
|
|
|
use serde::Deserialize;
|
2022-03-27 17:38:37 +02:00
|
|
|
use tokio::io::{AsyncBufReadExt, AsyncRead};
|
2021-08-10 01:04:20 +02:00
|
|
|
|
|
|
|
|
/// stdin with AsyncRead support
|
2022-03-27 17:38:37 +02:00
|
|
|
pub fn async_stdin() -> tokio::io::Stdin {
|
|
|
|
|
tokio::io::stdin()
|
2021-08-10 01:04:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// stdout with AsyncWrite support
|
2022-03-27 17:38:37 +02:00
|
|
|
pub fn async_stdout() -> tokio::io::Stdout {
|
|
|
|
|
tokio::io::stdout()
|
2021-08-10 01:04:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Creates a stream that parses JSON input line-by-line
|
|
|
|
|
pub fn json_input_stream<I, S>(input: I) -> impl Stream<Item = serde_json::Result<S>> + Unpin + Send
|
|
|
|
|
where
|
|
|
|
|
I: AsyncRead + Unpin + Send,
|
|
|
|
|
S: for<'a> Deserialize<'a>,
|
|
|
|
|
{
|
2022-03-27 17:38:37 +02:00
|
|
|
let line_reader = tokio::io::BufReader::new(input).lines();
|
|
|
|
|
tokio_stream::wrappers::LinesStream::new(line_reader)
|
2022-03-27 16:54:26 +02:00
|
|
|
.take_while(|x| futures::future::ready(x.is_ok()))
|
2021-08-10 01:04:20 +02:00
|
|
|
.map(Result::unwrap)
|
|
|
|
|
.map(|line| serde_json::from_str::<S>(&line))
|
|
|
|
|
}
|