From c83443d0b7ddf898a413a439a3d510c4e0b92196 Mon Sep 17 00:00:00 2001 From: Aleksey Yakovlev Date: Thu, 9 May 2024 13:56:46 +0700 Subject: [PATCH] added byte buffer impl --- src/cst/parser.rs | 1 - src/main.rs | 2 ++ src/rst/mod.rs | 1 + src/rst/node.rs | 1 + src/util/byte_buffer.rs | 72 +++++++++++++++++++++++++++++++++++++++++ src/util/mod.rs | 3 ++ 6 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 src/rst/mod.rs create mode 100644 src/rst/node.rs create mode 100644 src/util/byte_buffer.rs create mode 100644 src/util/mod.rs diff --git a/src/cst/parser.rs b/src/cst/parser.rs index ea135a0..66cdced 100644 --- a/src/cst/parser.rs +++ b/src/cst/parser.rs @@ -94,7 +94,6 @@ fn parse_constant(node: &AstNode) -> Result, +} + +impl ByteBuffer { + pub(crate) fn new() -> Self { + ByteBuffer { + inner: Vec::new() + } + } + + pub(crate) fn push_byte(&mut self, byte: u8) { + self.inner.push(byte); + } + + pub(crate) fn push_string(&mut self, string: String) { + self.inner.extend_from_slice(string.as_bytes()); + } + + pub(crate) fn push_u32(&mut self, num: u32) { + self.inner.extend_from_slice(num.to_be_bytes().as_slice()); + } + + pub(crate) fn len(&self) -> usize { + self.inner.len() + } + + pub(crate) fn as_vec(&self) -> Vec { + self.inner.clone() + } +} + +mod test { + use crate::util::ByteBuffer; + + #[test] + fn byte_push() { + let mut buffer = ByteBuffer::new(); + buffer.push_byte(0x01); + buffer.push_byte(0x02); + + assert_eq!(buffer.len(), 2); + + assert_eq!(buffer.as_vec(), vec![0x01, 0x02]); + } + + #[test] + fn string_push() { + let mut buffer = ByteBuffer::new(); + buffer.push_string("hello world".to_string()); + + assert_eq!(buffer.len(), 11); + + assert_eq!( + buffer.as_vec(), + vec![104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] + ); + } + + #[test] + fn u32_push() { + let mut buffer = ByteBuffer::new(); + buffer.push_u32(13); + + assert_eq!(buffer.len(), 4); + + assert_eq!( + buffer.as_vec(), + vec![0, 0, 0, 13] + ); + } +} diff --git a/src/util/mod.rs b/src/util/mod.rs new file mode 100644 index 0000000..fb9c0de --- /dev/null +++ b/src/util/mod.rs @@ -0,0 +1,3 @@ +mod byte_buffer; + +pub(crate) use byte_buffer::ByteBuffer; \ No newline at end of file