nop_json/
nop_json.rs

1pub use nop_json_derive::*;
2use crate::value::Value;
3
4use std::{io, io::Write, char, fmt};
5use std::collections::{HashMap, HashSet, BTreeMap, BTreeSet, LinkedList, VecDeque};
6use std::convert::TryInto;
7use numtoa::NumToA;
8
9pub const READER_BUFFER_SIZE: usize = 128;
10const FORMAT_NUM_WIDTH: usize = 10;
11const FORMAT_NUM_WIDTH_Z: [u8; FORMAT_NUM_WIDTH] = [b'0'; FORMAT_NUM_WIDTH];
12const FORMAT_NUM_WIDTH_0Z: &[u8] = b"0.0000000000";
13
14macro_rules! read_int
15{	($self:expr, $T:ty, $is_unsigned:expr) =>
16	{	{	let mut is_in_string = false;
17			let mut c = $self.lookahead;
18			loop
19			{	match c
20				{	b' ' | b'\t' | b'\r' | b'\n' =>
21					{	c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
22					}
23					b'n' =>
24					{	if is_in_string
25						{	$self.skip_string()?;
26							return Ok(0);
27						}
28						if let Some(b'u') = $self.iter.next()
29						{	if let Some(b'l') = $self.iter.next()
30							{	if let Some(b'l') = $self.iter.next()
31								{	if let Some(c) = $self.iter.next()
32									{	if !c.is_ascii_alphanumeric() && c!=b'_'
33										{	$self.lookahead = c;
34											return Ok(0 as $T);
35										}
36									}
37									else
38									{	$self.lookahead = b' ';
39										return Ok(0 as $T);
40									}
41								}
42							}
43						}
44						$self.lookahead = b' ';
45						return Err($self.format_error("Invalid JSON input: unexpected identifier"));
46					}
47					b'f' =>
48					{	if is_in_string
49						{	$self.skip_string()?;
50							return Ok(0);
51						}
52						if let Some(b'a') = $self.iter.next()
53						{	if let Some(b'l') = $self.iter.next()
54							{	if let Some(b's') = $self.iter.next()
55								{	if let Some(b'e') = $self.iter.next()
56									{	if let Some(c) = $self.iter.next()
57										{	if !c.is_ascii_alphanumeric() && c!=b'_'
58											{	$self.lookahead = c;
59												return Ok(0 as $T);
60											}
61										}
62										else
63										{	$self.lookahead = b' ';
64											return Ok(0 as $T);
65										}
66									}
67								}
68							}
69						}
70						$self.lookahead = b' ';
71						return Err($self.format_error("Invalid JSON input: unexpected identifier"));
72					}
73					b't' =>
74					{	if is_in_string
75						{	$self.skip_string()?;
76							return Ok(0);
77						}
78						if let Some(b'r') = $self.iter.next()
79						{	if let Some(b'u') = $self.iter.next()
80							{	if let Some(b'e') = $self.iter.next()
81								{	if let Some(c) = $self.iter.next()
82									{	if !c.is_ascii_alphanumeric() && c!=b'_'
83										{	$self.lookahead = c;
84											return Ok(1 as $T);
85										}
86									}
87									else
88									{	$self.lookahead = b' ';
89										return Ok(1 as $T);
90									}
91								}
92							}
93						}
94						$self.lookahead = b' ';
95						return Err($self.format_error("Invalid JSON input: unexpected identifier"));
96					}
97					b'0'..=b'9' | b'-' | b'.' =>
98					{	let mut is_negative = false;
99						let mut exponent = 0i32;
100						let mut is_after_dot = false;
101						let mut result = 0 as $T;
102						let mut ten = 10 as $T;
103						let mut is_error = false;
104						if c == b'-'
105						{	is_negative = true;
106							c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
107						}
108						loop
109						{	match c
110							{	b'0' =>
111								{	ten = ten.checked_mul(10).unwrap_or_else(|| {if !is_after_dot {is_error = true}; 0});
112								}
113								b'1'..= b'9' =>
114								{	if !is_after_dot
115									{	result = result.checked_mul(ten).unwrap_or_else(|| {is_error = true; 0});
116										result = result.checked_add(if $is_unsigned {(c - b'0') as $T} else {(b'0' as i8 - c as i8) as $T}).unwrap_or_else(|| {is_error = true; 0}); // if signed, make negative number (because wider range), and then negate (if not is_negative)
117										ten = 10 as $T;
118									}
119								}
120								b'.' => {is_after_dot = true}
121								b'e' | b'E' =>
122								{	c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
123									let mut n_is_negative = false;
124									match c
125									{	b'+' => {c = b'0'}
126										b'-' => {c = b'0'; n_is_negative = true}
127										b'0' ..= b'9' => {}
128										_ =>
129										{	$self.lookahead = c;
130											if is_in_string
131											{	if c != b'"' {$self.skip_string()?} else {$self.lookahead = b' '};
132												return Ok(0);
133											}
134											return Err($self.format_error("Invalid JSON input: invalid number format"));
135										}
136									};
137									let mut n: i32 = 0;
138									loop
139									{	match c
140										{	b'0' =>
141											{	n = n.checked_mul(10).unwrap_or_else(|| {is_error = true; 0});
142											}
143											b'1'..=b'9' =>
144											{	n = n.checked_mul(10).and_then(|n| n.checked_add((c-b'0') as i32)).unwrap_or_else(|| {is_error = true; 0});
145											}
146											_ =>
147											{	$self.lookahead = c;
148												break;
149											}
150										}
151										if let Some(new_c) = $self.iter.next()
152										{	c = new_c;
153										}
154										else
155										{	$self.lookahead = b' ';
156											if is_in_string
157											{	return Err($self.format_error("Invalid JSON input: unexpected end of input"));
158											}
159											break;
160										}
161									}
162									exponent = if n_is_negative {-n} else {n};
163									break;
164								}
165								_ =>
166								{	$self.lookahead = c;
167									break;
168								}
169							}
170							if let Some(new_c) = $self.iter.next()
171							{	c = new_c;
172							}
173							else
174							{	$self.lookahead = b' ';
175								if is_in_string
176								{	return Err($self.format_error("Invalid JSON input: unexpected end of input"));
177								}
178								break;
179							}
180						}
181						if !is_after_dot && ten>(10 as $T)
182						{	result = result.checked_mul(ten / (10 as $T)).unwrap_or_else(|| {is_error = true; 0});
183						}
184						if exponent != 0
185						{	result = result.checked_mul((10 as $T).checked_pow(exponent as u32).unwrap_or_else(|| {is_error = true; 0})).unwrap_or_else(|| {is_error = true; 0});
186						}
187						if $is_unsigned
188						{	if is_negative
189							{	is_error = true;
190							}
191						}
192						else if !is_negative // i built negative number (see above), so make it nonnegative
193						{	result = result.checked_neg().unwrap_or_else(|| {is_error = true; 0});
194						}
195						if is_error
196						{	if is_in_string
197							{	if $self.lookahead!=b'"' {$self.skip_string()?} else {$self.lookahead = b' '};
198							}
199							return Err($self.number_error());
200						}
201						if is_in_string
202						{	let mut c = $self.lookahead;
203							$self.lookahead = b' ';
204							while c.is_ascii_whitespace()
205							{	match $self.iter.next()
206								{	Some(new_c) => c = new_c,
207									None => return Err($self.format_error("Invalid JSON: unexpected end of input"))
208								}
209							}
210							if c != b'"'
211							{	$self.skip_string()?;
212								return Ok(0);
213							}
214						}
215						return Ok(result);
216					}
217					b'"' =>
218					{	if !is_in_string
219						{	is_in_string = true;
220							c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
221						}
222						else
223						{	$self.lookahead = b' ';
224							return Ok(0);
225						}
226					}
227					b'[' =>
228					{	if is_in_string
229						{	$self.skip_string()?;
230							return Ok(0);
231						}
232						$self.lookahead = b' ';
233						return Err($self.format_error("Invalid JSON input: value must be number, not array"));
234					}
235					b'{' =>
236					{	if is_in_string
237						{	$self.skip_string()?;
238							return Ok(0);
239						}
240						$self.lookahead = b' ';
241						return Err($self.format_error("Invalid JSON input: value must be number, not object"));
242					}
243					_ =>
244					{	if is_in_string
245						{	$self.skip_string()?;
246							return Ok(0);
247						}
248						$self.lookahead = b' ';
249						return Err($self.format_error_fmt(format_args!("Invalid JSON input: unexpected '{}'", String::from_utf8_lossy(&[c]))));
250					}
251				}
252			}
253		}
254	}
255}
256
257macro_rules! read_float
258{	($self:expr, $T:ty, $nan:expr, $infinity:expr, $neg_infinity:expr) =>
259	{	{	let mut is_in_string = false;
260			let mut c = $self.lookahead;
261			loop
262			{	match c
263				{	b' ' | b'\t' | b'\r' | b'\n' =>
264					{	c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
265					}
266					b'n' =>
267					{	if is_in_string
268						{	$self.skip_string()?;
269							return Ok($nan);
270						}
271						if let Some(b'u') = $self.iter.next()
272						{	if let Some(b'l') = $self.iter.next()
273							{	if let Some(b'l') = $self.iter.next()
274								{	if let Some(c) = $self.iter.next()
275									{	if !c.is_ascii_alphanumeric() && c!=b'_'
276										{	$self.lookahead = c;
277											return Ok(0 as $T);
278										}
279									}
280									else
281									{	$self.lookahead = b' ';
282										return Ok(0 as $T);
283									}
284								}
285							}
286						}
287						$self.lookahead = b' ';
288						return Err($self.format_error("Invalid JSON input: unexpected identifier"));
289					}
290					b'f' =>
291					{	if is_in_string
292						{	$self.skip_string()?;
293							return Ok($nan);
294						}
295						if let Some(b'a') = $self.iter.next()
296						{	if let Some(b'l') = $self.iter.next()
297							{	if let Some(b's') = $self.iter.next()
298								{	if let Some(b'e') = $self.iter.next()
299									{	if let Some(c) = $self.iter.next()
300										{	if !c.is_ascii_alphanumeric() && c!=b'_'
301											{	$self.lookahead = c;
302												return Ok(0 as $T);
303											}
304										}
305										else
306										{	$self.lookahead = b' ';
307											return Ok(0 as $T);
308										}
309									}
310								}
311							}
312						}
313						$self.lookahead = b' ';
314						return Err($self.format_error("Invalid JSON input: unexpected identifier"));
315					}
316					b't' =>
317					{	if is_in_string
318						{	$self.skip_string()?;
319							return Ok($nan);
320						}
321						if let Some(b'r') = $self.iter.next()
322						{	if let Some(b'u') = $self.iter.next()
323							{	if let Some(b'e') = $self.iter.next()
324								{	if let Some(c) = $self.iter.next()
325									{	if !c.is_ascii_alphanumeric() && c!=b'_'
326										{	$self.lookahead = c;
327											return Ok(1 as $T);
328										}
329									}
330									else
331									{	$self.lookahead = b' ';
332										return Ok(1 as $T);
333									}
334								}
335							}
336						}
337						$self.lookahead = b' ';
338						return Err($self.format_error("Invalid JSON input: unexpected identifier"));
339					}
340					b'0'..=b'9' | b'-' | b'.' =>
341					{	let mut is_negative = false;
342						let mut exponent = 0i32;
343						let mut is_after_dot = 0;
344						let mut result = 0 as $T;
345						let mut ten = 1;
346						let mut is_error = false;
347						if c == b'-'
348						{	is_negative = true;
349							c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
350							if is_in_string && c==b'I' // -Infinity?
351							{	$self.read_string_contents_as_bytes()?;
352								if $self.buffer_len >= 7 && &$self.buffer[.. 7] == b"nfinity"
353								{	if $self.buffer_len > 7 || $self.buffer[7 .. $self.buffer_len].iter().position(|c| !c.is_ascii_whitespace()).is_none()
354									{	return Ok($neg_infinity);
355									}
356								}
357								return Ok($nan);
358							}
359						}
360						loop
361						{	match c
362							{	b'0' =>
363								{	exponent += is_after_dot;
364									ten += 1;
365								}
366								b'1'..= b'9' =>
367								{	exponent += is_after_dot;
368									result *= match ten
369									{	1 => 10.0,
370										2 => 100.0,
371										3 => 1000.0,
372										4 => 10000.0,
373										5 => 100000.0,
374										6 => 1000000.0,
375										7 => 10000000.0,
376										8 => 100000000.0,
377										9 => 1000000000.0,
378										_ => (10 as $T).powi(ten)
379									};
380									result += (c - b'0') as $T;
381									ten = 1;
382								}
383								b'.' => {is_after_dot = -1}
384								b'e' | b'E' =>
385								{	c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
386									let mut n_is_negative = false;
387									match c
388									{	b'+' => {c = b'0'}
389										b'-' => {c = b'0'; n_is_negative = true}
390										b'0' ..= b'9' => {}
391										_ =>
392										{	$self.lookahead = c;
393											if is_in_string
394											{	if c != b'"' {$self.skip_string()?} else {$self.lookahead = b' '};
395												return Ok($nan);
396											}
397											return Err($self.format_error("Invalid JSON input: invalid number format"));
398										}
399									};
400									let mut n: i32 = 0;
401									loop
402									{	match c
403										{	b'0' =>
404											{	n = n.checked_mul(10).unwrap_or_else(|| {is_error = true; 0});
405											}
406											b'1'..=b'9' =>
407											{	n = n.checked_mul(10).and_then(|n| n.checked_add((c-b'0') as i32)).unwrap_or_else(|| {is_error = true; 0});
408											}
409											_ =>
410											{	$self.lookahead = c;
411												break;
412											}
413										}
414										if let Some(new_c) = $self.iter.next()
415										{	c = new_c;
416										}
417										else
418										{	$self.lookahead = b' ';
419											if is_in_string
420											{	return Err($self.format_error("Invalid JSON input: unexpected end of input"));
421											}
422											break;
423										}
424									}
425									match exponent.checked_add(if n_is_negative {-n} else {n})
426									{	Some(new_exponent) => exponent = new_exponent,
427										None => is_error = true
428									}
429									break;
430								}
431								_ =>
432								{	$self.lookahead = c;
433									break;
434								}
435							}
436							if let Some(new_c) = $self.iter.next()
437							{	c = new_c;
438							}
439							else
440							{	$self.lookahead = b' ';
441								if is_in_string
442								{	return Err($self.format_error("Invalid JSON input: unexpected end of input"));
443								}
444								break;
445							}
446						}
447						if is_error
448						{	if is_in_string
449							{	if $self.lookahead!=b'"' {$self.skip_string()?} else {$self.lookahead = b' '};
450							}
451							return Ok($nan);
452						}
453						exponent += ten - 1;
454						match exponent
455						{	0 => {},
456							1 => result *= 10.0,
457							2 => result *= 100.0,
458							3 => result *= 1000.0,
459							4 => result *= 10000.0,
460							5 => result *= 100000.0,
461							6 => result *= 1000000.0,
462							7 => result *= 10000000.0,
463							8 => result *= 100000000.0,
464							9 => result *= 1000000000.0,
465							_ => result *= (10 as $T).powi(exponent)
466						};
467						if is_negative
468						{	result = -result;
469						}
470						if is_in_string
471						{	let mut c = $self.lookahead;
472							$self.lookahead = b' ';
473							while c.is_ascii_whitespace()
474							{	match $self.iter.next()
475								{	Some(new_c) => c = new_c,
476									None => return Err($self.format_error("Invalid JSON: unexpected end of input"))
477								}
478							}
479							if c != b'"'
480							{	$self.skip_string()?;
481								return Ok($nan);
482							}
483						}
484						return Ok(result);
485					}
486					b'"' =>
487					{	if !is_in_string
488						{	is_in_string = true;
489							c = $self.iter.next().ok_or_else(|| $self.format_error("Invalid JSON: unexpected end of input"))?;
490						}
491						else
492						{	$self.lookahead = b' ';
493							return Ok($nan);
494						}
495					}
496					b'[' =>
497					{	if is_in_string
498						{	$self.skip_string()?;
499							return Ok($nan);
500						}
501						$self.lookahead = b' ';
502						return Err($self.format_error("Invalid JSON input: value must be number, not array"));
503					}
504					b'{' =>
505					{	if is_in_string
506						{	$self.skip_string()?;
507							return Ok($nan);
508						}
509						$self.lookahead = b' ';
510						return Err($self.format_error("Invalid JSON input: value must be number, not object"));
511					}
512					_ =>
513					{	if is_in_string
514						{	if c == b'I'
515							{	$self.read_string_contents_as_bytes()?;
516								if $self.buffer_len >= 7 && &$self.buffer[.. 7] == b"nfinity"
517								{	if $self.buffer_len > 7 || $self.buffer[7 .. $self.buffer_len].iter().position(|c| !c.is_ascii_whitespace()).is_none()
518									{	return Ok($infinity);
519									}
520								}
521							}
522							else
523							{	$self.skip_string()?;
524							}
525							return Ok($nan);
526						}
527						$self.lookahead = b' ';
528						return Err($self.format_error_fmt(format_args!("Invalid JSON input: unexpected '{}'", String::from_utf8_lossy(&[c]))));
529					}
530				}
531			}
532		}
533	}
534}
535
536
537/// Implementing this trait makes possible for any type (except unions) to be JSON deserializable. The common technique
538/// to implement this trait is automatically through `#[derive(TryFromJson)]`. Every type that implements `TryFromJson`
539/// must also implement [ValidateJson](trait.ValidateJson.html). And every deserializable field must implement `Default`.
540///
541/// # Examples
542///
543/// ```
544/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
545///
546/// #[derive(Default, TryFromJson, ValidateJson, DebugToJson, PartialEq)]
547/// struct Point {x: i32, y: i32}
548///
549/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
550/// #[json(type)]
551/// enum Geometry
552/// {	#[json(point)] Point(Point),
553/// 	#[json(cx, cy, r)] Circle(i32, i32, i32),
554/// 	Nothing,
555/// }
556///
557/// let mut reader = Reader::new(r#" {"type": "Point", "point": {"x": 0, "y": 0}} "#.bytes());
558/// let obj: Geometry = reader.read().unwrap();
559/// assert_eq!(obj, Geometry::Point(Point {x: 0, y: 0}));
560/// ```
561/// Here we deserialize a struct, and an enum. Struct `Point {x: 0, y: 0}` will be written as `{"x": 0, "y": 0}`.
562///
563/// We can use different names for "x" and "y". Every struct field can be optionally annotated with `#[json(field_name)]` attribute,
564/// or `#[json("field_name")]`.
565///
566/// For enums we need to give names to each field, plus to "variant" field. The name of the "variant" field is specified at enum level.
567/// In the example above, it's "type" (`#[json(type)]`). So `Geometry::Circle(0, 0, 1)` will be written as
568/// `{"type": "Circle", "cx": 0, "cy": 0, "r": 1}`.
569///
570/// Variant name is printed as it's called in enum ("Point", "Circle", "Nothing"). We can rename them if specify `#[json(variant_name(field_name_0, field_name_1, ...))]`.
571/// ```
572/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
573///
574/// #[derive(Default, TryFromJson, ValidateJson, DebugToJson, PartialEq)]
575/// struct Point {x: i32, y: i32}
576///
577/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
578/// #[json(var)]
579/// enum Geometry
580/// {	#[json(pnt(point))] Point(Point),
581/// 	#[json(cir(cx, cy, r))] Circle(i32, i32, i32),
582/// 	Nothing,
583/// }
584///
585/// let mut reader = Reader::new(r#" {"var": "pnt", "point": {"x": 0, "y": 0}} "#.bytes());
586/// let obj: Geometry = reader.read().unwrap();
587/// assert_eq!(obj, Geometry::Point(Point {x: 0, y: 0}));
588/// ```
589/// There's also another option: to choose variant according to content. To do so, we ommit `#[json(...)]` at enum level.
590/// This is only possible if variants have non-overlapping members.
591/// ```
592/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
593///
594/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
595/// struct Point {x: i32, y: i32}
596///
597/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
598/// enum Geometry
599/// {	#[json(point)] Point(Point),
600/// 	#[json(cx, cy, r)] Circle(i32, i32, i32),
601/// 	Nothing,
602/// }
603///
604/// let mut reader = Reader::new(r#" {"point": {"x": 0, "y": 0}} "#.bytes());
605/// let obj: Geometry = reader.read().unwrap();
606/// assert_eq!(obj, Geometry::Point(Point {x: 0, y: 0}));
607/// ```
608///
609/// To exclude a field from deserialization, and use default value for it, specify empty name (`#[json("")]`).
610///
611/// ```
612/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
613///
614/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
615/// struct Point {x: i32, y: i32, #[json("")] comments: String}
616///
617/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
618/// enum Geometry
619/// {	#[json(point)] Point(Point),
620/// 	#[json(cx, cy, r)] Circle(i32, i32, i32),
621/// 	Nothing,
622/// }
623///
624/// let mut reader = Reader::new(r#" {"point": {"x": 0, "y": 0, "comments": "hello"}} "#.bytes());
625/// let obj_0: Geometry = reader.read().unwrap();
626/// assert_eq!(obj_0, Geometry::Point(Point {x: 0, y: 0, comments: String::new()}));
627///
628/// let mut reader = Reader::new(r#" {"point": {"x": 0, "y": 0}} "#.bytes());
629/// let obj_0: Geometry = reader.read().unwrap();
630/// assert_eq!(obj_0, Geometry::Point(Point {x: 0, y: 0, comments: String::new()}));
631/// ```
632/// It's possible to validate object right after deserialization. To do so implement [ValidateJson](trait.ValidateJson.html).
633/// ```
634/// use nop_json::{Reader, TryFromJson, ValidateJson};
635///
636/// #[derive(TryFromJson, Debug)]
637/// struct FromTo {from: i32, to: i32}
638///
639/// impl ValidateJson for FromTo
640/// {	fn validate_json(self) -> Result<Self, String>
641/// 	{	if self.from <= self.to
642/// 		{	Ok(self)
643/// 		}
644/// 		else
645/// 		{	Err("to must be after from".to_string())
646/// 		}
647/// 	}
648/// }
649///
650/// let mut reader = Reader::new(r#" {"from": 1, "to": 2}  {"from": 2, "to": 1} "#.bytes());
651/// let from_to_1_2: Result<FromTo, std::io::Error> = reader.read();
652/// let from_to_2_1: Result<FromTo, std::io::Error> = reader.read();
653/// assert!(from_to_1_2.is_ok());
654/// assert!(from_to_2_1.is_err());
655///
656/// ```
657///
658/// ## Ignoring fields
659///
660/// By default invalid object properties report errors.
661/// ```
662/// use std::io;
663/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
664///
665/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
666/// struct Point {x: i32, y: i32}
667///
668/// let mut reader = Reader::new(r#" {"x": 0, "y": 1, "comments": "No comments"} "#.bytes());
669/// let obj_0: io::Result<Point> = reader.read();
670/// assert!(obj_0.is_err());
671/// ```
672///
673/// To ignore specific fields from JSON input, use `#[json_ignore(name_1, name_2)]` or `#[json_ignore("name_1", "name_2")]`.
674/// To ignore all unknown fields: `#[json_ignore]`.
675/// ```
676/// use std::io;
677/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
678///
679/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
680/// #[json_ignore]
681/// struct Point {x: i32, y: i32}
682///
683/// let mut reader = Reader::new(r#" {"x": 0, "y": 1, "comments": "No comments"} "#.bytes());
684/// let obj_0: Point = reader.read().unwrap();
685/// assert_eq!(obj_0, Point {x: 0, y: 1});
686/// ```
687/// In enums `#[json_ignore]` placed at enum level applies to all variants. Plus each variant can have it's own ignore list.
688/// ```
689/// use std::io;
690/// use nop_json::{Reader, TryFromJson, ValidateJson, DebugToJson};
691///
692/// #[derive(TryFromJson, ValidateJson, DebugToJson, PartialEq)]
693/// #[json(type)]
694/// #[json_ignore(comments)]
695/// enum Geometry
696/// {	#[json(point(x, y))]
697/// 	#[json_ignore(point_comments)]
698/// 	Point(i32, i32),
699///
700/// 	#[json(circle(cx, cy, r))]
701/// 	#[json_ignore(circle_comments)]
702/// 	Circle(i32, i32, i32),
703/// }
704///
705/// let mut reader = Reader::new(r#" {"type": "point", "x": 0, "y": 1, "comments": "No comments", "point_comments": "No comments"} "#.bytes());
706/// let obj_0: Geometry = reader.read().unwrap();
707/// assert_eq!(obj_0, Geometry::Point(0, 1));
708///
709/// let mut reader = Reader::new(r#" {"type": "point", "x": 0, "y": 1, "circle_comments": "No comments"} "#.bytes());
710/// let obj_0: io::Result<Geometry> = reader.read();
711/// assert!(obj_0.is_err());
712/// ```
713///
714/// ## Implementing TryFromJson manually
715///
716/// Automatic implementation through `#[derive(TryFromJson)]` has 1 limitation: object key string must be not longer
717/// than 128 bytes, or it will be truncated.
718///
719/// Sometimes there can be different reasons to implement `TryFromJson` manually.
720/// Let's see what the automatic implementation does expand to.
721/// ```
722/// use nop_json::{Reader, TryFromJson, ValidateJson};
723///
724/// struct Point {x: i32, y: i32}
725///
726/// impl ValidateJson for Point {}
727///
728/// impl TryFromJson for Point
729/// {	fn try_from_json<T>(reader: &mut Reader<T>) -> std::io::Result<Self> where T: Iterator<Item=u8>
730/// 	{	let mut x = None;
731/// 		let mut y = None;
732///
733/// 		reader.read_object_use_buffer
734/// 		(	|reader|
735/// 			{	match reader.get_key()
736/// 				{	b"x" => x = reader.read_prop("x")?,
737/// 					b"y" => y = reader.read_prop("y")?,
738/// 					_ => return Err(reader.format_error_fmt(format_args!("Invalid property: {}", String::from_utf8_lossy(reader.get_key()))))
739/// 				}
740/// 				Ok(())
741/// 			}
742/// 		)?;
743///
744/// 		let result = Self
745/// 		{	x: x.unwrap_or_default(),
746/// 			y: y.unwrap_or_default(),
747/// 		};
748/// 		result.validate_json().map_err(|msg| reader.format_error(&msg))
749/// 	}
750/// }
751/// ```
752/// This implementation uses [read_object_use_buffer()](struct.Reader.html#method.read_object_use_buffer) which reads object keys to internal buffer which is 128 bytes, without memory allocation.
753/// You can use [read_object()](struct.Reader.html#method.read_object) instead to read keys longer than 128 bytes. Also you can do different things in this implementation function.
754///
755/// The automatic `TryFromJson` implementation generates JSON objects. If our struct is just a wrapper around a primitive type, we may wish to serialize it to a primitive type.
756///
757/// ```
758/// use std::{io, fmt};
759/// use nop_json::{Reader, TryFromJson, DebugToJson, escape};
760///
761/// #[derive(PartialEq)]
762/// struct Wrapper
763/// {	value: String,
764/// 	comment: String,
765/// }
766///
767/// impl TryFromJson for Wrapper
768/// {	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
769/// 	{	reader.read::<String>().map(|value| Self {value, comment: Default::default()})
770/// 	}
771/// }
772/// impl DebugToJson for Wrapper
773/// {	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
774/// 	{	write!(f, "\"{}\"", escape(&self.value))
775/// 	}
776/// }
777/// impl fmt::Debug for Wrapper
778/// {	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
779/// 	{	DebugToJson::fmt(self, f)
780/// 	}
781/// }
782///
783/// let mut reader = Reader::new(r#" "the value" "#.bytes());
784/// let wrp: Wrapper = reader.read().unwrap();
785/// assert_eq!(wrp, Wrapper {value: "the value".to_string(), comment: "".to_string()});
786/// ```
787pub trait TryFromJson: Sized
788{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>;
789}
790
791impl TryFromJson for ()
792{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_and_discard()}
793}
794
795impl TryFromJson for isize
796{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_isize()}
797}
798
799impl TryFromJson for i128
800{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_i128()}
801}
802
803impl TryFromJson for i64
804{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_i64()}
805}
806
807impl TryFromJson for i32
808{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_i32()}
809}
810
811impl TryFromJson for i16
812{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_i16()}
813}
814
815impl TryFromJson for i8
816{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_i8()}
817}
818
819impl TryFromJson for usize
820{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_usize()}
821}
822
823impl TryFromJson for u128
824{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_u128()}
825}
826
827impl TryFromJson for u64
828{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_u64()}
829}
830
831impl TryFromJson for u32
832{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_u32()}
833}
834
835impl TryFromJson for u16
836{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_u16()}
837}
838
839impl TryFromJson for u8
840{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_u8()}
841}
842
843impl TryFromJson for f64
844{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_f64()}
845}
846
847impl TryFromJson for f32
848{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_f32()}
849}
850
851impl TryFromJson for bool
852{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_bool()}
853}
854
855impl TryFromJson for char
856{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_char()}
857}
858
859impl TryFromJson for String
860{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_string()}
861}
862
863impl TryFromJson for Value
864{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8> {reader.read_value()}
865}
866
867impl<U> TryFromJson for Box<U> where U: TryFromJson
868{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
869	{	Ok(Box::new(U::try_from_json(reader)?))
870	}
871}
872
873impl<U> TryFromJson for std::sync::RwLock<U> where U: TryFromJson
874{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
875	{	Ok(std::sync::RwLock::new(U::try_from_json(reader)?))
876	}
877}
878
879impl<U> TryFromJson for std::sync::Mutex<U> where U: TryFromJson
880{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
881	{	Ok(std::sync::Mutex::new(U::try_from_json(reader)?))
882	}
883}
884
885impl<U> TryFromJson for std::rc::Rc<U> where U: TryFromJson
886{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
887	{	Ok(std::rc::Rc::new(U::try_from_json(reader)?))
888	}
889}
890
891impl<U> TryFromJson for std::sync::Arc<U> where U: TryFromJson
892{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
893	{	Ok(std::sync::Arc::new(U::try_from_json(reader)?))
894	}
895}
896
897impl<U> TryFromJson for Option<U> where U: TryFromJson
898{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
899	{	if reader.get_next_char() != b'n'
900		{	Ok(Some(U::try_from_json(reader)?))
901		}
902		else // null or invalid
903		{	reader.read_and_discard()?; // Err if invalid
904			Ok(None)
905		}
906	}
907}
908
909impl<U> TryFromJson for Vec<U> where U: TryFromJson
910{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
911	{	let mut result = Vec::new();
912		reader.read_array
913		(	|reader|
914			{	result.push(reader.read_index()?);
915				Ok(())
916			}
917		)?;
918		Ok(result)
919	}
920}
921
922impl<U> TryFromJson for HashSet<U> where U: Eq + std::hash::Hash + TryFromJson
923{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
924	{	let mut result = HashSet::new();
925		reader.read_array
926		(	|reader|
927			{	result.insert(reader.read_index()?);
928				Ok(())
929			}
930		)?;
931		Ok(result)
932	}
933}
934
935impl<U> TryFromJson for LinkedList<U> where U: TryFromJson
936{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
937	{	let mut result = LinkedList::new();
938		reader.read_array
939		(	|reader|
940			{	result.push_back(reader.read_index()?);
941				Ok(())
942			}
943		)?;
944		Ok(result)
945	}
946}
947
948impl<U> TryFromJson for VecDeque<U> where U: TryFromJson
949{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
950	{	let mut result = VecDeque::new();
951		reader.read_array
952		(	|reader|
953			{	result.push_back(reader.read_index()?);
954				Ok(())
955			}
956		)?;
957		Ok(result)
958	}
959}
960
961impl<U> TryFromJson for BTreeSet<U> where U: std::cmp::Ord + TryFromJson
962{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
963	{	let mut result = BTreeSet::new();
964		reader.read_array
965		(	|reader|
966			{	result.insert(reader.read_index()?);
967				Ok(())
968			}
969		)?;
970		Ok(result)
971	}
972}
973
974impl<U> TryFromJson for HashMap<String, U> where U: TryFromJson
975{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
976	{	let mut result = HashMap::new();
977		reader.read_object
978		(	|reader, key|
979			{	result.insert(key, reader.read_index()?);
980				Ok(())
981			}
982		)?;
983		Ok(result)
984	}
985}
986
987impl<U> TryFromJson for BTreeMap<String, U> where U: TryFromJson
988{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
989	{	let mut result = BTreeMap::new();
990		reader.read_object
991		(	|reader, key|
992			{	result.insert(key, reader.read_index()?);
993				Ok(())
994			}
995		)?;
996		Ok(result)
997	}
998}
999
1000impl<U, V> TryFromJson for (U, V) where U: TryFromJson, V: TryFromJson
1001{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
1002	{	let (a, b) = match reader.next_token()?
1003		{	Token::Null => return Err(reader.format_error("Value must be array[2], not null")),
1004			Token::False => return Err(reader.format_error("Value must be array[2], not boolean")),
1005			Token::True => return Err(reader.format_error("Value must be array[2], not boolean")),
1006			Token::Number(_e, _n) => return Err(reader.format_error("Value must be array[2], not number")),
1007			Token::Quote => return Err(reader.format_error("Value must be array[2], not string")),
1008			Token::ArrayBegin =>
1009			{	// begin read tuple
1010				reader.path.push(PathItem::Index(0));
1011				// .0
1012				let a = U::try_from_json(reader)?;
1013				match reader.next_token()?
1014				{	Token::Null => return Err(reader.format_error("Invalid JSON input: expected ',', got null")),
1015					Token::False => return Err(reader.format_error("Invalid JSON input: expected ',', got false")),
1016					Token::True => return Err(reader.format_error("Invalid JSON input: expected ',', got true")),
1017					Token::Number(_e, _n) => return Err(reader.format_error("Invalid JSON input: expected ',', got number")),
1018					Token::Quote => return Err(reader.format_error("Invalid JSON input: expected ',', got string")),
1019					Token::ArrayBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '['")),
1020					Token::ArrayEnd => return Err(reader.format_error("Value must be array[2], not array[1]")),
1021					Token::ObjectBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '{'")),
1022					Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: expected ',', got '}'")),
1023					Token::Comma => {},
1024					Token::Colon => return Err(reader.format_error("Invalid JSON input: expected ',', got ':'")),
1025				}
1026				// next
1027				if let Some(p) = reader.path.last_mut()
1028				{	*p = PathItem::Index(1);
1029				}
1030				// .1
1031				let b = V::try_from_json(reader)?;
1032				match reader.next_token()?
1033				{	Token::Null => return Err(reader.format_error("Invalid JSON input: expected ',', got null")),
1034					Token::False => return Err(reader.format_error("Invalid JSON input: expected ',', got false")),
1035					Token::True => return Err(reader.format_error("Invalid JSON input: expected ',', got true")),
1036					Token::Number(_e, _n) => return Err(reader.format_error("Invalid JSON input: expected ',', got number")),
1037					Token::Quote => return Err(reader.format_error("Invalid JSON input: expected ',', got string")),
1038					Token::ArrayBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '['")),
1039					Token::ArrayEnd => {},
1040					Token::ObjectBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '{'")),
1041					Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: expected ',', got '}'")),
1042					Token::Comma => return Err(reader.format_error("Expected array with 2 elements, got more")),
1043					Token::Colon => return Err(reader.format_error("Invalid JSON input: expected ',', got ':'")),
1044				}
1045				// end read tuple
1046				reader.path.pop();
1047				(a, b)
1048			}
1049			Token::ArrayEnd => return Err(reader.format_error("Invalid JSON input: unexpected ']'")),
1050			Token::ObjectBegin => return Err(reader.format_error("Value must be array[2], not object")),
1051			Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: unexpected '}'")),
1052			Token::Comma => return Err(reader.format_error("Invalid JSON input: unexpected ','")),
1053			Token::Colon => return Err(reader.format_error("Invalid JSON input: unexpected ':'")),
1054		};
1055		Ok((a, b))
1056	}
1057}
1058
1059impl<U, V, W> TryFromJson for (U, V, W) where U: TryFromJson, V: TryFromJson, W: TryFromJson
1060{	fn try_from_json<T>(reader: &mut Reader<T>) -> io::Result<Self> where T: Iterator<Item=u8>
1061	{	let (a, b, c) = match reader.next_token()?
1062		{	Token::Null => return Err(reader.format_error("Value must be array[3], not null")),
1063			Token::False => return Err(reader.format_error("Value must be array[3], not boolean")),
1064			Token::True => return Err(reader.format_error("Value must be array[3], not boolean")),
1065			Token::Number(_e, _n) => return Err(reader.format_error("Value must be array[3], not number")),
1066			Token::Quote => return Err(reader.format_error("Value must be array[3], not string")),
1067			Token::ArrayBegin =>
1068			{	// begin read tuple
1069				reader.path.push(PathItem::Index(0));
1070				// .0
1071				let a = U::try_from_json(reader)?;
1072				match reader.next_token()?
1073				{	Token::Null => return Err(reader.format_error("Invalid JSON input: expected ',', got null")),
1074					Token::False => return Err(reader.format_error("Invalid JSON input: expected ',', got false")),
1075					Token::True => return Err(reader.format_error("Invalid JSON input: expected ',', got true")),
1076					Token::Number(_e, _n) => return Err(reader.format_error("Invalid JSON input: expected ',', got number")),
1077					Token::Quote => return Err(reader.format_error("Invalid JSON input: expected ',', got string")),
1078					Token::ArrayBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '['")),
1079					Token::ArrayEnd => return Err(reader.format_error("Value must be array[3], not array[1]")),
1080					Token::ObjectBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '{'")),
1081					Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: expected ',', got '}'")),
1082					Token::Comma => {},
1083					Token::Colon => return Err(reader.format_error("Invalid JSON input: expected ',', got ':'")),
1084				}
1085				// next
1086				if let Some(p) = reader.path.last_mut()
1087				{	*p = PathItem::Index(1);
1088				}
1089				// .1
1090				let b = V::try_from_json(reader)?;
1091				match reader.next_token()?
1092				{	Token::Null => return Err(reader.format_error("Invalid JSON input: expected ',', got null")),
1093					Token::False => return Err(reader.format_error("Invalid JSON input: expected ',', got false")),
1094					Token::True => return Err(reader.format_error("Invalid JSON input: expected ',', got true")),
1095					Token::Number(_e, _n) => return Err(reader.format_error("Invalid JSON input: expected ',', got number")),
1096					Token::Quote => return Err(reader.format_error("Invalid JSON input: expected ',', got string")),
1097					Token::ArrayBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '['")),
1098					Token::ArrayEnd => return Err(reader.format_error("Value must be array[3], not array[2]")),
1099					Token::ObjectBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '{'")),
1100					Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: expected ',', got '}'")),
1101					Token::Comma => {},
1102					Token::Colon => return Err(reader.format_error("Invalid JSON input: expected ',', got ':'")),
1103				}
1104				// next
1105				if let Some(p) = reader.path.last_mut()
1106				{	*p = PathItem::Index(2);
1107				}
1108				// .2
1109				let c = W::try_from_json(reader)?;
1110				match reader.next_token()?
1111				{	Token::Null => return Err(reader.format_error("Invalid JSON input: expected ',', got null")),
1112					Token::False => return Err(reader.format_error("Invalid JSON input: expected ',', got false")),
1113					Token::True => return Err(reader.format_error("Invalid JSON input: expected ',', got true")),
1114					Token::Number(_e, _n) => return Err(reader.format_error("Invalid JSON input: expected ',', got number")),
1115					Token::Quote => return Err(reader.format_error("Invalid JSON input: expected ',', got string")),
1116					Token::ArrayBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '['")),
1117					Token::ArrayEnd => {},
1118					Token::ObjectBegin => return Err(reader.format_error("Invalid JSON input: expected ',', got '{'")),
1119					Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: expected ',', got '}'")),
1120					Token::Comma => return Err(reader.format_error("Expected array with 3 elements, got more")),
1121					Token::Colon => return Err(reader.format_error("Invalid JSON input: expected ',', got ':'")),
1122				}
1123				// end read tuple
1124				reader.path.pop();
1125				(a, b, c)
1126			}
1127			Token::ArrayEnd => return Err(reader.format_error("Invalid JSON input: unexpected ']'")),
1128			Token::ObjectBegin => return Err(reader.format_error("Value must be array[3], not object")),
1129			Token::ObjectEnd => return Err(reader.format_error("Invalid JSON input: unexpected '}'")),
1130			Token::Comma => return Err(reader.format_error("Invalid JSON input: unexpected ','")),
1131			Token::Colon => return Err(reader.format_error("Invalid JSON input: unexpected ':'")),
1132		};
1133		Ok((a, b, c))
1134	}
1135}
1136
1137
1138// pub Reader
1139
1140#[derive(Debug, Clone, Copy, PartialEq)]
1141enum Token
1142{	Null, False, True, Number(i16, bool), Quote, ArrayBegin, ArrayEnd, ObjectBegin, ObjectEnd, Comma, Colon
1143}
1144
1145enum PathItem
1146{	Prop(&'static str),
1147	Index(usize),
1148}
1149
1150pub fn number_to_string(buffer: &mut [u8; READER_BUFFER_SIZE], mut len: usize, mut exponent: i16, is_negative: bool) -> Result<usize, ()>
1151{	if len == 0
1152	{	buffer[0] = b'0';
1153		return Ok(1);
1154	}
1155	let mut pos = 0;
1156	if is_negative
1157	{	if len == buffer.len()
1158		{	len -= 1;
1159			exponent = exponent.checked_add(1).ok_or(())?;
1160		}
1161		buffer.copy_within(0..len, 1);
1162		buffer[0] = b'-';
1163		pos = 1;
1164	}
1165	if exponent >= 0
1166	{	let e = exponent as usize;
1167		if len+e <= FORMAT_NUM_WIDTH
1168		{	// append zeroes according to exponent
1169			&mut buffer[pos+len .. pos+len+e].copy_from_slice(&FORMAT_NUM_WIDTH_Z[0 .. e]);
1170			return Ok(pos + len + e);
1171		}
1172	}
1173	else
1174	{	let e = exponent.wrapping_neg() as usize;
1175		if e < len && len < buffer.len()-1
1176		{	// insert dot in the middle of number
1177			buffer.copy_within(pos+len-e .. pos+len, pos+len-e+1);
1178			buffer[pos+len-e] = b'.';
1179			return Ok(pos + len + 1);
1180		}
1181		if e <= FORMAT_NUM_WIDTH
1182		{	// prepend with 0.000...
1183			buffer.copy_within(pos .. pos+len, pos+e-len+2);
1184			&mut buffer[pos .. pos+e-len+2].copy_from_slice(&FORMAT_NUM_WIDTH_0Z[0 .. e-len+2]);
1185			return Ok(e + 2);
1186		}
1187	}
1188	len += pos;
1189	let mut buffer_2 = [0u8; 24];
1190	loop
1191	{	let exponent_str = exponent.numtoa(10, &mut buffer_2);
1192		if len+1+exponent_str.len() > buffer.len()
1193		{	let overflow = len+1+exponent_str.len() - buffer.len();
1194			exponent = exponent.checked_add(overflow as i16).ok_or(())?;
1195			len -= overflow;
1196		}
1197		else
1198		{	buffer[len] = b'e';
1199			len += 1;
1200			&mut buffer[len .. len+exponent_str.len()].copy_from_slice(exponent_str);
1201			len += exponent_str.len();
1202			return Ok(len);
1203		}
1204	}
1205}
1206
1207pub struct Reader<T> where T: Iterator<Item=u8>
1208{	iter: T,
1209	lookahead: u8,
1210	path: Vec<PathItem>,
1211	last_index: usize,
1212	buffer_len: usize,
1213	buffer: [u8; READER_BUFFER_SIZE], // must be at least 48 bytes for correct number reading
1214}
1215impl<T> Reader<T> where T: Iterator<Item=u8>
1216{	/// Construct new reader object, that can read values from a JSON stream, passing an object that implements `Iterator<Item=u8>`.
1217	/// This allows to use `&str` as data source like this:
1218	/// ```
1219	/// # use nop_json::Reader;
1220	/// let source = "\"Data\"";
1221	/// let mut reader = Reader::new(source.bytes());
1222	/// ```
1223	/// To use `&[u8]` do this:
1224	/// ```
1225	/// # use nop_json::Reader;
1226	/// let source: &[u8] = b"\"Data\"";
1227	/// let mut reader = Reader::new(source.iter().map(|i| *i));
1228	/// ```
1229	/// To use `std::io::Read` as source, you can convert it to `Iterator<Item=u8>` like this:
1230	/// ```
1231	/// use std::io::Read;
1232	/// use nop_json::Reader;
1233	/// let source = std::io::stdin();
1234	/// let source = source.lock(); // this implements std::io::Read
1235	/// let mut reader = Reader::new(source.bytes().map(|b| b.unwrap()));
1236	/// ```
1237	/// Though, this will panic on i/o error. Another technique is to use `read_iter` crate.
1238	/// ```
1239	/// use read_iter::ReadIter;
1240	/// use nop_json::Reader;
1241	/// let mut source = ReadIter::new(std::io::stdin());
1242	/// let mut reader = Reader::new(&mut source);
1243	/// // ...
1244	/// source.take_last_error().unwrap();
1245	/// ```
1246	/// To read from file:
1247	/// ```no_run
1248	/// use std::fs::File;
1249	/// use read_iter::ReadIter;
1250	/// use nop_json::Reader;
1251	/// let mut source = ReadIter::new(File::open("/tmp/test.json").unwrap());
1252	/// let mut reader = Reader::new(&mut source);
1253	/// // ...
1254	/// source.take_last_error().unwrap();
1255	/// ```
1256	pub fn new(iter: T) -> Reader<T>
1257	{	Reader
1258		{	iter,
1259			lookahead: b' ',
1260			path: Vec::new(),
1261			last_index: 0,
1262			buffer_len: 0,
1263			buffer: [0u8; READER_BUFFER_SIZE],
1264		}
1265	}
1266
1267	/// Destroy this reader, unwrapping the underlying iterator that was passed to constructor when this object created.
1268	pub fn unwrap(self) -> T
1269	{	self.iter
1270	}
1271
1272	/// Read one JSON value from the stream.
1273	///
1274	/// The value will be converted to target variable type with [TryFromJson](trait.TryFromJson.html) trait.
1275	/// The conversion is inspired by Javascript values conversion.
1276	/// For example, a JSON string that represents a number (like "123.4e5") can be read to a numeric variable.
1277	pub fn read<U>(&mut self) -> io::Result<U> where U: TryFromJson
1278	{	U::try_from_json(self)
1279	}
1280
1281	/// This method is intended for use in cases when you want to implement [TryFromJson](trait.TryFromJson.html) manually.
1282	/// Use it when you read an object with [read_object()](struct.Reader.html#method.read_object) or [read_object_use_buffer()](struct.Reader.html#method.read_object_use_buffer).
1283	/// It works exactly like `read()`, but uses provided static string in error message. This string must be the name of the object property that you are reading.
1284	pub fn read_prop<U>(&mut self, prop: &'static str) -> io::Result<U> where U: TryFromJson
1285	{	self.path.push(PathItem::Prop(prop));
1286		let result = self.read();
1287		self.path.pop();
1288		result
1289	}
1290
1291	/// This method is intended for use in cases when you want to implement [TryFromJson](trait.TryFromJson.html) manually.
1292	/// Use it when you read an array with [read_array()](struct.Reader.html#method.read_array).
1293	/// It works exactly like `read()`, but if error occures, the error message will contain index number in array.
1294	/// The index number is stored internally, and is incremented each time you call `read_index()` (`read_array()` resets it).
1295	pub fn read_index<U>(&mut self) -> io::Result<U> where U: TryFromJson
1296	{	if let Some(p) = self.path.last_mut()
1297		{	*p = PathItem::Index(self.last_index);
1298			self.last_index += 1;
1299		}
1300		self.read()
1301	}
1302
1303	fn get_path_str(&self) -> String
1304	{	let mut s = "$".to_string();
1305		for i in &self.path
1306		{	match i
1307			{	PathItem::Prop(prop) => {s.push('.'); s.push_str(prop)}
1308				PathItem::Index(index) => s.push_str(&format!("[{}]", index))
1309			}
1310		}
1311		s
1312	}
1313
1314	/// Creates `std::io::Error` from given string.
1315	/// The error message will be prefixed with current path in objects/arrays tree.
1316	/// This path is built by [read_prop()](struct.Reader.html#method.read_prop) and [read_index()](struct.Reader.html#method.read_index).
1317	pub fn format_error(&self, msg: &str) -> io::Error
1318	{	let mut s = self.get_path_str();
1319		s.push_str(": ");
1320		s.push_str(msg);
1321		io::Error::new(io::ErrorKind::Other, s)
1322	}
1323
1324	/// Like [format_error()](struct.Reader.html#method.format_error), but receives `std::fmt::Arguments` object.
1325	/// Create it with `format_args!()`.
1326	pub fn format_error_fmt(&self, args: fmt::Arguments) -> io::Error
1327	{	let mut s = self.get_path_str();
1328		s.push_str(": ");
1329		use fmt::Write;
1330		s.write_fmt(args).ok();
1331		io::Error::new(io::ErrorKind::Other, s)
1332	}
1333
1334	fn number_error(&self) -> io::Error
1335	{	self.format_error("Invalid JSON input: Number is too big")
1336	}
1337
1338	fn get_next_char(&mut self) -> u8
1339	{	while self.lookahead.is_ascii_whitespace()
1340		{	match self.iter.next()
1341			{	Some(c) => self.lookahead = c,
1342				None => break
1343			}
1344		}
1345		self.lookahead
1346	}
1347
1348	fn next_token(&mut self) -> io::Result<Token>
1349	{	let mut c = self.lookahead;
1350		loop
1351		{	match c
1352			{	b' ' | b'\t' | b'\r' | b'\n' =>
1353				{	c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1354				}
1355				b'n' =>
1356				{	if let Some(b'u') = self.iter.next()
1357					{	if let Some(b'l') = self.iter.next()
1358						{	if let Some(b'l') = self.iter.next()
1359							{	if let Some(c) = self.iter.next()
1360								{	if !c.is_ascii_alphanumeric() && c!=b'_'
1361									{	self.lookahead = c;
1362										return Ok(Token::Null);
1363									}
1364								}
1365								else
1366								{	self.lookahead = b' ';
1367									return Ok(Token::Null);
1368								}
1369							}
1370						}
1371					}
1372					self.lookahead = b' ';
1373					return Err(self.format_error("Invalid JSON input: unexpected identifier"));
1374				}
1375				b'f' =>
1376				{	if let Some(b'a') = self.iter.next()
1377					{	if let Some(b'l') = self.iter.next()
1378						{	if let Some(b's') = self.iter.next()
1379							{	if let Some(b'e') = self.iter.next()
1380								{	if let Some(c) = self.iter.next()
1381									{	if !c.is_ascii_alphanumeric() && c!=b'_'
1382										{	self.lookahead = c;
1383											return Ok(Token::False);
1384										}
1385									}
1386									else
1387									{	self.lookahead = b' ';
1388										return Ok(Token::False);
1389									}
1390								}
1391							}
1392						}
1393					}
1394					self.lookahead = b' ';
1395					return Err(self.format_error("Invalid JSON input: unexpected identifier"));
1396				}
1397				b't' =>
1398				{	if let Some(b'r') = self.iter.next()
1399					{	if let Some(b'u') = self.iter.next()
1400						{	if let Some(b'e') = self.iter.next()
1401							{	if let Some(c) = self.iter.next()
1402								{	if !c.is_ascii_alphanumeric() && c!=b'_'
1403									{	self.lookahead = c;
1404										return Ok(Token::True);
1405									}
1406								}
1407								else
1408								{	self.lookahead = b' ';
1409									return Ok(Token::True);
1410								}
1411							}
1412						}
1413					}
1414					self.lookahead = b' ';
1415					return Err(self.format_error("Invalid JSON input: unexpected identifier"));
1416				}
1417				b'0'..=b'9' | b'-' | b'.' =>
1418				{	let mut is_negative = false;
1419					let mut exponent = 0i32;
1420					let mut is_after_dot = 0;
1421					let mut pos = 0;
1422					let mut n_trailing_zeroes = 0;
1423					if c == b'-'
1424					{	is_negative = true;
1425						c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1426					}
1427					loop
1428					{	match c
1429						{	b'0' =>
1430							{	exponent += is_after_dot;
1431								if pos > 0
1432								{	n_trailing_zeroes += 1;
1433									if pos < self.buffer.len()
1434									{	self.buffer[pos] = b'0';
1435										pos += 1;
1436									}
1437								}
1438							}
1439							b'1'..= b'9' =>
1440							{	exponent += is_after_dot;
1441								n_trailing_zeroes = 0;
1442								if pos < self.buffer.len()
1443								{	self.buffer[pos] = c;
1444									pos += 1;
1445								}
1446							}
1447							b'.' => {is_after_dot = -1}
1448							b'e' | b'E' =>
1449							{	c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1450								let mut n_is_negative = false;
1451								match c
1452								{	b'+' => {c = b'0'}
1453									b'-' => {c = b'0'; n_is_negative = true}
1454									b'0' ..= b'9' => {}
1455									_ =>
1456									{	self.lookahead = c;
1457										return Err(self.format_error("Invalid JSON input: invalid number format"));
1458									}
1459								};
1460								let mut n: i32 = 0;
1461								let mut is_error = false;
1462								loop
1463								{	match c
1464									{	b'0' =>
1465										{	n = match n.checked_mul(10)
1466											{	Some(n) => n,
1467												None => {is_error = true; n_trailing_zeroes = 1; 0} // i check for error inside if n_trailing_zeroes (for optimization)
1468											}
1469										}
1470										b'1'..=b'9' =>
1471										{	n = match n.checked_mul(10).and_then(|n| n.checked_add((c-b'0') as i32))
1472											{	Some(n) => n,
1473												None => {is_error = true; n_trailing_zeroes = 1; 0} // i check for error inside if n_trailing_zeroes (for optimization)
1474											}
1475										}
1476										_ =>
1477										{	self.lookahead = c;
1478											break;
1479										}
1480									}
1481									if let Some(new_c) = self.iter.next()
1482									{	c = new_c;
1483									}
1484									else
1485									{	self.lookahead = b' ';
1486										break;
1487									}
1488								}
1489								if n_trailing_zeroes > 0
1490								{	if is_error
1491									{	self.lookahead = b' ';
1492										return Err(self.number_error());
1493									}
1494									exponent += n_trailing_zeroes;
1495									pos -= n_trailing_zeroes as usize;
1496								}
1497								match exponent.checked_add(if n_is_negative {-n} else {n})
1498								{	Some(new_exponent) => exponent = new_exponent,
1499									None =>
1500									{	self.lookahead = b' ';
1501										return Err(self.number_error());
1502									}
1503								}
1504								break;
1505							}
1506							_ =>
1507							{	self.lookahead = c;
1508								exponent += n_trailing_zeroes;
1509								pos -= n_trailing_zeroes as usize;
1510								break;
1511							}
1512						}
1513						if let Some(new_c) = self.iter.next()
1514						{	c = new_c;
1515						}
1516						else
1517						{	self.lookahead = b' ';
1518							break;
1519						}
1520					}
1521					self.buffer_len = pos;
1522					return match exponent.try_into()
1523					{	Ok(exponent) => Ok(Token::Number(exponent, is_negative)),
1524						Err(_) => Err(self.number_error())
1525					};
1526				}
1527				b'"' =>
1528				{	// no need for: self.lookahead = ... because i will call read_string_contents() or read_string_contents_as_bytes() or skip_string() then
1529					return Ok(Token::Quote);
1530				}
1531				b'[' =>
1532				{	self.lookahead = b' ';
1533					return Ok(Token::ArrayBegin);
1534				}
1535				b']' =>
1536				{	self.lookahead = b' ';
1537					return Ok(Token::ArrayEnd);
1538				}
1539				b'{' =>
1540				{	self.lookahead = b' ';
1541					return Ok(Token::ObjectBegin);
1542				}
1543				b'}' =>
1544				{	self.lookahead = b' ';
1545					return Ok(Token::ObjectEnd);
1546				}
1547				b',' =>
1548				{	self.lookahead = b' ';
1549					return Ok(Token::Comma);
1550				}
1551				b':' =>
1552				{	self.lookahead = b' ';
1553					return Ok(Token::Colon);
1554				}
1555				_ =>
1556				{	self.lookahead = b' ';
1557					return Err(self.format_error_fmt(format_args!("Invalid JSON input: unexpected '{}'", String::from_utf8_lossy(&[c]))));
1558				}
1559			}
1560		}
1561	}
1562
1563	fn skip_string(&mut self) -> io::Result<()>
1564	{	self.lookahead = b' ';
1565		loop
1566		{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1567			match c
1568			{	b'"' =>
1569				{	break;
1570				}
1571				b'\\' =>
1572				{	self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1573				}
1574				_ => {}
1575			}
1576		}
1577		Ok(())
1578	}
1579
1580	fn u_escape_to_utf8(&mut self, buf_pos: usize) -> io::Result<usize>
1581	{	let c0 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1582		let c1 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1583		let c2 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1584		let c3 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1585		let c = (self.hex_to_u32(c0)? << 12) | (self.hex_to_u32(c1)? << 8) | (self.hex_to_u32(c2)? << 4) | self.hex_to_u32(c3)?;
1586		if c <= 0x7F
1587		{	if buf_pos == self.buffer.len()
1588			{	Ok(0)
1589			}
1590			else
1591			{	self.buffer[buf_pos] = c as u8;
1592				Ok(1)
1593			}
1594		}
1595		else if c <= 0x7FF
1596		{	if buf_pos+1 >= self.buffer.len()
1597			{	Ok((&mut self.buffer[buf_pos ..]).write(&[(0xC0 | (c >> 6)) as u8, (0x80 | (c & 0x3F)) as u8]).unwrap())
1598			}
1599			else
1600			{	self.buffer[buf_pos] = (0xC0 | (c >> 6)) as u8;
1601				self.buffer[buf_pos+1] = (0x80 | (c & 0x3F)) as u8;
1602				Ok(2)
1603			}
1604		}
1605		else if c <= 0xD7FF || c >= 0xE000
1606		{	if buf_pos+2 >= self.buffer.len()
1607			{	Ok((&mut self.buffer[buf_pos ..]).write(&[(0xE0 | (c >> 12)) as u8, (0x80 | ((c >> 6) & 0x3F)) as u8, (0x80 | (c & 0x3F)) as u8]).unwrap())
1608			}
1609			else
1610			{	self.buffer[buf_pos] = (0xE0 | (c >> 12)) as u8;
1611				self.buffer[buf_pos+1] = (0x80 | ((c >> 6) & 0x3F)) as u8;
1612				self.buffer[buf_pos+2] = (0x80 | (c & 0x3F)) as u8;
1613				Ok(2)
1614			}
1615		}
1616		else if c <= 0xDBFF
1617		{	// UTF-16 surrogate pairs
1618			let c0 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1619			let c1 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1620			let c2 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1621			let c3 = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1622			let cc = (self.hex_to_u32(c0)? << 12) | (self.hex_to_u32(c1)? << 8) | (self.hex_to_u32(c2)? << 4) | self.hex_to_u32(c3)?;
1623			if cc >= 0xDC00 && cc <= 0xDFFF
1624			{	let c = 0x10000 + (((c-0xD800) << 10) | (cc-0xDC00));
1625				Ok((&mut self.buffer[buf_pos ..]).write(&[0xFFu8, (c >> 18) as u8, (0x80 | ((c >> 12) & 0x3F)) as u8, (0x80 | ((c >> 6) & 0x3F)) as u8, (0x80 | (c & 0x3F)) as u8]).unwrap())
1626			}
1627			else
1628			{	Err(self.format_error("Invalid UTF-16 surrogate pair"))
1629			}
1630		}
1631		else
1632		{	Err(self.format_error("Escape sequence doesn't map to UTF-8"))
1633		}
1634	}
1635
1636	#[inline]
1637	fn hex_to_u32(&self, c: u8) -> io::Result<u32>
1638	{	match c
1639		{	b'0' ..= b'9' => Ok((c as u32) - (b'0' as u32)),
1640			b'a' ..= b'f' => Ok((c as u32) - ((b'a' - 10) as u32)),
1641			b'A' ..= b'F' => Ok((c as u32) - ((b'A' - 10) as u32)),
1642			_ => return Err(self.format_error("Invalid JSON input: error in escape sequence"))
1643		}
1644	}
1645
1646	fn read_string_contents(&mut self) -> io::Result<String>
1647	{	String::from_utf8(self.read_blob_contents()?).map_err(|_| self.format_error("Invalid UTF-8 string"))
1648	}
1649
1650	fn read_blob_contents(&mut self) -> io::Result<Vec<u8>>
1651	{	let mut bytes = Vec::new();
1652		loop
1653		{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1654			match c
1655			{	b'"' => break,
1656				b'\\' =>
1657				{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1658					match c
1659					{	b'r' => bytes.push(b'\r'),
1660						b'n' => bytes.push(b'\n'),
1661						b't' => bytes.push(b'\t'),
1662						b'b' => bytes.push(8),
1663						b'f' => bytes.push(12),
1664						b'u' =>
1665						{	let len = self.u_escape_to_utf8(0)?;
1666							bytes.extend_from_slice(&self.buffer[0 .. len]);
1667						},
1668						_ => bytes.push(c)
1669					}
1670				}
1671				_ => bytes.push(c)
1672			}
1673		}
1674		self.lookahead = b' ';
1675		Ok(bytes)
1676	}
1677
1678	fn read_string_contents_as_bytes(&mut self) -> io::Result<()>
1679	{	let mut len = 0;
1680		loop
1681		{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1682			match c
1683			{	b'"' =>
1684				{	self.lookahead = b' ';
1685					break;
1686				}
1687				b'\\' =>
1688				{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1689					match c
1690					{	b'r' =>
1691						{	if len < self.buffer.len() {self.buffer[len] = b'\r'; len += 1}
1692						},
1693						b'n' =>
1694						{	if len < self.buffer.len() {self.buffer[len] = b'\n'; len += 1}
1695						},
1696						b't' =>
1697						{	if len < self.buffer.len() {self.buffer[len] = b'\t'; len += 1}
1698						},
1699						b'b' =>
1700						{	if len < self.buffer.len() {self.buffer[len] = 8; len += 1}
1701						},
1702						b'f' =>
1703						{	if len < self.buffer.len() {self.buffer[len] = 12; len += 1}
1704						},
1705						b'u' =>
1706						{	len += self.u_escape_to_utf8(len)?
1707						},
1708						_ =>
1709						{	if len < self.buffer.len() {self.buffer[len] = c; len += 1}
1710						}
1711					}
1712				}
1713				_ => len += (&mut self.buffer[len ..]).write(&[c]).unwrap()
1714			}
1715		}
1716		self.buffer_len = len;
1717		Ok(())
1718	}
1719
1720	fn pipe_blob_contents<U>(&mut self, writer: &mut U) -> io::Result<()> where U: io::Write
1721	{	let mut len = 0;
1722		loop
1723		{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1724			let c = match c
1725			{	b'"' =>
1726				{	self.lookahead = b' ';
1727					break;
1728				}
1729				b'\\' =>
1730				{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1731					match c
1732					{	b'r' => b'\r',
1733						b'n' => b'\n',
1734						b't' => b'\t',
1735						b'b' => 8,
1736						b'f' => 12,
1737						b'u' =>
1738						{	if len+4 >= self.buffer.len() {writer.write_all(&self.buffer[0 .. len])?; len = 0}
1739							len += self.u_escape_to_utf8(len)?;
1740							continue;
1741						},
1742						_ => c
1743					}
1744				}
1745				_ => c
1746			};
1747			if len >= self.buffer.len() {writer.write_all(&self.buffer[0 .. len])?; len = 0}
1748			self.buffer[len] = c;
1749			len += 1;
1750		}
1751		if len > 0
1752		{	writer.write_all(&self.buffer[0 .. len])?;
1753		}
1754		Ok(())
1755	}
1756
1757	fn skip_array(&mut self) -> io::Result<()>
1758	{	enum State {AtValueOrEnd, AtValue, AtCommaOrEnd}
1759		let mut state = State::AtValueOrEnd;
1760		loop
1761		{	state = match state
1762			{	State::AtValueOrEnd =>
1763				{	match self.next_token()?
1764					{	Token::Null => State::AtCommaOrEnd,
1765						Token::False => State::AtCommaOrEnd,
1766						Token::True => State::AtCommaOrEnd,
1767						Token::Number(_e, _n) => State::AtCommaOrEnd,
1768						Token::Quote => {self.skip_string()?; State::AtCommaOrEnd },
1769						Token::ArrayBegin => {self.skip_array()?; State::AtCommaOrEnd },
1770						Token::ArrayEnd => break,
1771						Token::ObjectBegin => {self.skip_object()?; State::AtCommaOrEnd },
1772						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1773						Token::Comma => return Err(self.format_error("Invalid JSON input: unexpected ','")),
1774						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1775					}
1776				}
1777				State::AtValue =>
1778				{	match self.next_token()?
1779					{	Token::Null => State::AtCommaOrEnd,
1780						Token::False => State::AtCommaOrEnd,
1781						Token::True => State::AtCommaOrEnd,
1782						Token::Number(_e, _n) => State::AtCommaOrEnd,
1783						Token::Quote => {self.skip_string()?; State::AtCommaOrEnd },
1784						Token::ArrayBegin => {self.skip_array()?; State::AtCommaOrEnd },
1785						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: unexpected ']'")),
1786						Token::ObjectBegin => {self.skip_object()?; State::AtCommaOrEnd },
1787						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1788						Token::Comma => return Err(self.format_error("Invalid JSON input: unexpected ','")),
1789						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1790					}
1791				}
1792				State::AtCommaOrEnd =>
1793				{	match self.next_token()?
1794					{	Token::Null => return Err(self.format_error("Invalid JSON input: unexpected null literal")),
1795						Token::False => return Err(self.format_error("Invalid JSON input: unexpected false literal")),
1796						Token::True => return Err(self.format_error("Invalid JSON input: unexpected true literal")),
1797						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: unexpected number literal")),
1798						Token::Quote => return Err(self.format_error("Invalid JSON input: unexpected string")),
1799						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: unexpected '['")),
1800						Token::ArrayEnd => break,
1801						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: unexpected '{'")),
1802						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1803						Token::Comma => State::AtValue,
1804						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1805					}
1806				}
1807			};
1808		}
1809		Ok(())
1810	}
1811
1812	fn skip_object(&mut self) -> io::Result<()>
1813	{	enum State {AtKeyOrEnd, AtKey, AtColon, AtValue, AtCommaOrEnd}
1814		let mut state = State::AtKeyOrEnd;
1815		loop
1816		{	state = match state
1817			{	State::AtKeyOrEnd =>
1818				{	match self.next_token()?
1819					{	Token::Null => return Err(self.format_error("Invalid JSON input: unexpected null literal")),
1820						Token::False => return Err(self.format_error("Invalid JSON input: unexpected false literal")),
1821						Token::True => return Err(self.format_error("Invalid JSON input: unexpected true literal")),
1822						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: unexpected number literal")),
1823						Token::Quote => {self.skip_string()?; State::AtColon},
1824						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: unexpected '['")),
1825						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: unexpected ']'")),
1826						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: unexpected '{'")),
1827						Token::ObjectEnd => break,
1828						Token::Comma => return Err(self.format_error("Invalid JSON input: unexpected ','")),
1829						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1830					}
1831				}
1832				State::AtKey =>
1833				{	match self.next_token()?
1834					{	Token::Null => return Err(self.format_error("Invalid JSON input: unexpected null literal")),
1835						Token::False => return Err(self.format_error("Invalid JSON input: unexpected false literal")),
1836						Token::True => return Err(self.format_error("Invalid JSON input: unexpected true literal")),
1837						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: unexpected number literal")),
1838						Token::Quote => {self.skip_string()?; State::AtColon},
1839						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: unexpected '['")),
1840						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: unexpected ']'")),
1841						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: unexpected '{'")),
1842						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1843						Token::Comma => return Err(self.format_error("Invalid JSON input: unexpected ','")),
1844						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1845					}
1846				}
1847				State::AtColon =>
1848				{	match self.next_token()?
1849					{	Token::Null => return Err(self.format_error("Invalid JSON input: unexpected null literal")),
1850						Token::False => return Err(self.format_error("Invalid JSON input: unexpected false literal")),
1851						Token::True => return Err(self.format_error("Invalid JSON input: unexpected true literal")),
1852						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: unexpected number literal")),
1853						Token::Quote => return Err(self.format_error("Invalid JSON input: unexpected string")),
1854						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: unexpected '['")),
1855						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: unexpected ']'")),
1856						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: unexpected '{'")),
1857						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1858						Token::Comma => return Err(self.format_error("Invalid JSON input: unexpected ','")),
1859						Token::Colon => State::AtValue,
1860					}
1861				}
1862				State::AtValue =>
1863				{	match self.next_token()?
1864					{	Token::Null => State::AtCommaOrEnd,
1865						Token::False => State::AtCommaOrEnd,
1866						Token::True => State::AtCommaOrEnd,
1867						Token::Number(_e, _n) => State::AtCommaOrEnd,
1868						Token::Quote => {self.skip_string()?; State::AtCommaOrEnd },
1869						Token::ArrayBegin => {self.skip_array()?; State::AtCommaOrEnd },
1870						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: unexpected ']'")),
1871						Token::ObjectBegin => {self.skip_object()?; State::AtCommaOrEnd },
1872						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1873						Token::Comma => return Err(self.format_error("Invalid JSON input: unexpected ','")),
1874						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1875					}
1876				}
1877				State::AtCommaOrEnd =>
1878				{	match self.next_token()?
1879					{	Token::Null => return Err(self.format_error("Invalid JSON input: unexpected null literal")),
1880						Token::False => return Err(self.format_error("Invalid JSON input: unexpected false literal")),
1881						Token::True => return Err(self.format_error("Invalid JSON input: unexpected true literal")),
1882						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: unexpected number literal")),
1883						Token::Quote => return Err(self.format_error("Invalid JSON input: unexpected string")),
1884						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: unexpected '['")),
1885						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: unexpected ']'")),
1886						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: unexpected '{'")),
1887						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: unexpected '}'")),
1888						Token::Comma => State::AtKey,
1889						Token::Colon => return Err(self.format_error("Invalid JSON input: unexpected ':'")),
1890					}
1891				}
1892			};
1893		}
1894		Ok(())
1895	}
1896
1897	/// Use read::<bool>() to read booleans.
1898	fn read_bool(&mut self) -> io::Result<bool>
1899	{	match self.next_token()?
1900		{	Token::Null => Ok(false),
1901			Token::False => Ok(false),
1902			Token::True => Ok(true),
1903			Token::Number(_e, _n) => Ok(self.buffer_len != 0),
1904			Token::Quote =>
1905			{	let c = self.iter.next().ok_or_else(|| self.format_error("Invalid JSON: unexpected end of input"))?;
1906				if c == b'"'
1907				{	self.lookahead = b' ';
1908					Ok(false)
1909				}
1910				else
1911				{	self.skip_string()?;
1912					Ok(true)
1913				}
1914			},
1915			Token::ArrayBegin => {self.skip_array()?; Ok(true)},
1916			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
1917			Token::ObjectBegin => {self.skip_object()?; Ok(true)},
1918			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
1919			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
1920			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
1921		}
1922	}
1923
1924	/// Use read::<isize>() to read isize numbers.
1925	fn read_isize(&mut self) -> io::Result<isize>
1926	{	read_int!(self, isize, false)
1927	}
1928
1929	/// Use read::<i128>() to read i128 numbers.
1930	fn read_i128(&mut self) -> io::Result<i128>
1931	{	read_int!(self, i128, false)
1932	}
1933
1934	/// Use read::<i64>() to read i64 numbers.
1935	fn read_i64(&mut self) -> io::Result<i64>
1936	{	read_int!(self, i64, false)
1937	}
1938
1939	/// Use read::<i32>() to read i32 numbers.
1940	fn read_i32(&mut self) -> io::Result<i32>
1941	{	read_int!(self, i32, false)
1942	}
1943
1944	/// Use read::<i16>() to read i16 numbers.
1945	fn read_i16(&mut self) -> io::Result<i16>
1946	{	read_int!(self, i16, false)
1947	}
1948
1949	/// Use read::<i8>() to read i8 numbers.
1950	fn read_i8(&mut self) -> io::Result<i8>
1951	{	read_int!(self, i8, false)
1952	}
1953
1954	/// Use read::<usize>() to read usize numbers.
1955	fn read_usize(&mut self) -> io::Result<usize>
1956	{	read_int!(self, usize, true)
1957	}
1958
1959	/// Use read::<u128>() to read u128 numbers.
1960	fn read_u128(&mut self) -> io::Result<u128>
1961	{	read_int!(self, u128, true)
1962	}
1963
1964	/// Use read::<u64>() to read u64 numbers.
1965	fn read_u64(&mut self) -> io::Result<u64>
1966	{	read_int!(self, u64, true)
1967	}
1968
1969	/// Use read::<u32>() to read u32 numbers.
1970	fn read_u32(&mut self) -> io::Result<u32>
1971	{	read_int!(self, u32, true)
1972	}
1973
1974	/// Use read::<u16>() to read u16 numbers.
1975	fn read_u16(&mut self) -> io::Result<u16>
1976	{	read_int!(self, u16, true)
1977	}
1978
1979	/// Use read::<u8>() to read u8 numbers.
1980	fn read_u8(&mut self) -> io::Result<u8>
1981	{	read_int!(self, u8, true)
1982	}
1983
1984	/// Use read::<f64>() to read f64 numbers.
1985	fn read_f64(&mut self) -> io::Result<f64>
1986	{	read_float!(self, f64, std::f64::NAN, std::f64::INFINITY, std::f64::NEG_INFINITY)
1987	}
1988
1989	/// Use read::<f32>() to read f32 numbers.
1990	fn read_f32(&mut self) -> io::Result<f32>
1991	{	read_float!(self, f32, std::f32::NAN, std::f32::INFINITY, std::f32::NEG_INFINITY)
1992	}
1993
1994	fn read_and_discard(&mut self) -> io::Result<()>
1995	{	match self.next_token()?
1996		{	Token::Null => Ok(()),
1997			Token::False => Ok(()),
1998			Token::True => Ok(()),
1999			Token::Number(_exponent, _is_negative) => Ok(()),
2000			Token::Quote => {self.skip_string()?; Ok(())},
2001			Token::ArrayBegin => {self.skip_array()?; Ok(())},
2002			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2003			Token::ObjectBegin => {self.skip_object()?; Ok(())},
2004			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2005			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2006			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2007		}
2008	}
2009
2010	/// Use read::<String>() to read strings.
2011	fn read_string(&mut self) -> io::Result<String>
2012	{	match self.next_token()?
2013		{	Token::Null => Ok("null".to_string()),
2014			Token::False => Ok("false".to_string()),
2015			Token::True => Ok("true".to_string()),
2016			Token::Number(exponent, is_negative) =>
2017			{	let len = number_to_string(&mut self.buffer, self.buffer_len, exponent, is_negative).map_err(|_| self.number_error())?;
2018				Ok(String::from_utf8_lossy(&self.buffer[0 .. len]).into_owned())
2019			},
2020			Token::Quote => self.read_string_contents(),
2021			Token::ArrayBegin => Err(self.format_error("Value must be string, not array")),
2022			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2023			Token::ObjectBegin => Err(self.format_error("Value must be string, not object")),
2024			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2025			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2026			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2027		}
2028	}
2029
2030	/// Reads a JSON string (numbers, booleans and null will be converted to strings) to internal buffer, which is 128 bytes long.
2031	/// And return a reference to the read bytes. Long strings will be truncated.
2032	pub fn read_bytes(&mut self) -> io::Result<&[u8]>
2033	{	match self.next_token()?
2034		{	Token::Null =>
2035			{	&mut self.buffer[0 .. 4].copy_from_slice(b"null");
2036				Ok(&self.buffer[0 .. 4])
2037			},
2038			Token::False =>
2039			{	&mut self.buffer[0 .. 5].copy_from_slice(b"false");
2040				Ok(&self.buffer[0 .. 5])
2041			},
2042			Token::True =>
2043			{	&mut self.buffer[0 .. 4].copy_from_slice(b"true");
2044				Ok(&self.buffer[0 .. 4])
2045			},
2046			Token::Number(exponent, is_negative) =>
2047			{	let len = number_to_string(&mut self.buffer, self.buffer_len, exponent, is_negative).map_err(|_| self.number_error())?;
2048				Ok(&self.buffer[0 .. len])
2049			},
2050			Token::Quote =>
2051			{	self.read_string_contents_as_bytes()?;
2052				Ok(&self.buffer[0 .. self.buffer_len])
2053			},
2054			Token::ArrayBegin => Err(self.format_error("Value must be string, not array")),
2055			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2056			Token::ObjectBegin => Err(self.format_error("Value must be string, not object")),
2057			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2058			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2059			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2060		}
2061	}
2062
2063	/// This function allows us to exploit standard JSON containers to pass binary data (BLOBs, binary large objects, or `Vec<u8>`).
2064	///
2065	/// Accodring to JSON standard only valid unicode strings are valid JSON values. But the standard doesn't specify what kind of unicode it must be: utf-8, utf-16, or other.
2066	/// What is invalid utf-8 can be valid utf-16, and what is invalid utf-16 can be valid something else. If we pack an invalid utf-8 sequence to a JSON container
2067	/// and hand it to some other application, that application will encounter errors when it will try to convert it to a string, and it will say that the JSON
2068	/// was invalid. But that application can not convert the bytes to string, and use the bytes themselves.
2069	///
2070	/// The wisdom is how to pack bytes that way. There's trouble here only with bytes in range `80 - FF`. Here is how we can encode our binary object:
2071	///
2072	///   - `00 - 1F` - we can encode with the `\u00xx` encoding - this is the only option.
2073	///   - `20 - 7F` except `"` and `\` - we can leave intact - they are valid utf-8 JSON, or optionally we can encode them with `\u00xx`.
2074	///   - `"` and `\` - escape with a slash.
2075	///   - `80 - FF` - leave them as they are. They make our string invalid utf-8, but we cannot encode them with `\u00xx`. Because `\u0080` will expand to 2-byte utf-8 character on JSON-decoding.
2076	///
2077	/// Decoding example:
2078	/// ```
2079	/// use nop_json::Reader;
2080	///
2081	/// let mut reader = Reader::new(b" \"\x80\x81\" ".iter().map(|i| *i));
2082	///
2083	/// let data = reader.read_blob().unwrap();
2084	/// assert_eq!(data, b"\x80\x81");
2085	/// ```
2086	///
2087	/// Encoding (and decoding back) example:
2088	/// ```
2089	/// use nop_json::{escape_bytes, Reader};
2090	/// use std::io::Write;
2091	///
2092	/// let data = b"\x80\x81";
2093	/// let mut json_container = Vec::with_capacity(100);
2094	/// json_container.push(b'"');
2095	/// json_container.write_all(escape_bytes(data).as_ref()).unwrap();
2096	/// json_container.push(b'"');
2097	/// assert_eq!(json_container, vec![b'"', b'\x80', b'\x81', b'"']);
2098	///
2099	/// let mut reader = Reader::new(json_container.iter().map(|i| *i));
2100	/// let data_back = reader.read_blob().unwrap();
2101	/// assert_eq!(data_back, data);
2102	/// ```
2103	pub fn read_blob(&mut self) -> io::Result<Vec<u8>>
2104	{	match self.next_token()?
2105		{	Token::Null => Ok(Vec::new()),
2106			Token::False => Err(self.format_error("Value must be string, not boolean")),
2107			Token::True => Err(self.format_error("Value must be string, not boolean")),
2108			Token::Number(_exponent, _is_negative) => Err(self.format_error("Value must be string, not number")),
2109			Token::Quote => self.read_blob_contents(),
2110			Token::ArrayBegin => Err(self.format_error("Value must be string, not array")),
2111			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2112			Token::ObjectBegin => Err(self.format_error("Value must be string, not object")),
2113			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2114			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2115			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2116		}
2117	}
2118
2119	/// Like [read_blob()](struct.Reader.html#method.read_blob), but pipes data to the provided writer.
2120	pub fn pipe_blob<U>(&mut self, writer: &mut U) -> io::Result<()> where U: io::Write
2121	{	match self.next_token()?
2122		{	Token::Null => Ok(()),
2123			Token::False => Err(self.format_error("Value must be string, not boolean")),
2124			Token::True => Err(self.format_error("Value must be string, not boolean")),
2125			Token::Number(_exponent, _is_negative) => Err(self.format_error("Value must be string, not number")),
2126			Token::Quote => self.pipe_blob_contents(writer),
2127			Token::ArrayBegin => Err(self.format_error("Value must be string, not array")),
2128			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2129			Token::ObjectBegin => Err(self.format_error("Value must be string, not object")),
2130			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2131			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2132			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2133		}
2134	}
2135
2136	fn read_char(&mut self) -> io::Result<char>
2137	{	self.read_bytes()?;
2138		if self.buffer_len == 0
2139		{	return Err(self.format_error("Expected a character, got empty string"));
2140		}
2141		let c = self.buffer[0] as u32;
2142		if c&0x80 == 0 // 0xxxxxxx
2143		{	return Ok(self.buffer[0] as char);
2144		}
2145		else if c&0xE0 == 0xC0 // 110xxxxx
2146		{	if self.buffer_len >= 2
2147			{	let c = (self.buffer[1] as u32) & 0x3F | ((c & 0x1F) << 6);
2148				return Ok(char::from_u32(c).unwrap());
2149			}
2150		}
2151		else if c&0xF0 == 0xE0 // 1110xxxx
2152		{	if self.buffer_len >= 3
2153			{	let c = (self.buffer[2] as u32) & 0x3F | (((self.buffer[1] as u32) & 0x3F) << 6) | ((c & 0xF) << 12);
2154				return Ok(char::from_u32(c).unwrap());
2155			}
2156		}
2157		else if c&0xF8 == 0xF0 // 11110xxx
2158		{	if self.buffer_len >= 4
2159			{	let c = (self.buffer[3] as u32) & 0x3F | (((self.buffer[2] as u32) & 0x3F) << 6) | (((self.buffer[1] as u32) & 0x3F) << 12) | ((c & 0x7) << 18);
2160				return Ok(char::from_u32(c).unwrap());
2161			}
2162		}
2163		return Err(self.format_error("Invalid UTF-8 string"));
2164	}
2165
2166	/// This method is intended for use in cases when you want to implement [TryFromJson](trait.TryFromJson.html) manually.
2167	/// This method reads a JSON object from stream.
2168	///
2169	/// First it reads starting `{` char from the stream.
2170	/// Then it reads a property name.
2171	/// Then for each property name read, it calls given callback function, assuming that from this function you will read the property value using [read_prop()](struct.Reader.html#method.read_prop).
2172	/// Reading the value with [read()](struct.Reader.html#method.read) will also work, but in case of error, the error message will not contain path to the property where error occured.
2173	///
2174	/// Example:
2175	/// ```
2176	/// # use nop_json::Reader;
2177	/// # fn main() -> std::io::Result<()> {
2178	///
2179	/// let mut reader = Reader::new(r#" {"x": 10, "y": "the y"} "#.bytes());
2180	///
2181	/// let mut x: Option<i32> = None;
2182	/// let mut y = String::new();
2183	///
2184	/// reader.read_object
2185	/// (	|reader, prop|
2186	/// 	{	match prop.as_ref()
2187	/// 		{	"x" => x = reader.read_prop("x")?,
2188	/// 			"y" => y = reader.read_prop("y")?,
2189	/// 			_ => return Err(reader.format_error_fmt(format_args!("Invalid property: {}", prop)))
2190	/// 		}
2191	/// 		Ok(())
2192	/// 	}
2193	/// )?;
2194	///
2195	/// assert_eq!(x, Some(10));
2196	/// assert_eq!(y, "the y".to_string());
2197	///
2198	/// # Ok(())
2199	/// # }
2200	/// ```
2201	pub fn read_object<F>(&mut self, mut on_value: F) -> io::Result<bool> where F: FnMut(&mut Self, String) -> io::Result<()>
2202	{	match self.next_token()?
2203		{	Token::Null => Ok(false),
2204			Token::False => Err(self.format_error("Value must be object, not boolean")),
2205			Token::True => Err(self.format_error("Value must be object, not boolean")),
2206			Token::Number(_e, _n) => Err(self.format_error("Value must be object, not number")),
2207			Token::Quote => Err(self.format_error("Value must be object, not string")),
2208			Token::ArrayBegin => Err(self.format_error("Value must be object, not array")),
2209			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2210			Token::ObjectBegin =>
2211			{	loop
2212				{	match self.next_token()?
2213					{	Token::Null => return Err(self.format_error("Invalid JSON input: expected key, got null")),
2214						Token::False => return Err(self.format_error("Invalid JSON input: expected key, got false")),
2215						Token::True => return Err(self.format_error("Invalid JSON input: expected key, got true")),
2216						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected key, got number")),
2217						Token::Quote => {},
2218						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected key, got '['")),
2219						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected key, got ']'")),
2220						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected key, got '{'")),
2221						Token::ObjectEnd => break,
2222						Token::Comma => return Err(self.format_error("Invalid JSON input: expected key, got ','")),
2223						Token::Colon => return Err(self.format_error("Invalid JSON input: expected key, got ':'")),
2224					}
2225					let key = self.read_string_contents()?;
2226					match self.next_token()?
2227					{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ':', got null")),
2228						Token::False => return Err(self.format_error("Invalid JSON input: expected ':', got false")),
2229						Token::True => return Err(self.format_error("Invalid JSON input: expected ':', got true")),
2230						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ':', got number")),
2231						Token::Quote => return Err(self.format_error("Invalid JSON input: expected ':', got string")),
2232						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ':', got '['")),
2233						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected ':', got ']'")),
2234						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ':', got '{'")),
2235						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: expected ':', got '}'")),
2236						Token::Comma => return Err(self.format_error("Invalid JSON input: expected ':', got ','")),
2237						Token::Colon => {},
2238					}
2239					on_value(self, key)?;
2240					match self.next_token()?
2241					{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got null")),
2242						Token::False => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got false")),
2243						Token::True => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got true")),
2244						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got number")),
2245						Token::Quote => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got string")),
2246						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got '['")),
2247						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got ']'")),
2248						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got '{'")),
2249						Token::ObjectEnd => break,
2250						Token::Comma => {},
2251						Token::Colon => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got ':'")),
2252					}
2253				}
2254				Ok(true)
2255			}
2256			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2257			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2258			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2259		}
2260	}
2261
2262	/// This method is intended for use in cases when you want to implement [TryFromJson](trait.TryFromJson.html) manually.
2263	/// This method reads a JSON object from stream.
2264	///
2265	/// First it reads starting `{` char from the stream.
2266	/// Then it reads a property name, and stores it in internal buffer. You can get it with [get_key()](struct.Reader.html#method.get_key).
2267	/// The buffer is 128 bytes long, so if the property name is longer, it will be truncated. To avoid this limitation, use [read_object()](struct.Reader.html#method.read_object).
2268	/// Then for each property name read, it calls given callback function, assuming that from this function you will read the property value using [read_prop()](struct.Reader.html#method.read_prop).
2269	/// Reading the value with [read()](struct.Reader.html#method.read) will also work, but in case of error, the error message will not contain path to the property where error occured.
2270	///
2271	/// Example:
2272	/// ```
2273	/// # use nop_json::Reader;
2274	/// # fn main() -> std::io::Result<()> {
2275	///
2276	/// let mut reader = Reader::new(r#" {"x": 10, "y": "the y"} "#.bytes());
2277	///
2278	/// let mut x: Option<i32> = None;
2279	/// let mut y = String::new();
2280	///
2281	/// reader.read_object_use_buffer
2282	/// (	|reader|
2283	/// 	{	match reader.get_key()
2284	/// 		{	b"x" => x = reader.read_prop("x")?,
2285	/// 			b"y" => y = reader.read_prop("y")?,
2286	/// 			_ => return Err(reader.format_error_fmt(format_args!("Invalid property: {}", String::from_utf8_lossy(reader.get_key()))))
2287	/// 		}
2288	/// 		Ok(())
2289	/// 	}
2290	/// )?;
2291	///
2292	/// assert_eq!(x, Some(10));
2293	/// assert_eq!(y, "the y".to_string());
2294	///
2295	/// # Ok(())
2296	/// # }
2297	/// ```
2298	pub fn read_object_use_buffer<F>(&mut self, mut on_value: F) -> io::Result<bool> where F: FnMut(&mut Self) -> io::Result<()>
2299	{	match self.next_token()?
2300		{	Token::Null => Ok(false),
2301			Token::False => Err(self.format_error("Value must be object, not boolean")),
2302			Token::True => Err(self.format_error("Value must be object, not boolean")),
2303			Token::Number(_e, _n) => Err(self.format_error("Value must be object, not number")),
2304			Token::Quote => Err(self.format_error("Value must be object, not string")),
2305			Token::ArrayBegin => Err(self.format_error("Value must be object, not array")),
2306			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2307			Token::ObjectBegin =>
2308			{	loop
2309				{	match self.next_token()?
2310					{	Token::Null => return Err(self.format_error("Invalid JSON input: expected key, got null")),
2311						Token::False => return Err(self.format_error("Invalid JSON input: expected key, got false")),
2312						Token::True => return Err(self.format_error("Invalid JSON input: expected key, got true")),
2313						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected key, got number")),
2314						Token::Quote => {},
2315						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected key, got '['")),
2316						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected key, got ']'")),
2317						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected key, got '{'")),
2318						Token::ObjectEnd => break,
2319						Token::Comma => return Err(self.format_error("Invalid JSON input: expected key, got ','")),
2320						Token::Colon => return Err(self.format_error("Invalid JSON input: expected key, got ':'")),
2321					}
2322					self.read_string_contents_as_bytes()?;
2323					match self.next_token()?
2324					{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ':', got null")),
2325						Token::False => return Err(self.format_error("Invalid JSON input: expected ':', got false")),
2326						Token::True => return Err(self.format_error("Invalid JSON input: expected ':', got true")),
2327						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ':', got number")),
2328						Token::Quote => return Err(self.format_error("Invalid JSON input: expected ':', got string")),
2329						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ':', got '['")),
2330						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected ':', got ']'")),
2331						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ':', got '{'")),
2332						Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: expected ':', got '}'")),
2333						Token::Comma => return Err(self.format_error("Invalid JSON input: expected ':', got ','")),
2334						Token::Colon => {},
2335					}
2336					on_value(self)?;
2337					match self.next_token()?
2338					{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got null")),
2339						Token::False => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got false")),
2340						Token::True => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got true")),
2341						Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got number")),
2342						Token::Quote => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got string")),
2343						Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got '['")),
2344						Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got ']'")),
2345						Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got '{'")),
2346						Token::ObjectEnd => break,
2347						Token::Comma => {},
2348						Token::Colon => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got ':'")),
2349					}
2350				}
2351				Ok(true)
2352			}
2353			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2354			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2355			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2356		}
2357	}
2358
2359	/// See [read_object_use_buffer()](struct.Reader.html#method.read_object_use_buffer).
2360	pub fn get_key(&self) -> &[u8]
2361	{	&self.buffer[0 .. self.buffer_len]
2362	}
2363
2364	/// This method is intended for use in cases when you want to implement [TryFromJson](trait.TryFromJson.html) manually.
2365	/// This method reads a JSON array from stream.
2366	///
2367	/// First it reads starting `[` char from the stream.
2368	/// Then it calls given callback function as many times as needed to read each value till terminating `]`.
2369	/// The callback function is assumed to call [read_index()](struct.Reader.html#method.read_index) to read next array element.
2370	///
2371	/// Example:
2372	/// ```
2373	/// # use nop_json::Reader;
2374	/// # fn main() -> std::io::Result<()> {
2375	///
2376	/// let mut reader = Reader::new(r#" ["One", "Two", "Three"] "#.bytes());
2377	///
2378	/// let mut value: Vec<String> = Vec::new();
2379	///
2380	/// reader.read_array
2381	/// (	|reader|
2382	/// 	{	value.push(reader.read_index()?);
2383	/// 		Ok(())
2384	/// 	}
2385	/// )?;
2386	///
2387	/// assert_eq!(value, vec!["One".to_string(), "Two".to_string(), "Three".to_string()]);
2388	///
2389	/// # Ok(())
2390	/// # }
2391	/// ```
2392	pub fn read_array<F>(&mut self, mut on_value: F) -> io::Result<bool> where F: FnMut(&mut Self) -> io::Result<()>
2393	{	match self.next_token()?
2394		{	Token::Null => Ok(false),
2395			Token::False => Err(self.format_error("Value must be array, not boolean")),
2396			Token::True => Err(self.format_error("Value must be array, not boolean")),
2397			Token::Number(_e, _n) => Err(self.format_error("Value must be array, not number")),
2398			Token::Quote => Err(self.format_error("Value must be array, not string")),
2399			Token::ArrayBegin =>
2400			{	if self.get_next_char() == b']'
2401				{	self.lookahead = b' ';
2402				}
2403				else
2404				{	self.path.push(PathItem::Index(0));
2405					self.last_index = 0;
2406					loop
2407					{	on_value(self)?;
2408						match self.next_token()?
2409						{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got null")),
2410							Token::False => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got false")),
2411							Token::True => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got true")),
2412							Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got number")),
2413							Token::Quote => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got string")),
2414							Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got '['")),
2415							Token::ArrayEnd => break,
2416							Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got '{'")),
2417							Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got '}'")),
2418							Token::Comma => {},
2419							Token::Colon => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got ':'")),
2420						}
2421					}
2422					self.path.pop();
2423				}
2424				Ok(true)
2425			}
2426			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2427			Token::ObjectBegin => Err(self.format_error("Value must be array, not object")),
2428			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2429			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2430			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2431		}
2432	}
2433
2434	fn read_value(&mut self) -> io::Result<Value>
2435	{	match self.next_token()?
2436		{	Token::Null => Ok(Value::Null),
2437			Token::False => Ok(Value::Bool(false)),
2438			Token::True => Ok(Value::Bool(true)),
2439			Token::Number(exponent, is_negative) =>
2440			{	let mut mantissa = 0u64;
2441				for c in &self.buffer[.. self.buffer_len]
2442				{	mantissa = mantissa.checked_mul(10).ok_or_else(|| self.number_error())?;
2443					mantissa = mantissa.checked_add((*c - b'0') as u64).ok_or_else(|| self.number_error())?;
2444				}
2445				Ok(Value::Number(mantissa, exponent, is_negative))
2446			},
2447			Token::Quote => Ok(Value::String(self.read_string_contents()?)),
2448			Token::ArrayBegin =>
2449			{	let mut vec = Vec::new();
2450				if self.get_next_char() == b']'
2451				{	self.lookahead = b' ';
2452				}
2453				else
2454				{	loop
2455					{	vec.push(self.read_value()?);
2456						match self.next_token()?
2457						{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got null")),
2458							Token::False => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got false")),
2459							Token::True => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got true")),
2460							Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got number")),
2461							Token::Quote => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got string")),
2462							Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got '['")),
2463							Token::ArrayEnd => break,
2464							Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got '{'")),
2465							Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got '}'")),
2466							Token::Comma => {},
2467							Token::Colon => return Err(self.format_error("Invalid JSON input: expected ',' or ']', got ':'")),
2468						}
2469					}
2470				}
2471				Ok(Value::Array(vec))
2472			}
2473			Token::ArrayEnd => Err(self.format_error("Invalid JSON input: unexpected ']'")),
2474			Token::ObjectBegin =>
2475			{	let mut obj = HashMap::new();
2476				if self.get_next_char() == b'}'
2477				{	self.lookahead = b' ';
2478				}
2479				else
2480				{	loop
2481					{	match self.next_token()?
2482						{	Token::Null => return Err(self.format_error("Invalid JSON input: expected key, got null")),
2483							Token::False => return Err(self.format_error("Invalid JSON input: expected key, got false")),
2484							Token::True => return Err(self.format_error("Invalid JSON input: expected key, got true")),
2485							Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected key, got number")),
2486							Token::Quote => {},
2487							Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected key, got '['")),
2488							Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected key, got ']'")),
2489							Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected key, got '{'")),
2490							Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: expected key, got '}'")),
2491							Token::Comma => return Err(self.format_error("Invalid JSON input: expected key, got ','")),
2492							Token::Colon => return Err(self.format_error("Invalid JSON input: expected key, got ':'")),
2493						}
2494						let key = self.read_string_contents()?;
2495						match self.next_token()?
2496						{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ':', got null")),
2497							Token::False => return Err(self.format_error("Invalid JSON input: expected ':', got false")),
2498							Token::True => return Err(self.format_error("Invalid JSON input: expected ':', got true")),
2499							Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ':', got number")),
2500							Token::Quote => return Err(self.format_error("Invalid JSON input: expected ':', got string")),
2501							Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ':', got '['")),
2502							Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected ':', got ']'")),
2503							Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ':', got '{'")),
2504							Token::ObjectEnd => return Err(self.format_error("Invalid JSON input: expected ':', got '}'")),
2505							Token::Comma => return Err(self.format_error("Invalid JSON input: expected ':', got ','")),
2506							Token::Colon => {},
2507						}
2508						obj.insert(key, self.read_value()?);
2509						match self.next_token()?
2510						{	Token::Null => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got null")),
2511							Token::False => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got false")),
2512							Token::True => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got true")),
2513							Token::Number(_e, _n) => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got number")),
2514							Token::Quote => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got string")),
2515							Token::ArrayBegin => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got '['")),
2516							Token::ArrayEnd => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got ']'")),
2517							Token::ObjectBegin => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got '{'")),
2518							Token::ObjectEnd => break,
2519							Token::Comma => {},
2520							Token::Colon => return Err(self.format_error("Invalid JSON input: expected ',' or '}', got ':'")),
2521						}
2522					}
2523				}
2524				Ok(Value::Object(obj))
2525			},
2526			Token::ObjectEnd => Err(self.format_error("Invalid JSON input: unexpected '}'")),
2527			Token::Comma => Err(self.format_error("Invalid JSON input: unexpected ','")),
2528			Token::Colon => Err(self.format_error("Invalid JSON input: unexpected ':'")),
2529		}
2530	}
2531}