veilid/veilid-core/src/veilid_api/serialize_helpers.rs

43 lines
1.3 KiB
Rust
Raw Normal View History

2022-06-08 01:31:05 +00:00
use super::*;
2022-06-10 21:07:10 +00:00
use core::fmt::Debug;
2022-02-07 02:18:42 +00:00
2022-07-01 20:20:43 +00:00
// XXX: Don't trace these functions as they are used in the transfer of API logs, which will recurse!
// #[instrument(level = "trace", ret, err)]
2022-06-10 21:07:10 +00:00
pub fn deserialize_json<'a, T: de::Deserialize<'a> + Debug>(
2022-02-07 02:18:42 +00:00
arg: &'a str,
2022-06-10 21:07:10 +00:00
) -> Result<T, VeilidAPIError> {
2022-06-08 01:31:05 +00:00
serde_json::from_str(arg).map_err(|e| VeilidAPIError::ParseError {
2022-02-07 02:18:42 +00:00
message: e.to_string(),
2022-06-10 21:07:10 +00:00
value: format!(
"deserialize_json:\n---\n{}\n---\n to type {}",
arg,
std::any::type_name::<T>()
),
2022-02-07 02:18:42 +00:00
})
}
2022-07-01 20:20:43 +00:00
// #[instrument(level = "trace", ret, err)]
2022-06-10 21:07:10 +00:00
pub fn deserialize_opt_json<T: de::DeserializeOwned + Debug>(
2022-02-07 02:18:42 +00:00
arg: Option<String>,
2022-06-08 01:31:05 +00:00
) -> Result<T, VeilidAPIError> {
2022-06-10 21:07:10 +00:00
let arg = arg.as_ref().ok_or_else(|| VeilidAPIError::ParseError {
2022-06-08 01:31:05 +00:00
message: "invalid null string".to_owned(),
2022-06-10 21:07:10 +00:00
value: format!(
"deserialize_json_opt: null to type {}",
std::any::type_name::<T>()
),
2022-02-07 02:18:42 +00:00
})?;
2022-06-10 21:07:10 +00:00
deserialize_json(arg)
2022-02-07 02:18:42 +00:00
}
2022-07-01 20:20:43 +00:00
// #[instrument(level = "trace", ret)]
2022-06-10 21:07:10 +00:00
pub fn serialize_json<T: Serialize + Debug>(val: T) -> String {
match serde_json::to_string(&val) {
Ok(v) => v,
Err(e) => {
panic!("failed to serialize json value: {}\nval={:?}", e, val);
}
}
2022-02-07 02:18:42 +00:00
}