hpl_toolkit/utils/
short_string.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
use std::io::Read;

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 ShortString(String);

impl ShortString {
    pub fn new(string: String) -> std::io::Result<Self> {
        if string.len() > 255 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Short string length shall not exceed 255",
            ));
        }
        Ok(Self(string))
    }

    pub fn new_unchecked(string: String) -> Self {
        Self::new(string).expect("Short string length shall not exceed 255")
    }

    pub unsafe fn new_unsafe(string: String) -> Self {
        Self::new_unchecked(string)
    }

    pub fn to_string(&self) -> String {
        self.0.clone()
    }

    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl From<String> for ShortString {
    fn from(value: String) -> Self {
        Self::new_unchecked(value)
    }
}

impl From<&String> for ShortString {
    fn from(value: &String) -> Self {
        Self::new_unchecked(value.to_owned())
    }
}

impl Into<String> for ShortString {
    fn into(self) -> String {
        self.0
    }
}

impl PartialEq<String> for ShortString {
    fn eq(&self, other: &String) -> bool {
        self.0 == *other
    }
}

impl From<&str> for ShortString {
    fn from(value: &str) -> Self {
        Self::new_unchecked(value.to_string())
    }
}

impl AnchorSerialize for ShortString {
    fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        let length = self.0.len() as u8;
        length.serialize(writer)?;
        writer.write(self.0.as_bytes())?;
        Ok(())
    }
}

impl AnchorDeserialize for ShortString {
    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 string = String::new();
        reader.take(buf[0] as u64).read_to_string(&mut string)?;
        Ok(Self(string))
    }
}

#[cfg(feature = "idl-build")]
impl anchor_lang::IdlBuild for ShortString {
    /// Returns the full module path of the type.
    fn __anchor_private_full_path() -> String {
        format!(
            "{0}::{1}",
            "hpl_toolkit::utils::short_string", "ShortString",
        )
    }
}

#[cfg(feature = "compression")]
impl ToNode for ShortString {
    fn to_node(&self) -> [u8; 32] {
        self.0.to_node()
    }
}

#[cfg(feature = "schema")]
impl ToSchema for ShortString {
    fn schema() -> Schema {
        String::schema()
    }

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