mqtt_packet/
data_type.rs

1use crate::Error;
2use std::convert::{TryFrom, TryInto};
3use std::io;
4use std::io::prelude::*;
5use std::string::String;
6
7#[derive(Debug, PartialEq)]
8pub enum VariableByte {
9  One(u8),
10  Two(u16),
11  Three(u32),
12  Four(u32),
13}
14
15/// Data types defined by the MQTT v5 spec.
16#[derive(Debug, PartialEq)]
17pub enum DataType {
18  Byte(u8),
19  TwoByteInteger(u16),
20  FourByteInteger(u32),
21  VariableByteInteger(VariableByte),
22  Utf8EncodedString(String),
23  BinaryData(Vec<u8>),
24  Utf8StringPair(String, String),
25}
26
27impl From<DataType> for u16 {
28  fn from(t: DataType) -> Self {
29    if let DataType::TwoByteInteger(value) = t {
30      return value;
31    } else {
32      return 0;
33    }
34  }
35}
36
37impl DataType {
38  /// Reads one byte from the reader and attempts to convert the byte to DataType::Byte (u8).
39  ///
40  /// [1.5.1 Bits](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901007)
41  ///
42  /// Bits in a byte are labelled 7 to 0. Bit number 7 is the most significant
43  /// bit, the least significant bit is assigned bit number 0.
44  ///
45  /// # Examples
46  ///
47  /// ```rust
48  /// use mqtt_packet::DataType;
49  /// use std::io;
50  ///
51  /// let data: Vec<u8> = vec![0xFF, 0x02];
52  /// let mut reader = io::BufReader::new(&data[..]);
53  /// let byte = DataType::parse_byte(&mut reader).unwrap();
54  /// assert_eq!(byte, DataType::Byte(255));
55  /// ```
56  pub fn parse_byte<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
57    let mut buffer = [0; 1];
58    reader.read(&mut buffer)?;
59    return Ok(Self::Byte(u8::from_be_bytes(buffer)));
60  }
61
62  /// Reads two bytes from the reader and attempts to convert the bytes to DataType::TwoByteInteger (u16).
63  ///
64  /// [1.5.2 Two Byte Integer](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901008)
65  ///
66  /// Two Byte Integer data values are 16-bit unsigned integers in big-endian
67  /// order: the high order byte precedes the lower order byte. This means that a
68  /// 16-bit word is presented on the network as Most Significant Byte (MSB),
69  /// followed by Least Significant Byte (LSB).
70  ///
71  /// # Examples
72  ///
73  /// ```rust
74  /// use mqtt_packet::DataType;
75  /// use std::io;
76  ///
77  /// let data: Vec<u8> = vec![0x01, 0x02, 0x03];
78  /// let mut reader = io::BufReader::new(&data[..]);
79  /// let two = DataType::parse_two_byte_int(&mut reader).unwrap();
80  /// assert_eq!(two, DataType::TwoByteInteger(258));
81  /// ```
82  pub fn parse_two_byte_int<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
83    let mut buffer = [0; 2];
84    reader.read(&mut buffer)?;
85    return Ok(Self::TwoByteInteger(u16::from_be_bytes(buffer)));
86  }
87
88  /// Reads four bytes from the reader and attempts to convert the bytes to DataType::FourByteInteger (u32).
89  ///
90  /// [1.5.3 Four Byte Integer](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901009)
91  ///
92  /// Four Byte Integer data values are 32-bit unsigned integers in big-endian
93  /// order: the high order byte precedes the successively lower order bytes.
94  /// This means that a 32-bit word is presented on the network as Most
95  /// Significant Byte (MSB), followed by the next most Significant Byte (MSB),
96  /// followed by the next most Significant Byte (MSB), followed by Least
97  /// Significant Byte (LSB).
98  ///
99  /// # Examples
100  ///
101  /// ```rust
102  /// use mqtt_packet::DataType;
103  /// use std::io;
104  ///
105  /// let data: Vec<u8> = vec![0x01, 0x02, 0x03, 0x04, 0x05];
106  /// let mut reader = io::BufReader::new(&data[..]);
107  /// let four = DataType::parse_four_byte_int(&mut reader).unwrap();
108  /// assert_eq!(four, DataType::FourByteInteger(16909060));
109  /// ```
110  pub fn parse_four_byte_int<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
111    let mut buffer = [0; 4];
112    reader.read(&mut buffer)?;
113    return Ok(Self::FourByteInteger(u32::from_be_bytes(buffer)));
114  }
115
116  fn parse_string<R: io::Read>(reader: &mut R) -> Result<String, Error> {
117    // get the expected length of the string
118    let mut length_buffer = [0; 2];
119
120    reader.read(&mut length_buffer)?;
121
122    let length = u16::from_be_bytes(length_buffer);
123
124    // read the string
125    let mut handle = reader.take(u64::from(length));
126    let mut buffer = vec![];
127    handle.read_to_end(&mut buffer)?;
128    let s = String::from_utf8(buffer)?;
129
130    return Ok(s);
131  }
132
133  /// Reads bytes from the reader and attempts to convert the bytes to DataType::Utf8EncodedString (String).
134  ///
135  /// [1.5.4 UTF-8 Encoded String](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901010)
136  ///
137  /// Text fields within the MQTT Control Packets described later are encoded as
138  /// UTF-8 strings. UTF-8 is an efficient encoding of Unicode
139  /// characters that optimizes the encoding of ASCII characters in support of
140  /// text-based communications.
141  ///
142  /// Each of these strings is prefixed with a Two Byte Integer length field that
143  /// gives the number of bytes in a UTF-8 encoded string itself, as illustrated
144  /// in Figure 1.1 Structure of UTF-8 Encoded Strings below. Consequently, the
145  /// maximum size of a UTF-8 Encoded String is 65,535 bytes.
146  ///
147  /// Unless stated otherwise all UTF-8 encoded strings can have any length in
148  /// the range 0 to 65,535 bytes.
149  ///
150  /// # Examples
151  ///
152  /// ```rust
153  /// use std::io;
154  /// use mqtt_packet::DataType;
155  ///
156  /// let data: Vec<u8> = vec![
157  ///   0, 11, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 100, 100, 100,
158  /// ];
159  ///
160  /// let mut reader = io::BufReader::new(&data[..]);
161  /// let result = DataType::parse_utf8_string(&mut reader).unwrap();
162  /// assert_eq!(
163  ///   result,
164  ///   DataType::Utf8EncodedString(String::from("hello world"))
165  /// );
166  /// ```
167  pub fn parse_utf8_string<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
168    let s = Self::parse_string(reader)?;
169    return Ok(Self::Utf8EncodedString(s));
170  }
171
172  /// Reads bytes from the reader and attempts to convert the bytes to DataType::VariableByteInteger (u8, 16, or u32).
173  ///
174  /// [1.5.5 Variable Byte Integer](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901011)
175  ///
176  /// The Variable Byte Integer is encoded using an encoding scheme which uses a
177  /// single byte for values up to 127. Larger values are handled as follows. The
178  /// least significant seven bits of each byte encode the data, and the most
179  /// significant bit is used to indicate whether there are bytes following in
180  /// the representation. Thus, each byte encodes 128 values and a "continuation
181  /// bit". The maximum number of bytes in the Variable Byte Integer field is four.
182  /// The encoded value MUST use the minimum number of bytes necessary to represent
183  /// the value.
184  ///
185  /// The algorithm for decoding a Variable Byte Integer type is as follows:
186  /// ```txt
187  /// multiplier = 1
188  /// value = 0
189  ///
190  /// do
191  ///    encodedByte = 'next byte from stream'
192  ///    value += (encodedByte AND 127) * multiplier
193  ///
194  ///    if (multiplier > 128*128*128)
195  ///       throw Error(Malformed Variable Byte Integer)
196  ///    multiplier *= 128
197  /// while ((encodedByte AND 128) != 0)
198  /// ```
199  ///
200  /// # Examples
201  ///
202  /// ```rust
203  /// use mqtt_packet::{DataType, VariableByte};
204  /// use std::io;
205  ///
206  /// let data: Vec<u8> = vec![0x80, 0x80, 0x80, 0x01];
207  /// let mut reader = io::BufReader::new(&data[..]);
208  /// let mut vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
209  ///
210  /// assert_eq!(
211  ///   vari_type,
212  ///   DataType::VariableByteInteger(VariableByte::Four(2097152))
213  /// );
214  /// ```
215  pub fn parse_variable_byte_int<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
216    let mut multiplier: i32 = 1;
217    let mut value: i32 = 0;
218
219    loop {
220      let mut b = [0; 1];
221      reader.read(&mut b)?;
222
223      value = value + i32::from(b[0] & 127) * multiplier;
224
225      if multiplier > (128 * 128 * 128) {
226        return Err(Error::ParseError);
227      }
228
229      multiplier = multiplier * 128;
230
231      if (b[0] & 128) == 0 {
232        break;
233      }
234    }
235
236    let parsed = match value {
237      n if n <= 127 => Self::VariableByteInteger(VariableByte::One(u8::try_from(value)?)),
238      n if n <= 16383 => Self::VariableByteInteger(VariableByte::Two(u16::try_from(value)?)),
239      n if n <= 2097151 => Self::VariableByteInteger(VariableByte::Three(u32::try_from(value)?)),
240      _ => Self::VariableByteInteger(VariableByte::Four(u32::try_from(value)?)),
241    };
242
243    return Ok(parsed);
244  }
245
246  /// Reads bytes from the reader and attempts to convert the bytes to DataType::BinaryData (Vec<u8>).
247  ///
248  /// [1.5.6 Binary Data](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901012)
249  ///
250  /// Binary Data is represented by a Two Byte Integer length which indicates the
251  /// number of data bytes, followed by that number of bytes. Thus, the length of
252  /// Binary Data is limited to the range of 0 to 65,535 Bytes.
253  ///
254  /// # Examples
255  ///
256  /// ```rust
257  /// use mqtt_packet::DataType;
258  /// use std::io;
259  ///
260  /// let data: Vec<u8> = vec![
261  ///   0, 10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
262  /// ];
263  ///
264  /// let mut reader = io::BufReader::new(&data[..]);
265  /// let result = DataType::parse_binary_data(&mut reader).unwrap();
266  ///
267  /// let expected: Vec<u8> = vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09];
268  /// assert_eq!(result, DataType::BinaryData(expected));
269  /// ```
270  pub fn parse_binary_data<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
271    // determine the length of the binary data
272    let mut length_buffer = [0; 2];
273    reader.read(&mut length_buffer)?;
274    let length = u16::from_be_bytes(length_buffer);
275
276    // read the data
277    let mut handle = reader.take(u64::from(length));
278    let mut buffer = vec![];
279    handle.read_to_end(&mut buffer)?;
280
281    return Ok(Self::BinaryData(buffer));
282  }
283
284  /// Reads bytes from the reader and attempts to convert the bytes to DataType::Utf8StringPair (String, String).
285  ///
286  ///  [1.5.7 UTF-8 String Pair](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901013)
287  ///
288  /// A UTF-8 String Pair consists of two UTF-8 Encoded Strings. This data type
289  /// is used to hold name-value pairs. The first string serves as the name, and
290  /// the second string contains the value.
291  ///
292  /// Both strings MUST comply with the requirements for UTF-8 Encoded Strings.
293  /// If a receiver (Client or Server) receives a string pair
294  /// which does not meet these requirements it is a Malformed Packet. Refer to
295  /// section 4.13 for information about handling errors.
296  ///
297  /// # Examples
298  ///
299  /// ```rust
300  /// use mqtt_packet::DataType;
301  /// use std::io;
302  /// ```
303  pub fn parse_utf8_string_pair<R: io::Read>(reader: &mut R) -> Result<Self, Error> {
304    let str_one = Self::parse_string(reader)?;
305    let str_two = Self::parse_string(reader)?;
306
307    return Ok(Self::Utf8StringPair(str_one, str_two));
308  }
309
310  /// Used by into_bytes() for calculating length for strings, string pairs, and binary data.
311  /// The length of arrays is limited to the range of 0 to 65,535 bytes. Because of that we
312  /// need to convert usize to a two byte u8 array.
313  fn calculate_length(data: Vec<u8>) -> Result<Vec<u8>, Error> {
314    if data.len() > 65535 {
315      return Err(Error::GenerateError);
316    }
317
318    let length = u16::try_from(data.len() & 0xFFFF)
319      .unwrap()
320      .to_be_bytes()
321      .to_vec();
322
323    return Ok([&length[..], &data[..]].concat());
324  }
325
326  /// Used by into_bytes() to format variable byte ints into the format defined in the
327  /// MQTT v5 spec.
328  ///
329  /// The algorithm for encoding a non-negative integer (X) into the Variable Byte
330  /// Integer encoding scheme is as follows:
331  ///
332  /// ```txt
333  /// do
334  ///    encodedByte = X MOD 128
335  ///    X = X DIV 128
336  ///    // if there are more data to encode, set the top bit of this byte
337  ///    if (X > 0)
338  ///       encodedByte = encodedByte OR 128
339  ///    endif
340  ///    'output' encodedByte
341  /// while (X > 0)
342  /// ```
343  ///
344  /// Where MOD is the modulo operator (% in C), DIV is integer division (/ in C),
345  /// and OR is bit-wise or (| in C).
346  fn encode_variable_byte(data: &VariableByte) -> Result<Vec<u8>, Error> {
347    let mut bytes = vec![];
348    let mut number: u32 = match data {
349      VariableByte::One(value) => u32::from(*value),
350      VariableByte::Two(value) => u32::from(*value),
351      VariableByte::Three(value) => u32::from(*value),
352      VariableByte::Four(value) => u32::from(*value),
353    };
354
355    if number > 268435455 {
356      return Err(Error::GenerateError);
357    }
358
359    loop {
360      // we are safe to unwrap here because (number % 128) will neveer be bigger than 127
361      let mut encoded_byte: u8 = (number % 128).try_into().unwrap();
362      number = number / 128;
363
364      if number > 0 {
365        encoded_byte = encoded_byte | 128;
366        bytes.push(encoded_byte);
367      } else {
368        bytes.push(encoded_byte);
369        break;
370      }
371    }
372
373    return Ok(bytes);
374  }
375
376  /// Convert DataType variants into u8 vectors.
377  pub fn into_bytes(&self) -> Result<Vec<u8>, Error> {
378    let bytes = match self {
379      Self::Byte(value) => value.to_be_bytes().to_vec(),
380      Self::TwoByteInteger(value) => value.to_be_bytes().to_vec(),
381      Self::FourByteInteger(value) => value.to_be_bytes().to_vec(),
382      Self::VariableByteInteger(value) => Self::encode_variable_byte(value)?,
383      Self::Utf8EncodedString(value) => Self::calculate_length(value.as_bytes().to_vec())?,
384      Self::BinaryData(value) => Self::calculate_length(value.to_vec())?,
385      Self::Utf8StringPair(one, two) => [
386        Self::calculate_length(one.as_bytes().to_vec())?,
387        Self::calculate_length(two.as_bytes().to_vec())?,
388      ]
389      .concat(),
390    };
391
392    return Ok(bytes);
393  }
394}
395
396#[cfg(test)]
397mod tests {
398  use super::{DataType, VariableByte};
399  use crate::Error;
400  use std::io;
401
402  #[test]
403  fn type_into() {
404    let data: Vec<u8> = vec![0x01, 0x02, 0x03];
405    let mut reader = io::BufReader::new(&data[..]);
406    let two = DataType::parse_two_byte_int(&mut reader).unwrap();
407    let mut check: u16 = two.into();
408    assert_eq!(258, check);
409
410    // any other type should return 0 for now
411    let zero = vec![0x01, 0x02, 0x03, 0x04, 0x05];
412    reader = io::BufReader::new(&zero[..]);
413    let four = DataType::parse_four_byte_int(&mut reader).unwrap();
414    check = four.into();
415    assert_eq!(0, check);
416  }
417
418  #[test]
419  fn variable_byte_one() {
420    let min: Vec<u8> = vec![0x00];
421    let mut reader = io::BufReader::new(&min[..]);
422    let mut vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
423    assert_eq!(
424      vari_type,
425      DataType::VariableByteInteger(VariableByte::One(0))
426    );
427
428    let max = vec![0x7F];
429    reader = io::BufReader::new(&max[..]);
430    vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
431    assert_eq!(
432      vari_type,
433      DataType::VariableByteInteger(VariableByte::One(127))
434    );
435  }
436
437  #[test]
438  fn variable_byte_two() {
439    let min: Vec<u8> = vec![0x80, 0x01];
440    let mut reader = io::BufReader::new(&min[..]);
441    let mut vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
442    assert_eq!(
443      vari_type,
444      DataType::VariableByteInteger(VariableByte::Two(128))
445    );
446
447    let max: Vec<u8> = vec![0xFF, 0x7F];
448    reader = io::BufReader::new(&max[..]);
449    vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
450    assert_eq!(
451      vari_type,
452      DataType::VariableByteInteger(VariableByte::Two(16383))
453    );
454  }
455
456  #[test]
457  fn variable_byte_three() {
458    let min: Vec<u8> = vec![0x80, 0x80, 0x01];
459    let mut reader = io::BufReader::new(&min[..]);
460    let mut vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
461    assert_eq!(
462      vari_type,
463      DataType::VariableByteInteger(VariableByte::Three(16384))
464    );
465
466    let max: Vec<u8> = vec![0xFF, 0xFF, 0x7F];
467    reader = io::BufReader::new(&max[..]);
468    vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
469    assert_eq!(
470      vari_type,
471      DataType::VariableByteInteger(VariableByte::Three(2097151))
472    );
473  }
474
475  #[test]
476  fn variable_byte_four() {
477    let min: Vec<u8> = vec![0x80, 0x80, 0x80, 0x01];
478    let mut reader = io::BufReader::new(&min[..]);
479    let mut vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
480    assert_eq!(
481      vari_type,
482      DataType::VariableByteInteger(VariableByte::Four(2097152))
483    );
484
485    let max: Vec<u8> = vec![0xFF, 0xFF, 0xFF, 0x7F];
486    reader = io::BufReader::new(&max[..]);
487    vari_type = DataType::parse_variable_byte_int(&mut reader).unwrap();
488    assert_eq!(
489      vari_type,
490      DataType::VariableByteInteger(VariableByte::Four(268435455))
491    );
492  }
493
494  #[test]
495  fn variable_byte_error() {
496    let vari: Vec<u8> = vec![0xFF, 0xFF, 0xFF, 0xFF];
497    let mut reader = io::BufReader::new(&vari[..]);
498    let vari_err = DataType::parse_variable_byte_int(&mut reader).unwrap_err();
499    assert_eq!(vari_err, Error::ParseError);
500  }
501
502  #[test]
503  fn string_pair() {
504    let data: Vec<u8> = vec![
505      0, 11, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 0, 7, 102, 111, 111, 32, 98, 97,
506      114, 1, 1, 1, 1,
507    ];
508
509    let mut reader = io::BufReader::new(&data[..]);
510    let result = DataType::parse_utf8_string_pair(&mut reader).unwrap();
511
512    assert_eq!(
513      result,
514      DataType::Utf8StringPair(String::from("hello world"), String::from("foo bar"))
515    );
516  }
517
518  #[test]
519  fn byte_into_bytes() {
520    let value = DataType::Byte(255);
521    let expected: Vec<u8> = vec![0xFF];
522    assert_eq!(value.into_bytes().unwrap(), expected);
523  }
524
525  #[test]
526  fn two_byte_int_into_bytes() {
527    let value = DataType::TwoByteInteger(258);
528    let expected: Vec<u8> = vec![0x01, 0x02];
529    assert_eq!(value.into_bytes().unwrap(), expected);
530  }
531
532  #[test]
533  fn four_byte_into_bytes() {
534    let value = DataType::FourByteInteger(16909060);
535    let expected: Vec<u8> = vec![0x01, 0x02, 0x03, 0x04];
536    assert_eq!(value.into_bytes().unwrap(), expected);
537  }
538
539  #[test]
540  fn variable_byte_one_into_bytes() {
541    let mut vari = DataType::VariableByteInteger(VariableByte::One(0));
542    let mut expected: Vec<u8> = vec![0x00];
543    assert_eq!(vari.into_bytes().unwrap(), expected);
544
545    vari = DataType::VariableByteInteger(VariableByte::One(127));
546    expected = vec![0x7F];
547    assert_eq!(vari.into_bytes().unwrap(), expected);
548  }
549
550  #[test]
551  fn variable_byte_two_into_bytes() {
552    let mut vari = DataType::VariableByteInteger(VariableByte::Two(128));
553    let mut expected: Vec<u8> = vec![0x80, 0x01];
554    assert_eq!(vari.into_bytes().unwrap(), expected);
555
556    vari = DataType::VariableByteInteger(VariableByte::Two(16383));
557    expected = vec![0xFF, 0x7F];
558    assert_eq!(vari.into_bytes().unwrap(), expected);
559  }
560
561  #[test]
562  fn variable_byte_three_into_bytes() {
563    let mut vari = DataType::VariableByteInteger(VariableByte::Three(16384));
564    let mut expected: Vec<u8> = vec![0x80, 0x80, 0x01];
565    assert_eq!(vari.into_bytes().unwrap(), expected);
566
567    vari = DataType::VariableByteInteger(VariableByte::Three(2097151));
568    expected = vec![0xFF, 0xFF, 0x7F];
569    assert_eq!(vari.into_bytes().unwrap(), expected);
570  }
571
572  #[test]
573  fn variable_byte_four_into_bytes() {
574    let mut vari = DataType::VariableByteInteger(VariableByte::Four(2097152));
575    let mut expected: Vec<u8> = vec![0x80, 0x80, 0x80, 0x01];
576    assert_eq!(vari.into_bytes().unwrap(), expected);
577
578    vari = DataType::VariableByteInteger(VariableByte::Four(268435455));
579    expected = vec![0xFF, 0xFF, 0xFF, 0x7F];
580    assert_eq!(vari.into_bytes().unwrap(), expected);
581  }
582
583  #[test]
584  fn variable_byte_into_bytes_error() {
585    let vari = DataType::VariableByteInteger(VariableByte::Four(268435456));
586    let err = vari.into_bytes().unwrap_err();
587    assert_eq!(err, Error::GenerateError);
588  }
589
590  #[test]
591  fn utf8_string_into_bytes() {
592    let value = DataType::Utf8EncodedString("hello world".to_string());
593    let expected: Vec<u8> = vec![0, 11, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];
594    assert_eq!(value.into_bytes().unwrap(), expected);
595  }
596
597  #[test]
598  fn utf8_string_pair_into_bytes() {
599    let value = DataType::Utf8StringPair("hello world".to_string(), "foo bar".to_string());
600    let expected: Vec<u8> = vec![
601      0, 11, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 0, 7, 102, 111, 111, 32, 98, 97,
602      114,
603    ];
604    assert_eq!(value.into_bytes().unwrap(), expected);
605  }
606
607  #[test]
608  fn binary_data_into_bytes() {
609    let data: Vec<u8> = vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09];
610    let value = DataType::BinaryData(data);
611
612    let expected: Vec<u8> = vec![
613      0, 10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
614    ];
615    assert_eq!(value.into_bytes().unwrap(), expected);
616  }
617
618  #[test]
619  fn into_bytes_max_length() {
620    let data = [0u8; 65536];
621    let value = DataType::BinaryData(data.to_vec());
622    let err = value.into_bytes().unwrap_err();
623    assert_eq!(err, Error::GenerateError);
624  }
625}