vdf_reader/entry/
value.rs

1use super::Entry;
2use crate::entry::{string_is_array, ParseItem, Statement};
3use crate::error::{ParseStringError, SerdeParseError};
4use crate::VdfError;
5use serde::de::{Error, Visitor};
6use serde::{Deserialize, Deserializer, Serialize};
7use std::borrow::Cow;
8use std::fmt::Formatter;
9use std::ops::{Deref, DerefMut};
10
11#[derive(Clone, PartialEq, Eq, Debug, Serialize, Default)]
12#[serde(transparent)]
13pub struct Value(String);
14
15impl From<Cow<'_, str>> for Value {
16    fn from(value: Cow<'_, str>) -> Value {
17        Value(value.into())
18    }
19}
20impl From<&'_ str> for Value {
21    fn from(value: &str) -> Value {
22        Value(value.into())
23    }
24}
25
26impl From<String> for Value {
27    fn from(value: String) -> Value {
28        Value(value)
29    }
30}
31
32impl From<Statement> for Value {
33    fn from(value: Statement) -> Value {
34        Value(value.into())
35    }
36}
37
38impl From<Value> for Entry {
39    fn from(value: Value) -> Self {
40        Entry::Value(value)
41    }
42}
43
44impl From<Value> for String {
45    fn from(value: Value) -> Self {
46        value.0
47    }
48}
49
50impl Deref for Value {
51    type Target = str;
52
53    fn deref(&self) -> &Self::Target {
54        &self.0
55    }
56}
57
58impl DerefMut for Value {
59    fn deref_mut(&mut self) -> &mut Self::Target {
60        &mut self.0
61    }
62}
63
64impl Value {
65    /// Try to convert the entry to the given type.
66    pub fn to<T: ParseItem>(self) -> Result<T, ParseStringError> {
67        T::from_str(&self.0)
68    }
69}
70
71impl<'de> Deserialize<'de> for Value {
72    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
73    where
74        D: Deserializer<'de>,
75    {
76        struct ValueVisitor;
77
78        impl Visitor<'_> for ValueVisitor {
79            type Value = String;
80
81            fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
82                write!(formatter, "any string like value")
83            }
84
85            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
86            where
87                E: Error,
88            {
89                Ok(if v { "1".into() } else { "0".into() })
90            }
91
92            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
93            where
94                E: Error,
95            {
96                Ok(v.to_string())
97            }
98
99            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
100            where
101                E: Error,
102            {
103                Ok(v.to_string())
104            }
105
106            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
107            where
108                E: Error,
109            {
110                Ok(v.to_string())
111            }
112
113            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
114            where
115                E: Error,
116            {
117                Ok(v.into())
118            }
119
120            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
121            where
122                E: Error,
123            {
124                Ok(v)
125            }
126        }
127
128        deserializer.deserialize_str(ValueVisitor).map(Value)
129    }
130}
131
132impl<'de> Deserializer<'de> for Value {
133    type Error = VdfError;
134
135    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
136    where
137        V: Visitor<'de>,
138    {
139        if let Ok(int) = i64::from_str(&self.0) {
140            return visitor.visit_i64(int);
141        }
142        if let Ok(float) = f64::from_str(&self.0) {
143            return visitor.visit_f64(float);
144        }
145        if string_is_array(&self.0) {
146            return self.deserialize_seq(visitor);
147        }
148        visitor.visit_string(self.0)
149    }
150
151    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
152    where
153        V: Visitor<'de>,
154    {
155        visitor.visit_bool(self.to()?)
156    }
157
158    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
159    where
160        V: Visitor<'de>,
161    {
162        visitor.visit_i8(self.to()?)
163    }
164
165    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
166    where
167        V: Visitor<'de>,
168    {
169        visitor.visit_i16(self.to()?)
170    }
171
172    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
173    where
174        V: Visitor<'de>,
175    {
176        visitor.visit_i32(self.to()?)
177    }
178
179    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
180    where
181        V: Visitor<'de>,
182    {
183        visitor.visit_i64(self.to()?)
184    }
185
186    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
187    where
188        V: Visitor<'de>,
189    {
190        visitor.visit_u8(self.to()?)
191    }
192
193    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
194    where
195        V: Visitor<'de>,
196    {
197        visitor.visit_u16(self.to()?)
198    }
199
200    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
201    where
202        V: Visitor<'de>,
203    {
204        visitor.visit_u32(self.to()?)
205    }
206
207    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
208    where
209        V: Visitor<'de>,
210    {
211        visitor.visit_u64(self.to()?)
212    }
213
214    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
215    where
216        V: Visitor<'de>,
217    {
218        visitor.visit_f32(self.to()?)
219    }
220
221    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
222    where
223        V: Visitor<'de>,
224    {
225        visitor.visit_f64(self.to()?)
226    }
227
228    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
229    where
230        V: Visitor<'de>,
231    {
232        let mut chars = self.0.chars();
233        match (chars.next(), chars.next()) {
234            (Some(_), None) => Ok(()),
235            _ => Err(SerdeParseError::new("char", &self.0, 0..0, "")),
236        }?;
237
238        visitor.visit_str(&self.0)
239    }
240
241    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
242    where
243        V: Visitor<'de>,
244    {
245        visitor.visit_str(&self.0)
246    }
247
248    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
249    where
250        V: Visitor<'de>,
251    {
252        visitor.visit_string(self.0)
253    }
254
255    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
256    where
257        V: Visitor<'de>,
258    {
259        visitor.visit_bytes(self.0.as_bytes())
260    }
261
262    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
263    where
264        V: Visitor<'de>,
265    {
266        visitor.visit_byte_buf(self.0.into_bytes())
267    }
268
269    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
270    where
271        V: Visitor<'de>,
272    {
273        if self.0.is_empty() {
274            return visitor.visit_none();
275        }
276        visitor.visit_some(self)
277    }
278
279    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
280    where
281        V: Visitor<'de>,
282    {
283        if !self.0.is_empty() {
284            return Err(SerdeParseError::new("unit", self.0.as_ref(), 0..0, "").into());
285        }
286        visitor.visit_unit()
287    }
288
289    fn deserialize_unit_struct<V>(
290        self,
291        _name: &'static str,
292        visitor: V,
293    ) -> Result<V::Value, Self::Error>
294    where
295        V: Visitor<'de>,
296    {
297        if !self.0.is_empty() {
298            return Err(SerdeParseError::new("unit", self.0.as_ref(), 0..0, "").into());
299        }
300        visitor.visit_unit()
301    }
302
303    fn deserialize_newtype_struct<V>(
304        self,
305        _name: &'static str,
306        visitor: V,
307    ) -> Result<V::Value, Self::Error>
308    where
309        V: Visitor<'de>,
310    {
311        visitor.visit_newtype_struct(self)
312    }
313
314    fn deserialize_seq<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
315    where
316        V: Visitor<'de>,
317    {
318        Err(SerdeParseError::new("seq", self.0.as_ref(), 0..0, "").into())
319    }
320
321    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
322    where
323        V: Visitor<'de>,
324    {
325        self.deserialize_seq(visitor)
326    }
327
328    fn deserialize_tuple_struct<V>(
329        self,
330        _name: &'static str,
331        _len: usize,
332        visitor: V,
333    ) -> Result<V::Value, Self::Error>
334    where
335        V: Visitor<'de>,
336    {
337        self.deserialize_seq(visitor)
338    }
339
340    fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
341    where
342        V: Visitor<'de>,
343    {
344        Err(SerdeParseError::new("map", self.0.as_ref(), 0..0, "").into())
345    }
346
347    fn deserialize_struct<V>(
348        self,
349        _name: &'static str,
350        _fields: &'static [&'static str],
351        _visitor: V,
352    ) -> Result<V::Value, Self::Error>
353    where
354        V: Visitor<'de>,
355    {
356        Err(SerdeParseError::new("struct", self.0.as_ref(), 0..0, "").into())
357    }
358
359    fn deserialize_enum<V>(
360        self,
361        _name: &'static str,
362        _variants: &'static [&'static str],
363        _visitor: V,
364    ) -> Result<V::Value, Self::Error>
365    where
366        V: Visitor<'de>,
367    {
368        Err(SerdeParseError::new("map", self.0.as_ref(), 0..0, "").into())
369    }
370
371    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
372    where
373        V: Visitor<'de>,
374    {
375        self.deserialize_str(visitor)
376    }
377
378    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
379    where
380        V: Visitor<'de>,
381    {
382        self.deserialize_any(visitor)
383    }
384}
385
386#[cfg(test)]
387#[track_caller]
388fn unwrap_err<T>(r: Result<T, crate::VdfError>) -> T {
389    r.map_err(miette::Error::from).unwrap()
390}
391
392#[test]
393fn test_serde_value() {
394    let j = r#"1"#;
395    assert_eq!(Value("1".into()), unwrap_err(crate::from_str(j)));
396
397    let j = r#""foo bar""#;
398    assert_eq!(Value("foo bar".into()), unwrap_err(crate::from_str(j)));
399}
400
401#[test]
402fn test_serde_from_value() {
403    let j = Value::from("1");
404    assert!(unwrap_err(crate::from_entry(j.into())));
405}