sqlx_core_guts/mysql/io/
buf_mut.rs1use bytes::BufMut;
2
3pub trait MySqlBufMutExt: BufMut {
4 fn put_uint_lenenc(&mut self, v: u64);
5
6 fn put_str_lenenc(&mut self, v: &str);
7
8 fn put_bytes_lenenc(&mut self, v: &[u8]);
9}
10
11impl MySqlBufMutExt for Vec<u8> {
12 fn put_uint_lenenc(&mut self, v: u64) {
13 if v < 251 {
17 self.push(v as u8);
18 } else if v < 0x1_00_00 {
19 self.push(0xfc);
20 self.extend(&(v as u16).to_le_bytes());
21 } else if v < 0x1_00_00_00 {
22 self.push(0xfd);
23 self.extend(&(v as u32).to_le_bytes()[..3]);
24 } else {
25 self.push(0xfe);
26 self.extend(&v.to_le_bytes());
27 }
28 }
29
30 fn put_str_lenenc(&mut self, v: &str) {
31 self.put_bytes_lenenc(v.as_bytes());
32 }
33
34 fn put_bytes_lenenc(&mut self, v: &[u8]) {
35 self.put_uint_lenenc(v.len() as u64);
36 self.extend(v);
37 }
38}
39
40#[test]
41fn test_encodes_int_lenenc_u8() {
42 let mut buf = Vec::with_capacity(1024);
43 buf.put_uint_lenenc(0xFA as u64);
44
45 assert_eq!(&buf[..], b"\xFA");
46}
47
48#[test]
49fn test_encodes_int_lenenc_u16() {
50 let mut buf = Vec::with_capacity(1024);
51 buf.put_uint_lenenc(std::u16::MAX as u64);
52
53 assert_eq!(&buf[..], b"\xFC\xFF\xFF");
54}
55
56#[test]
57fn test_encodes_int_lenenc_u24() {
58 let mut buf = Vec::with_capacity(1024);
59 buf.put_uint_lenenc(0xFF_FF_FF as u64);
60
61 assert_eq!(&buf[..], b"\xFD\xFF\xFF\xFF");
62}
63
64#[test]
65fn test_encodes_int_lenenc_u64() {
66 let mut buf = Vec::with_capacity(1024);
67 buf.put_uint_lenenc(std::u64::MAX);
68
69 assert_eq!(&buf[..], b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF");
70}
71
72#[test]
73fn test_encodes_int_lenenc_fb() {
74 let mut buf = Vec::with_capacity(1024);
75 buf.put_uint_lenenc(0xFB as u64);
76
77 assert_eq!(&buf[..], b"\xFC\xFB\x00");
78}
79
80#[test]
81fn test_encodes_int_lenenc_fc() {
82 let mut buf = Vec::with_capacity(1024);
83 buf.put_uint_lenenc(0xFC as u64);
84
85 assert_eq!(&buf[..], b"\xFC\xFC\x00");
86}
87
88#[test]
89fn test_encodes_int_lenenc_fd() {
90 let mut buf = Vec::with_capacity(1024);
91 buf.put_uint_lenenc(0xFD as u64);
92
93 assert_eq!(&buf[..], b"\xFC\xFD\x00");
94}
95
96#[test]
97fn test_encodes_int_lenenc_fe() {
98 let mut buf = Vec::with_capacity(1024);
99 buf.put_uint_lenenc(0xFE as u64);
100
101 assert_eq!(&buf[..], b"\xFC\xFE\x00");
102}
103
104#[test]
105fn test_encodes_int_lenenc_ff() {
106 let mut buf = Vec::with_capacity(1024);
107 buf.put_uint_lenenc(0xFF as u64);
108
109 assert_eq!(&buf[..], b"\xFC\xFF\x00");
110}
111
112#[test]
113fn test_encodes_string_lenenc() {
114 let mut buf = Vec::with_capacity(1024);
115 buf.put_str_lenenc("random_string");
116
117 assert_eq!(&buf[..], b"\x0Drandom_string");
118}
119
120#[test]
121fn test_encodes_byte_lenenc() {
122 let mut buf = Vec::with_capacity(1024);
123 buf.put_bytes_lenenc(b"random_string");
124
125 assert_eq!(&buf[..], b"\x0Drandom_string");
126}