1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
use crate::error::{Error, ErrorCode, Result};
use crate::format::{Arbitrary, Binary, Character, Expression, Hex, Octal};
use arrayvec::ArrayVec;
use lexical_core::FormattedSize;
use lexical_core::NumberFormatBuilder;
const RESPONSE_DATA_SEPARATOR: u8 = b',';
const RESPONSE_HEADER_SEPARATOR: u8 = b' ';
const RESPONSE_MESSAGE_UNIT_SEPARATOR: u8 = b';';
const RESPONSE_MESSAGE_TERMINATOR: u8 = b'\n';
pub trait Data {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()>;
}
macro_rules! impl_non_decimal_data {
($prefix:literal, $name:ident, $radix:literal; $typ:ty) => {
impl Data for $name<$typ> {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
let mut buf = [b'0'; <$typ>::FORMATTED_SIZE];
const FORMAT: u128 = NumberFormatBuilder::from_radix($radix);
let options = lexical_core::WriteIntegerOptions::new();
let slc = lexical_core::write_with_options::<_, FORMAT>(self.0, &mut buf, &options);
formatter.push_str($prefix)?;
formatter.push_str(slc)
}
}
};
}
macro_rules! impl_integer {
($typ:ty) => {
impl Data for $typ {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
let mut buf = [b'0'; <$typ>::FORMATTED_SIZE_DECIMAL];
let slc = lexical_core::write::<$typ>(*self, &mut buf);
formatter.push_str(slc)
}
}
impl_non_decimal_data!(b"#H", Hex, 16; $typ);
impl_non_decimal_data!(b"#Q", Octal, 8; $typ);
impl_non_decimal_data!(b"#B", Binary, 2; $typ);
};
}
impl_integer!(u8);
impl_integer!(i8);
impl_integer!(u16);
impl_integer!(i16);
impl_integer!(u32);
impl_integer!(i32);
impl_integer!(u64);
impl_integer!(i64);
impl_integer!(isize);
impl_integer!(usize);
macro_rules! impl_real {
($typ:ty) => {
impl Data for $typ {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
if self.is_nan() {
formatter.push_str(b"9.91E+37")
} else if self.is_infinite() {
if self.is_sign_negative() {
formatter.push_str(b"-9.9E+37")
} else {
formatter.push_str(b"9.9E+37")
}
} else {
let mut buf = [b'0'; <$typ>::FORMATTED_SIZE_DECIMAL];
let slc = lexical_core::write::<$typ>(*self, &mut buf);
formatter.push_str(slc)
}
}
}
};
}
impl_real!(f32);
impl_real!(f64);
impl Data for bool {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
if *self {
formatter.push_byte(b'1')
} else {
formatter.push_byte(b'0')
}
}
}
impl<'a> Data for Arbitrary<'a> {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
let mut buf = [0u8; usize::FORMATTED_SIZE_DECIMAL];
let slc = lexical_core::write::<usize>(self.0.len(), &mut buf);
if slc.len() > 9 {
Err(ErrorCode::ExecutionError.into())
} else {
formatter.push_byte(b'#')?;
slc.len().format_response_data(formatter)?;
formatter.push_str(slc)?;
formatter.push_str(self.0)
}
}
}
impl<'a> Data for Character<'a> {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
formatter.push_ascii(self.0)
}
}
impl<'a> Data for Expression<'a> {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
formatter.push_byte(b'(')?;
formatter.push_ascii(self.0)?;
formatter.push_byte(b')')
}
}
impl<'a> Data for &'a str {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
Arbitrary(self.as_bytes()).format_response_data(formatter)
}
}
impl<'a> Data for &'a [u8] {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
if !self.is_ascii() {
Err(ErrorCode::ExecutionError.into())
} else {
let mut first = true;
formatter.push_byte(b'"')?;
for ss in self.split(|x| *x == b'"') {
if !first {
formatter.push_str(br#""""#)?;
}
formatter.push_ascii(ss)?;
first = false;
}
formatter.push_byte(b'"')
}
}
}
impl Data for Error {
fn format_response_data(&self, formatter: &mut dyn Formatter) -> Result<()> {
self.get_code().format_response_data(formatter)?;
formatter.data_separator()?;
#[cfg(feature = "extended-error")]
{
if let Some(ext) = self.get_extended() {
formatter.push_byte(b'"')?;
formatter.push_str(self.get_message())?;
formatter.push_byte(b';')?;
formatter.push_str(ext)?;
formatter.push_byte(b'"')
} else {
self.get_message().format_response_data(formatter)
}
}
#[cfg(not(feature = "extended-error"))]
{
self.get_message().format_response_data(formatter)
}
}
}
pub trait Formatter {
fn push_str(&mut self, s: &[u8]) -> Result<()>;
fn push_ascii(&mut self, s: &[u8]) -> Result<()> {
debug_assert!(s.is_ascii());
self.push_str(s)
}
fn push_byte(&mut self, b: u8) -> Result<()>;
fn as_slice(&self) -> &[u8];
fn clear(&mut self);
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn message_start(&mut self) -> Result<()>;
fn message_end(&mut self) -> Result<()>;
fn data_separator(&mut self) -> Result<()> {
self.push_byte(RESPONSE_DATA_SEPARATOR)
}
fn header_separator(&mut self) -> Result<()> {
self.push_byte(RESPONSE_HEADER_SEPARATOR)
}
fn response_unit(&mut self) -> Result<ResponseUnit>;
}
pub struct ResponseUnit<'a> {
fmt: &'a mut dyn Formatter,
result: Result<()>,
has_header: bool,
has_data: bool,
}
impl<'a> ResponseUnit<'a> {
pub fn header(&mut self, header: &[u8]) -> &mut Self {
debug_assert!(!self.has_data, "Tried to put header after data");
self.result = self.result.and_then(|_| {
if self.has_header {
self.fmt.push_byte(b':')?;
}
self.fmt.push_str(header)
});
self.has_header = true;
self
}
pub fn data<U>(&mut self, data: U) -> &mut Self
where
U: Data,
{
self.result = self.result.and_then(|_| {
if self.has_data {
self.fmt.data_separator()?;
} else if self.has_header {
self.fmt.header_separator()?;
}
data.format_response_data(self.fmt)
});
self.has_data = true;
self
}
pub fn finish(&mut self) -> Result<()> {
self.result
}
}
pub struct ArrayVecFormatter<const CAP: usize> {
vec: ArrayVec<u8, CAP>,
pub(crate) has_units: bool,
}
impl<const CAP: usize> Default for ArrayVecFormatter<CAP> {
fn default() -> Self {
ArrayVecFormatter {
vec: ArrayVec::<u8, CAP>::new(),
has_units: false,
}
}
}
impl<const CAP: usize> ArrayVecFormatter<CAP> {
pub fn new() -> Self {
ArrayVecFormatter::default()
}
}
impl<const CAP: usize> Formatter for ArrayVecFormatter<CAP> {
fn push_str(&mut self, s: &[u8]) -> Result<()> {
self.vec
.try_extend_from_slice(s)
.map_err(|_| ErrorCode::OutOfMemory.into())
}
fn push_byte(&mut self, b: u8) -> Result<()> {
self.vec
.try_push(b)
.map_err(|_| ErrorCode::OutOfMemory.into())
}
fn as_slice(&self) -> &[u8] {
self.vec.as_slice()
}
fn clear(&mut self) {
self.vec.clear();
}
fn len(&self) -> usize {
self.vec.len()
}
fn message_start(&mut self) -> Result<()> {
self.has_units = false;
Ok(())
}
fn message_end(&mut self) -> Result<()> {
self.push_byte(RESPONSE_MESSAGE_TERMINATOR)
}
fn response_unit(&mut self) -> Result<ResponseUnit> {
if self.has_units {
self.push_byte(RESPONSE_MESSAGE_UNIT_SEPARATOR)?;
}
self.has_units = true;
Ok(ResponseUnit {
fmt: self,
result: Ok(()),
has_header: false,
has_data: false,
})
}
}
#[test]
fn test_vecarray() {
let mut array = ArrayVecFormatter::<16>::new();
array.message_start().unwrap();
array
.response_unit()
.unwrap()
.data(&b"potato"[..])
.data(0u8)
.finish()
.unwrap();
array.response_unit().unwrap().data(42i16).finish().unwrap();
array.message_end().unwrap();
assert_eq!(array.as_slice(), b"\"potato\",0;42\n");
}
#[test]
fn test_outamemory() {
let mut array = ArrayVecFormatter::<1>::new();
array.push_byte(b'x').unwrap();
assert_eq!(
array.push_byte(b'x'),
Err(Error::from(ErrorCode::OutOfMemory))
);
assert_eq!(
array.push_str(b"x"),
Err(Error::from(ErrorCode::OutOfMemory))
);
}
#[test]
fn test_f32() {
let mut array = ArrayVecFormatter::<32>::new();
f32::INFINITY.format_response_data(&mut array).unwrap();
array.data_separator().unwrap();
f32::NEG_INFINITY.format_response_data(&mut array).unwrap();
array.data_separator().unwrap();
f32::NAN.format_response_data(&mut array).unwrap();
assert_eq!(array.as_slice(), b"9.9E+37,-9.9E+37,9.91E+37");
}