use serde_json::{Map, Value, json};
use super::{Capture, capture_of, capture_value};
use crate::boundary::codec::fields::{opt_val, str_of, u64_of};
pub const PARTIAL: &str = "partial";
pub const SINCE: &str = "since";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Piece {
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Offsets {
pub stdout: u64,
pub stderr: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Post {
Partial(Piece),
Capture(Capture),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Standing {
pub partial: Option<Piece>,
pub capture: Option<Capture>,
}
pub fn piece_value(piece: &Piece) -> Value {
json!({ "stdout": piece.stdout, "stderr": piece.stderr })
}
pub fn piece_of(v: &Value) -> Result<Piece, String> {
let o = v.as_object().ok_or("partial: not a JSON object")?;
Ok(Piece {
stdout: str_of(o, "stdout")?,
stderr: str_of(o, "stderr")?,
})
}
pub fn offsets_value(since: Offsets) -> Value {
json!({ "stdout": since.stdout, "stderr": since.stderr })
}
pub fn offsets_of(v: &Value) -> Result<Offsets, String> {
let o = v.as_object().ok_or("since: not a JSON object")?;
Ok(Offsets {
stdout: u64_of(o, "stdout")?,
stderr: u64_of(o, "stderr")?,
})
}
pub fn post_into(map: &mut Map<String, Value>, post: &Post) {
let (key, value) = match post {
Post::Partial(piece) => (PARTIAL, piece_value(piece)),
Post::Capture(capture) => ("capture", capture_value(capture)),
};
map.insert(key.to_owned(), value);
}
pub fn post_of(o: &Map<String, Value>) -> Result<Post, String> {
match (o.get("capture"), o.get(PARTIAL)) {
(Some(capture), _) => capture_of(capture).map(Post::Capture),
(None, Some(partial)) => piece_of(partial).map(Post::Partial),
(None, None) => Err("complete: missing capture".to_owned()),
}
}
pub fn standing_into(map: &mut Map<String, Value>, standing: &Standing) {
if let Some(piece) = &standing.partial {
map.insert(PARTIAL.to_owned(), piece_value(piece));
}
if let Some(capture) = &standing.capture {
map.insert("capture".to_owned(), capture_value(capture));
}
}
pub fn standing_of(o: &Map<String, Value>) -> Result<Standing, String> {
Ok(Standing {
partial: opt_val(o, PARTIAL, piece_of)?,
capture: opt_val(o, "capture", capture_of)?,
})
}
pub fn since_into(map: &mut Map<String, Value>, since: Option<Offsets>) {
if let Some(since) = since {
map.insert(SINCE.to_owned(), offsets_value(since));
}
}
pub fn since_of(o: &Map<String, Value>) -> Result<Option<Offsets>, String> {
opt_val(o, SINCE, offsets_of)
}