sheave_core/messages/amf/v0/
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use std::{
    borrow::Cow,
    fmt::{
        Display,
        Formatter,
        Result as FormatResult
    },
    io::Result as IOResult,
    ops::{
        Deref,
        DerefMut
    },
    string::String as StdString
};
use crate::{
    Decoder,
    Encoder,
    ByteBuffer
};
use super::{
    Marker,
    super::{
        ensure_marker,
        invalid_string
    }
};

/// The UTF-8 string of AMF data types.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AmfString(StdString);

impl AmfString {
    /// Constructs an AMF's String.
    pub fn new(string: StdString) -> Self {
        Self(string)
    }
}

impl Deref for AmfString {
    type Target = StdString;

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

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

impl<'a> PartialEq<&'a str> for AmfString {
    fn eq(&self, other: &&'a str) -> bool {
        self.0.eq(other)
    }
}

impl<'a> PartialEq<Cow<'a, str>> for AmfString {
    fn eq(&self, other: &Cow<'a, str>) -> bool {
        self.0.eq(other)
    }
}

impl<'a> PartialEq<AmfString> for &'a str {
    fn eq(&self, other: &AmfString) -> bool {
        self.eq(&other.0)
    }
}

impl<'a> PartialEq<AmfString> for Cow<'a, str> {
    fn eq(&self, other: &AmfString) -> bool {
        self.eq(&other.0)
    }
}

impl PartialEq<AmfString> for str {
    fn eq(&self, other: &AmfString) -> bool {
        self.eq(&other.0)
    }
}

impl PartialEq<StdString> for AmfString {
    fn eq(&self, other: &StdString) -> bool {
        self.0.eq(other)
    }
}

impl PartialEq<AmfString> for StdString {
    fn eq(&self, other: &AmfString) -> bool {
        self.eq(&other.0)
    }
}

impl From<&str> for AmfString {
    fn from(s: &str) -> Self {
        Self(s.into())
    }
}

impl Display for AmfString {
    fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult {
        Display::fmt(&self.0, f)
    }
}

impl Decoder<AmfString> for ByteBuffer {
    /// Decodes bytes into an AMF's String.
    ///
    /// # Errors
    ///
    /// * [`InsufficientBufferLength`]
    ///
    /// When buffer isn't remained at least 3 bytes.
    ///
    /// * [`InconsistentMarker`]
    ///
    /// When a marker byte doesn't indicate the AMF String.
    ///
    /// * [`InvalidString`]
    ///
    /// When bytes are invalid for a UTF-8 string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sheave_core::{
    ///     ByteBuffer,
    ///     Decoder,
    ///     messages::amf::v0::{
    ///         Marker,
    ///         AmfString
    ///     }
    /// };
    ///
    /// let s = "hello world!".as_bytes();
    /// let mut buffer = ByteBuffer::default();
    /// buffer.put_u8(Marker::AmfString as u8);
    /// buffer.put_u16_be(s.len() as u16);
    /// buffer.put_bytes(s);
    /// assert!(Decoder::<AmfString>::decode(&mut buffer).is_ok());
    ///
    /// let mut buffer = ByteBuffer::default();
    /// buffer.put_u8(Marker::Number as u8);
    /// buffer.put_u16_be(s.len() as u16);
    /// buffer.put_bytes(s);
    /// assert!(Decoder::<AmfString>::decode(&mut buffer).is_err());
    ///
    /// // This is a missing sequence of the "sparkle heart(💖)".
    /// let bytes = vec![0, 159, 146, 150];
    /// let mut buffer = ByteBuffer::default();
    /// buffer.put_u8(Marker::AmfString as u8);
    /// buffer.put_u16_be(bytes.len() as u16);
    /// buffer.put_bytes(&bytes);
    /// assert!(Decoder::<AmfString>::decode(&mut buffer).is_err());
    ///
    /// let mut buffer = ByteBuffer::default();
    /// assert!(Decoder::<AmfString>::decode(&mut buffer).is_err())
    /// ```
    ///
    /// [`InsufficientBufferLength`]: crate::byte_buffer::InsufficientBufferLength
    /// [`InconsistentMarker`]: crate::messages::amf::InconsistentMarker
    /// [`InvalidString`]: crate::messages::amf::InvalidString
    fn decode(&mut self) -> IOResult<AmfString> {
        self.get_u8().and_then(
            |marker| ensure_marker(Marker::AmfString as u8, marker)
        )?;

        let len = self.get_u16_be()? as usize;
        if len == 0 {
            return Ok("".into())
        }
        let bytes = self.get_bytes(len)?;
        StdString::from_utf8(bytes.to_vec()).map(AmfString::new).map_err(invalid_string)
    }
}

impl Encoder<AmfString> for ByteBuffer {
    /// Encodes an AMF String into bytes.
    ///
    /// # Panics
    ///
    /// Its length must be the range of 16 bits.
    /// If it exceeds, a panic is occured.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::panic::catch_unwind;
    /// use sheave_core::{
    ///     ByteBuffer,
    ///     Encoder,
    ///     messages::amf::v0::{
    ///         Marker,
    ///         AmfString
    ///     }
    /// };
    ///
    /// let s = "hello world!";
    /// let mut buffer = ByteBuffer::default();
    /// buffer.encode(&AmfString::from(s));
    /// let bytes: Vec<u8> = buffer.into();
    /// assert_eq!(Marker::AmfString as u8, bytes[0]);
    /// assert_eq!((s.len() as u16).to_be_bytes().as_slice(), &bytes[1..3]);
    /// assert_eq!(s.as_bytes(), &bytes[3..]);
    ///
    /// let result = catch_unwind(
    ///     || {
    ///         let mut buffer = ByteBuffer::default();
    ///         buffer.encode(&AmfString::new("a".repeat(1 + u16::MAX as usize)))
    ///     }
    /// );
    /// assert!(result.is_err())
    /// ```
    fn encode(&mut self, string: &AmfString) {
        assert!(string.len() <= u16::MAX as usize);
        self.put_u8(Marker::AmfString as u8);
        self.put_u16_be(string.len() as u16);
        self.put_bytes(string.as_bytes());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decode_string() {
        let string = "connect".as_bytes();
        let mut buffer = ByteBuffer::default();
        buffer.put_u8(Marker::AmfString as u8);
        buffer.put_u16_be(string.len() as u16);
        buffer.put_bytes(string);
        let result: IOResult<AmfString> = buffer.decode();
        assert!(result.is_ok());
        let string = result.unwrap();
        assert_eq!("connect", string)
    }

    #[test]
    fn encode_string() {
        let string = AmfString::from("connect");
        let mut buffer = ByteBuffer::default();
        buffer.encode(&string);
        let result: Vec<u8> = buffer.into();
        assert_eq!(Marker::AmfString as u8, result[0]);
        assert_eq!(&(string.len() as u16).to_be_bytes(), &result[1..3]);
        assert_eq!("connect".as_bytes(), &result[3..])
    }

    #[test]
    #[should_panic]
    fn panic_when_length_exceeded() {
        let mut buffer = ByteBuffer::default();
        buffer.encode(&AmfString::new("a".repeat(1 + u16::MAX as usize)));
    }
}