|
| 1 | +use serde::de::Visitor; |
| 2 | +use serde::Deserializer; |
| 3 | +use std::fmt::Formatter; |
| 4 | +use std::marker::PhantomData; |
| 5 | + |
| 6 | +// phantom data ise required to allow parametrizing on `T` without actual `T` data |
| 7 | +struct VectorVisitor<T: From<String>>(PhantomData<T>); |
| 8 | + |
| 9 | +impl<T: From<String>> VectorVisitor<T> { |
| 10 | + fn new() -> Self { |
| 11 | + VectorVisitor(PhantomData) |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +impl<'de, T: From<String>> Visitor<'de> for VectorVisitor<T> { |
| 16 | + type Value = Vec<T>; |
| 17 | + |
| 18 | + fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { |
| 19 | + formatter.write_str("either a sequence, or a comma or newline separated string") |
| 20 | + } |
| 21 | + |
| 22 | + fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Vec<T>, E> { |
| 23 | + Ok(value |
| 24 | + .split(['\n', ',']) |
| 25 | + .map(|s| T::from(s.to_owned())) |
| 26 | + .collect()) |
| 27 | + } |
| 28 | + |
| 29 | + fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error> |
| 30 | + where |
| 31 | + A: serde::de::SeqAccess<'de>, |
| 32 | + { |
| 33 | + let mut ret = Vec::new(); |
| 34 | + while let Some(el) = seq.next_element::<String>()? { |
| 35 | + ret.push(T::from(el)); |
| 36 | + } |
| 37 | + Ok(ret) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/// deserialize into a vector of `T` either of: |
| 42 | +/// * a sequence of elements serializable into `String`s, or |
| 43 | +/// * a single element serializable into `String`, then split on `,` and `\n` |
| 44 | +/// This is required to be in scope when the `extractor_cli_config` macro is used. |
| 45 | +pub(crate) fn deserialize_newline_or_comma_separated<'a, D: Deserializer<'a>, T: From<String>>( |
| 46 | + deserializer: D, |
| 47 | +) -> Result<Vec<T>, D::Error> { |
| 48 | + deserializer.deserialize_seq(VectorVisitor::new()) |
| 49 | +} |
0 commit comments