use serde::Serialize;
use serde_json::Value;
pub fn to_hex(bytes: &[u8]) -> String {
hex::encode(bytes)
}
pub fn from_hex(s: &str) -> Result<Vec<u8>, String> {
hex::decode(s.trim()).map_err(|e| e.to_string())
}
pub fn to_base58(bytes: &[u8]) -> String {
bs58::encode(bytes).into_string()
}
pub fn from_base58(s: &str) -> Result<Vec<u8>, String> {
bs58::decode(s).into_vec().map_err(|e| e.to_string())
}
pub fn canonical_json<T: Serialize>(value: &T) -> Result<String, String> {
let raw = serde_json::to_value(value).map_err(|e| e.to_string())?;
let sorted = sort_json_value(&raw);
serde_json::to_string(&sorted).map_err(|e| e.to_string())
}
pub fn sort_json_value(v: &Value) -> Value {
match v {
Value::Object(map) => {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
let mut sorted_map = serde_json::Map::new();
for k in keys {
if let Some(val) = map.get(&k) {
sorted_map.insert(k, sort_json_value(val));
}
}
Value::Object(sorted_map)
}
Value::Array(arr) => Value::Array(arr.iter().map(sort_json_value).collect()),
other => other.clone(),
}
}
pub fn canonical_yaml<T: Serialize>(value: &T) -> Result<String, String> {
serde_yaml::to_string(value).map_err(|e| e.to_string())
}
#[cfg(test)]
pub fn canonical_parity_corpus() -> Vec<serde_json::Value> {
use serde_json::json;
vec![json!(null), json!(true), json!(0), json!(-17), json!(1.5), json!(1e10), json!("plain"),
json!("quote \" and backslash \\"), json!("unicode: héllo 世界"), json!([]), json!({}),
json!({"b": 1, "a": 2}), json!({"z": [1, {"y": 2, "x": 3}], "a": "s"}),
json!({"n": null, "arr": [null, 1]}), json!({"nested": {"deep": {"deeper": [true, false]}}}),
json!([[[[]]]]), json!({"empty_obj": {}, "empty_arr": []})]
}