lil_json/
lib.rs

1#![no_std]
2#![feature(doc_cfg)]
3
4use core::fmt::{Debug, Display, Formatter};
5use embedded_io::{Write};
6use numtoa::base10;
7#[cfg(feature = "alloc")]
8use elsa::FrozenVec;
9
10trait StringWrite {
11    type StringWriteFailure: Debug;
12    fn write_string(&mut self, data: &str) -> Result<(),(usize,Self::StringWriteFailure)>;
13}
14
15impl<T: Write> StringWrite for T {
16    type StringWriteFailure = T::Error;
17    fn write_string(&mut self, mut data: &str) -> Result<(),(usize,Self::StringWriteFailure)> {
18        let mut written = 0_usize;
19        loop {
20            if data.is_empty() {
21                return Ok(());
22            }
23            let n = match self.write(data.as_bytes()) {
24                Ok(0) => panic!("zero write"),
25                Err(e) => return Err((written,e)),
26                Ok(n) => n,
27            };
28            written += n;
29            data = data.split_at(n).1
30        }
31    }
32}
33
34struct FormatWrapper<T: ?Sized> {
35    inner: T,
36}
37
38impl<T> FormatWrapper<T> {
39    fn new(inner: T) -> Self {
40        FormatWrapper { inner }
41    }
42}
43
44impl<'a> StringWrite for FormatWrapper<&mut Formatter<'a>> {
45    type StringWriteFailure = core::fmt::Error;
46    fn write_string(&mut self, data: &str) -> Result<(),(usize,Self::StringWriteFailure)> {
47        match self.inner.write_str(data) {
48            Ok(()) => {
49                Ok(())
50            },
51            Err(e) => {
52                Err((0,e))
53            },
54        }
55    }
56}
57
58/// trait for an optionally mutable collection of JSON array values
59pub trait ValueBuffer<'a>: AsRef<[JsonValue<'a>]> {
60
61    /// convenience one-liner to call JsonArray::wrap_init on this Sized type, consuming it
62    fn into_json_array(self) -> JsonArray<Self> where Self: Sized {
63        JsonArray::wrap_init(self)
64    }
65    
66    /// convenience one-liner to call JsonArray::wrap_init on an immutable reference to this type
67    fn as_json_array(&self) -> JsonArray<&Self> {
68        JsonArray::wrap_init(self)
69    }
70
71}
72
73/// ValueBuffer is automatically implemented for all types that implement AsRef<[JsonField<'data,'data>]>
74impl <'a,T: AsRef<[JsonValue<'a>]>> ValueBuffer<'a> for T {}
75
76
77/// trait for a mutable collection of JSON array values
78pub trait ValueBufferMut<'a>: ValueBuffer<'a> +  AsMut<[JsonField<'a,'a>]> {
79
80    /// convenience one-liner to call JsonObject::wrap_init on a mutable reference to this type
81    fn as_json_array_mut(&mut self) -> JsonArray<&mut Self> {
82        JsonArray::wrap_init(self)
83    }
84}
85
86/// ValueBufferMut is automatically implemented for all types that implement FieldBuffer + AsMut<[JsonField<'data,'data>]>
87impl <'a,T: ValueBuffer<'a> + AsMut<[JsonField<'a,'a>]>> ValueBufferMut<'a> for T {}
88
89
90/// trait for an optionally mutable collection of JSON object fields
91pub trait FieldBuffer<'data>: AsRef<[JsonField<'data,'data>]> {
92
93    /// convenience one-liner to call JsonObject::wrap_init on this Sized type, consuming it
94    fn into_json_object(self) -> JsonObject<Self> where Self: Sized {
95        JsonObject::wrap_init(self)
96    }
97    
98    /// convenience one-liner to call JsonObject::wrap_init on an immutable reference to this type
99    fn as_json_object(&self) -> JsonObject<&Self> {
100        JsonObject::wrap_init(self)
101    }
102
103}
104
105/// FieldBuffer is automatically implemented for all types that implement AsRef<[JsonField<'data,'data>]>
106impl <'a,T: AsRef<[JsonField<'a,'a>]>> FieldBuffer<'a> for T {}
107
108/// trait for a mutable collection of JSON object fields
109pub trait FieldBufferMut<'a>: FieldBuffer<'a> +  AsMut<[JsonField<'a,'a>]> {
110
111    /// convenience one-liner to call JsonObject::wrap_init on a mutable reference to this type
112    fn as_json_object_mut(&mut self) -> JsonObject<&mut Self> {
113        JsonObject::wrap_init(self)
114    }
115
116}
117
118/// FieldBufferMut is automatically implemented for all types that implement FieldBuffer + AsMut<[JsonField<'data,'data>]>
119impl <'a,T: FieldBuffer<'a> + AsMut<[JsonField<'a,'a>]>> FieldBufferMut<'a> for T {}
120
121/// the various reasons parsing JSON can fail
122#[derive(Debug,PartialEq,Eq,Clone,Copy)]
123pub enum JsonParseFailure {
124    /// there was no error, but the data slice is incomplete
125    Incomplete,
126    /// there was no error, but there were more fields than the provided field buffer could hold
127    FieldBufferTooSmall,
128    /// there was no error, but there were more fields than the provided string escape buffer could hold
129    EscapeBufferTooSmall,
130    /// there was an error in the JSON structure of the data
131    InvalidStructure,
132    /// an invalid JSON string was encountered
133    InvalidStringField,
134    /// an invalid JSON number was encountered
135    InvalidNumericField,
136    /// a valid JSON number was encountered but we failed to interpret it
137    NumberParseError,
138    /// an invalid JSON boolean was encountered
139    InvalidBooleanField,
140    /// an invalid JSON null was encountered
141    InvalidNullField,
142}
143
144/// terminal (non-nested) JSON types
145#[derive(Debug,PartialEq,Eq,Clone,Copy)]
146pub enum JsonValue<'a> {
147    /// a JSON string - it will be automatically escaped
148    String(&'a str),
149    /// a JSON boolean
150    Boolean(bool),
151    /// a JSON number
152    Number(i64),
153    /// a JSON null value
154    Null,
155}
156
157impl <'a> JsonValue<'a> {
158    fn parse(data: &'a [u8], escape_buffer_slice: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
159        let mut escape_buffer = StringBuffer::Finite(0, escape_buffer_slice);
160        let mut current_data_index = 0_usize;
161        skip_whitespace(&mut current_data_index, data)?;
162        // let first_character = data[current_data_index];
163        let value = if data[current_data_index] == b'"' {
164                let unescaped_string_value = unescape_json_string(&mut current_data_index, data, &mut escape_buffer)?;
165                JsonValue::String(unescaped_string_value)
166            } else if data[current_data_index] == b'n' {
167                skip_literal(&mut current_data_index, data, "null", JsonParseFailure::InvalidBooleanField)?;
168                JsonValue::Null
169            } else if data[current_data_index] == b't' || data[current_data_index] == b'f' {
170                let expect_true = data[current_data_index] == b't';
171                skip_literal(&mut current_data_index, data, if expect_true { "true" } else { "false"}, JsonParseFailure::InvalidBooleanField)?;
172                JsonValue::Boolean(expect_true)
173            } else if data[current_data_index] == b'-' {
174                // negative number
175                let minus_sign_numeric_start_index = current_data_index;
176                current_data_index += 1;
177                skip_numeric(&mut current_data_index, data)?;
178                let minus_sign_numeric_end = current_data_index;
179                if minus_sign_numeric_end - minus_sign_numeric_start_index == 1 {
180                    // no digits found
181                    return Err(JsonParseFailure::InvalidNumericField);
182                }
183                let numeric_string = core::str::from_utf8(&data[minus_sign_numeric_start_index..minus_sign_numeric_end]).expect("skipped negative number digit(s)");
184                let numeric_value: i64 = match numeric_string.parse() {
185                    Ok(i) => i,
186                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
187                };
188                JsonValue::Number(numeric_value)
189            } else if data[current_data_index] >= b'0' && data[current_data_index] < b'9' {
190                // positive number
191                let numeric_start_index = current_data_index;
192                current_data_index += 1;
193                skip_numeric(&mut current_data_index, data)?;
194                let numeric_after_index = current_data_index;
195                let numeric_string = core::str::from_utf8(&data[numeric_start_index..numeric_after_index]).expect("skipped positive number digit(s)");
196                let numeric_value: i64 = match numeric_string.parse() {
197                    Ok(i) => i,
198                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
199                };
200                JsonValue::Number(numeric_value)
201            } else {
202                return Err(JsonParseFailure::InvalidStructure);
203            };
204            Ok((current_data_index,value))
205    }
206}
207
208impl<'a> Default for JsonValue<'a> {
209    fn default() -> Self { JsonValue::Null }
210}
211
212impl From<i64> for JsonValue<'static> {
213    fn from(n: i64) -> Self {
214        Self::Number(n)
215    }
216}
217
218impl From<bool> for JsonValue<'static> {
219    fn from(b: bool) -> Self {
220        Self::Boolean(b)
221    }
222}
223
224impl From<()> for JsonValue<'static> {
225    fn from(_: ()) -> Self {
226        Self::Null
227    }
228}
229
230impl<'a> From<&'a str> for JsonValue<'a> {
231    fn from(s: &'a str) -> Self {
232        Self::String(s)
233    }
234}
235
236/// a field within a JSON object
237#[derive(Debug,PartialEq,Eq,Clone,Copy)]
238pub struct JsonField<'a,'b> {
239    pub key: &'a str,
240    pub value: JsonValue<'b>,
241}
242
243impl <'a,'b> JsonField<'a,'b> {
244    /// create a new JSON object field with the given key & value
245    pub const fn new(key: &'a str, value: JsonValue<'b>) -> Self {
246        JsonField { key, value }
247    }
248
249    /// convenience helper to get the json field as a (key,value) tuple
250    pub const fn from_tuple(tuple: (&'a str, JsonValue<'b>)) -> Self {
251        Self::new(tuple.0, tuple.1)
252    }
253
254    /// convenience helper to get the json field as a (key,value) tuple
255    pub const fn as_tuple(&self) -> (&'a str, JsonValue<'b>) {
256        (self.key, self.value)
257    }
258
259    /// convenience helper to create a new JSON object string field
260    pub const fn new_string(key: &'a str, value: &'b str) -> Self {
261        Self::new(key, JsonValue::String(value))
262    }
263    /// convenience helper to create a new JSON object number field
264    pub const fn new_number(key: &'a str, value: i64) -> Self {
265        Self::new(key, JsonValue::Number(value))
266    }
267    /// convenience helper to create a new JSON object boolean field
268    pub const fn new_boolean(key: &'a str, value: bool) -> Self {
269        Self::new(key, JsonValue::Boolean(value))
270    }
271}
272
273/// two JsonObjects are equal if their initialized fields are identical (in the same order)
274impl<'a,T: FieldBuffer<'a>> PartialEq for JsonObject<T> {
275    fn eq(&self, other: &JsonObject<T>) -> bool {
276        self.num_fields == other.num_fields && PartialEq::eq(self.fields.as_ref(), other.fields.as_ref())
277    }
278}
279
280/// PartialEq for JsonObject is reflexive
281impl<'a,T: FieldBuffer<'a>> Eq for JsonObject<T> {}
282
283/// a default JSON field with static lifetime
284pub const EMPTY_FIELD: JsonField<'static,'static> = JsonField{ key: "", value: JsonValue::Number(0)};
285
286impl <'a,'b,V: Into<JsonValue<'b>>> From<(&'a str, V)> for JsonField<'a,'b> {
287    fn from(tuple: (&'a str, V)) -> Self {
288        Self::new(tuple.0, tuple.1.into())
289    }
290}
291
292impl <'a,'b> Default for JsonField<'a,'b> {
293    fn default() -> Self {
294        EMPTY_FIELD
295    }
296}
297
298/// 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.
299#[derive(Debug,Clone,Copy)]
300pub struct JsonArray<Values> {
301    values: Values,
302    num_values: usize,
303}
304
305impl<T> JsonArray<T> {
306    /// consume this JsonObject to return (field buffer, num fields considered initialized)
307    pub fn into_inner(self) -> (T,usize) {
308        (self.values,self.num_values)
309    }
310}
311
312impl<'a,T: FieldBuffer<'a> + Default + ?Sized> Default for JsonArray<T> {
313    fn default() -> Self {
314        JsonArray { values: T::default(), num_values: 0 }
315    }
316}
317
318impl <'a,T: ValueBuffer<'a>> JsonArray<T> {
319
320    /// wrap a collection of values into a JsonArray and considers none of the values to be initialized
321    pub const fn wrap(values: T) -> Self {
322        JsonArray { values, num_values: 0 }
323    }
324
325    /// wrap a collection of fields into a JsonObject and considers all of the fields to be initialized
326    pub fn wrap_init(values: T) -> Self {
327        let num_values = values.as_ref().len();
328        JsonArray { values, num_values }
329    }
330
331    /// get the number of initialized values in this JsonArray. Same as self.values().len()
332    pub const fn len(&self) -> usize {
333        self.num_values
334    }
335
336    /// get the max number of values this JsonArray can store
337    pub fn capacity(&self) -> usize {
338        self.values.as_ref().len()
339    }
340
341    /// get an immutable reference to the initialized values of this JsonArray
342    pub fn values(&self) -> &[JsonValue<'a>] {
343        self.values.as_ref().split_at(self.num_values).0
344    }
345
346    pub fn serialize<Output: Write>(&self, mut output: Output) -> Result<usize,Output::Error> {
347        serialize_json_array_internal(&mut output, self.values().as_ref())
348    }
349
350}
351
352impl <'a,T: ValueBuffer<'a>> Display for JsonArray<T> {
353    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
354        match serialize_json_array_internal(
355            &mut FormatWrapper::new(fmt),
356            self.values.as_ref(),
357        ) {
358            Ok(_) => Ok(()),
359            Err(e) => Err(e)
360        }
361    }
362}
363
364/// ArrayJsonObject is a type alias for a JsonObject that wraps an array. It has extra functionality when compared to any other type of JsonObject.
365pub type ArrayJsonArray<'a,const N: usize> = JsonArray<[JsonValue<'a>; N]>;
366
367impl<'a,const N: usize> ArrayJsonArray<'a,N> {
368    
369    /// convenience method to initialize a new array & call JsonObject::wrap on it
370    pub const fn new() -> Self {
371        JsonArray::wrap([JsonValue::Null; N])
372    }
373
374    /// convenience method to automatically create an ArrayJsonObject if object parsing is successful
375    // pub fn new_parsed(data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
376    //     let mut ret = Self::new();
377    //     let data_end = ret.parse(data, escape_buffer)?;
378    //     Ok((data_end,ret))
379    // }
380
381    /// similar to JsonObject::push but supports const contexts & only returns a reference
382    pub const fn push_const(&mut self, value: JsonValue<'a>) -> Result<(),()> {
383        if self.num_values == N {
384            return Err(());
385        }
386        self.values[self.num_values] = value;
387        self.num_values += 1;
388        Ok(())
389    }
390
391    /// similar to JsonObject::pop but supports const contexts
392    pub const fn pop_const(&mut self) -> Option<&JsonValue<'a>> {
393        match self.values_const().split_last() {
394            None => return None,
395            Some((split,_remaining)) => return Some(split),
396        }
397    }
398
399    /// same as JsonObject::fields but supports const contexts
400    pub const fn values_const(&self) -> &[JsonValue<'a>] {
401        self.values.split_at(self.num_values).0
402    }
403
404    /// same as JsonObject::fields_mut but supports const contexts
405    pub const fn values_mut_const(&mut self) -> &mut [JsonValue<'a>] {
406        self.values.split_at_mut(self.num_values).0
407    }
408}
409
410
411/// 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
412#[derive(Debug,Clone,Copy)]
413pub struct JsonObject<Fields> {
414    fields: Fields,
415    num_fields: usize,
416}
417
418impl<T> JsonObject<T> {
419    /// consume this JsonObject to return (field buffer, num fields considered initialized)
420    pub fn into_inner(self) -> (T,usize) {
421        (self.fields,self.num_fields)
422    }
423}
424
425impl<'a,T: FieldBuffer<'a> + Default + ?Sized> Default for JsonObject<T> {
426    fn default() -> Self {
427        JsonObject::wrap(T::default())
428    }
429}
430
431impl <'a,T: FieldBuffer<'a>> JsonObject<T> {
432
433    /// wrap a collection of fields into a JsonObject and considers none of the fields to be initialized
434    pub const fn wrap(fields: T) -> Self {
435        JsonObject { fields, num_fields: 0 }
436    }
437
438    /// wrap a collection of fields into a JsonObject and considers all of the fields to be initialized
439    pub fn wrap_init(fields: T) -> Self {
440        let num_fields = fields.as_ref().len();
441        JsonObject { fields, num_fields }
442    }
443
444    /// get the number of initialized fields in this JsonObject. Same as self.fields().len().
445    pub const fn len(&self) -> usize {
446        self.num_fields
447    }
448
449    /// get the max number of fields this JsonObject can store.
450    pub fn capacity(&self) -> usize {
451        self.fields.as_ref().len()
452    }
453
454    /// get an immutable reference to the initialized fields of this JsonObject
455    pub fn fields(&self) -> &[JsonField<'a,'a>] {
456        self.fields.as_ref().split_at(self.num_fields).0
457    }
458
459    /// attempt to serialize this JsonObject into the provided output & returns the number of bytes written on success
460    pub fn serialize<Output: Write>(&self, mut output: Output) -> Result<usize,Output::Error> {
461        serialize_json_object_internal(&mut output, self.fields().as_ref())
462    }
463}
464
465impl <'a,T: FieldBuffer<'a>> Display for JsonObject<T> {
466    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
467        match serialize_json_object_internal(
468            &mut FormatWrapper::new(fmt),
469            self.fields.as_ref(),
470        ) {
471            Ok(_) => Ok(()),
472            Err(e) => Err(e)
473        }
474    }
475}
476
477impl <'a,T: FieldBuffer<'a>> From<T> for JsonObject<T> {
478    fn from(t: T) -> Self {
479        Self::wrap_init(t)
480    }
481}
482
483impl <'a,T: FieldBufferMut<'a>> JsonObject<T> {
484
485    /// get a mutable reference to the initialized fields of this JsonObject
486    pub fn fields_mut(&mut self) -> &mut [JsonField<'a,'a>] {
487        self.fields.as_mut().split_at_mut(self.num_fields).0
488    }
489
490    /// attempt to push a new field - returns the field if there is not enough space
491    pub fn push<'x: 'a,'y: 'a>(&mut self, field: JsonField<'x,'y>) -> Result<(),JsonField<'x,'y>> {
492        if self.num_fields == self.fields.as_ref().len(){
493            return Err(field);
494        }
495        self.fields.as_mut()[self.num_fields] = field;
496        self.num_fields += 1;
497        Ok(())
498    }
499
500    /// attempt to pop an existing field - returns None if there are no initialized fields
501    pub fn pop(&mut self) -> Option<JsonField<'a,'a>> {
502        if self.num_fields == 0 {
503            return None;
504        }
505        self.num_fields -= 1;
506        Some(core::mem::take(&mut self.fields.as_mut()[self.num_fields+1]))
507    }
508
509    /// convenience helper to create and push a new field
510    pub fn push_field<'x: 'a,'y: 'a>(&mut self, key: &'x str, value: JsonValue<'y>) -> Result<(),()> {
511        if self.num_fields == self.fields.as_ref().len(){
512            return Err(());
513        }
514        self.fields.as_mut()[self.num_fields] = JsonField { key, value };
515        self.num_fields += 1;
516        Ok(())
517    }
518
519    /// 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
520    pub fn parse(&mut self, data: &'a [u8], string_escape_buffer: &'a mut [u8]) -> Result<usize,JsonParseFailure> {
521        let (data_end, parsed_fields) = parse_json_object(
522            data,
523            ParseBuffer::Finite(0, self.fields.as_mut()),
524            &mut StringBuffer::Finite(0, string_escape_buffer),
525        )?;
526        let new_num_fields = parsed_fields;
527        self.num_fields = new_num_fields;
528        Ok(data_end)
529    }
530
531}
532
533impl <'a,T: FieldBufferMut<'a> + Default> JsonObject<T> {
534
535    /// convenience method to automatically create a JsonObject if object parsing is successful
536    pub fn default_parsed(data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
537        let mut ret = Self::default();
538        let num_bytes = ret.parse(data, escape_buffer)?;
539        Ok((num_bytes,ret))
540    }
541
542}
543
544
545/// ArrayJsonObject is a type alias for a JsonObject that wraps an array. It has extra functionality when compared to any other type of JsonObject.
546pub type ArrayJsonObject<'a,const N: usize> = JsonObject<[JsonField<'a,'a>; N]>;
547
548impl<'a,const N: usize> ArrayJsonObject<'a,N> {
549
550    /// convenience method to initialize a new array & call JsonObject::wrap on it
551    pub const fn new() -> Self {
552        JsonObject::wrap([EMPTY_FIELD; N])
553    }
554
555    /// convenience method to automatically create an ArrayJsonObject if object parsing is successful
556    pub fn new_parsed(data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<(usize,Self),JsonParseFailure> {
557        let mut ret = Self::new();
558        let data_end = ret.parse(data, escape_buffer)?;
559        Ok((data_end,ret))
560    }
561
562    /// similar to JsonObject::push but supports const contexts & only returns a reference
563    pub const fn push_const(&mut self, key: &'a str, value: JsonValue<'a>) -> Result<(),()> {
564        if self.num_fields == N {
565            return Err(());
566        }
567        self.fields[self.num_fields] = JsonField { key, value: value };
568        self.num_fields += 1;
569        Ok(())
570    }
571
572    /// similar to JsonObject::pop but supports const contexts
573    pub const fn pop_const(&mut self) -> Option<&JsonField<'a,'a>> {
574        match self.fields_const().split_last() {
575            None => return None,
576            Some((split,_remaining)) => return Some(split),
577        }
578    }
579
580    /// same as JsonObject::fields but supports const contexts
581    pub const fn fields_const(&self) -> &[JsonField<'a,'a>] {
582        self.fields.split_at(self.num_fields).0
583    }
584
585    /// same as JsonObject::fields_mut but supports const contexts
586    pub const fn fields_mut_const(&mut self) -> &mut [JsonField<'a,'a>] {
587        self.fields.split_at_mut(self.num_fields).0
588    }
589
590}
591
592#[cfg(any(feature = "alloc", doc))]
593#[doc(cfg(feature = "alloc"))]
594extern crate alloc as alloclib;
595#[cfg(any(feature = "alloc", doc))]
596#[doc(cfg(feature = "alloc"))]
597use alloclib::{string::String, vec::Vec};
598
599/// a buffer that any sized type can be written to
600pub enum ParseBuffer<'a,T> {
601    /// a finite buffer of T
602    Finite(usize, &'a mut [T]),
603    /// an infinite buffer of T
604    #[cfg(any(feature = "alloc", doc))]
605    #[doc(cfg(feature = "alloc"))]
606    Infinite(usize,&'a mut Vec<T>)
607}
608
609impl<'a,T> ParseBuffer<'a,T> {
610
611    fn write_thing(&mut self, thing: T) -> Result<(),JsonParseFailure> {
612        match self {
613            ParseBuffer::Finite(position, slice) => {
614                if *position == (*slice).len() {
615                    Err(JsonParseFailure::FieldBufferTooSmall)
616                } else {
617                    slice[*position] = thing;
618                    *position += 1;
619                    Ok(())
620                }
621            },
622            #[cfg(feature = "alloc")]
623            #[doc(cfg(feature = "alloc"))]
624            ParseBuffer::Infinite(position,vec) => {
625                if *position < vec.len() {
626                    vec[*position] = thing;
627                    *position += 1;
628                    Ok(())
629                } else {
630                    vec.push(thing);
631                    *position += 1;
632                    Ok(())
633                }
634            }
635        }
636    }
637
638    const fn consume(self) -> usize {
639        match self {
640            ParseBuffer::Finite(n, _) => n,
641            #[cfg(feature = "alloc")]
642            #[doc(cfg(feature = "alloc"))]
643            ParseBuffer::Infinite(n, _) => n,
644        }
645    }
646}
647
648/// a buffer that string slices can be written to
649pub enum StringBuffer<'a> {
650    Finite(usize, &'a mut [u8]),
651    #[cfg(feature = "alloc")]
652    #[doc(cfg(feature = "alloc"))]
653    Infinite(String,&'a FrozenVec<String>),
654}
655
656impl<'a> StringBuffer<'a> {
657    fn write_part(&mut self, string: &str) -> Result<(),JsonParseFailure> {
658        if string.len() == 0 {
659            return Ok(())
660        }
661        match self {
662            StringBuffer::Finite(position, slice) => {
663                let needed = string.len();
664                let have = slice.len() - *position;
665                if needed > have {
666                    return Err(JsonParseFailure::EscapeBufferTooSmall);
667                }
668                let target = slice.split_at_mut(*position).1.split_at_mut(needed).0;
669                target.copy_from_slice(string.as_bytes());
670                *position += needed;
671                Ok(())
672            },
673            #[cfg(feature = "alloc")]
674            #[doc(cfg(feature = "alloc"))]
675            StringBuffer::Infinite(current_string, _frozen_vec) => {
676                current_string.push_str(string);
677                Ok(())
678            },
679        }
680    }
681    fn consume_string(&mut self) -> &'a str {
682        match self {
683            StringBuffer::Finite(position, slice) => {
684                let (ret, remaining) = core::mem::take(slice).split_at_mut(*position);
685                *slice = remaining;
686                *position = 0;
687                // safety: this data was written from &str
688                unsafe { core::str::from_utf8_unchecked(ret) }
689            },
690            #[cfg(feature = "alloc")]
691            #[doc(cfg(feature = "alloc"))]
692            StringBuffer::Infinite(current_string, frozen_vec) => {
693                let completed_string = core::mem::replace(current_string, String::new());
694                let x = frozen_vec.push_get(completed_string);
695                x
696            },
697        }
698    }
699}
700
701
702
703/// 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.
704/// returns (num bytes consumed,num fields parsed) on success
705pub fn parse_json_object<'input_data: 'escaped_data,'escaped_data>(
706    data: &'input_data [u8],
707    mut field_buffer: ParseBuffer<'_,JsonField<'escaped_data,'escaped_data>>,
708    string_escape_buffer: &mut StringBuffer<'escaped_data>,
709) -> Result<(usize,usize),JsonParseFailure> {
710    let mut current_data_index = 0;
711    // let mut current_field_index = 0;
712    let mut map_entry_needs_comma = false;
713    skip_whitespace(&mut current_data_index, data)?;
714    if data[current_data_index] != b'{' {
715        return Err(JsonParseFailure::InvalidStructure);
716    }
717    let _map_start_index = current_data_index;
718    current_data_index += 1;
719    while current_data_index < data.len()  {
720        skip_whitespace(&mut current_data_index, data)?;
721        if data[current_data_index] == b'}' {
722            return Ok((current_data_index+1,field_buffer.consume()))
723        } else if map_entry_needs_comma  {
724            if data[current_data_index] != b',' {
725                return Err(JsonParseFailure::InvalidStructure);
726            }
727            current_data_index += 1;
728            map_entry_needs_comma = false;
729        } else {
730            map_entry_needs_comma = true;
731            // let key_start_quote_index = current_data_index;
732            // current_data_index += 1; // include the quote for json string
733
734            let string_key = unescape_json_string(&mut current_data_index, data, string_escape_buffer)?;
735
736            // skip_json_string(&mut current_data_index, data)?;
737            // let key_end_quote_index = current_data_index;
738            // let string_key = core::str::from_utf8(&data[key_start_quote_index+1..key_end_quote_index]).expect("skipped json object key string");
739            // current_data_index += 1;
740            skip_whitespace(&mut current_data_index, data)?;
741            if data[current_data_index] != b':' {
742                return Err(JsonParseFailure::InvalidStructure);
743            }
744            current_data_index += 1;
745            skip_whitespace(&mut current_data_index, data)?;
746
747            if data[current_data_index] == b'"' {
748                let unescaped_string_value = unescape_json_string(&mut current_data_index, data, string_escape_buffer)?;
749                field_buffer.write_thing(JsonField::new(string_key, JsonValue::String(unescaped_string_value)))?;
750            } else if data[current_data_index] == b'n' {
751                skip_literal(&mut current_data_index, data, "null", JsonParseFailure::InvalidBooleanField)?;
752                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Null))?;
753            } else if data[current_data_index] == b't' || data[current_data_index] == b'f' {
754                let expect_true = data[current_data_index] == b't';
755                skip_literal(&mut current_data_index, data, if expect_true { "true" } else { "false"}, JsonParseFailure::InvalidBooleanField)?;
756                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Boolean(expect_true)))?;
757            } else if data[current_data_index] == b'-' {
758                // negative number
759                let minus_sign_numeric_start_index = current_data_index;
760                current_data_index += 1;
761                skip_numeric(&mut current_data_index, data)?;
762                let minus_sign_numeric_end = current_data_index;
763                if minus_sign_numeric_end - minus_sign_numeric_start_index == 1 {
764                    // no digits found
765                    return Err(JsonParseFailure::InvalidNumericField);
766                }
767                let numeric_string = core::str::from_utf8(&data[minus_sign_numeric_start_index..minus_sign_numeric_end]).expect("skipped negative number digit(s)");
768                let numeric_value: i64 = match numeric_string.parse() {
769                    Ok(i) => i,
770                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
771                };
772                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Number(numeric_value)))?;
773            } else if data[current_data_index] >= b'0' && data[current_data_index] < b'9' {
774                // positive number
775                let numeric_start_index = current_data_index;
776                current_data_index += 1;
777                skip_numeric(&mut current_data_index, data)?;
778                let numeric_after_index = current_data_index;
779                let numeric_string = core::str::from_utf8(&data[numeric_start_index..numeric_after_index]).expect("skipped positive number digit(s)");
780                let numeric_value: i64 = match numeric_string.parse() {
781                    Ok(i) => i,
782                    Err(_parse_int_error) => return Err(JsonParseFailure::NumberParseError),
783                };
784                field_buffer.write_thing(JsonField::new(string_key, JsonValue::Number(numeric_value)))?;
785            } else {
786                return Err(JsonParseFailure::InvalidStructure);
787            }
788        }
789    }
790    Err(JsonParseFailure::Incomplete)
791}
792
793const fn escape_char(c: char) -> Option<&'static str> {
794    Some(match c {
795        '"' => r#"\""#, // quotation mark
796        '\\' => r#"\\"#, // reverse solidus
797        '/' => r#"\/"#, // solidus
798        '\u{0008}' =>  r#"\b"#, // backspace
799        '\u{000C}' =>  r#"\f"#, // form feed
800        '\n' =>  r#"\n"#, // line feed
801        '\r' => r#"\r"#, // carriage return
802        '\t' => r#"\t"#, // character tabulation
803        _ => return None,
804    })
805}
806
807const fn unescape_char(c: char) -> Option<char> {
808    Some(match c {
809        '"' => '"',
810        '\\' => '\\',
811        '/' => '/',
812        'b' => '\u{0008}',
813        'f' => '\u{000C}',
814        'n' => '\n',
815        'r' => '\r',
816        't' => '\t',
817        _ => return None,
818    })
819}
820
821fn unescape_json_string<'data,'escaped>(index: &mut usize, data: &[u8], escaped: &mut StringBuffer<'escaped>) -> Result<&'escaped str,JsonParseFailure> {
822    if data[*index] != b'\"' {
823        return Err(JsonParseFailure::InvalidStringField);
824    }
825    *index += 1;
826    let mut current_char_escaped = false;
827    let mut encoding_buffer = [0_u8; 4];
828    while *index < data.len() {
829        let current_char = data[*index];
830        if !current_char.is_ascii() {
831            return Err(JsonParseFailure::InvalidStringField);
832        } else if current_char_escaped {
833            if let Some(unescaped_char) = unescape_char(current_char as char) {
834                let encoded = unescaped_char.encode_utf8(&mut encoding_buffer);
835                escaped.write_part(&encoded)?;
836                *index += 1;
837                current_char_escaped = false;
838            } else {
839                return Err(JsonParseFailure::InvalidStringField);
840            }
841        } else if current_char == '\\' as u8 {
842            current_char_escaped = true;
843            *index += 1;
844        } else if current_char == '"' as u8 {
845            *index += 1;
846            return Ok(escaped.consume_string());
847        } else {
848            let encoded = (current_char as char).encode_utf8(&mut encoding_buffer);
849            escaped.write_part(&encoded)?;
850            *index += 1;
851        }
852        // else if '\\' as u8 == current_char {
853        //     if current_char_escaped {
854        //         escaped.write_part("\\")?;
855        //         current_char_escaped = false;
856        //     } else {
857        //         current_char_escaped = true;
858        //     }
859        // } else if '"' as u8 == current_char {
860        //     if current_char_escaped {
861        //         escaped.write_part(r#"""#)?;
862        //         current_char_escaped = false;
863        //     } else {
864        //         *index += 1;
865        //         return Ok(escaped.consume_string());
866        //     }
867        // } else if let Some(escape_sequence) = escape_char(current_char as char) {
868        //     if !current_char_escaped {
869        //         return Err(JsonParseFailure::InvalidStringField);
870        //     }
871        //     let mut char_buffer = [0_u8; 4];
872        //     let char_as_str = (current_char as char).encode_utf8(&mut char_buffer);
873        //     escaped.write_part(char_as_str)?;
874        //     *index += char_as_str.len();
875        //     current_char_escaped = false;
876        // } else {
877        //     let mut char_buffer = [0_u8; 4];
878        //     let char_as_str = (current_char as char).encode_utf8(&mut char_buffer);
879        //     escaped.write_part(char_as_str)?;
880        //     *index += char_as_str.len();
881        //     current_char_escaped = false;
882        // }
883    }
884    Err(JsonParseFailure::Incomplete)
885}
886
887const fn skip_numeric(index: &mut usize, data: &[u8]) -> Result<(),JsonParseFailure> {
888    while *index < data.len() && data[*index] <= b'9' && data[*index] >= b'0' {
889        *index += 1;
890    }
891    if *index == data.len() {
892        Err(JsonParseFailure::Incomplete)
893    } else if data[*index].is_ascii_whitespace() || data[*index] == b',' || data[*index] == b'}' {
894        Ok(())
895    } else {
896        Err(JsonParseFailure::InvalidNumericField)
897    }
898}
899
900fn skip_literal(index: &mut usize, data: &[u8], target: &str, field_error_type: JsonParseFailure) -> Result<(),JsonParseFailure> {
901    let start = *index;
902    while (*index - start) < target.len() {
903        if *index >= data.len() {
904            return Err(JsonParseFailure::Incomplete)
905        }
906        if data[*index] != target.as_bytes()[*index-start] {
907            return Err(field_error_type);
908        }
909        *index += 1;
910    }
911    Ok(())
912}
913
914fn skip_whitespace(index: &mut usize, data: &[u8]) -> Result<(),JsonParseFailure> {
915    while *index < data.len() && data[*index].is_ascii_whitespace() {
916        *index += 1;
917    }
918    if *index == data.len() {
919        Err(JsonParseFailure::Incomplete)
920    } else {
921        Ok(())
922    }
923}
924
925/// 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.
926fn serialize_json_array<'data, Output: Write>(
927    output: &mut Output,
928    fields: &[JsonValue<'data>],
929) -> Result<usize, Output::Error> {
930    serialize_json_array_internal(output, fields)
931}
932
933fn serialize_json_array_internal<'data, Output: StringWrite>(
934    output: &mut Output,
935    fields: &[JsonValue<'data>],
936) -> Result<usize, Output::StringWriteFailure> {
937    let mut ret = 0;
938    tracked_write(output,&mut ret , LEFT_SQUARE_BRACKET)?;
939    let mut value_needs_comma = false;
940    for value in fields.as_ref().iter() {
941        if value_needs_comma {
942            tracked_write(output,&mut ret , ",")?;
943        } else {
944            value_needs_comma = true;
945        }
946        match *value {
947            JsonValue::Boolean(b) => if b {
948                tracked_write(output,&mut ret , "true")?;
949            } else {
950                tracked_write(output,&mut ret , "false")?;
951            },
952            JsonValue::Null => {
953                tracked_write(output,&mut ret , "null")?;
954            },
955            JsonValue::Number(n) => {
956                tracked_write(output,&mut ret , base10::i64(n).as_str())?;
957            },
958            JsonValue::String(s) => {
959                write_escaped_json_string(output, &mut ret , s)?;
960            },
961        }
962    }
963    tracked_write(output, &mut ret , RIGHT_SQUARE_BRACKET)?;
964    Ok(ret)
965}
966
967// const LEFT_SQUARE_BRACKET_CHAR: char = '{';
968const LEFT_SQUARE_BRACKET: &str = "[";
969const LEFT_CURLY_BRACKET: &str = "{";
970const RIGHT_SQUARE_BRACKET: &str = "]";
971const RIGHT_CURLY_BRACKET: &str = "}";
972const COLON: &str = ":";
973const COMMA: &str = ",";
974
975/// 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.
976pub fn serialize_json_object<'data, Output: Write>(
977    output: &mut Output,
978    fields: &[JsonField<'data,'data>],
979) -> Result<usize, Output::Error> {
980    serialize_json_object_internal(output, fields)
981}
982
983fn serialize_json_object_internal<'data, Output: StringWrite>(
984    output: &mut Output,
985    fields: &[JsonField<'data,'data>],
986) -> Result<usize, Output::StringWriteFailure> {
987    let mut ret = 0;
988    tracked_write(output,&mut ret , LEFT_CURLY_BRACKET)?;
989    let mut field_needs_comma = false;
990    for field in fields.as_ref().iter() {
991        if field_needs_comma {
992            tracked_write(output,&mut ret , COMMA)?;
993        } else {
994            field_needs_comma = true;
995        }
996        write_escaped_json_string(output, &mut ret , field.key)?;
997        tracked_write(output, &mut ret , COLON)?;
998        match field.value {
999            JsonValue::Boolean(b) => if b {
1000                tracked_write(output,&mut ret , "true")?;
1001            } else {
1002                tracked_write(output,&mut ret , "false")?;
1003            },
1004            JsonValue::Null => {
1005                tracked_write(output,&mut ret , "null")?;
1006            },
1007            JsonValue::Number(n) => {
1008                tracked_write(output,&mut ret , base10::i64(n).as_str())?;
1009            },
1010            JsonValue::String(s) => {
1011                write_escaped_json_string(output, &mut ret , s)?;
1012            },
1013        }
1014    }
1015    tracked_write(output, &mut ret , RIGHT_CURLY_BRACKET)?;
1016    Ok(ret)
1017}
1018
1019fn tracked_write<T: StringWrite>(output: &mut T, counter: &mut usize, data: &str) -> Result<(), T::StringWriteFailure> {
1020    match output.write_string(data) {
1021        Ok(()) => {
1022            *counter += data.len();
1023            Ok(())
1024        },
1025        Err((partial, e)) => {
1026            *counter += partial;
1027            Err(e)
1028        },
1029    }
1030}
1031
1032fn write_escaped_json_string<T: StringWrite>(output: &mut T, counter: &mut usize, data: &str) -> Result<(), T::StringWriteFailure> {
1033    tracked_write(output, counter, "\"")?;
1034    for field_character in data.chars() {
1035        if !field_character.is_ascii() {
1036            continue;
1037        } else if let Some(escape_sequence) = escape_char(field_character) {
1038            tracked_write(output, counter, escape_sequence)?;
1039        } else {
1040            tracked_write(output, counter, field_character.encode_utf8(&mut [0_u8; 4]))?;
1041        }
1042    }
1043    tracked_write(output, counter, "\"")?;
1044    Ok(())
1045}
1046
1047#[cfg(feature = "alloc")]
1048#[doc(cfg(feature = "alloc"))]
1049mod alloc {
1050
1051    extern crate alloc as alloclib;
1052    
1053
1054    use alloclib::string::String;
1055    use alloclib::vec::Vec;
1056
1057    pub use elsa::FrozenVec;
1058
1059    use crate::{parse_json_object, FieldBufferMut, JsonField, JsonObject, JsonParseFailure, ParseBuffer, StringBuffer};
1060
1061    impl <'a, T: FieldBufferMut<'a>> JsonObject<T> {
1062        /// 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
1063        /// returns num bytes consumed on success
1064        pub fn parse_alloc_buffer(&mut self, data: &'a [u8], escape_buffer: &'a FrozenVec<String>) -> Result<usize,JsonParseFailure> {
1065            let (data_end, parsed_fields) = parse_json_object(
1066                data,
1067                ParseBuffer::Finite(0,self.fields.as_mut()),
1068                &mut crate::StringBuffer::Infinite(String::new(), escape_buffer)
1069            )?;
1070            let new_num_fields = parsed_fields;
1071            self.num_fields = new_num_fields;
1072            Ok(data_end)
1073        }
1074    }
1075
1076    impl <'a, T: AsMut<Vec<JsonField<'a,'a>>>> JsonObject<T> {
1077
1078        /// 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
1079        /// returns num bytes consumed on success
1080        pub fn parse_alloc_fields(&mut self, data: &'a [u8], escape_buffer: &'a mut [u8]) -> Result<usize,JsonParseFailure> {
1081            let (data_end, parsed_fields) = parse_json_object(
1082                data,
1083                ParseBuffer::Infinite(0, self.fields.as_mut()),
1084                &mut StringBuffer::Finite(0, escape_buffer),
1085            )?;
1086            let new_num_fields = parsed_fields;
1087            self.num_fields = new_num_fields;
1088            Ok(data_end)
1089        }
1090
1091        /// 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
1092        /// returns num bytes consumed on success
1093        pub fn parse_alloc(&mut self, data: &'a [u8], escape_buffer: &'a FrozenVec<String>) -> Result<usize,JsonParseFailure> {
1094            let (data_end, parsed_fields) = parse_json_object(
1095                data,
1096                ParseBuffer::Infinite(0, self.fields.as_mut()),
1097                &mut crate::StringBuffer::Infinite(String::new(), escape_buffer),
1098            )?;
1099            let new_num_fields = parsed_fields;
1100            self.num_fields = new_num_fields;
1101            Ok(data_end)
1102        }
1103    }
1104
1105    // impl<V> JsonBuffer<V> for Vec<V> {}
1106    // impl<V> JsonBuffer<V> for &Vec<V> {}
1107    // impl<V> JsonBuffer<V> for &mut Vec<V> {}
1108    // impl<V> JsonBufferMut<V> for Vec<V> {
1109    //     fn set_or_push_value(&mut self, n: usize, value: V) -> Result<(), JsonParseFailure> {
1110    //         assert!(n <= self.len());
1111    //         if n == self.len() {
1112    //             self.push(value);
1113    //         } else {
1114    //             self[n] = value;
1115    //         }
1116    //         Ok(())
1117    //     }
1118    // }
1119    // impl<V> JsonBufferMut<V> for &mut Vec<V> {
1120    //     fn set_or_push_value(&mut self, n: usize, value: V) -> Result<(), JsonParseFailure> {
1121    //         assert!(n <= self.len());
1122    //         if n == self.len() {
1123    //             self.push(value);
1124    //         } else {
1125    //             self[n] = value;
1126    //         }
1127    //         Ok(())
1128    //     }
1129    // }
1130
1131
1132}
1133
1134
1135#[cfg(feature = "std")]
1136#[doc(cfg(feature = "std"))]
1137mod stdlib {
1138    extern crate std;
1139    use embedded_io_adapters::std::FromStd;
1140    use crate::FieldBuffer;
1141    use crate::JsonObject;
1142
1143    impl <'a,T: FieldBuffer<'a>> JsonObject<T> {
1144        /// convenience method to serialize to types implementing std::io::Write by wrapping it with embedded_io_adapters::std::FromStd
1145        pub fn serialize_std<Output: std::io::Write>(&self, output: Output) -> Result<usize,std::io::Error> {
1146            self.serialize(FromStd::new(output))
1147        }
1148    }
1149}
1150
1151#[cfg(all(test,feature = "alloc"))]
1152mod test_alloc {
1153    use super::*;
1154
1155    extern crate alloc;
1156    use alloc::vec::Vec;
1157    use alloclib::string::ToString;
1158
1159    #[test]
1160    fn test_parse_core_vec_no_alloc_too_many_fields() {
1161        match parse_json_object(
1162            br#"{"a":0}"#,
1163            ParseBuffer::Finite(0,&mut Vec::new()),
1164            &mut StringBuffer::Finite(0, &mut [0_u8; 256]),
1165        ) {
1166            Err(JsonParseFailure::FieldBufferTooSmall) => {},
1167            other => panic!("{:?}", other),
1168        }
1169    }
1170
1171    #[test]
1172    fn test_parse_core_vec_with_alloc_simple() {
1173        let mut fields = Vec::new();
1174        match parse_json_object(
1175            br#"{"a":0}"#,
1176            ParseBuffer::Infinite(0,&mut fields),
1177            &mut StringBuffer::Finite(0, &mut [0_u8; 256])
1178        ) {
1179            Ok((num_bytes, num_fields)) => {
1180                assert_eq!(7, num_bytes);
1181                assert_eq!(1, num_fields);
1182                assert_eq!(1, fields.len());
1183                assert_eq!(JsonField::new("a", JsonValue::Number(0)), fields[0])
1184            },
1185            other => panic!("{:?}", other),
1186        }
1187
1188    }
1189
1190    #[test]
1191    fn test_parse_core_vec_success_empty() {
1192        let (bytes_consumed,num_fields_parsed) = parse_json_object(
1193            b"{}",
1194            ParseBuffer::Infinite(0,&mut Vec::new()),
1195            &mut StringBuffer::Finite(0, &mut [0_u8; 256])
1196        ).unwrap();
1197        assert_eq!(2,bytes_consumed);
1198        assert_eq!(0,num_fields_parsed);
1199    }
1200
1201    #[test]
1202    fn test_parse_object_vec_success_empty() {
1203        let mut escape_buffer = [0_u8; 256];
1204        let mut parser = JsonObject::wrap(Vec::new());
1205        let bytes_consumed =  parser.parse(b"{}", &mut escape_buffer).unwrap();
1206        assert_eq!(0,parser.fields().len());
1207        assert_eq!(bytes_consumed, 2);
1208    }
1209
1210    #[test]
1211    fn test_serialize_empty_to_string() {
1212        let string: String = ArrayJsonObject::<0>::new().to_string();
1213        assert_eq!("{}", string);
1214    }
1215
1216
1217}
1218
1219#[cfg(test)]
1220mod test_core {
1221
1222    use super::*;
1223
1224    #[test]
1225    fn test_parse_value_string() {
1226        let data = br#""this is a string""#;
1227        match JsonValue::parse(data, &mut [0_u8; 16]) {
1228            Ok((value_end,value)) => {
1229                assert_eq!(data.len(),value_end);
1230                match value {
1231                    JsonValue::String(s) => {
1232                        assert_eq!("this is a string", s);
1233                    },
1234                    other => panic!("{:?}", other),
1235                }
1236            },
1237            other => panic!("{:?}", other),
1238        }
1239    }
1240
1241    #[test]
1242    fn test_parse_value_integer() {
1243        let data = br#"12345 "#;
1244        match JsonValue::parse(data, &mut [0_u8; 16]) {
1245            Ok((value_end,value)) => {
1246                assert_eq!(data.len(),value_end+1); // need non-numeric to recognize end
1247                match value {
1248                    JsonValue::Number(n) => {
1249                        assert_eq!(12345, n);
1250                    },
1251                    other => panic!("{:?}", other),
1252                }
1253            },
1254            other => panic!("{:?}", other),
1255        }
1256    }
1257
1258    #[test]
1259    fn test_parse_value_null() {
1260        let data = br#"null"#;
1261        match JsonValue::parse(data, &mut [0_u8; 16]) {
1262            Ok((value_end,value)) => {
1263                assert_eq!(data.len(),value_end);
1264                match value {
1265                    JsonValue::Null => {},
1266                    other => panic!("{:?}", other),
1267                }
1268            },
1269            other => panic!("{:?}", other),
1270        }
1271    }
1272
1273    #[test]
1274    fn test_parse_object_empty_core() {
1275        let mut escape_buffer = [0_u8; 256];
1276        let (bytes_consumed,num_fields) = parse_json_object(
1277            b"{}",
1278            ParseBuffer::Finite(0,&mut []),
1279            &mut StringBuffer::Finite(0, &mut escape_buffer),
1280        ).unwrap();
1281        assert_eq!(bytes_consumed, 2);
1282        assert_eq!(num_fields, 0);
1283    }
1284
1285    #[test]
1286    fn test_parse_object_empty_trait_array() {
1287        let mut parser = JsonObject::wrap([]);
1288        let bytes_consumed = parser.parse(b"{}", &mut []).unwrap();
1289        assert_eq!(bytes_consumed, 2);
1290        assert_eq!(parser.len(), 0);
1291    }
1292
1293    #[test]
1294    fn test_parse_object_empty_trait_slice() {
1295        let mut parser = JsonObject::wrap(&mut []);
1296        let bytes_consumed = parser.parse(b"{}", &mut []).unwrap();
1297        assert_eq!(bytes_consumed, 2);
1298        assert_eq!(parser.len(), 0);
1299    }
1300
1301    #[test]
1302    fn test_parse_object_empty_arrayhelper() {
1303        let mut parser = ArrayJsonObject::<0>::new();
1304        let bytes_consumed = parser.parse(b"{}", &mut []).unwrap();
1305        assert_eq!(bytes_consumed, 2);
1306        assert_eq!(parser.len(), 0);
1307    }
1308
1309    #[test]
1310    fn test_parse_object_simple() {
1311        let data = br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false,"null_thing":null}"#;
1312        let mut escape_buffer = [0_u8; 256];
1313        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1314        assert_eq!(data_end, data.len());
1315        let test_fields = json_object.fields();
1316        assert_eq!(5, test_fields.len());
1317        assert_eq!(JsonField { key: "sub", value: JsonValue::String("1234567890")}, test_fields[0]);
1318        assert_eq!(JsonField { key: "name", value: JsonValue::String("John Doe")}, test_fields[1]);
1319        assert_eq!(JsonField { key: "iat", value: JsonValue::Number(1516239022)}, test_fields[2]);
1320        assert_eq!(JsonField { key: "something", value: JsonValue::Boolean(false)}, test_fields[3]);
1321        assert_eq!(JsonField { key: "null_thing", value: JsonValue::Null}, test_fields[4]);
1322    }
1323
1324    #[test]
1325    fn test_parse_object_empty_strings() {
1326        let data = br#"{"":""}"#;
1327        let mut escape_buffer = [0_u8; 256];
1328        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1329        assert_eq!(data_end, data.len());
1330        let test_fields = json_object.fields();
1331        assert_eq!(1, test_fields.len());
1332        assert_eq!(JsonField { key: "", value: JsonValue::String("")}, test_fields[0]);
1333    }
1334
1335        #[test]
1336    fn test_parse_object_backspace_strings() {
1337        let data = br#"{"\b":""}"#;
1338        let mut escape_buffer = [0_u8; 256];
1339        let (data_end,json_object) = ArrayJsonObject::<50>::new_parsed(data, &mut escape_buffer).unwrap();
1340        assert_eq!(data_end, data.len());
1341        let test_fields = json_object.fields();
1342        assert_eq!(1, test_fields.len());
1343        assert_eq!(JsonField { key: "\u{0008}", value: JsonValue::String("")}, test_fields[0]);
1344    }
1345
1346    #[test]
1347    fn test_parse_object_ignore_trailing_whitespace() {
1348        let data = br#"{}    "#; // add 4 spaces to the end
1349        let (data_end,_) = ArrayJsonObject::<0>::new_parsed(data,&mut []).unwrap();
1350        assert_eq!(data_end, data.len() - 4);
1351    }
1352
1353    #[test]
1354    fn test_parse_object_failure_too_many_fields() {
1355        let mut escape_buffer = [0_u8; 256];
1356        match ArrayJsonObject::<0>::new_parsed(br#"{"some":"thing"}"#,&mut escape_buffer) {
1357            Err(JsonParseFailure::FieldBufferTooSmall) => {},
1358            other => panic!("{:?}", other)
1359        }
1360    }
1361
1362    // #[test]
1363    // fn test_parse_object_failure_invalid_number_minus() {
1364    //     match ArrayJsonObject::<1>::new_parsed(br#"{"": -}"#,&mut []) {
1365    //         Err(JsonParseFailure::InvalidNumericField) => {},
1366    //         other => panic!("{:?}", other)
1367    //     }
1368    // }
1369
1370    #[test]
1371    fn test_parse_object_failure_incomplete_a() {
1372        match ArrayJsonObject::<0>::new_parsed(b"{",&mut []) {
1373            Err(JsonParseFailure::Incomplete) => {},
1374            other => panic!("{:?}", other)
1375        }
1376    }
1377
1378    #[test]
1379    fn test_parse_object_failure_incomplete_b() {
1380        let mut escape_buffer = [0_u8; 256];
1381        match ArrayJsonObject::<50>::new_parsed(
1382            br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false"#,
1383            &mut escape_buffer,
1384        ) {
1385            Err(JsonParseFailure::Incomplete) => {},
1386            other => panic!("{:?}", other)
1387        }
1388    }
1389
1390    #[test]
1391    fn test_serialize_array_empty() {
1392        let mut buffer = [0_u8; 2];
1393        let test_array = ArrayJsonArray::<0>::new();
1394        let n = test_array.serialize(buffer.as_mut_slice()).unwrap();
1395        assert_eq!(b"[]", buffer.split_at(n).0)
1396    }
1397
1398    #[test]
1399    fn test_display_array_empty() {
1400        let mut buffer = [0_u8; 2];
1401        buffer.as_mut_slice().write_fmt(format_args!("{}", ArrayJsonArray::<0>::new())).unwrap();
1402        assert_eq!(b"[]", buffer.as_slice())
1403    }
1404
1405    #[test]
1406    fn test_serialize_object_empty() {
1407        let mut buffer = [0_u8; 2];
1408        let test_object = ArrayJsonObject::<0>::new();
1409        let n = test_object.serialize(buffer.as_mut_slice()).unwrap();
1410        assert_eq!(b"{}", buffer.split_at(n).0)
1411    }
1412
1413    #[test]
1414    fn test_display_object_empty() {
1415        let mut buffer = [0_u8; 2];
1416        buffer.as_mut_slice().write_fmt(format_args!("{}", ArrayJsonObject::<0>::new())).unwrap();
1417        assert_eq!(b"{}", buffer.as_slice())
1418    }
1419
1420    #[test]
1421    fn test_serialize_object_simple() {
1422        let mut buffer = [0_u8; 1000];
1423        let mut test_map = ArrayJsonObject::<50>::new();
1424        test_map.push_field("sub", JsonValue::String("1234567890")).unwrap();
1425        test_map.push_field("name", JsonValue::String("John Doe")).unwrap();
1426        test_map.push_field("iat", JsonValue::Number(1516239022)).unwrap();
1427        test_map.push_field("something", JsonValue::Boolean(false)).unwrap();
1428        test_map.push_field("null_thing", JsonValue::Null).unwrap();
1429        let n = test_map.serialize(buffer.as_mut_slice()).unwrap();
1430        assert_eq!(br#"{"sub":"1234567890","name":"John Doe","iat":1516239022,"something":false,"null_thing":null}"#, buffer.split_at(n).0)
1431    }
1432
1433}