vdf_reader/entry/
array.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
use super::Entry;
use crate::entry::Value;
use crate::VdfError;
use serde::de::{DeserializeSeed, SeqAccess};
use serde::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};

/// An array of entries (items that have the same key).
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize, Default)]
#[serde(transparent)]
pub struct Array(Vec<Entry>);

impl Array {
    pub(crate) fn from_space_separated(str: &str) -> Self {
        let items = str
            .split(' ')
            .filter(|part| !part.is_empty())
            .map(Value::from)
            .map(Entry::from)
            .collect();
        Array(items)
    }
}

impl From<Vec<Entry>> for Array {
    fn from(value: Vec<Entry>) -> Self {
        Array(value)
    }
}
impl From<Entry> for Array {
    fn from(value: Entry) -> Self {
        Array(vec![value])
    }
}

impl From<Array> for Entry {
    fn from(array: Array) -> Self {
        Entry::Array(array)
    }
}

impl Deref for Array {
    type Target = Vec<Entry>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Array {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

pub(crate) struct ArraySeq {
    iter: std::vec::IntoIter<Entry>,
}

impl ArraySeq {
    pub(crate) fn new(array: Array) -> Self {
        ArraySeq {
            iter: array.0.into_iter(),
        }
    }
}

impl<'de> SeqAccess<'de> for ArraySeq {
    type Error = VdfError;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
    where
        T: DeserializeSeed<'de>,
    {
        let next = match self.iter.next() {
            Some(next) => next,
            None => return Ok(None),
        };

        seed.deserialize(next).map(Some)
    }
}