lib_ruby_parser_ast/
bytes.rs1#[derive(Debug, Clone, PartialEq, Eq)]
3#[repr(C)]
4pub struct Bytes {
5 pub raw: Vec<u8>,
7}
8
9impl Default for Bytes {
10 fn default() -> Self {
11 Self::new(vec![])
12 }
13}
14
15impl Bytes {
16 pub fn new(raw: Vec<u8>) -> Self {
18 Self { raw }
19 }
20
21 pub fn as_raw(&self) -> &Vec<u8> {
23 &self.raw
24 }
25
26 pub fn into_raw(self) -> Vec<u8> {
28 self.raw
29 }
30
31 pub fn set_raw(&mut self, raw: Vec<u8>) {
33 self.raw = raw
34 }
35
36 pub fn push(&mut self, item: u8) {
38 self.raw.push(item);
39 }
40
41 pub fn empty() -> Self {
43 Self::new(vec![])
44 }
45
46 pub fn as_str_lossy(&self) -> Result<&str, std::str::Utf8Error> {
48 std::str::from_utf8(self.as_raw())
49 }
50
51 pub fn to_string_lossy(&self) -> String {
53 String::from_utf8_lossy(self.as_raw()).into_owned()
54 }
55
56 pub fn to_string(&self) -> Result<String, std::string::FromUtf8Error> {
58 String::from_utf8(self.as_raw().to_vec())
59 }
60
61 pub fn into_string(self) -> Result<String, std::string::FromUtf8Error> {
63 String::from_utf8(self.into_raw())
64 }
65
66 pub fn is_valid_utf8(&self) -> bool {
68 std::str::from_utf8(self.as_raw()).is_ok()
69 }
70
71 pub fn is_empty(&self) -> bool {
73 self.as_raw().is_empty()
74 }
75
76 pub fn len(&self) -> usize {
78 self.as_raw().len()
79 }
80
81 pub fn clear(&mut self) {
83 self.set_raw(vec![])
84 }
85}
86
87impl std::ops::Index<usize> for Bytes {
88 type Output = u8;
89
90 fn index(&self, index: usize) -> &Self::Output {
91 self.raw.index(index)
92 }
93}
94
95#[test]
96fn test_new() {
97 let bytes = Bytes::new(vec![1, 2, 3]);
98 drop(bytes);
99}
100
101#[test]
102fn test_as_raw() {
103 let bytes = Bytes::new(vec![1, 2, 3]);
104
105 assert_eq!(bytes.as_raw(), &vec![1, 2, 3])
106}
107
108#[test]
109fn test_into_raw() {
110 let bytes = Bytes::new(vec![1, 2, 3]);
111
112 assert_eq!(bytes.into_raw(), vec![1, 2, 3])
113}
114
115#[test]
116fn test_set_raw() {
117 let mut bytes = Bytes::new(vec![1, 2, 3]);
118 bytes.set_raw(vec![4, 5, 6]);
119
120 assert_eq!(bytes.as_raw(), &vec![4, 5, 6])
121}
122
123#[test]
124fn test_push() {
125 let mut bytes = Bytes::default();
126 for i in 0..10 {
127 bytes.push(i);
128 }
129 assert_eq!(bytes.as_raw(), &vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
130}