pop_launcher/
codec.rs

1// Copyright 2021 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4use futures::{Stream, StreamExt};
5use serde::Deserialize;
6use tokio::io::{AsyncBufReadExt, AsyncRead};
7
8/// stdin with [`AsyncWrite`] support
9#[must_use]
10#[inline]
11pub fn async_stdin() -> tokio::io::Stdin {
12    tokio::io::stdin()
13}
14
15/// stdout with [`AsyncWrite`] support
16#[must_use]
17#[inline]
18pub fn async_stdout() -> tokio::io::Stdout {
19    tokio::io::stdout()
20}
21
22/// Creates a stream that parses JSON input line-by-line
23pub fn json_input_stream<I, S>(input: I) -> impl Stream<Item = serde_json::Result<S>> + Unpin + Send
24where
25    I: AsyncRead + Unpin + Send,
26    S: for<'a> Deserialize<'a>,
27{
28    let line_reader = tokio::io::BufReader::new(input).lines();
29    tokio_stream::wrappers::LinesStream::new(line_reader)
30        .take_while(|x| futures::future::ready(x.is_ok()))
31        .map(Result::unwrap)
32        .map(|line| serde_json::from_str::<S>(&line))
33}