summaryrefslogtreecommitdiffstats
path: root/crates/rebel-runner/src/util/cjson.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/rebel-runner/src/util/cjson.rs')
-rw-r--r--crates/rebel-runner/src/util/cjson.rs37
1 files changed, 37 insertions, 0 deletions
diff --git a/crates/rebel-runner/src/util/cjson.rs b/crates/rebel-runner/src/util/cjson.rs
new file mode 100644
index 0000000..e3840ce
--- /dev/null
+++ b/crates/rebel-runner/src/util/cjson.rs
@@ -0,0 +1,37 @@
+use std::{
+ fs::File,
+ io::{self, Write},
+ path::Path,
+};
+
+use digest::{self, Digest};
+use olpc_cjson::CanonicalFormatter;
+use serde::Serialize;
+use serde_json::error::Result;
+
+pub fn new_serializer<W: Write>(writer: W) -> serde_json::Serializer<W, CanonicalFormatter> {
+ serde_json::Serializer::with_formatter(writer, CanonicalFormatter::new())
+}
+
+pub fn to_writer<W: Write, T: ?Sized + Serialize>(writer: W, value: &T) -> Result<()> {
+ let mut ser = new_serializer(writer);
+ value.serialize(&mut ser)
+}
+
+pub fn to_file<P: AsRef<Path>, T: ?Sized + Serialize>(path: P, value: &T) -> io::Result<()> {
+ let file = File::create(path)?;
+ to_writer(&file, value)?;
+ file.sync_all()
+}
+
+pub fn to_string<T: ?Sized + Serialize>(value: &T) -> Result<String> {
+ let mut ret = Vec::new();
+ to_writer(&mut ret, value)?;
+ Ok(String::from_utf8(ret).unwrap())
+}
+
+pub fn digest<D: Digest + Write, T: ?Sized + Serialize>(value: &T) -> Result<digest::Output<D>> {
+ let mut digest = <D as Digest>::new();
+ to_writer(&mut digest, value)?;
+ Ok(digest.finalize())
+}