1use std::usize;
2
3use bytes::{Buf, BufMut, Bytes, BytesMut};
4use jt_util::bytes::{IBuffRead, IBuffWrite};
5
6#[derive(Debug)]
7pub struct JtBytesMut {
8 buf: BytesMut,
9 xor: u8,
10}
11impl IBuffWrite for JtBytesMut {
12 fn put_u8(&mut self, n: u8) {
13 self.xor ^= n;
14 self.put_u8_no_xor(n);
15 }
16}
17impl JtBytesMut {
18 pub fn with_capacity(capacity: usize) -> Self {
19 let mut buf = BytesMut::with_capacity(capacity);
20 buf.put_u8(0x7Eu8);
21 JtBytesMut { buf, xor: 0 }
22 }
23 pub fn end(&mut self) {
24 self.put_u8_no_xor(self.xor);
25 self.buf.put_u8(0x7Eu8);
26 }
27 fn put_u8_no_xor(&mut self, n: u8) {
28 if n == 0x7e {
29 self.buf.put_slice(&[0x7d, 0x02]);
30 } else if n == 0x7d {
31 self.buf.put_slice(&[0x7d, 0x01]);
32 } else {
33 self.buf.put_u8(n);
34 }
35 }
36 pub fn freeze(self) -> Bytes {
37 self.buf.freeze()
38 }
39}
40
41#[derive(Debug)]
42pub struct JtBytes {
43 buf: Bytes,
44}
45impl IBuffRead for JtBytes {
46 fn get_u64(&mut self) -> u64 {
47 self.buf.get_u64()
48 }
49
50 fn get_u16(&mut self) -> u16 {
51 self.buf.get_u16()
52 }
53
54 fn get_u8(&mut self) -> u8 {
55 self.buf.get_u8()
56 }
57 fn split_to(&mut self, at: usize) -> Bytes {
58 self.buf.split_to(at)
59 }
60 fn to_bytes(&mut self) -> Bytes {
61 self.buf.clone()
62 }
63
64 fn get_u32(&mut self) -> u32 {
65 self.buf.get_u32()
66 }
67
68 fn len(&self) -> usize {
69 self.buf.len()
70 }
71
72 fn get(&self, index: usize) -> Option<&u8> {
73 self.buf.get(index)
74 }
75}
76impl From<Bytes> for JtBytes {
77 fn from(bufold: Bytes) -> Self {
78 JtBytes { buf: bufold }
79 }
80}