lil_json/
lib.rs

1#![no_std]
2
3use core::{fmt::{Debug, Display, Formatter, Write as CoreFmtWrite}, str::Chars};
4use embedded_io::{ErrorType, Write};
5use numtoa::base10;
6
7#[cfg(feature = "alloc")]
8extern crate elsa;
9#[cfg(feature = "alloc")]
10use elsa::FrozenVec;
11
12const UNICODE_HIGH_SURROGATE_RANGE: core::ops::Range<u16> = 0xD800..0xDBFF;
13const UNICODE_LOW_SURROGATE_RANGE: core::ops::Range<u16> = 0xDC00..0xDFFF;
14
15/// a buffer for an growable string escape buffer. enabled with `alloc` feature.
16#[cfg(feature = "alloc")]
17pub type AllocEscapeBuffer = FrozenVec<String>;
18
19/// trait for types that JSON can be serialized into. mainly meant for internal usage.
20pub trait StringWrite {
21    type StringWriteFailure: Debug;
22    fn write_char(&mut self, data: char, bytes_to_skip: usize) -> Result<usize,(usize,Self::StringWriteFailure)>;
23}
24
25impl<T: Write + ErrorType> StringWrite for T {
26    type StringWriteFailure = T::Error;
27    fn write_char(&mut self, data: char, resume_from: usize) -> Result<usize,(usize,Self::StringWriteFailure)> {
28        debug_assert!(resume_from <= 4);
29        let mut str_buffer = [0_u8; 4];
30        let encoded_string = data.encode_utf8(str_buffer.as_mut_slice()).as_bytes();
31        let to_skip = core::cmp::min(encoded_string.len(), resume_from);
32        let target = encoded_string.split_at(to_skip).1;
33        if target.is_empty() {
34            return Ok(0);
35        }
36        match self.write_all(target) {
37            Ok(()) => Ok(target.len() + to_skip),
38            Err(e) => Err((0,e))
39        }
40    }
41}
42
43struct FormatWrapper<T: ?Sized> {
44    inner: T,
45}
46
47impl<T> FormatWrapper<T> {
48    fn new(inner: T) -> Self {
49        FormatWrapper { inner }
50    }
51}
52
53impl<'a> StringWrite for FormatWrapper<&mut Formatter<'a>> {
54    type StringWriteFailure = core::fmt::Error;
55    fn write_char(&mut self, data: char, bytes_to_skip: usize) -> Result<usize,(usize,Self::StringWriteFailure)> {
56        assert!(bytes_to_skip == 0);
57        let mut encoding_buffer = [0_u8; 4];
58        let n = data.encode_utf8(encoding_buffer.as_mut_slice()).len();
59        match self.inner.write_char(data) {
60            Ok(()) => Ok(n),
61            Err(e) => Err((0,e))
62        }
63    }
64}
65
66/// trait for an optionally mutable collection of JSON array values
67pub trait ValueBuffer<'a>: AsRef<[JsonValue<'a>]> {
68
69    /// convenience one-liner to call JsonArray::wrap_init on this Sized type, consuming it
70    fn into_json_array(self) -> JsonArray<Self> where Self: Sized {
71        JsonArray::wrap_init(self)
72    }
73    
74    /// convenience one-liner to call JsonArray::wrap_init on an immutable reference to this type
75    fn as_json_array(&self) -> JsonArray<&Self> {
76        JsonArray::wrap_init(self)
77    }
78
79}
80
81/// ValueBuffer is automatically implemented for all types that implement AsRef<[JsonField<'data,'data>]>
82impl <'a,T: AsRef<[JsonValue<'a>]>> ValueBuffer<'a> for T {}
83
84
85/// trait for a mutable collection of JSON array values
86pub trait ValueBufferMut<'a>: ValueBuffer<'a> +  AsMut<[JsonValue<'a>]> {
87
88    /// convenience one-liner to call JsonObject::wrap_init on a mutable reference to this type
89    fn as_json_array_mut(&mut self) -> JsonArray<&mut Self> {
90        JsonArray::wrap_init(self)
91    }
92}
93
94/// ValueBufferMut is automatically implemented for all types that implement FieldBuffer + AsMut<[JsonField<'data,'data>]>
95impl <'a,T: ValueBuffer<'a> + AsMut<[JsonValue<'a>]>> ValueBufferMut<'a> for T {}
96
97
98/// trait for all optionally mutable collection of JSON object fields
99pub trait FieldBuffer<'data>: AsRef<[JsonField<'data,'data>]> {
100
101    /// convenience one-liner to call JsonObject::wrap_init on this Sized type, moving it
102    fn into_json_object(self) -> JsonObject<Self> where Self: Sized {
103        JsonObject::wrap_init(self)
104    }
105    
106    /// convenience one-liner to call JsonObject::wrap_init on an immutable reference to this type
107    fn as_json_object(&self) -> JsonObject<&Self> {
108        JsonObject::wrap_init(self)
109    }
110
111}
112
113/// FieldBuffer is automatically implemented for all types that implement AsRef<[JsonField<'data,'data>]>
114impl <'a,T: AsRef<[JsonField<'a,'a>]>> FieldBuffer<'a> for T {}
115
116/// trait for a mutable collection of JSON object fields
117pub trait FieldBufferMut<'a>: FieldBuffer<'a> +  AsMut<[JsonField<'a,'a>]> {
118
119    /// convenience one-liner to call JsonObject::wrap_init on a mutable reference to this type
120    fn as_json_object_mut(&mut self) -> JsonObject<&mut Self> {
121        JsonObject::wrap_init(self)
122    }
123
124}
125
126/// FieldBufferMut is automatically implemented for all types that implement FieldBuffer + AsMut<[JsonField<'data,'data>]>
127impl <'a,T: FieldBuffer<'a> + AsMut<[JsonField<'a,'a>]>> FieldBufferMut<'a> for T {}
128
129/// the various reasons parsing JSON can fail
130#[derive(Debug,PartialEq,Eq,Clone,Copy)]
131pub enum JsonParseFailure {
132    /// there was no error, but the data slice is incomplete
133    Incomplete,
134    /// there was no error, but there were more fields than the provided field buffer could hold
135    FieldBufferTooSmall,
136    /// there was no error, but there were more fields than the provided string escape buffer could hold
137    EscapeBufferTooSmall,
138    /// there was an error in the JSON structure of the data
139    InvalidStructure,
140    /// an invalid JSON string was encountered
141    InvalidStringField,
142    /// an invalid JSON number was encountered
143    InvalidNumericField,
144    /// a valid JSON number was encountered but we failed to interpret it
145    NumberParseError,
146    /// an invalid JSON boolean was encountered
147    InvalidBooleanField,
148    /// an invalid JSON null was encountered
149    InvalidNullField,
150}
151
152/// terminal (non-nested) JSON types
153#[derive(Debug,PartialEq,Eq,Clone,Copy)]
154pub enum JsonValue<'a> {
155    /// a JSON string - it will be automatically escaped
156    String(&'a str),
157    /// a JSON boolean
158    Boolean(bool),
159    /// a JSON number
160    Number(i64),
161    /// a JSON null value
162    Null,
163}
164
165impl <'a> JsonValue<'a> {
166    pub fn parse(data: &'a [u8], escape_buffer_slice: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
167        let mut escape_buffer = StringBuffer::Finite(0, escape_buffer_slice);
168        let mut current_data_index = 0_usize;
169        skip_whitespace(&mut current_data_index, data)?;
170        // let first_character = data[current_data_index];
171        let value = if data[current_data_index] == b'"' {
172                let unescaped_string_value = unescape_json_string(&mut current_data_index, data, &mut escape_buffer)?;
173                JsonValue::String(unescaped_string_value)
174            } else if data[current_data_index] == b'n' {
175                skip_literal(&mut current_data_index, data, "null", JsonParseFailure::InvalidBooleanField)?;
176                JsonValue::Null
177            } else if data[current_data_index] == b't' || data[current_data_index] == b'f' {
178                let expect_true = data[current_data_index] == b't';
179                skip_literal(&mut current_data_index, data, if expect_true { "true" } else { "false"}, JsonParseFailure::InvalidBooleanField)?;
180                JsonValue::Boolean(expect_true)
181            } else if data[current_data_index] == b'-' {
182                // negative number
183                let minus_sign_numeric_start_index = current_data_index;
184                current_data_index += 1;
185                skip_numeric(&mut current_data_index, data)?;
186                let minus_sign_numeric_end = current_data_index;
187                if minus_sign_numeric_end - minus_sign_numeric_start_index == 1 {
188                    // no digits found
189                    return Err(JsonParseFailure::InvalidNumericField);
190                }
191                let numeric_string = core::str::from_utf8(&data[minus_sign_numeric_start_index..minus_sign_numeric_end]).expect("skipped negative number digit(s)");
192                let numeric_value: i64 = match numeric_string.parse() {
193                    Ok(i) => i,
194                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
195                };
196                JsonValue::Number(numeric_value)
197            } else if data[current_data_index] >= b'0' && data[current_data_index] < b'9' {
198                // positive number
199                let numeric_start_index = current_data_index;
200                current_data_index += 1;
201                skip_numeric(&mut current_data_index, data)?;
202                let numeric_after_index = current_data_index;
203                let numeric_string = core::str::from_utf8(&data[numeric_start_index..numeric_after_index]).expect("skipped positive number digit(s)");
204                let numeric_value: i64 = match numeric_string.parse() {
205                    Ok(i) => i,
206                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
207                };
208                JsonValue::Number(numeric_value)
209            } else {
210                return Err(JsonParseFailure::InvalidStructure);
211            };
212            Ok((current_data_index,value))
213    }
214}
215
216impl<'a> Default for JsonValue<'a> {
217    fn default() -> Self { JsonValue::Null }
218}
219
220impl From<i64> for JsonValue<'static> {
221    fn from(n: i64) -> Self {
222        Self::Number(n)
223    }
224}
225
226impl From<bool> for JsonValue<'static> {
227    fn from(b: bool) -> Self {
228        Self::Boolean(b)
229    }
230}
231
232impl From<()> for JsonValue<'static> {
233    fn from(_: ()) -> Self {
234        Self::Null
235    }
236}
237
238impl<'a> From<&'a str> for JsonValue<'a> {
239    fn from(s: &'a str) -> Self {
240        Self::String(s)
241    }
242}
243
244/// a default JSON value with static lifetime. equivalent to `JsonValue::Null`.
245pub const EMPTY_VALUE: JsonValue<'static> = JsonValue::Null;
246
247/// a field within a JSON object
248#[derive(Debug,PartialEq,Eq,Clone,Copy)]
249pub struct JsonField<'a,'b> {
250    pub key: &'a str,
251    pub value: JsonValue<'b>,
252}
253
254impl <'a,'b> JsonField<'a,'b> {
255    /// create a new JSON object field with the given key & value
256    pub const fn new(key: &'a str, value: JsonValue<'b>) -> Self {
257        JsonField { key, value }
258    }
259
260    /// convenience helper to get the json field as a (key,value) tuple
261    pub const fn from_tuple(tuple: (&'a str, JsonValue<'b>)) -> Self {
262        Self::new(tuple.0, tuple.1)
263    }
264
265    /// convenience helper to get the json field as a (key,value) tuple
266    pub const fn as_tuple(&self) -> (&'a str, JsonValue<'b>) {
267        (self.key, self.value)
268    }
269
270    /// convenience helper to create a new JSON object string field
271    pub const fn new_string(key: &'a str, value: &'b str) -> Self {
272        Self::new(key, JsonValue::String(value))
273    }
274    /// convenience helper to create a new JSON object number field
275    pub const fn new_number(key: &'a str, value: i64) -> Self {
276        Self::new(key, JsonValue::Number(value))
277    }
278    /// convenience helper to create a new JSON object boolean field
279    pub const fn new_boolean(key: &'a str, value: bool) -> Self {
280        Self::new(key, JsonValue::Boolean(value))
281    }
282}
283
284/// two JsonObjects are equal if their initialized fields are identical (in the same order)
285impl<'a,T: FieldBuffer<'a>> PartialEq for JsonObject<T> {
286    fn eq(&self, other: &JsonObject<T>) -> bool {
287        self.num_fields == other.num_fields && PartialEq::eq(self.fields.as_ref(), other.fields.as_ref())
288    }
289}
290
291/// PartialEq for JsonObject is reflexive
292impl<'a,T: FieldBuffer<'a>> Eq for JsonObject<T> {}
293
294/// a default JSON field with static lifetime. equivalent to `JsonField::new("", JsonValue::Null)`
295pub const EMPTY_FIELD: JsonField<'static,'static> = JsonField{ key: "", value: JsonValue::Null};
296
297impl <'a,'b,V: Into<JsonValue<'b>>> From<(&'a str, V)> for JsonField<'a,'b> {
298    fn from(tuple: (&'a str, V)) -> Self {
299        Self::new(tuple.0, tuple.1.into())
300    }
301}
302
303impl <'a,'b> Default for JsonField<'a,'b> {
304    fn default() -> Self {
305        EMPTY_FIELD
306    }
307}
308
309/// JsonObject represents an RFC 8259 JSON Array. It wraps a mutable or immutable buffer of JSON values.  The easiest way to use it is through the ArrayJsonArray type alias, however you can use JsonArray directly to wrap your own buffer like a heap allocated Vec.
310#[derive(Debug,Clone,Copy)]
311pub struct JsonArray<Values> {
312    values: Values,
313    num_values: usize,
314}
315
316impl<T> JsonArray<T> {
317    /// consume this JsonObject to return (field buffer, num fields considered initialized)
318    pub fn into_inner(self) -> (T,usize) {
319        (self.values,self.num_values)
320    }
321}
322
323impl<'a,T: FieldBuffer<'a> + Default + ?Sized> Default for JsonArray<T> {
324    fn default() -> Self {
325        JsonArray { values: T::default(), num_values: 0 }
326    }
327}
328
329impl <'a,T: ValueBuffer<'a>> JsonArray<T> {
330
331    /// wrap a collection of values into a JsonArray and considers none of the values to be initialized
332    pub const fn wrap(values: T) -> Self {
333        JsonArray { values, num_values: 0 }
334    }
335
336    /// wrap a collection of fields into a JsonObject and considers all of the fields to be initialized
337    pub fn wrap_init(values: T) -> Self {
338        let num_values = values.as_ref().len();
339        JsonArray { values, num_values }
340    }
341
342    /// get the number of initialized values in this JsonArray. Same as self.values().len()
343    pub const fn len(&self) -> usize {
344        self.num_values
345    }
346
347    /// get the max number of values this JsonArray can store
348    pub fn capacity(&self) -> usize {
349        self.values.as_ref().len()
350    }
351
352    /// get an immutable reference to the initialized values of this JsonArray
353    pub fn values(&self) -> &[JsonValue<'a>] {
354        self.values.as_ref().split_at(self.num_values).0
355    }
356
357    /// attempt to serialize this JsonArray into the provided output & returns the number of bytes written on success
358    pub fn serialize<Output: Write>(&self, mut output: Output) -> Result<usize,Output::Error> {
359        match serialize_json_array(&mut output, self.values().as_ref(), 0) {
360            Ok(n) => Ok(n),
361            Err((_written,e)) => Err(e),
362        }
363    }
364
365    /// attempt to serialize this JsonArray into the provided output starting from `resume_from` & returns the number of bytes written on both success & failure
366    pub fn serialize_resume<Output: Write>(&self, mut output: Output, resume_from: usize) -> Result<usize,(usize,Output::Error)> {
367        serialize_json_array(&mut output, self.values().as_ref(), resume_from)
368    }
369
370}
371
372impl <'a,T: ValueBufferMut<'a>> JsonArray<T> {
373    
374    /// get a mutable reference to the initialized fields of this JsonObject
375    pub fn values_mut(&mut self) -> &mut [JsonValue<'a>] {
376        self.values.as_mut().split_at_mut(self.num_values).0
377    }
378
379    /// attempt to push a new field - fails if there is not enough space
380    pub fn push<V: Into<JsonValue<'a>>>(&mut self, value: V) -> Result<(),()> {
381        if self.num_values == self.values.as_ref().len(){
382            return Err(());
383        }
384        self.values.as_mut()[self.num_values] = value.into();
385        self.num_values += 1;
386        Ok(())
387    }
388
389    /// attempt to pop an existing value - returns None if there are no initialized values
390    pub fn pop(&mut self) -> Option<JsonValue<'a>> {
391        if self.num_values == 0 {
392            return None;
393        }
394        self.num_values -= 1;
395        Some(core::mem::take(&mut self.values.as_mut()[self.num_values+1]))
396    }
397
398    /// attempt to parse a JSON object from the provided data slice and write its fields into this JsonObject - returns a tuple of (num bytes consumed, num fields parsed) on success
399    pub fn parse(&mut self, data: &'a [u8], string_escape_buffer: &'a mut [u8]) -> Result<usize,JsonParseFailure> {
400        let (data_end, parsed_fields) = parse_json_array(
401            data,
402            ParseBuffer::Finite(0, self.values.as_mut()),
403            &mut StringBuffer::Finite(0, string_escape_buffer),
404        )?;
405        let new_num_fields = parsed_fields;
406        self.num_values = new_num_fields;
407        Ok(data_end)
408    }
409
410}
411
412impl <'a,T: ValueBuffer<'a>> Display for JsonArray<T> {
413    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
414        match serialize_json_array(
415            &mut FormatWrapper::new(fmt),
416            self.values.as_ref(),
417            0,
418        ) {
419            Ok(_) => Ok(()),
420            Err((_written,e)) => Err(e),
421        }
422    }
423}
424
425/// ArrayJsonObject is a type alias for a JsonObject that wraps an array. It has extra functionality when compared to any other type of JsonObject.
426pub type ArrayJsonArray<'a,const N: usize> = JsonArray<[JsonValue<'a>; N]>;
427
428impl<'a,const N: usize> ArrayJsonArray<'a,N> {
429    
430    /// convenience method to initialize a new array & call JsonObject::wrap on it
431    pub const fn new() -> Self {
432        JsonArray::wrap([JsonValue::Null; N])
433    }
434
435    /// convenience method to automatically create an ArrayJsonObject if object parsing is successful
436    // pub fn new_parsed(data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
437    //     let mut ret = Self::new();
438    //     let data_end = ret.parse(data, escape_buffer)?;
439    //     Ok((data_end,ret))
440    // }
441
442    /// similar to JsonObject::push but supports const contexts & only returns a reference
443    pub const fn push_const(&mut self, value: JsonValue<'a>) -> Result<(),()> {
444        if self.num_values == N {
445            return Err(());
446        }
447        self.values[self.num_values] = value;
448        self.num_values += 1;
449        Ok(())
450    }
451
452    /// similar to JsonObject::pop but supports const contexts
453    pub const fn pop_const(&mut self) -> Option<&JsonValue<'a>> {
454        match self.values_const().split_last() {
455            None => return None,
456            Some((split,_remaining)) => return Some(split),
457        }
458    }
459
460    /// same as JsonObject::fields but supports const contexts
461    pub const fn values_const(&self) -> &[JsonValue<'a>] {
462        self.values.split_at(self.num_values).0
463    }
464
465    /// same as JsonObject::fields_mut but supports const contexts
466    pub const fn values_mut_const(&mut self) -> &mut [JsonValue<'a>] {
467        self.values.split_at_mut(self.num_values).0
468    }
469}
470
471
472/// JsonObject represents an RFC 8259 JSON Object. It wraps a mutable or immutable buffer of object fields. The easiest way to use it is through the ArrayJsonObject type alias, however you can use JsonObject directly to wrap your own buffer like a heap allocated Vec
473#[derive(Debug,Clone,Copy)]
474pub struct JsonObject<Fields> {
475    fields: Fields,
476    num_fields: usize,
477}
478
479impl<T> JsonObject<T> {
480    /// consume this JsonObject to return (field buffer, num fields considered initialized)
481    pub fn into_inner(self) -> (T,usize) {
482        (self.fields,self.num_fields)
483    }
484}
485
486impl<'a,T: FieldBuffer<'a> + Default + ?Sized> Default for JsonObject<T> {
487    fn default() -> Self {
488        JsonObject::wrap(T::default())
489    }
490}
491
492impl <'a,T: FieldBuffer<'a>> JsonObject<T> {
493
494    /// wrap a collection of fields into a JsonObject and considers none of the fields to be initialized
495    pub const fn wrap(fields: T) -> Self {
496        JsonObject { fields, num_fields: 0 }
497    }
498
499    /// wrap a collection of fields into a JsonObject and considers all of the fields to be initialized
500    pub fn wrap_init(fields: T) -> Self {
501        let num_fields = fields.as_ref().len();
502        JsonObject { fields, num_fields }
503    }
504
505    /// get the number of initialized fields in this JsonObject. Same as self.fields().len().
506    pub const fn len(&self) -> usize {
507        self.num_fields
508    }
509
510    /// get the max number of fields this JsonObject can store.
511    pub fn capacity(&self) -> usize {
512        self.fields.as_ref().len()
513    }
514
515    /// get an immutable reference to the initialized fields of this JsonObject
516    pub fn fields(&self) -> &[JsonField<'a,'a>] {
517        self.fields.as_ref().split_at(self.num_fields).0
518    }
519
520    /// attempt to serialize this JsonObject into the provided output & returns the number of bytes written on success
521    pub fn serialize<Output: Write>(&self, mut output: Output) -> Result<usize,Output::Error> {
522        match serialize_json_object(&mut output, self.fields().as_ref(), 0) {
523            Ok(n) => Ok(n),
524            Err((_written,e)) => Err(e),
525        }
526    }
527
528    /// attempt to serialize this JsonObject into the provided output starting from `resume_from` & returns the number of bytes written on both success & failure
529    pub fn serialize_resume<Output: Write>(&self, mut output: Output, resume_from: usize) -> Result<usize,(usize,Output::Error)> {
530        serialize_json_object(&mut output, self.fields().as_ref(), resume_from)
531    }
532}
533
534impl <'a,T: FieldBuffer<'a>> Display for JsonObject<T> {
535    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
536        match serialize_json_object(
537            &mut FormatWrapper::new(fmt),
538            self.fields.as_ref().split_at(self.num_fields).0,
539            0
540        ) {
541            Ok(_) => Ok(()),
542            Err((_written,e)) => Err(e),
543        }
544    }
545}
546
547impl <'a,T: FieldBuffer<'a>> From<T> for JsonObject<T> {
548    fn from(t: T) -> Self {
549        Self::wrap_init(t)
550    }
551}
552
553impl <'a,T: FieldBufferMut<'a>> JsonObject<T> {
554
555    /// get a mutable reference to the initialized fields of this JsonObject
556    pub fn fields_mut(&mut self) -> &mut [JsonField<'a,'a>] {
557        self.fields.as_mut().split_at_mut(self.num_fields).0
558    }
559
560    /// attempt to push a new field - returns the field if there is not enough space
561    pub fn push<'x: 'a,'y: 'a>(&mut self, field: JsonField<'x,'y>) -> Result<(),JsonField<'x,'y>> {
562        if self.num_fields == self.fields.as_ref().len(){
563            return Err(field);
564        }
565        self.fields.as_mut()[self.num_fields] = field;
566        self.num_fields += 1;
567        Ok(())
568    }
569
570    /// attempt to pop an existing field - returns None if there are no initialized fields
571    pub fn pop(&mut self) -> Option<JsonField<'a,'a>> {
572        if self.num_fields == 0 {
573            return None;
574        }
575        self.num_fields -= 1;
576        Some(core::mem::take(&mut self.fields.as_mut()[self.num_fields+1]))
577    }
578
579    /// convenience helper to create and push a new field
580    pub fn push_field<'x: 'a,'y: 'a>(&mut self, key: &'x str, value: JsonValue<'y>) -> Result<(),()> {
581        if self.num_fields == self.fields.as_ref().len(){
582            return Err(());
583        }
584        self.fields.as_mut()[self.num_fields] = JsonField { key, value };
585        self.num_fields += 1;
586        Ok(())
587    }
588
589    /// attempt to parse a JSON object from the provided data slice and write its fields into this JsonObject - returns a tuple of (num bytes consumed, num fields parsed) on success
590    pub fn parse(&mut self, data: &'a [u8], string_escape_buffer: &'a mut [u8]) -> Result<usize,JsonParseFailure> {
591        let (data_end, parsed_fields) = parse_json_object(
592            data,
593            ParseBuffer::Finite(0, self.fields.as_mut()),
594            &mut StringBuffer::Finite(0, string_escape_buffer),
595        )?;
596        let new_num_fields = parsed_fields;
597        self.num_fields = new_num_fields;
598        Ok(data_end)
599    }
600
601}
602
603impl <'a,T: FieldBufferMut<'a> + Default> JsonObject<T> {
604
605    /// convenience method to automatically create a JsonObject if object parsing is successful
606    pub fn default_parsed(data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
607        let mut ret = Self::default();
608        let num_bytes = ret.parse(data, escape_buffer)?;
609        Ok((num_bytes,ret))
610    }
611
612}
613
614
615/// ArrayJsonObject is a type alias for a JsonObject that wraps an array. It has extra functionality when compared to any other type of JsonObject.
616pub type ArrayJsonObject<'a,const N: usize> = JsonObject<[JsonField<'a,'a>; N]>;
617
618impl<'a,const N: usize> ArrayJsonObject<'a,N> {
619
620    /// convenience method to initialize a new array & call JsonObject::wrap on it
621    pub const fn new() -> Self {
622        JsonObject::wrap([EMPTY_FIELD; N])
623    }
624
625    /// convenience method to automatically create an ArrayJsonObject if object parsing is successful
626    pub fn new_parsed(data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
627        let mut ret = Self::new();
628        let data_end = ret.parse(data, escape_buffer)?;
629        Ok((data_end,ret))
630    }
631
632    /// similar to JsonObject::push but supports const contexts & only returns a reference
633    pub const fn push_const(&mut self, key: &'a str, value: JsonValue<'a>) -> Result<(),()> {
634        if self.num_fields == N {
635            return Err(());
636        }
637        self.fields[self.num_fields] = JsonField { key, value: value };
638        self.num_fields += 1;
639        Ok(())
640    }
641
642    /// similar to JsonObject::pop but supports const contexts
643    pub const fn pop_const(&mut self) -> Option<&JsonField<'a,'a>> {
644        match self.fields_const().split_last() {
645            None => return None,
646            Some((split,_remaining)) => return Some(split),
647        }
648    }
649
650    /// same as JsonObject::fields but supports const contexts
651    pub const fn fields_const(&self) -> &[JsonField<'a,'a>] {
652        self.fields.split_at(self.num_fields).0
653    }
654
655    /// same as JsonObject::fields_mut but supports const contexts
656    pub const fn fields_mut_const(&mut self) -> &mut [JsonField<'a,'a>] {
657        self.fields.split_at_mut(self.num_fields).0
658    }
659
660}
661
662#[cfg(feature = "alloc")]
663extern crate alloc;
664#[cfg(feature = "alloc")]
665use alloc::{string::String, vec::Vec};
666
667/// a buffer that any sized type can be written to. `ParseBuffer::Infinite` is only available with the `alloc` feature enabled.
668pub enum ParseBuffer<'a,T> {
669    /// a finite buffer of T
670    Finite(usize, &'a mut [T]),
671    /// an infinite buffer of T
672    #[cfg(feature = "alloc")]
673    Infinite(usize,&'a mut Vec<T>)
674}
675
676impl<'a,T> ParseBuffer<'a,T> {
677
678    fn write_thing(&mut self, thing: T) -> Result<(),JsonParseFailure> {
679        match self {
680            ParseBuffer::Finite(position, slice) => {
681                if *position == (*slice).len() {
682                    Err(JsonParseFailure::FieldBufferTooSmall)
683                } else {
684                    slice[*position] = thing;
685                    *position += 1;
686                    Ok(())
687                }
688            },
689            #[cfg(feature = "alloc")]
690            ParseBuffer::Infinite(position,vec) => {
691                if *position < vec.len() {
692                    vec[*position] = thing;
693                    *position += 1;
694                    Ok(())
695                } else {
696                    vec.push(thing);
697                    *position += 1;
698                    Ok(())
699                }
700            }
701        }
702    }
703
704    const fn consume(self) -> usize {
705        match self {
706            ParseBuffer::Finite(n, _) => n,
707            #[cfg(feature = "alloc")]
708            ParseBuffer::Infinite(n, _) => n,
709        }
710    }
711}
712
713// pub enum StringOutput<T> {
714//     Write(usize,T),
715
716//     String(String),
717// }
718
719/// a buffer that string slices can be written to
720pub enum StringBuffer<'a> {
721    Finite(usize, &'a mut [u8]),
722    #[cfg(feature = "alloc")]
723    Infinite(String,&'a AllocEscapeBuffer),
724}
725
726impl<'a> StringBuffer<'a> {
727    fn write_part(&mut self, string: &str) -> Result<(),JsonParseFailure> {
728        if string.len() == 0 {
729            return Ok(())
730        }
731        match self {
732            StringBuffer::Finite(position, slice) => {
733                let needed = string.len();
734                let have = slice.len() - *position;
735                if needed > have {
736                    return Err(JsonParseFailure::EscapeBufferTooSmall);
737                }
738                let target = slice.split_at_mut(*position).1.split_at_mut(needed).0;
739                target.copy_from_slice(string.as_bytes());
740                *position += needed;
741                Ok(())
742            },
743            #[cfg(feature = "alloc")]
744            StringBuffer::Infinite(current_string, _frozen_vec) => {
745                current_string.push_str(string);
746                Ok(())
747            },
748        }
749    }
750    fn consume_string(&mut self) -> &'a str {
751        match self {
752            StringBuffer::Finite(position, slice) => {
753                let (ret, remaining) = core::mem::take(slice).split_at_mut(*position);
754                *slice = remaining;
755                *position = 0;
756                // safety: this data was written from &str
757                unsafe { core::str::from_utf8_unchecked(ret) }
758            },
759            #[cfg(feature = "alloc")]
760            StringBuffer::Infinite(current_string, frozen_vec) => {
761                let completed_string = core::mem::replace(current_string, String::new());
762                let x = frozen_vec.push_get(completed_string);
763                x
764            },
765        }
766    }
767}
768
769
770/// the core function that powers parsing in the JsonArray API. It attempts to parse the fields of a json object from the provided data slice into the provided parse buffer.
771/// returns (num bytes consumed,num values parsed) on success
772pub fn parse_json_array<'input_data: 'escaped_data,'escaped_data>(
773    data: &'input_data [u8],
774    mut field_buffer: ParseBuffer<'_,JsonValue<'escaped_data>>,
775    string_escape_buffer: &mut StringBuffer<'escaped_data>,
776) -> Result<(usize,usize),JsonParseFailure> {
777    let mut current_data_index = 0;
778    // let mut current_field_index = 0;
779    let mut map_entry_needs_comma = false;
780    skip_whitespace(&mut current_data_index, data)?;
781    if data[current_data_index] != b'[' {
782        return Err(JsonParseFailure::InvalidStructure);
783    }
784    let _map_start_index = current_data_index;
785    current_data_index += 1;
786    while current_data_index < data.len()  {
787        skip_whitespace(&mut current_data_index, data)?;
788        if data[current_data_index] == b']' {
789            return Ok((current_data_index+1,field_buffer.consume()))
790        } else if map_entry_needs_comma  {
791            if data[current_data_index] != b',' {
792                return Err(JsonParseFailure::InvalidStructure);
793            }
794            current_data_index += 1;
795            map_entry_needs_comma = false;
796        } else {
797            map_entry_needs_comma = true;
798            skip_whitespace(&mut current_data_index, data)?;
799            if data[current_data_index] == b'"' {
800                let unescaped_string_value = unescape_json_string(&mut current_data_index, data, string_escape_buffer)?;
801                field_buffer.write_thing(JsonValue::String(unescaped_string_value))?;
802            } else if data[current_data_index] == b'n' {
803                skip_literal(&mut current_data_index, data, "null", JsonParseFailure::InvalidBooleanField)?;
804                field_buffer.write_thing(JsonValue::Null)?;
805            } else if data[current_data_index] == b't' || data[current_data_index] == b'f' {
806                let expect_true = data[current_data_index] == b't';
807                skip_literal(&mut current_data_index, data, if expect_true { "true" } else { "false"}, JsonParseFailure::InvalidBooleanField)?;
808                field_buffer.write_thing(JsonValue::Boolean(expect_true))?;
809            } else if data[current_data_index] == b'-' {
810                // negative number
811                let minus_sign_numeric_start_index = current_data_index;
812                current_data_index += 1;
813                skip_numeric(&mut current_data_index, data)?;
814                let minus_sign_numeric_end = current_data_index;
815                if minus_sign_numeric_end - minus_sign_numeric_start_index == 1 {
816                    // no digits found
817                    return Err(JsonParseFailure::InvalidNumericField);
818                }
819                let numeric_string = core::str::from_utf8(&data[minus_sign_numeric_start_index..minus_sign_numeric_end]).expect("skipped negative number digit(s)");
820                let numeric_value: i64 = match numeric_string.parse() {
821                    Ok(i) => i,
822                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
823                };
824                field_buffer.write_thing(JsonValue::Number(numeric_value))?;
825            } else if data[current_data_index] >= b'0' && data[current_data_index] < b'9' {
826                // positive number
827                let numeric_start_index = current_data_index;
828                current_data_index += 1;
829                skip_numeric(&mut current_data_index, data)?;
830                let numeric_after_index = current_data_index;
831                let numeric_string = core::str::from_utf8(&data[numeric_start_index..numeric_after_index]).expect("skipped positive number digit(s)");
832                let numeric_value: i64 = match numeric_string.parse() {
833                    Ok(i) => i,
834                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
835                };
836                field_buffer.write_thing(JsonValue::Number(numeric_value))?;
837            } else {
838                return Err(JsonParseFailure::InvalidStructure);
839            }
840        }
841    }
842    Err(JsonParseFailure::Incomplete)
843}
844
845/// the core function that powers parsing in the JsonObject API. It attempts to parse the fields of a json object from the provided data slice into the provided parse buffer.
846/// returns (num bytes consumed,num fields parsed) on success
847pub fn parse_json_object<'input_data: 'escaped_data,'escaped_data>(
848    data: &'input_data [u8],
849    mut field_buffer: ParseBuffer<'_,JsonField<'escaped_data,'escaped_data>>,
850    string_escape_buffer: &mut StringBuffer<'escaped_data>,
851) -> Result<(usize,usize),JsonParseFailure> {
852    let mut current_data_index = 0;
853    // let mut current_field_index = 0;
854    let mut map_entry_needs_comma = false;
855    skip_whitespace(&mut current_data_index, data)?;
856    if data[current_data_index] != b'{' {
857        return Err(JsonParseFailure::InvalidStructure);
858    }
859    let _map_start_index = current_data_index;
860    current_data_index += 1;
861    while current_data_index < data.len()  {
862        skip_whitespace(&mut current_data_index, data)?;
863        if data[current_data_index] == b'}' {
864            return Ok((current_data_index+1,field_buffer.consume()))
865        } else if map_entry_needs_comma  {
866            if data[current_data_index] != b',' {
867                return Err(JsonParseFailure::InvalidStructure);
868            }
869            current_data_index += 1;
870            map_entry_needs_comma = false;
871        } else {
872            map_entry_needs_comma = true;
873            // let key_start_quote_index = current_data_index;
874            // current_data_index += 1; // include the quote for json string
875
876            let string_key = unescape_json_string(&mut current_data_index, data, string_escape_buffer)?;
877
878            // skip_json_string(&mut current_data_index, data)?;
879            // let key_end_quote_index = current_data_index;
880            // let string_key = core::str::from_utf8(&data[key_start_quote_index+1..key_end_quote_index]).expect("skipped json object key string");
881            // current_data_index += 1;
882            skip_whitespace(&mut current_data_index, data)?;
883            if data[current_data_index] != b':' {
884                return Err(JsonParseFailure::InvalidStructure);
885            }
886            current_data_index += 1;
887            skip_whitespace(&mut current_data_index, data)?;
888
889            if data[current_data_index] == b'"' {
890                let unescaped_string_value = unescape_json_string(&mut current_data_index, data, string_escape_buffer)?;
891                field_buffer.write_thing(JsonField::new(string_key, JsonValue::String(unescaped_string_value)))?;
892            } else if data[current_data_index] == b'n' {
893                skip_literal(&mut current_data_index, data, "null", JsonParseFailure::InvalidBooleanField)?;
894                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Null))?;
895            } else if data[current_data_index] == b't' || data[current_data_index] == b'f' {
896                let expect_true = data[current_data_index] == b't';
897                skip_literal(&mut current_data_index, data, if expect_true { "true" } else { "false"}, JsonParseFailure::InvalidBooleanField)?;
898                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Boolean(expect_true)))?;
899            } else if data[current_data_index] == b'-' {
900                // negative number
901                let minus_sign_numeric_start_index = current_data_index;
902                current_data_index += 1;
903                skip_numeric(&mut current_data_index, data)?;
904                let minus_sign_numeric_end = current_data_index;
905                if minus_sign_numeric_end - minus_sign_numeric_start_index == 1 {
906                    // no digits found
907                    return Err(JsonParseFailure::InvalidNumericField);
908                }
909                let numeric_string = core::str::from_utf8(&data[minus_sign_numeric_start_index..minus_sign_numeric_end]).expect("skipped negative number digit(s)");
910                let numeric_value: i64 = match numeric_string.parse() {
911                    Ok(i) => i,
912                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
913                };
914                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Number(numeric_value)))?;
915            } else if data[current_data_index] >= b'0' && data[current_data_index] < b'9' {
916                // positive number
917                let numeric_start_index = current_data_index;
918                current_data_index += 1;
919                skip_numeric(&mut current_data_index, data)?;
920                let numeric_after_index = current_data_index;
921                let numeric_string = core::str::from_utf8(&data[numeric_start_index..numeric_after_index]).expect("skipped positive number digit(s)");
922                let numeric_value: i64 = match numeric_string.parse() {
923                    Ok(i) => i,
924                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
925                };
926                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Number(numeric_value)))?;
927            } else {
928                return Err(JsonParseFailure::InvalidStructure);
929            }
930        }
931    }
932    Err(JsonParseFailure::Incomplete)
933}
934
935const fn get_required_escape_sequence(c: char) -> Option<&'static str> {
936    // TODO: optionally escape solidus
937    Some(match c {
938        // control characters (U+0000 through U+001F), quotation mark, & reverse solidus must be escaped
939        // https://datatracker.ietf.org/doc/html/rfc8259#section-7
940        '"' => r#"\""#, // quotation mark
941        '\\' => r#"\\"#, // reverse solidus
942        '\u{0000}' => r#"\u0000"#, // null
943        '\u{0001}' => r#"\u0001"#, // start of heading
944        '\u{0002}' => r#"\u0002"#, // start of text
945        '\u{0003}' => r#"\u0003"#, // end of text
946        '\u{0004}' => r#"\u0004"#, // end of transmission
947        '\u{0005}' => r#"\u0005"#, // enquiry
948        '\u{0006}' => r#"\u0006"#, // acknowledge
949        '\u{0007}' => r#"\u0007"#, // bell
950        '\u{0008}' => r#"\b"#,     // backspace
951        '\u{0009}' => r#"\t"#,     // horizontal tab
952        '\u{000A}' => r#"\n"#,     // line feed
953        '\u{000B}' => r#"\u000B"#, // vertical tab
954        '\u{000C}' => r#"\f"#,     // form feed
955        '\u{000D}' => r#"\r"#,     // carriage return
956        '\u{000E}' => r#"\u000E"#, // shift out
957        '\u{000F}' => r#"\u000F"#, // shift in
958        '\u{0010}' => r#"\u0010"#, // data link escape
959        '\u{0011}' => r#"\u0011"#, // device control 1
960        '\u{0012}' => r#"\u0012"#, // device control 2
961        '\u{0013}' => r#"\u0013"#, // device control 3
962        '\u{0014}' => r#"\u0014"#, // device control 4
963        '\u{0015}' => r#"\u0015"#, // negative acknowledge
964        '\u{0016}' => r#"\u0016"#, // synchronous idle
965        '\u{0017}' => r#"\u0017"#, // end of transmission block
966        '\u{0018}' => r#"\u0018"#, // cancel
967        '\u{0019}' => r#"\u0019"#, // end of medium
968        '\u{001A}' => r#"\u001A"#, // substitute
969        '\u{001B}' => r#"\u001B"#, // escape
970        '\u{001C}' => r#"\u001C"#, // file separator
971        '\u{001D}' => r#"\u001D"#, // group separator
972        '\u{001E}' => r#"\u001E"#, // record separator
973        '\u{001F}' => r#"\u001F"#, // unit separator
974        _ => return None,
975    })
976}
977
978const fn unescape_two_character(c: char) -> Option<char> {
979    Some(match c {
980        '"' => '"', // quotation mark
981        '\\' => '\\', // reverse solidus
982        '/' => '/', // solidus
983        'b' => '\u{0008}', // backspace
984        'f' => '\u{000C}', // form feed
985        'n' => '\n', // line feed
986        'r' => '\r', // carriage return
987        't' => '\t', // character tabulation
988        _ => return None,
989    })
990}
991
992const fn require_hex_digit(c: Option<char>, missing_error: JsonParseFailure) -> Result<u8,JsonParseFailure> {
993    let ch = match c {
994        Some(d) => d,
995        None => {
996            return Err(missing_error);
997        },
998    };
999    let ret = if ch >= '0' && ch <= '9' {
1000        (ch as u8) - b'0'
1001    } else if ch >= 'a' && ch <= 'f' {
1002        (ch as u8) - b'a' + 10
1003    } else if ch >= 'A' && ch <= 'F' {
1004        (ch as u8) - b'A' + 10
1005    } else {
1006        return Err(JsonParseFailure::InvalidStringField);
1007    };
1008    Ok(ret)
1009}
1010
1011fn require_hex_escape_sequence(data: &mut Chars<'_>, missing_error: JsonParseFailure) -> Result<u16,JsonParseFailure> {
1012    let mut ret: u16 = 0;
1013    for _ in 0..4 {
1014        ret = (ret << 4) | (require_hex_digit(data.next(), missing_error)? as u16);
1015    }
1016    Ok(ret)
1017}
1018
1019fn require_character<const EXPECTED_CHAR: char>(
1020    data: &mut Chars<'_>,
1021    not_found_result: JsonParseFailure
1022) -> Result<(),JsonParseFailure> {
1023    match data.next() {
1024        Some(c) => {
1025            if c == EXPECTED_CHAR {
1026                Ok(())
1027            } else {
1028                Err(JsonParseFailure::InvalidStringField)
1029            }
1030        },
1031        None => Err(not_found_result),
1032    }
1033}
1034
1035fn unescape_json_string<'data,'escaped>(index: &mut usize, data: &[u8], escaped: &mut StringBuffer<'escaped>) -> Result<&'escaped str,JsonParseFailure> {
1036    if data[*index] != b'\"' {
1037        return Err(JsonParseFailure::InvalidStringField);
1038    }
1039    let remaining_data = data.split_at(*index+1).1;
1040    let chunk_iterator = remaining_data.utf8_chunks();
1041
1042    let mut encoding_buffer = [0_u8; 4];
1043    let mut string_bytes_consumed = '\"'.len_utf8(); // account for starting quote
1044    let mut last_character_was_escape = false;
1045    // while let Some(chunk) = chunk_iterator.next() {
1046    for chunk in chunk_iterator {
1047        // let next_valid_chunk = chunk.valid();
1048        let mut valid_character_iterator = chunk.valid().chars().into_iter();
1049        let followed_by_invalid_data = !chunk.invalid().is_empty();
1050        let incomplete_error = JsonParseFailure::Incomplete;
1051
1052        while let Some(next_character) = valid_character_iterator.next() {
1053            string_bytes_consumed += next_character.len_utf8();
1054            if last_character_was_escape {
1055                last_character_was_escape = false;
1056                if let Some(unescaped_char) = unescape_two_character(next_character) {
1057                    escaped.write_part(unescaped_char.encode_utf8(&mut encoding_buffer))?;
1058                } else if next_character != 'u' {
1059                    return Err(JsonParseFailure::InvalidStringField);
1060                } else {
1061
1062                    let hex_value = require_hex_escape_sequence(&mut valid_character_iterator, incomplete_error)?;
1063                    string_bytes_consumed += 4; // account for 4 hex digits
1064                    if !UNICODE_HIGH_SURROGATE_RANGE.contains(&hex_value) {
1065                        // normal single unicode escape sequence
1066                        let unescaped_character = match char::from_u32(hex_value as u32) {
1067                            Some(c) => c,
1068                            None => return Err(JsonParseFailure::InvalidStringField),
1069                        };
1070                        escaped.write_part(unescaped_character.encode_utf8(&mut encoding_buffer))?;
1071                    } else {
1072                        // surrogate pair of escape sequences - expect another \uXXXX sequence
1073                        require_character::<'\\'>(
1074                            &mut valid_character_iterator,
1075                            incomplete_error,
1076                        )?;
1077                        string_bytes_consumed += 1;
1078                        require_character::<'u'>(
1079                            &mut valid_character_iterator,
1080                            incomplete_error,
1081                        )?;
1082                        string_bytes_consumed += 1;
1083
1084                        let second_hex_value = require_hex_escape_sequence(&mut valid_character_iterator, incomplete_error)?;
1085                        string_bytes_consumed += 4; // account for 4 hex digits
1086                        if !UNICODE_LOW_SURROGATE_RANGE.contains(&second_hex_value) {
1087                            return Err(JsonParseFailure::InvalidStringField);
1088                        }
1089                        let combined_code_point: u32 = 0x10000 + ((hex_value as u32 - 0xD800) << 10) + (second_hex_value as u32 - 0xDC00);
1090                        let unescaped_surrogate_character = match char::from_u32(combined_code_point) {
1091                            Some(c) => c,
1092                            None => return Err(JsonParseFailure::InvalidStringField),
1093                        };
1094                        escaped.write_part(unescaped_surrogate_character.encode_utf8(&mut encoding_buffer))?;
1095                    }
1096                }
1097            } else if next_character == '"' {
1098                *index += string_bytes_consumed;
1099                return Ok(escaped.consume_string());
1100            } else if next_character == '\\' {
1101                last_character_was_escape = true;
1102            } else if get_required_escape_sequence(next_character).is_some() {
1103                // invalid character that should have been escaped
1104                return Err(JsonParseFailure::InvalidStringField);
1105            } else {
1106                escaped.write_part(next_character.encode_utf8(&mut encoding_buffer))?;
1107            }
1108        }
1109
1110        if followed_by_invalid_data {
1111            return Err(JsonParseFailure::InvalidStringField);
1112        }
1113    }
1114    Err(JsonParseFailure::Incomplete)
1115}
1116
1117const fn skip_numeric(index: &mut usize, data: &[u8]) -> Result<(),JsonParseFailure> {
1118    while *index < data.len() && data[*index] <= b'9' && data[*index] >= b'0' {
1119        *index += 1;
1120    }
1121    if *index == data.len() {
1122        Err(JsonParseFailure::Incomplete)
1123    } else if data[*index].is_ascii_whitespace() || data[*index] == b',' || data[*index] == b'}' {
1124        Ok(())
1125    } else {
1126        Err(JsonParseFailure::InvalidNumericField)
1127    }
1128}
1129
1130fn skip_literal(index: &mut usize, data: &[u8], target: &str, field_error_type: JsonParseFailure) -> Result<(),JsonParseFailure> {
1131    let start = *index;
1132    while (*index - start) < target.len() {
1133        if *index >= data.len() {
1134            return Err(JsonParseFailure::Incomplete)
1135        }
1136        if data[*index] != target.as_bytes()[*index-start] {
1137            return Err(field_error_type);
1138        }
1139        *index += 1;
1140    }
1141    Ok(())
1142}
1143
1144fn skip_whitespace(index: &mut usize, data: &[u8]) -> Result<(),JsonParseFailure> {
1145    while *index < data.len() && data[*index].is_ascii_whitespace() {
1146        *index += 1;
1147    }
1148    if *index == data.len() {
1149        Err(JsonParseFailure::Incomplete)
1150    } else {
1151        Ok(())
1152    }
1153}
1154
1155/// the core function that powers serialization in the JsonArray API. It attempts to serialize the provided values as a JSON array into the provided output & returns the number of bytes written on success.
1156pub fn serialize_json_array<'data, Output: StringWrite>(
1157    output: &mut Output,
1158    fields: &[JsonValue<'data>],
1159    resume_from: usize,
1160) -> Result<usize, (usize,Output::StringWriteFailure)> {
1161    let mut ret = 0;
1162    tracked_write(output,&mut ret , &resume_from, LEFT_SQUARE_BRACKET)?;
1163    let mut value_needs_comma = false;
1164    for value in fields.as_ref().iter() {
1165        if value_needs_comma {
1166            tracked_write(output,&mut ret , &resume_from, ",")?;
1167        } else {
1168            value_needs_comma = true;
1169        }
1170        match *value {
1171            JsonValue::Boolean(b) => if b {
1172                tracked_write(output,&mut ret , &resume_from, "true")?;
1173            } else {
1174                tracked_write(output,&mut ret , &resume_from, "false")?;
1175            },
1176            JsonValue::Null => {
1177                tracked_write(output,&mut ret , &resume_from, "null")?;
1178            },
1179            JsonValue::Number(n) => {
1180                tracked_write(output,&mut ret , &resume_from, base10::i64(n).as_str())?;
1181            },
1182            JsonValue::String(s) => {
1183                write_escaped_json_string(output, &mut ret , &resume_from, s)?;
1184            },
1185        }
1186    }
1187    tracked_write(output, &mut ret , &resume_from, RIGHT_SQUARE_BRACKET)?;
1188    Ok(ret.saturating_sub(resume_from))
1189}
1190
1191// const LEFT_SQUARE_BRACKET_CHAR: char = '{';
1192const LEFT_SQUARE_BRACKET: &str = "[";
1193const LEFT_CURLY_BRACKET: &str = "{";
1194const RIGHT_SQUARE_BRACKET: &str = "]";
1195const RIGHT_CURLY_BRACKET: &str = "}";
1196const COLON: &str = ":";
1197const COMMA: &str = ",";
1198
1199/// the core function that powers serialization in the JsonObject API. It attempts to serialize the provided fields as a JSON object into the provided output, & returns the number of bytes written on success.
1200pub fn serialize_json_object<'data, Output: StringWrite>(
1201    output: &mut Output,
1202    fields: &[JsonField<'data,'data>],
1203    resume_from: usize,
1204) -> Result<usize, (usize,Output::StringWriteFailure)> {
1205    let mut ret = 0;
1206    tracked_write(output,&mut ret , &resume_from, LEFT_CURLY_BRACKET)?;
1207    let mut field_needs_comma = false;
1208    for field in fields.as_ref().iter() {
1209        if field_needs_comma {
1210            tracked_write(output,&mut ret , &resume_from, COMMA)?;
1211        } else {
1212            field_needs_comma = true;
1213        }
1214        write_escaped_json_string(output, &mut ret , &resume_from, field.key)?;
1215        tracked_write(output, &mut ret, &resume_from, COLON)?;
1216        match field.value {
1217            JsonValue::Boolean(b) => if b {
1218                tracked_write(output,&mut ret , &resume_from, "true")?;
1219            } else {
1220                tracked_write(output,&mut ret , &resume_from, "false")?;
1221            },
1222            JsonValue::Null => {
1223                tracked_write(output,&mut ret , &resume_from, "null")?;
1224            },
1225            JsonValue::Number(n) => {
1226                tracked_write(output,&mut ret , &resume_from, base10::i64(n).as_str())?;
1227            },
1228            JsonValue::String(s) => {
1229                write_escaped_json_string(output, &mut ret , &resume_from, s)?;
1230            },
1231        }
1232    }
1233    tracked_write(output, &mut ret, &resume_from, RIGHT_CURLY_BRACKET)?;
1234    Ok(ret.saturating_sub(resume_from))
1235}
1236
1237fn tracked_write<T: StringWrite>(output: &mut T, counter: &mut usize, resume_from: &usize, the_string: &str) -> Result<(), (usize,T::StringWriteFailure)> {
1238    let mut encoding_buffer = [0_u8; 4];
1239    for char in the_string.chars() {
1240        let encoded_char = char.encode_utf8(encoding_buffer.as_mut_slice());
1241        let to_skip = if resume_from <= counter {
1242            0
1243        } else {
1244            let to_skip = *resume_from - *counter;
1245            if to_skip >= encoded_char.len() {
1246                *counter += encoded_char.len();
1247                continue;
1248            } else {
1249                to_skip
1250            }
1251        };
1252        match output.write_char(char, to_skip) {
1253            Ok(n_success) => *counter += n_success,
1254            Err((n_failed, e)) => {
1255                *counter += n_failed;
1256                return Err((counter.saturating_sub(*resume_from), e));
1257            },
1258        };
1259    }
1260    Ok(())
1261}
1262
1263fn write_escaped_json_string<T: StringWrite>(output: &mut T, counter: &mut usize, resume_from: &usize, data: &str) -> Result<(), (usize,T::StringWriteFailure)> {
1264    tracked_write(output, counter, resume_from, "\"")?;
1265    for field_character in data.chars() {
1266        if let Some(escape_sequence) = get_required_escape_sequence(field_character) {
1267            tracked_write(output, counter, resume_from, escape_sequence)?;
1268        } else {
1269            tracked_write(output, counter, resume_from, field_character.encode_utf8(&mut [0_u8; 4]))?;
1270        }
1271    }
1272    tracked_write(output, counter, resume_from, "\"")?;
1273    Ok(())
1274}
1275
1276#[cfg(feature = "alloc")]
1277mod alloclib {
1278
1279    extern crate alloc;
1280    
1281
1282    use alloc::string::String;
1283    use alloc::vec::Vec;
1284
1285    use crate::{parse_json_object, AllocEscapeBuffer, FieldBufferMut, JsonArray, JsonField, JsonObject, JsonParseFailure, ParseBuffer, StringBuffer, ValueBufferMut};
1286
1287    impl <'a,T: ValueBufferMut<'a>> JsonArray<T> {
1288
1289        // TODO
1290        // /// attempt to parse a JSON object from the provided data slice and write its fields into this JsonObject while allocating space as needed for storing escaped strings
1291        // /// returns num bytes consumed on success
1292        // pub fn parse_alloc_escape(&mut self, data: &'a [u8], escape_buffer: &'a FrozenVec<String>) -> Result<usize,JsonParseFailure> {
1293        //     let (data_end, parsed_fields) = parse_json_object(
1294        //         data,
1295        //         ParseBuffer::Finite(0,self.values.as_mut()),
1296        //         &mut crate::StringBuffer::Infinite(String::new(), escape_buffer)
1297        //     )?;
1298        //     let new_num_fields = parsed_fields;
1299        //     self.num_fields = new_num_fields;
1300        //     Ok(data_end)
1301        // }
1302
1303    }
1304
1305    impl <'a,T: FieldBufferMut<'a>> JsonObject<T> {
1306
1307        /// attempt to parse a JSON object from the provided data slice and write its fields into this JsonObject while allocating space as needed for storing escaped strings
1308        /// returns num bytes consumed on success
1309        pub fn parse_alloc_escape(&mut self, data: &'a [u8], escape_buffer: &'a AllocEscapeBuffer) -> Result<usize,JsonParseFailure> {
1310            let (data_end, parsed_fields) = parse_json_object(
1311                data,
1312                ParseBuffer::Finite(0,self.fields.as_mut()),
1313                &mut crate::StringBuffer::Infinite(String::new(), escape_buffer)
1314            )?;
1315            let new_num_fields = parsed_fields;
1316            self.num_fields = new_num_fields;
1317            Ok(data_end)
1318        }
1319
1320    }
1321
1322    impl <'a, T: AsMut<Vec<JsonField<'a,'a>>>> JsonObject<T> {
1323
1324        /// attempt to parse a JSON object from the provided data slice and write its fields into this JsonObject while allocating space as needed for storing parsed fields
1325        /// returns num bytes consumed on success
1326        pub fn parse_alloc_fields(&mut self, data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<usize,JsonParseFailure> {
1327            let (data_end, parsed_fields) = parse_json_object(
1328                data,
1329                ParseBuffer::Infinite(0, self.fields.as_mut()),
1330                &mut StringBuffer::Finite(0, escape_buffer),
1331            )?;
1332            let new_num_fields = parsed_fields;
1333            self.num_fields = new_num_fields;
1334            Ok(data_end)
1335        }
1336
1337        /// attempt to parse a JSON object from the provided data slice and write its fields into this JsonObject while allocating space as needed for storing parsed fields & escaped strings
1338        /// returns num bytes consumed on success
1339        pub fn parse_alloc(&mut self, data: &'a [u8], escape_buffer: &'a AllocEscapeBuffer) -> Result<usize,JsonParseFailure> {
1340            let (data_end, parsed_fields) = parse_json_object(
1341                data,
1342                ParseBuffer::Infinite(0, self.fields.as_mut()),
1343                &mut crate::StringBuffer::Infinite(String::new(), escape_buffer),
1344            )?;
1345            let new_num_fields = parsed_fields;
1346            self.num_fields = new_num_fields;
1347            Ok(data_end)
1348        }
1349    }
1350
1351}
1352
1353
1354#[cfg(feature = "std")]
1355mod stdlib {
1356    extern crate std;
1357    use embedded_io_adapters::std::FromStd;
1358    use crate::FieldBuffer;
1359    use crate::JsonObject;
1360
1361    impl <'a,T: FieldBuffer<'a>> JsonObject<T> {
1362        /// convenience method to serialize to types implementing std::io::Write by wrapping it with embedded_io_adapters::std::FromStd
1363        pub fn serialize_std<Output: std::io::Write>(&self, output: Output) -> Result<usize,std::io::Error> {
1364            self.serialize(FromStd::new(output))
1365        }
1366    }
1367}
1368
1369#[cfg(all(test,feature = "alloc"))]
1370mod test_alloc {
1371    use super::*;
1372
1373    extern crate alloc;
1374    use alloc::vec::Vec;
1375    use alloc::string::ToString;
1376
1377    #[test]
1378    fn test_parse_core_vec_no_alloc_too_many_fields() {
1379        match parse_json_object(
1380            br#"{"a":0}"#,
1381            ParseBuffer::Finite(0,&mut Vec::new()),
1382            &mut StringBuffer::Finite(0, &mut [0_u8; 256]),
1383        ) {
1384            Err(JsonParseFailure::FieldBufferTooSmall) => {},
1385            other => panic!("{:?}", other),
1386        }
1387    }
1388
1389    #[test]
1390    fn test_parse_core_vec_with_alloc_simple() {
1391        let mut fields = Vec::new();
1392        match parse_json_object(
1393            br#"{"a":0}"#,
1394            ParseBuffer::Infinite(0,&mut fields),
1395            &mut StringBuffer::Finite(0, &mut [0_u8; 256])
1396        ) {
1397            Ok((num_bytes, num_fields)) => {
1398                assert_eq!(7, num_bytes);
1399                assert_eq!(1, num_fields);
1400                assert_eq!(1, fields.len());
1401                assert_eq!(JsonField::new("a", JsonValue::Number(0)), fields[0])
1402            },
1403            other => panic!("{:?}", other),
1404        }
1405
1406    }
1407
1408    #[test]
1409    fn test_parse_core_vec_success_empty() {
1410        let (bytes_consumed,num_fields_parsed) = parse_json_object(
1411            b"{}",
1412            ParseBuffer::Infinite(0,&mut Vec::new()),
1413            &mut StringBuffer::Finite(0, &mut [0_u8; 256])
1414        ).unwrap();
1415        assert_eq!(2,bytes_consumed);
1416        assert_eq!(0,num_fields_parsed);
1417    }
1418
1419    #[test]
1420    fn test_parse_object_vec_success_empty() {
1421        let mut escape_buffer = [0_u8; 256];
1422        let mut parser = JsonObject::wrap(Vec::new());
1423        let bytes_consumed =  parser.parse(b"{}", &mut escape_buffer).unwrap();
1424        assert_eq!(0,parser.fields().len());
1425        assert_eq!(bytes_consumed, 2);
1426    }
1427
1428    #[test]
1429    fn test_serialize_empty_to_string() {
1430        let string: String = ArrayJsonObject::<0>::new().to_string();
1431        assert_eq!("{}", string);
1432    }
1433
1434
1435}
1436
1437#[cfg(test)]
1438mod test_core {
1439
1440    use embedded_io::SliceWriteError;
1441
1442    use super::*;
1443
1444    #[test]
1445    fn test_parse_value_string_empty() {
1446        let data = br#""""#;
1447        match JsonValue::parse(data, &mut [0_u8; 0]) {
1448            Ok((bytes_consumed,value)) => {
1449                assert_eq!(data.len(),bytes_consumed);
1450                match value {
1451                    JsonValue::String(s) => {
1452                        assert_eq!("", s);
1453                    },
1454                    other => panic!("{:?}", other),
1455                }
1456            },
1457            other => panic!("{:?}", other),
1458        }
1459    }
1460
1461    #[test]
1462    fn test_parse_value_string_simple() {
1463        let data = br#""this is a string""#;
1464        match JsonValue::parse(data, &mut [0_u8; 16]) {
1465            Ok((value_end,value)) => {
1466                assert_eq!(data.len(),value_end);
1467                match value {
1468                    JsonValue::String(s) => {
1469                        assert_eq!("this is a string", s);
1470                    },
1471                    other => panic!("{:?}", other),
1472                }
1473            },
1474            other => panic!("{:?}", other),
1475        }
1476    }
1477
1478    #[test]
1479    fn test_parse_value_string_unicode_raw_g_clef() {
1480        let data = "\"𝄞\"";
1481        match JsonValue::parse(data.as_bytes(), &mut [0_u8; 16]) {
1482            Ok((value_end,value)) => {
1483                assert_eq!(data.len(),value_end);
1484                match value {
1485                    JsonValue::String(s) => {
1486                        assert_eq!("𝄞", s);
1487                    },
1488                    other => panic!("{:?}", other),
1489                }
1490            },
1491            other => panic!("{:?}", other),
1492        }
1493    }
1494
1495    #[test]
1496    fn test_parse_value_string_unicode_escaped_hex_digits_single() {
1497        let data = br#""\u0032""#;
1498        match JsonValue::parse(data, &mut [0_u8; 16]) {
1499            Ok((value_end,value)) => {
1500                assert_eq!(data.len(),value_end);
1501                match value {
1502                    JsonValue::String(s) => {
1503                        assert_eq!("2", s);
1504                    },
1505                    other => panic!("{:?}", other),
1506                }
1507            },
1508            other => panic!("{:?}", other),
1509        }
1510    }
1511
1512    #[test]
1513    fn test_parse_value_string_unicode_escaped_hex_digits_multiple() {
1514        let data = br#""\u0032\u0033\u0034""#;
1515        match JsonValue::parse(data, &mut [0_u8; 16]) {
1516            Ok((value_end,value)) => {
1517                assert_eq!(data.len(),value_end);
1518                match value {
1519                    JsonValue::String(s) => {
1520                        assert_eq!("234", s);
1521                    },
1522                    other => panic!("{:?}", other),
1523                }
1524            },
1525            other => panic!("{:?}", other),
1526        }
1527    }
1528
1529    #[test]
1530    fn test_parse_value_string_unicode_escaped_hex_digits_surrogate_pair_g_clef() {
1531        let data = br#""\uD834\uDD1E""#;
1532        match JsonValue::parse(data, &mut [0_u8; 16]) {
1533            Ok((value_end,value)) => {
1534                assert_eq!(data.len(),value_end);
1535                match value {
1536                    JsonValue::String(s) => {
1537                        assert_eq!("𝄞", s);
1538                    },
1539                    other => panic!("{:?}", other),
1540                }
1541            },
1542            other => panic!("{:?}", other),
1543        }
1544    }
1545
1546    #[test]
1547    fn test_parse_value_string_unicode_escaped_hex_digits_surrogate_pair_multiple() {
1548        let data = br#""\uD834\uDD1E\uD83D\uDE05\uD83D\uDC80""#;
1549        match JsonValue::parse(data, &mut [0_u8; 16]) {
1550            Ok((value_end,value)) => {
1551                assert_eq!(data.len(),value_end);
1552                match value {
1553                    JsonValue::String(s) => {
1554                        assert_eq!("𝄞😅💀", s);
1555                    },
1556                    other => panic!("{:?}", other),
1557                }
1558            },
1559            other => panic!("{:?}", other),
1560        }
1561    }
1562
1563    #[test]
1564    fn test_parse_value_string_unicode_escaped_hex_digits_mixed_with_surrogate() {
1565        let data = br#""\u006C\u006D\u0061\u006F\uD83D\uDE24\u006C\u006D\u0061\u006F""#;
1566        match JsonValue::parse(data, &mut [0_u8; 12]) {
1567            Ok((value_end,value)) => {
1568                assert_eq!(data.len(),value_end);
1569                match value {
1570                    JsonValue::String(s) => {
1571                        assert_eq!("lmao😤lmao", s);
1572                    },
1573                    other => panic!("{:?}", other),
1574                }
1575            },
1576            other => panic!("{:?}", other),
1577        }
1578    }
1579
1580    #[test]
1581    fn test_parse_value_string_ignore_trailing_whitespace() {
1582        let data = br#""hello"  "#; // add 2 spaces at the end
1583        match JsonValue::parse(data, &mut [0_u8; 16]) {
1584            Ok((value_end,value)) => {
1585                assert_eq!(data.len()-2,value_end);
1586                match value {
1587                    JsonValue::String(s) => {
1588                        assert_eq!("hello", s);
1589                    },
1590                    other => panic!("{:?}", other),
1591                }
1592            },
1593            other => panic!("{:?}", other),
1594        }
1595    }
1596
1597    #[test]
1598    fn test_parse_value_string_failure_unescaped_newline() {
1599        let data = "\"\n\"";
1600        match JsonValue::parse(data.as_bytes(), &mut [0_u8; 16]) {
1601            Err(JsonParseFailure::InvalidStringField) => {},
1602            Err(other) => {
1603                panic!("unexpected error: {:?}", other);
1604            },
1605            Ok((value_end,value)) => {
1606                panic!("unexpected success: {} {:?}", value_end, value);
1607            },
1608        }
1609    }
1610
1611    #[test]
1612    fn test_parse_value_integer() {
1613        let data = br#"12345 "#;
1614        match JsonValue::parse(data, &mut [0_u8; 16]) {
1615            Ok((value_end,value)) => {
1616                assert_eq!(data.len(),value_end+1); // need non-numeric to recognize end
1617                match value {
1618                    JsonValue::Number(n) => {
1619                        assert_eq!(12345, n);
1620                    },
1621                    other => panic!("{:?}", other),
1622                }
1623            },
1624            other => panic!("{:?}", other),
1625        }
1626    }
1627
1628    #[test]
1629    fn test_parse_value_null() {
1630        let data = br#"null"#;
1631        match JsonValue::parse(data, &mut [0_u8; 16]) {
1632            Ok((value_end,value)) => {
1633                assert_eq!(data.len(),value_end);
1634                match value {
1635                    JsonValue::Null => {},
1636                    other => panic!("{:?}", other),
1637                }
1638            },
1639            other => panic!("{:?}", other),
1640        }
1641    }
1642
1643    #[test]
1644    fn test_parse_array_empty_core() {
1645        let mut escape_buffer = [0_u8; 0];
1646        let (bytes_consumed,num_values) = parse_json_array(
1647            b"[]",
1648            ParseBuffer::Finite(0,&mut []),
1649            &mut StringBuffer::Finite(0, &mut escape_buffer),
1650        ).unwrap();
1651        assert_eq!(bytes_consumed, 2);
1652        assert_eq!(num_values, 0);
1653    }
1654
1655    #[test]
1656    fn test_parse_array_empty_trait_array() {
1657        let mut parser = JsonArray::wrap([]);
1658        let bytes_consumed = parser.parse(b"[]", &mut []).unwrap();
1659        assert_eq!(bytes_consumed, 2);
1660        assert_eq!(parser.len(), 0);
1661    }
1662
1663    #[test]
1664    fn test_parse_object_empty_core() {
1665        let mut escape_buffer = [0_u8; 0];
1666        let (bytes_consumed,num_fields) = parse_json_object(
1667            b"{}",
1668            ParseBuffer::Finite(0,&mut []),
1669            &mut StringBuffer::Finite(0, &mut escape_buffer),
1670        ).unwrap();
1671        assert_eq!(bytes_consumed, 2);
1672        assert_eq!(num_fields, 0);
1673    }
1674
1675    #[test]
1676    fn test_parse_object_empty_trait_array() {
1677        let mut parser = JsonObject::wrap([]);
1678        let bytes_consumed = parser.parse(b"{}", &mut []).unwrap();
1679        assert_eq!(bytes_consumed, 2);
1680        assert_eq!(parser.len(), 0);
1681    }
1682
1683    #[test]
1684    fn test_parse_object_empty_trait_slice() {
1685        let mut parser = JsonObject::wrap(&mut []);
1686        let bytes_consumed = parser.parse(b"{}", &mut []).unwrap();
1687        assert_eq!(bytes_consumed, 2);
1688        assert_eq!(parser.len(), 0);
1689    }
1690
1691    #[test]
1692    fn test_parse_object_empty_arrayhelper() {
1693        let mut parser = ArrayJsonObject::<0>::new();
1694        let bytes_consumed = parser.parse(b"{}", &mut []).unwrap();
1695        assert_eq!(bytes_consumed, 2);
1696        assert_eq!(parser.len(), 0);
1697    }
1698
1699    #[test]
1700    fn test_parse_object_simple() {
1701        let data = br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false,"null_thing":null}"#;
1702        let mut escape_buffer = [0_u8; 256];
1703        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1704        assert_eq!(data_end, data.len());
1705        let test_fields = json_object.fields();
1706        assert_eq!(5, test_fields.len());
1707        assert_eq!(JsonField { key: "sub", value: JsonValue::String("1234567890")}, test_fields[0]);
1708        assert_eq!(JsonField { key: "name", value: JsonValue::String("John Doe")}, test_fields[1]);
1709        assert_eq!(JsonField { key: "iat", value: JsonValue::Number(1516239022)}, test_fields[2]);
1710        assert_eq!(JsonField { key: "something", value: JsonValue::Boolean(false)}, test_fields[3]);
1711        assert_eq!(JsonField { key: "null_thing", value: JsonValue::Null}, test_fields[4]);
1712    }
1713
1714    #[test]
1715    fn test_parse_object_empty_strings() {
1716        let data = br#"{"":""}"#;
1717        let mut escape_buffer = [0_u8; 0];
1718        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1719        assert_eq!(data_end, data.len());
1720        let test_fields = json_object.fields();
1721        assert_eq!(1, test_fields.len());
1722        assert_eq!(JsonField { key: "", value: JsonValue::String("")}, test_fields[0]);
1723    }
1724
1725    #[test]
1726    fn test_parse_object_escape_backspace() {
1727        let data = br#"{"\b":null}"#;
1728        let mut escape_buffer = [0_u8; 1];
1729        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1730        assert_eq!(data_end, data.len());
1731        let test_fields = json_object.fields();
1732        assert_eq!(1, test_fields.len());
1733        assert_eq!(JsonField { key: "\u{0008}", value: JsonValue::Null}, test_fields[0]);
1734    }
1735
1736    #[test]
1737    fn test_parse_object_escape_newline() {
1738        let data = br#"{"\n":null}"#;
1739        let mut escape_buffer = [0_u8; 1];
1740        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1741        assert_eq!(data_end, data.len());
1742        let test_fields = json_object.fields();
1743        assert_eq!(1, test_fields.len());
1744        assert_eq!(JsonField { key: "\n", value: JsonValue::Null}, test_fields[0]);
1745    }
1746
1747    #[test]
1748    fn test_parse_object_escape_carriage_return() {
1749        let data = br#"{"\r":null}"#;
1750        let mut escape_buffer = [0_u8; 1];
1751        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1752        assert_eq!(data_end, data.len());
1753        let test_fields = json_object.fields();
1754        assert_eq!(1, test_fields.len());
1755        assert_eq!(JsonField { key: "\r", value: JsonValue::Null}, test_fields[0]);
1756    }
1757
1758    #[test]
1759    fn test_parse_object_escape_quote() {
1760        let data = br#"{"\"":null}"#;
1761        let mut escape_buffer = [0_u8; 1];
1762        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1763        assert_eq!(data_end, data.len());
1764        let test_fields = json_object.fields();
1765        assert_eq!(1, test_fields.len());
1766        assert_eq!(JsonField { key: "\"", value: JsonValue::Null}, test_fields[0]);
1767    }
1768
1769    #[test]
1770    fn test_parse_object_ignore_trailing_whitespace() {
1771        let data = br#"{}    "#; // add 4 spaces to the end
1772        let (data_end,_) = ArrayJsonObject::<0>::new_parsed(data,&mut []).unwrap();
1773        assert_eq!(data_end, data.len() - 4);
1774    }
1775
1776    #[test]
1777    fn test_parse_object_failure_too_many_fields() {
1778        match ArrayJsonObject::<0>::new_parsed(br#"{"some":"thing"}"#, &mut [0_u8; 256]) {
1779            Err(JsonParseFailure::FieldBufferTooSmall) => {},
1780            other => panic!("{:?}", other)
1781        }
1782    }
1783
1784    #[test]
1785    fn test_parse_object_failure_invalid_number_minus() {
1786        match ArrayJsonObject::<1>::new_parsed(br#"{"": -}"#, &mut []) {
1787            Err(JsonParseFailure::InvalidNumericField) => {},
1788            other => panic!("{:?}", other)
1789        }
1790    }
1791
1792    #[test]
1793    fn test_parse_object_failure_incomplete_a() {
1794        match ArrayJsonObject::<0>::new_parsed(b"{",&mut []) {
1795            Err(JsonParseFailure::Incomplete) => {},
1796            other => panic!("{:?}", other)
1797        }
1798    }
1799
1800    #[test]
1801    fn test_parse_object_failure_incomplete_b() {
1802        let mut escape_buffer = [0_u8; 256];
1803        match ArrayJsonObject::<50>::new_parsed(
1804            br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false"#,
1805            &mut escape_buffer,
1806        ) {
1807            Err(JsonParseFailure::Incomplete) => {},
1808            other => panic!("{:?}", other)
1809        }
1810    }
1811
1812    #[test]
1813    fn test_serialize_array_empty() {
1814        let mut buffer = [0_u8; 2];
1815        let test_array = ArrayJsonArray::<0>::new();
1816        let n = test_array.serialize(buffer.as_mut_slice()).unwrap();
1817        assert_eq!(b"[]", buffer.split_at(n).0)
1818    }
1819
1820    #[test]
1821    fn test_serialize_resume_array_empty() {
1822        let mut buffer = [0_u8; 2];
1823        let test_array = ArrayJsonArray::<0>::new();
1824        let n = test_array.serialize_resume(buffer.as_mut_slice(),1).unwrap();
1825        assert_eq!(b"]", buffer.split_at(n).0)
1826    }
1827
1828    #[test]
1829    fn test_display_array_empty() {
1830        let mut buffer = [0_u8; 2];
1831        buffer.as_mut_slice().write_fmt(format_args!("{}", ArrayJsonArray::<0>::new())).unwrap();
1832        assert_eq!(b"[]", buffer.as_slice())
1833    }
1834    
1835    #[test]
1836    fn test_serialize_array_simple() {
1837        let mut buffer = [0_u8; 1000];
1838        let mut test_map = ArrayJsonArray::<4>::new();
1839        test_map.push(JsonValue::String("hello world")).unwrap();
1840        test_map.push(JsonValue::Number(1516239022)).unwrap();
1841        test_map.push(JsonValue::Boolean(false)).unwrap();
1842        test_map.push(JsonValue::Null).unwrap();
1843        let n = test_map.serialize(buffer.as_mut_slice()).unwrap();
1844        assert_eq!(br#"["hello world",1516239022,false,null]"#, buffer.split_at(n).0)
1845    }
1846    
1847    #[test]
1848    fn test_serialize_object_empty() {
1849        let mut buffer = [0_u8; 2];
1850        let test_object = ArrayJsonObject::<0>::new();
1851        let n = test_object.serialize(buffer.as_mut_slice()).unwrap();
1852        assert_eq!(b"{}", buffer.split_at(n).0)
1853    }
1854
1855    #[test]
1856    fn test_serialize_resume_object_empty() {
1857        let mut buffer = [0_u8; 2];
1858        let test_object = ArrayJsonObject::<0>::new();
1859        let n = test_object.serialize_resume(buffer.as_mut_slice(), 1).unwrap();
1860        assert_eq!(b"}", buffer.split_at(n).0)
1861    }
1862
1863    #[test]
1864    fn test_serialize_resume_skip_object_empty() {
1865        let mut buffer = [0_u8; 2];
1866        let test_object = ArrayJsonObject::<0>::new();
1867        let n = test_object.serialize_resume(buffer.as_mut_slice(), 2).unwrap();
1868        assert_eq!(b"", buffer.split_at(n).0)
1869    }
1870
1871    #[test]
1872    fn test_serialize_resume_too_many_object_empty() {
1873        let mut buffer = [0_u8; 2];
1874        let test_object = ArrayJsonObject::<0>::new();
1875        let n = test_object.serialize_resume(buffer.as_mut_slice(), 3).unwrap();
1876        assert_eq!(b"", buffer.split_at(n).0)
1877    }
1878
1879    #[test]
1880    fn test_display_object_empty() {
1881        let mut buffer = [0_u8; 2];
1882        buffer.as_mut_slice().write_fmt(format_args!("{}", ArrayJsonObject::<0>::new())).unwrap();
1883        assert_eq!(b"{}", buffer.as_slice())
1884    }
1885
1886    #[test]
1887    fn test_serialize_object_simple() {
1888        let mut buffer = [0_u8; 1000];
1889        let mut test_map = ArrayJsonObject::<50>::new();
1890        test_map.push_field("sub", JsonValue::String("1234567890")).unwrap();
1891        test_map.push_field("name", JsonValue::String("John Doe")).unwrap();
1892        test_map.push_field("iat", JsonValue::Number(1516239022)).unwrap();
1893        test_map.push_field("something", JsonValue::Boolean(false)).unwrap();
1894        test_map.push_field("null_thing", JsonValue::Null).unwrap();
1895        let n = test_map.serialize(buffer.as_mut_slice()).unwrap();
1896        assert_eq!(br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false,"null_thing":null}"#, buffer.split_at(n).0)
1897    }
1898
1899    #[test]
1900    fn test_serialize_resume_object_simple() {
1901        const SKIP: usize = 10;
1902        const EXPECTED: &[u8] = br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false,"null_thing":null}"#.split_at(SKIP).1;
1903
1904        let mut buffer = [0_u8; 1000];
1905        let mut test_map = ArrayJsonObject::<50>::new();
1906        test_map.push_field("sub", JsonValue::String("1234567890")).unwrap();
1907        test_map.push_field("name", JsonValue::String("John Doe")).unwrap();
1908        test_map.push_field("iat", JsonValue::Number(1516239022)).unwrap();
1909        test_map.push_field("something", JsonValue::Boolean(false)).unwrap();
1910        test_map.push_field("null_thing", JsonValue::Null).unwrap();
1911        let n = test_map.serialize_resume(buffer.as_mut_slice(), 10).unwrap();
1912        assert_eq!(EXPECTED, buffer.split_at(n).0)
1913    }
1914
1915    #[test]
1916    fn test_serialize_resume_object_single_byte() {
1917        const EXPECTED: &[u8] = br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false,"null_thing":null}"#;
1918
1919        let mut buffer = [0_u8; 1];
1920        let mut test_map = ArrayJsonObject::<50>::new();
1921        test_map.push_field("sub", JsonValue::String("1234567890")).unwrap();
1922        test_map.push_field("name", JsonValue::String("John Doe")).unwrap();
1923        test_map.push_field("iat", JsonValue::Number(1516239022)).unwrap();
1924        test_map.push_field("something", JsonValue::Boolean(false)).unwrap();
1925        test_map.push_field("null_thing", JsonValue::Null).unwrap();
1926
1927        // attempt to resume from every each byte
1928        for (index,expected_byte) in EXPECTED.iter().enumerate() {
1929            match test_map.serialize_resume(buffer.as_mut_slice(), index) {
1930                Err((1,SliceWriteError::Full)) => {
1931                    assert_eq!(*expected_byte as char, buffer[0] as char)
1932                },
1933                Ok(0) => assert_eq!(EXPECTED.len(),index),
1934                Ok(1) => assert_eq!(EXPECTED.len()-1,index),
1935                unexpected => panic!("{:?}", unexpected),
1936            };
1937        }
1938    }
1939
1940}