1use crate::ast::Aggregate;
4use crate::decode::{self, JsonCodable, Reader, Result};
5use crate::json::{Object, Value};
6use crate::strings;
7
8#[derive(Clone, Debug, PartialEq, Default)]
9pub struct Format {
10 pub singular: bool,
11 pub relationships: Vec<(String, Format)>,
13 pub aggregate: Option<Aggregate>,
16}
17
18impl Format {
19 pub fn set_relationship(&mut self, name: &str, format: Format) {
22 match self
23 .relationships
24 .binary_search_by(|(k, _)| strings::utf16(k, name))
25 {
26 Ok(i) => self.relationships[i].1 = format,
27 Err(i) => self.relationships.insert(i, (name.to_owned(), format)),
28 }
29 }
30}
31
32impl JsonCodable for Format {
33 fn from_json(v: &Value) -> Result<Self> {
34 let r = Reader::new(v, "object")?;
35 let mut relationships = r
36 .optional("relationships", |v| decode::record(v, Format::from_json))?
37 .unwrap_or_default();
38 relationships.sort_by(|a, b| strings::utf16(&a.0, &b.0));
39 Ok(Format {
40 singular: r.optional_bool("singular")?.unwrap_or(false),
41 relationships,
42 aggregate: r.optional("aggregate", Aggregate::from_json)?,
43 })
44 }
45
46 fn to_json(&self) -> Value {
47 let rels: Object = self
48 .relationships
49 .iter()
50 .map(|(k, f)| (k.clone(), f.to_json()))
51 .collect();
52 let mut o = Object::new();
53 o.insert("singular", Value::Bool(self.singular));
54 o.insert("relationships", Value::Object(rels));
55 if let Some(a) = &self.aggregate {
56 o.insert("aggregate", a.to_json());
57 }
58 Value::Object(o)
59 }
60}