|
| 1 | +//! Catalyst Signed Document `section` field type defition. |
| 2 | +
|
| 3 | +use std::{fmt::Display, str::FromStr}; |
| 4 | + |
| 5 | +use coset::cbor::Value; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | + |
| 8 | +/// 'section' field type defition, which is a JSON path string |
| 9 | +#[derive(Clone, Debug, PartialEq)] |
| 10 | +pub struct Section(jsonpath_rust::JsonPath<serde_json::Value>); |
| 11 | + |
| 12 | +impl Display for Section { |
| 13 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 14 | + self.0.fmt(f) |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +impl Serialize for Section { |
| 19 | + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 20 | + where S: serde::Serializer { |
| 21 | + self.to_string().serialize(serializer) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +impl<'de> Deserialize<'de> for Section { |
| 26 | + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 27 | + where D: serde::Deserializer<'de> { |
| 28 | + let str = String::deserialize(deserializer)?; |
| 29 | + Ok(Self::from_str(&str).map_err(|e| serde::de::Error::custom(e))?) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +impl FromStr for Section { |
| 34 | + type Err = anyhow::Error; |
| 35 | + |
| 36 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 37 | + Ok(Self( |
| 38 | + jsonpath_rust::JsonPath::<serde_json::Value>::from_str(&s)?, |
| 39 | + )) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl From<Section> for Value { |
| 44 | + fn from(value: Section) -> Self { |
| 45 | + Value::Text(value.to_string()) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl TryFrom<&Value> for Section { |
| 50 | + type Error = anyhow::Error; |
| 51 | + |
| 52 | + fn try_from(val: &Value) -> anyhow::Result<Self> { |
| 53 | + let str = val |
| 54 | + .as_text() |
| 55 | + .ok_or(anyhow::anyhow!("Not a cbor string type"))?; |
| 56 | + Ok(Self::from_str(str)?) |
| 57 | + } |
| 58 | +} |
0 commit comments