Skip to main content

provenant/output_schema/
serde_helpers.rs

1// SPDX-FileCopyrightText: Provenant contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use serde::ser::Error as SerError;
5use serde::{Serialize, Serializer};
6use serde_json::{Map, Value};
7use std::collections::HashMap;
8
9pub fn serialize_optional_map_as_object<S, T>(
10    value: &Option<HashMap<String, T>>,
11    serializer: S,
12) -> Result<S::Ok, S::Error>
13where
14    S: Serializer,
15    T: Serialize,
16{
17    match value {
18        Some(map) => map.serialize(serializer),
19        None => HashMap::<String, T>::new().serialize(serializer),
20    }
21}
22
23pub fn is_false(value: &bool) -> bool {
24    !value
25}
26
27pub fn insert_json<S, E>(map: &mut Map<String, Value>, key: &str, value: S) -> Result<(), E>
28where
29    S: Serialize,
30    E: SerError,
31{
32    map.insert(
33        key.to_string(),
34        serde_json::to_value(value).map_err(E::custom)?,
35    );
36    Ok(())
37}