]> git.proxmox.com Git - proxmox-backup.git/commitdiff
add tools::json for canonical json generation
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Fri, 15 Jan 2021 10:06:15 +0000 (11:06 +0100)
committerThomas Lamprecht <t.lamprecht@proxmox.com>
Fri, 15 Jan 2021 14:19:52 +0000 (15:19 +0100)
moving this from backup::manifest, no functional changes

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
src/tools.rs
src/tools/json.rs [new file with mode: 0644]

index 599bbd04535cc6ad1d3855f5a3582a69fe07adba..d96cd647e08502e0668f6ef8ecec00937e56f9f6 100644 (file)
@@ -28,6 +28,7 @@ pub mod format;
 pub mod fs;
 pub mod fuse_loop;
 pub mod http;
+pub mod json;
 pub mod logrotate;
 pub mod loopdev;
 pub mod lru_cache;
diff --git a/src/tools/json.rs b/src/tools/json.rs
new file mode 100644 (file)
index 0000000..c81afcc
--- /dev/null
@@ -0,0 +1,49 @@
+use anyhow::{bail, Error};
+use serde_json::Value;
+
+// Generate canonical json
+pub fn to_canonical_json(value: &Value) -> Result<Vec<u8>, Error> {
+    let mut data = Vec::new();
+    write_canonical_json(value, &mut data)?;
+    Ok(data)
+}
+
+pub fn write_canonical_json(value: &Value, output: &mut Vec<u8>) -> Result<(), Error> {
+    match value {
+        Value::Null => bail!("got unexpected null value"),
+        Value::String(_) | Value::Number(_) | Value::Bool(_) => {
+            serde_json::to_writer(output, &value)?;
+        }
+        Value::Array(list) => {
+            output.push(b'[');
+            let mut iter = list.iter();
+            if let Some(item) = iter.next() {
+                write_canonical_json(item, output)?;
+                for item in iter {
+                    output.push(b',');
+                    write_canonical_json(item, output)?;
+                }
+            }
+            output.push(b']');
+        }
+        Value::Object(map) => {
+            output.push(b'{');
+            let mut keys: Vec<&str> = map.keys().map(String::as_str).collect();
+            keys.sort();
+            let mut iter = keys.into_iter();
+            if let Some(key) = iter.next() {
+                serde_json::to_writer(&mut *output, &key)?;
+                output.push(b':');
+                write_canonical_json(&map[key], output)?;
+                for key in iter {
+                    output.push(b',');
+                    serde_json::to_writer(&mut *output, &key)?;
+                    output.push(b':');
+                    write_canonical_json(&map[key], output)?;
+                }
+            }
+            output.push(b'}');
+        }
+    }
+    Ok(())
+}