1use core::ops::Index;
5
6pub struct JsonBuffer<const N: usize> {
11 buf: [u8; N],
12 len: usize,
13}
14
15impl<const N: usize> Default for JsonBuffer<N> {
16 fn default() -> Self {
17 Self::new()
18 }
19}
20
21impl<const N: usize> JsonBuffer<N> {
22 pub const fn new() -> Self {
24 Self {
25 buf: [0; N],
26 len: 0,
27 }
28 }
29
30 pub const fn len(&self) -> usize {
32 self.len
33 }
34
35 pub const fn capacity(&self) -> usize {
37 N
38 }
39
40 pub const fn is_empty(&self) -> bool {
42 self.len == 0
43 }
44
45 pub const fn push_byte(&mut self, byte: u8) {
47 assert!(self.len < N, "const_json buffer overflow");
48 self.buf[self.len] = byte;
49 self.len += 1;
50 }
51
52 pub const fn push_lit(&mut self, text: &str) {
54 let bytes = text.as_bytes();
55 let mut idx = 0;
56 let len = bytes.len();
57 while idx < len {
58 self.push_byte(bytes[idx]);
59 idx += 1;
60 }
61 }
62
63 pub const fn push_escaped(&mut self, value: &str) {
65 let bytes = value.as_bytes();
66 let mut idx = 0;
67 let len = bytes.len();
68 while idx < len {
69 let b = bytes[idx];
70 match b {
71 b'"' => {
72 self.push_byte(b'\\');
73 self.push_byte(b'"');
74 }
75 b'\\' => {
76 self.push_byte(b'\\');
77 self.push_byte(b'\\');
78 }
79 b'\n' => {
80 self.push_byte(b'\\');
81 self.push_byte(b'n');
82 }
83 b'\r' => {
84 self.push_byte(b'\\');
85 self.push_byte(b'r');
86 }
87 b'\t' => {
88 self.push_byte(b'\\');
89 self.push_byte(b't');
90 }
91 0x20..=0x7E => {
92 self.push_byte(b);
93 }
94 _ => {
95 self.push_byte(b'\\');
97 self.push_byte(b'u');
98 self.push_byte(b'0');
99 self.push_byte(b'0');
100 let hi = (b >> 4) & 0x0F;
101 let lo = b & 0x0F;
102 self.push_byte(hex_digit(hi));
103 self.push_byte(hex_digit(lo));
104 }
105 }
106 idx += 1;
107 }
108 }
109
110 pub const fn as_bytes(&self) -> &[u8] {
112 unsafe { core::slice::from_raw_parts(self.buf.as_ptr(), self.len) }
113 }
114
115 pub const fn as_str(&self) -> &str {
121 match core::str::from_utf8(self.as_bytes()) {
122 Ok(text) => text,
123 Err(_) => panic!("JsonBuffer::as_str called on non-UTF-8 buffer contents"),
124 }
125 }
126
127 pub const fn into_inner(self) -> ([u8; N], usize) {
129 (self.buf, self.len)
130 }
131
132 pub const fn clear(&mut self) {
134 self.len = 0;
135 }
136}
137
138impl<const N: usize> Index<usize> for JsonBuffer<N> {
139 type Output = u8;
140
141 fn index(&self, index: usize) -> &Self::Output {
142 &self.buf[index]
143 }
144}
145
146const fn hex_digit(nibble: u8) -> u8 {
147 match nibble {
148 0..=9 => b'0' + nibble,
149 10..=15 => b'a' + (nibble - 10),
150 _ => b'0',
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::JsonBuffer;
157
158 #[test]
159 #[should_panic(expected = "called on non-UTF-8 buffer contents")]
160 fn as_str_rejects_invalid_utf8() {
161 let mut buffer = JsonBuffer::<1>::new();
162 buffer.push_byte(0xff);
163 let _ = buffer.as_str();
164 }
165}