hpl_toolkit/utils/
short_vec.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
use anchor_lang::prelude::*;

#[cfg(feature = "compression")]
use crate::compression::*;

#[cfg(feature = "schema")]
use crate::schema::*;

#[cfg_attr(feature = "debug", derive(Debug))]
#[derive(Clone, Eq, PartialEq)]
pub struct ShortVec<T: Clone + AnchorSerialize + AnchorDeserialize>(Vec<T>);

impl<T: Clone + AnchorSerialize + AnchorDeserialize> ShortVec<T> {
    pub fn new(vec: Vec<T>) -> std::io::Result<Self> {
        if vec.len() > 255 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Short string length shall not exceed 255",
            ));
        }
        Ok(Self(vec))
    }

    pub fn new_unchecked(vec: Vec<T>) -> Self {
        Self::new(vec).expect("Short Vec length shall not exceed 255")
    }

    pub unsafe fn new_unsafe(vec: Vec<T>) -> Self {
        Self::new_unchecked(vec)
    }

    pub fn to_vec(&self) -> Vec<T> {
        self.0.clone()
    }

    pub fn into_vec(self) -> Vec<T> {
        self.0
    }
}

impl<T: Clone + AnchorSerialize + AnchorDeserialize> Into<Vec<T>> for ShortVec<T> {
    fn into(self) -> Vec<T> {
        self.0
    }
}

impl<T: Clone + AnchorSerialize + AnchorDeserialize> From<Vec<T>> for ShortVec<T> {
    fn from(value: Vec<T>) -> Self {
        Self::new_unchecked(value)
    }
}

impl<T: Clone + AnchorSerialize + AnchorDeserialize> From<&Vec<T>> for ShortVec<T> {
    fn from(value: &Vec<T>) -> Self {
        Self::new_unchecked(value.to_vec())
    }
}

impl<T: Clone + AnchorSerialize + AnchorDeserialize + PartialEq> PartialEq<Vec<T>> for ShortVec<T> {
    fn eq(&self, other: &Vec<T>) -> bool {
        self.0 == *other
    }
}

impl<T: AnchorSerialize + AnchorDeserialize + Clone> AnchorSerialize for ShortVec<T> {
    fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        let length = self.0.len() as u8;
        length.serialize(writer)?;
        self.0.iter().try_for_each(|item| item.serialize(writer))?;
        Ok(())
    }
}

impl<T: AnchorSerialize + AnchorDeserialize + Clone> AnchorDeserialize for ShortVec<T> {
    fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
        let mut buf: [u8; 1] = [0; 1];
        let limit = reader.read(&mut buf)?;
        if limit != 1 {
            #[cfg(feature = "log")]
            crate::logger::debug!("limit: {}, Buf: {:?}", limit, buf);
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Unexpected length of input",
            ));
        }

        let mut vec = Vec::<T>::new();

        for _ in 0..buf[0] {
            vec.push(T::deserialize_reader(reader)?);
        }

        Ok(Self(vec))
    }
}

#[cfg(feature = "idl-build")]
impl<T: AnchorSerialize + AnchorDeserialize + Clone> anchor_lang::IdlBuild for ShortVec<T> {
    /// Returns the full module path of the type.
    fn __anchor_private_full_path() -> String {
        format!("{0}::{1}", "hpl_toolkit::utils::short_vec", "ShortVec",)
    }
}

#[cfg(feature = "compression")]
impl<T: Clone + AnchorSerialize + AnchorDeserialize + ToNode> ToNode for ShortVec<T> {
    fn to_node(&self) -> [u8; 32] {
        self.0.to_node()
    }
}

#[cfg(feature = "schema")]
impl<T: Clone + AnchorSerialize + AnchorDeserialize + ToNode + ToSchema> ToSchema for ShortVec<T> {
    fn schema() -> Schema {
        Vec::<T>::schema()
    }

    fn schema_value(&self) -> SchemaValue {
        self.0.schema_value()
    }
}