shex_ast/ast/serde_string_or_struct.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
//! Tools for working with fields that might contain a string, or might
//! contain a struct.
//! This code is based on: <https://github.com/emk/compose_yml/blob/7e8e0f47dcc41cf08e15fe082ef4c40b5f0475eb/src/v2/string_or_struct.rs>
use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, SeqAccess};
use serde::ser::{Serialize, Serializer};
use std::fmt::{self, Display};
use std::marker::PhantomData;
use std::str::FromStr;
/// Handle a value which may either a struct that deserializes as type `T`,
/// or a bare string that can be turned into a type `T` using
/// `FromStr::from_str`. We do this in a clever way that allows us to be
/// generic over multiple such types, and which allows us to use the
/// structure deserialization code automatically generated by serde.
///
/// An earlier and much uglier version of this parser was the inspiration
/// for [this official `serde`
/// example](https://serde.rs/string-or-struct.html), which in turn forms
/// the basis of this code.
pub fn deserialize_string_or_struct<'de, T, D>(d: D) -> Result<T, D::Error>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
D: Deserializer<'de>,
{
/// Declare an internal visitor type to handle our input.
struct StringOrStruct<T>(PhantomData<T>);
impl<'de, T> de::Visitor<'de> for StringOrStruct<T>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
{
type Value = T;
fn visit_str<E>(self, value: &str) -> Result<T, E>
where
E: de::Error,
{
FromStr::from_str(value).map_err(|err| {
// Just convert the underlying error type into a string and
// pass it to serde as a custom error.
de::Error::custom(format!("{}", err))
})
}
fn visit_map<M>(self, visitor: M) -> Result<T, M::Error>
where
M: de::MapAccess<'de>,
{
let mvd = de::value::MapAccessDeserializer::new(visitor);
Deserialize::deserialize(mvd)
}
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a string or a map")
}
}
d.deserialize_any(StringOrStruct(PhantomData))
}
/// Like `string_or_struct`, but it also handles the case where the
/// value is optional.
///
/// We could probably make this more generic, supporting underlying
/// functions other than `string_or_struct`, but that's a project for
/// another day.
pub fn deserialize_opt_string_or_struct<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
D: Deserializer<'de>,
{
/// Declare an internal visitor type to handle our input.
struct OptStringOrStruct<T>(PhantomData<T>);
impl<'de, T> de::Visitor<'de> for OptStringOrStruct<T>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
{
type Value = Option<T>;
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserialize_string_or_struct(deserializer).map(Some)
}
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a null, a string or a map")
}
}
d.deserialize_option(OptStringOrStruct(PhantomData))
}
/// Some structs can be serialized as a string,
/// but only under certain circumstances.
pub trait SerializeStringOrStruct: Serialize {
/// Serialize either a string representation of this struct, or a full
/// struct if the object cannot be represented as a string.
fn serialize_string_or_struct<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer;
}
/// Serialize the specified value as a string if we can, and a struct
/// otherwise.
pub fn serialize_string_or_struct<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
T: SerializeStringOrStruct,
S: Serializer,
{
value.serialize_string_or_struct(serializer)
}
/// Like `serialize_string_or_struct`, but can also handle missing values.
pub fn serialize_opt_string_or_struct<T, S>(
value: &Option<T>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
T: SerializeStringOrStruct,
S: Serializer,
{
/// A fun little trick: We need to pass `value` to `serialize_some`,
/// but we don't want `serialize_some` to call the normal `serialize`
/// method on it.
/// So we define a local wrapper type that overrides the
/// serialization. This is one of the more subtle tricks of generic
/// programming in Rust: using a "newtype" wrapper struct to override
/// how a trait is applied to a class.
struct Wrap<'a, T>(&'a T)
where
T: SerializeStringOrStruct;
impl<'a, T> Serialize for Wrap<'a, T>
where
T: 'a + SerializeStringOrStruct,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
Wrap(v) => serialize_string_or_struct(v, serializer),
}
}
}
match *value {
None => serializer.serialize_none(),
Some(ref v) => serializer.serialize_some(&Wrap(v)),
}
}
pub fn deserialize_opt_box_string_or_struct<'de, T, D>(d: D) -> Result<Option<Box<T>>, D::Error>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
D: Deserializer<'de>,
{
/// Declare an internal visitor type to handle our input.
struct OptBoxStringOrStruct<T>(PhantomData<T>);
impl<'de, T> de::Visitor<'de> for OptBoxStringOrStruct<T>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
{
type Value = Option<Box<T>>;
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserialize_string_or_struct(deserializer).map(|e| Some(Box::new(e)))
}
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a null, a string or a map")
}
}
d.deserialize_option(OptBoxStringOrStruct(PhantomData))
}
/// Like `serialize_string_or_struct`, but can also handle missing values.
pub fn serialize_opt_box_string_or_struct<T, S>(
value: &Option<Box<T>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
T: SerializeStringOrStruct,
S: Serializer,
{
/// A fun little trick: We need to pass `value` to `serialize_some`,
/// but we don't want `serialize_some` to call the normal `serialize`
/// method on it.
/// So we define a local wrapper type that overrides the
/// serialization. This is one of the more subtle tricks of generic
/// programming in Rust: using a "newtype" wrapper struct to override
/// how a trait is applied to a class.
struct Wrap<'a, T>(&'a T)
where
T: SerializeStringOrStruct;
impl<'a, T> Serialize for Wrap<'a, T>
where
T: 'a + SerializeStringOrStruct,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
Wrap(v) => serialize_string_or_struct(v, serializer),
}
}
}
match *value {
None => serializer.serialize_none(),
Some(ref v) => serializer.serialize_some(&Wrap(v.as_ref())),
}
}
#[derive(Debug, Clone)]
pub struct SeqAccessError;
// This is just an unfinished attempt...
#[allow(dead_code)]
pub fn deserialize_vec_box_string_or_struct<'de, T, D>(d: D) -> Result<Vec<Box<T>>, D::Error>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
D: Deserializer<'de>,
{
/// Declare an internal visitor type to handle our input.
struct VecBoxStringOrStruct<T>(PhantomData<T>);
struct SeqAccessStringOrStruct<T>(PhantomData<T>);
impl<'de, T> de::SeqAccess<'de> for SeqAccessStringOrStruct<T>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
{
type Error = serde_json::Error;
fn next_element_seed<A>(
&mut self,
_v: A,
) -> Result<Option<<A as DeserializeSeed<'de>>::Value>, <Self as SeqAccess<'de>>::Error>
where
A: DeserializeSeed<'de>,
{
todo!()
}
}
impl<'de, T> de::Visitor<'de> for VecBoxStringOrStruct<T>
where
T: Deserialize<'de> + FromStr,
<T as FromStr>::Err: Display,
{
type Value = Vec<Box<T>>;
fn visit_seq<A>(self, mut visitor: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut values = Vec::new();
while let Some(value) = visitor.next_element()? {
values.push(value);
}
Ok(values)
}
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "an array of values")
}
}
d.deserialize_seq(VecBoxStringOrStruct(PhantomData))
}
/// Like `serialize_string_or_struct`, but can also handle missing values.
#[allow(dead_code)]
pub fn serialize_vec_box_string_or_struct<T, S>(
_value: &[Box<T>],
serializer: S,
) -> Result<S::Ok, S::Error>
where
T: SerializeStringOrStruct,
S: Serializer,
{
/// A fun little trick: We need to pass `value` to `serialize_some`,
/// but we don't want `serialize_some` to call the normal `serialize`
/// method on it.
/// So we define a local wrapper type that overrides the
/// serialization. This is one of the more subtle tricks of generic
/// programming in Rust: using a "newtype" wrapper struct to override
/// how a trait is applied to a class.
struct Wrap<'a, T>(&'a T)
where
T: SerializeStringOrStruct;
impl<'a, T> Serialize for Wrap<'a, T>
where
T: 'a + SerializeStringOrStruct,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
Wrap(v) => serialize_string_or_struct(v, serializer),
}
}
}
/* match *value {
None => serializer.serialize_none(),
Some(ref v) => serializer.serialize_some(&Wrap(v.as_ref())),
}*/
serializer.serialize_none()
}