Skip to main content

ion_rs/types/
bytes.rs

1use crate::ion_data::{IonDataHash, IonDataOrd, IonEq};
2use std::cmp::Ordering;
3use std::hash::{Hash, Hasher};
4
5/// An owned, immutable byte array.
6/// ```rust
7/// use ion_rs::Bytes;
8/// let ivm: &[u8] = &[0xEA_u8, 0x01, 0x00, 0xE0]; // Ion 1.0 version marker
9/// let bytes: Bytes = ivm.into();
10/// assert_eq!(&bytes, ivm);
11/// ```
12/// ```rust
13/// use ion_rs::Bytes;
14/// let bytes: Bytes = "hello".into();
15/// assert_eq!(&bytes, "hello".as_bytes());
16/// ```
17/// ```rust
18/// use ion_rs::Bytes;
19/// let bytes: Bytes = b"world".into();
20/// assert_eq!(&bytes, b"world".as_slice());
21/// ```
22#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd)]
23pub struct Bytes {
24    data: Vec<u8>,
25}
26
27impl From<Bytes> for Vec<u8> {
28    fn from(data: Bytes) -> Self {
29        data.data
30    }
31}
32
33impl IonEq for Bytes {
34    fn ion_eq(&self, other: &Self) -> bool {
35        self == other
36    }
37}
38
39impl IonDataOrd for Bytes {
40    fn ion_cmp(&self, other: &Self) -> Ordering {
41        self.cmp(other)
42    }
43}
44
45impl IonDataHash for Bytes {
46    fn ion_data_hash<H: Hasher>(&self, state: &mut H) {
47        self.data.hash(state);
48    }
49}
50
51impl PartialEq<[u8]> for Bytes {
52    fn eq(&self, other: &[u8]) -> bool {
53        self.as_ref().eq(other)
54    }
55}
56
57impl From<Vec<u8>> for Bytes {
58    fn from(data: Vec<u8>) -> Self {
59        Bytes { data }
60    }
61}
62
63impl From<&[u8]> for Bytes {
64    fn from(data: &[u8]) -> Self {
65        Bytes {
66            data: data.to_vec(),
67        }
68    }
69}
70
71impl<const N: usize> From<&[u8; N]> for Bytes {
72    fn from(data: &[u8; N]) -> Self {
73        Bytes {
74            data: data.to_vec(),
75        }
76    }
77}
78
79impl From<&str> for Bytes {
80    fn from(text: &str) -> Self {
81        Bytes {
82            data: text.as_bytes().into(),
83        }
84    }
85}
86
87impl AsRef<[u8]> for Bytes {
88    fn as_ref(&self) -> &[u8] {
89        &self.data
90    }
91}