quanttide_work/
outcome.rs1use serde_json::{Value as Json, json};
9
10#[derive(Debug, Clone, Default, PartialEq)]
12pub struct Outcome {
13 pub ok: bool,
14 pub lines: Vec<String>,
16 pub columns: Vec<String>,
18 pub rows: Vec<Vec<String>>,
19 pub data: Option<Json>,
21}
22
23impl Outcome {
24 pub fn new(ok: bool) -> Self {
25 Outcome {
26 ok,
27 ..Default::default()
28 }
29 }
30
31 pub fn lines(ok: bool, lines: Vec<String>) -> Self {
33 Outcome {
34 ok,
35 lines,
36 ..Default::default()
37 }
38 }
39
40 pub fn with_first(mut self, line: String) -> Self {
42 self.lines.insert(0, line);
43 self
44 }
45
46 pub fn with_data(mut self, data: Json) -> Self {
48 self.data = Some(data);
49 self
50 }
51
52 pub fn to_json(&self) -> Json {
54 let mut envelope = serde_json::Map::new();
55 envelope.insert("ok".to_string(), json!(self.ok));
56 envelope.insert("lines".to_string(), json!(self.lines));
57 envelope.insert("columns".to_string(), json!(self.columns));
58 envelope.insert("rows".to_string(), json!(self.rows));
59 if let Some(data) = &self.data {
60 envelope.insert("data".to_string(), data.clone());
61 }
62 Json::Object(envelope)
63 }
64
65 pub fn data_json(&self) -> Json {
67 match &self.data {
68 Some(data) => data.clone(),
69 None => self.to_json(),
70 }
71 }
72
73 pub fn from_json(value: &Json) -> Self {
75 Outcome {
76 ok: value.get("ok").and_then(Json::as_bool).unwrap_or(false),
77 lines: strings(value.get("lines")),
78 columns: strings(value.get("columns")),
79 rows: value
80 .get("rows")
81 .and_then(Json::as_array)
82 .map(|rows| rows.iter().map(|row| strings(Some(row))).collect())
83 .unwrap_or_default(),
84 data: value.get("data").cloned(),
85 }
86 }
87}
88
89fn strings(value: Option<&Json>) -> Vec<String> {
91 value
92 .and_then(Json::as_array)
93 .map(|items| {
94 items
95 .iter()
96 .map(|item| match item {
97 Json::String(text) => text.clone(),
98 other => other.to_string(),
99 })
100 .collect()
101 })
102 .unwrap_or_default()
103}