nop_json/
value.rs

1use crate::debug_to_json::DebugToJson;
2
3use std::char;
4use std::fmt;
5use std::collections::{HashMap, BTreeMap, LinkedList, VecDeque};
6use std::convert::{TryInto, TryFrom};
7use std::str::FromStr;
8use std::ops::Index;
9use numtoa::NumToA;
10
11const FORMAT_NUM_WIDTH: usize = 10;
12const FORMAT_NUM_WIDTH_Z: [u8; FORMAT_NUM_WIDTH] = [b'0'; FORMAT_NUM_WIDTH];
13const FORMAT_NUM_WIDTH_0Z: &[u8] = b"0.0000000000";
14
15/// Type to store any JSON node.
16///
17/// Numbers are represented by 3 parts: mantissa, exponent, sign.
18///
19/// Many built-in types can be converted to `Value`.
20/// ```
21/// use nop_json::Value;
22/// use std::convert::TryInto;
23///
24/// let v0: Value = 3u32.try_into().unwrap();
25/// let v1: Value = vec![true, false, true].try_into().unwrap();
26/// assert_eq!(v0, Value::Number(3, 0, false));
27/// assert_eq!(v1, Value::Array(vec![Value::Bool(true), Value::Bool(false), Value::Bool(true)]));
28/// ```
29///
30/// And the `Value` can be converted to many types.
31/// ```
32/// use nop_json::Value;
33/// use std::convert::TryInto;
34///
35/// let v0: u32 = Value::Number(3, 0, false).try_into().unwrap();
36/// let v1: Vec<bool> = Value::Array(vec![Value::Bool(true), Value::Bool(false), Value::Bool(true)]).try_into().unwrap();
37/// assert_eq!(v0, 3u32);
38/// assert_eq!(v1, vec![true, false, true]);
39/// ```
40#[derive(Clone, PartialEq)]
41pub enum Value
42{	Null,
43	Bool(bool),
44	Number(u64, i16, bool),
45	String(String),
46	Array(Vec<Value>),
47	Object(HashMap<String, Value>)
48}
49
50impl Value
51{	pub fn is_null(&self) -> bool
52	{	match *self {Value::Null => true, _ => false}
53	}
54
55	pub fn is_bool(&self) -> bool
56	{	match *self {Value::Bool(_) => true, _ => false}
57	}
58
59	pub fn is_number(&self) -> bool
60	{	match *self {Value::Number(_, _, _) => true, _ => false}
61	}
62
63	pub fn is_string(&self) -> bool
64	{	match *self {Value::String(_) => true, _ => false}
65	}
66
67	pub fn is_array(&self) -> bool
68	{	match *self {Value::Array(_) => true, _ => false}
69	}
70
71	pub fn is_object(&self) -> bool
72	{	match *self {Value::Object(_) => true, _ => false}
73	}
74}
75
76impl fmt::Debug for Value
77{	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
78	{	DebugToJson::fmt(self, f)
79	}
80}
81
82impl fmt::Display for Value
83{	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
84	{	DebugToJson::fmt(self, f)
85	}
86}
87
88// 1. From value
89
90macro_rules! impl_from_value_float
91{	($ty:ty) =>
92	{	impl TryFrom<Value> for $ty
93		{	type Error = ();
94
95			fn try_from(value: Value) -> Result<Self, Self::Error>
96			{	match value
97				{	Value::Null => Ok(0.0),
98					Value::Bool(v) => Ok(if v {1.0} else {0.0}),
99					Value::Number(mantissa, exponent, is_negative) =>
100					{	let mut result = (mantissa as Self)*((10.0 as Self).powi(exponent as i32));
101						if is_negative
102						{	result = -result;
103						}
104						Ok(result)
105					},
106					Value::String(v) =>
107					{	v.parse().map_err(|_| ())
108					},
109					Value::Array(_v) => Err(()),
110					Value::Object(_v) => Err(()),
111				}
112			}
113		}
114	}
115}
116
117macro_rules! impl_from_value_signed
118{	($ty:ty) =>
119	{	impl TryFrom<Value> for $ty
120		{	type Error = ();
121
122			fn try_from(value: Value) -> Result<Self, Self::Error>
123			{	match value
124				{	Value::Null => Ok(0),
125					Value::Bool(v) => Ok(if v {1} else {0}),
126					Value::Number(mantissa, exponent, is_negative) =>
127					{	let mut result = if is_negative
128						{	Self::try_from(i64::try_from(mantissa).map_err(|_| ())?.wrapping_neg()).map_err(|_| ())?
129						}
130						else
131						{	Self::try_from(mantissa).map_err(|_| ())?
132						};
133						if exponent != 0
134						{	if exponent > 0
135							{	result = result.checked_mul((10 as Self).checked_pow(exponent as u32).ok_or(())?).ok_or(())?;
136							}
137							else
138							{	result = result / (10 as Self).checked_pow(exponent.checked_neg().ok_or(())? as u32).ok_or(())?;
139							}
140						}
141						Ok(result)
142					},
143					Value::String(v) =>
144					{	v.parse().map_err(|_| ())
145					},
146					Value::Array(_v) => Err(()),
147					Value::Object(_v) => Err(()),
148				}
149			}
150		}
151	}
152}
153
154macro_rules! impl_from_value_unsigned
155{	($ty:ty) =>
156	{	impl TryFrom<Value> for $ty
157		{	type Error = ();
158
159			fn try_from(value: Value) -> Result<Self, Self::Error>
160			{	match value
161				{	Value::Null => Ok(0),
162					Value::Bool(v) => Ok(if v {1} else {0}),
163					Value::Number(mantissa, exponent, is_negative) =>
164					{	if is_negative
165						{	return Err(());
166						}
167						let mut result = Self::try_from(mantissa).map_err(|_| ())?;
168						if exponent != 0
169						{	if exponent > 0
170							{	result = result.checked_mul((10 as Self).checked_pow(exponent as u32).ok_or(())?).ok_or(())?;
171							}
172							else
173							{	result = result / (10 as Self).checked_pow(exponent.checked_neg().ok_or(())? as u32).ok_or(())?;
174							}
175						}
176						Ok(result)
177					},
178					Value::String(v) =>
179					{	v.parse().map_err(|_| ())
180					},
181					Value::Array(_v) => Err(()),
182					Value::Object(_v) => Err(()),
183				}
184			}
185		}
186	}
187}
188
189impl_from_value_float!(f64);
190impl_from_value_float!(f32);
191impl_from_value_signed!(isize);
192impl_from_value_signed!(i128);
193impl_from_value_signed!(i64);
194impl_from_value_signed!(i32);
195impl_from_value_signed!(i16);
196impl_from_value_signed!(i8);
197impl_from_value_unsigned!(usize);
198impl_from_value_unsigned!(u128);
199impl_from_value_unsigned!(u64);
200impl_from_value_unsigned!(u32);
201impl_from_value_unsigned!(u16);
202impl_from_value_unsigned!(u8);
203
204impl TryFrom<Value> for ()
205{	type Error = ();
206
207	fn try_from(value: Value) -> Result<Self, Self::Error>
208	{	match value
209		{	Value::Null => Ok(()),
210			Value::Bool(_v) => Err(()),
211			Value::Number(_mantissa, _exponent, _is_negative) => Err(()),
212			Value::String(_v) => Err(()),
213			Value::Array(_v) => Err(()),
214			Value::Object(_v) => Err(()),
215		}
216	}
217}
218
219impl TryFrom<Value> for bool
220{	type Error = ();
221
222	fn try_from(value: Value) -> Result<Self, Self::Error>
223	{	match value
224		{	Value::Null => Ok(false),
225			Value::Bool(v) => Ok(v),
226			Value::Number(mantissa, _exponent, _is_negative) => Ok(mantissa != 0),
227			Value::String(_v) => Ok(true),
228			Value::Array(_v) => Ok(true),
229			Value::Object(_v) => Ok(true),
230		}
231	}
232}
233
234impl TryFrom<Value> for char
235{	type Error = ();
236
237	fn try_from(value: Value) -> Result<Self, Self::Error>
238	{	match value
239		{	Value::Null => Ok('n'),
240			Value::Bool(v) => Ok(if v {'t'} else {'f'}),
241			Value::Number(mantissa, _exponent, is_negative) =>
242			{	if is_negative
243				{	Ok('-')
244				}
245				else if mantissa == 0
246				{	Ok('0')
247				}
248				else
249				{	let mut buffer = [0u8; 24];
250					let s = String::from_utf8_lossy(mantissa.numtoa(10, &mut buffer));
251					Ok(s.chars().next().unwrap())
252				}
253			},
254			Value::String(v) => v.chars().next().ok_or(()),
255			Value::Array(_v) => Err(()),
256			Value::Object(_v) => Err(()),
257		}
258	}
259}
260
261impl TryFrom<Value> for String
262{	type Error = ();
263
264	fn try_from(value: Value) -> Result<Self, Self::Error>
265	{	match value
266		{	Value::Null => Ok("null".to_string()),
267			Value::Bool(v) => Ok(if v {"true".to_string()} else {"false".to_string()}),
268			Value::Number(mantissa, exponent, is_negative) =>
269			{	let mut buffer = [0u8; 24];
270				let mantissa = mantissa.numtoa(10, &mut buffer);
271				let len = mantissa.len();
272				if exponent >= 0
273				{	let e = exponent as usize;
274					if len+e <= FORMAT_NUM_WIDTH
275					{	// append zeroes according to exponent
276						let mut vec = if !is_negative
277						{	Vec::with_capacity(mantissa.len() + e)
278						}
279						else
280						{	let mut vec = Vec::with_capacity(mantissa.len() + e + 1);
281							vec.push(b'-');
282							vec
283						};
284						vec.extend_from_slice(mantissa);
285						vec.extend_from_slice(&FORMAT_NUM_WIDTH_Z[0 .. e]);
286						return String::from_utf8(vec).map_err(|_| ());
287					}
288				}
289				else
290				{	let e = exponent.wrapping_neg() as usize;
291					if e < len
292					{	// insert dot in the middle of number
293						let mut vec = if !is_negative
294						{	Vec::with_capacity(mantissa.len() + 1)
295						}
296						else
297						{	let mut vec = Vec::with_capacity(mantissa.len() + 2);
298							vec.push(b'-');
299							vec
300						};
301						vec.extend_from_slice(&mantissa[0 .. len-e]);
302						vec.push(b'.');
303						vec.extend_from_slice(&mantissa[len-e ..]);
304						return String::from_utf8(vec).map_err(|_| ());
305					}
306					if e <= FORMAT_NUM_WIDTH
307					{	// prepend with 0.000...
308						let mut vec = if !is_negative
309						{	Vec::with_capacity(mantissa.len() + e-len+2)
310						}
311						else
312						{	let mut vec = Vec::with_capacity(mantissa.len() + e-len+3);
313							vec.push(b'-');
314							vec
315						};
316						vec.extend_from_slice(&FORMAT_NUM_WIDTH_0Z[0 .. e-len+2]);
317						vec.extend_from_slice(mantissa);
318						return String::from_utf8(vec).map_err(|_| ());
319					}
320				}
321				let mut buffer = [0u8; 24];
322				let exponent = exponent.numtoa(10, &mut buffer);
323				let mut vec = if !is_negative
324				{	Vec::with_capacity(mantissa.len() + exponent.len() + 1)
325				}
326				else
327				{	let mut vec = Vec::with_capacity(mantissa.len() + exponent.len() + 2);
328					vec.push(b'-');
329					vec
330				};
331				vec.extend_from_slice(mantissa);
332				vec.push(b'e');
333				vec.extend_from_slice(exponent);
334				String::from_utf8(vec).map_err(|_| ())
335			},
336			Value::String(v) => Ok(v),
337			Value::Array(_v) => Err(()),
338			Value::Object(_v) => Err(()),
339		}
340	}
341}
342
343impl<T> TryFrom<Value> for Vec<T> where T: TryFrom<Value>
344{	type Error = ();
345
346	fn try_from(value: Value) -> Result<Self, Self::Error>
347	{	match value
348		{	Value::Null => Ok(Vec::new()),
349			Value::Bool(_v) => Err(()),
350			Value::Number(_mantissa, _exponent, _is_negative) => Err(()),
351			Value::String(_v) => Err(()),
352			Value::Array(v) =>
353			{	let mut arr = Vec::with_capacity(v.len());
354				for item in v
355				{	arr.push(item.try_into().map_err(|_| ())?)
356				}
357				Ok(arr)
358			}
359			Value::Object(_v) => Err(()),
360		}
361	}
362}
363
364// 2. To value
365
366macro_rules! impl_from_value_signed
367{	($ty:ty) =>
368	{	impl TryFrom<$ty> for Value
369		{	type Error = ();
370
371			fn try_from(value: $ty) -> Result<Self, Self::Error>
372			{	if value >= 0
373				{	Ok(Value::Number(value.try_into().map_err(|_| ())?, 0, false))
374				}
375				else
376				{	Ok(Value::Number(i64::try_from(value).map_err(|_| ())?.wrapping_neg() as u64, 0, true))
377				}
378			}
379		}
380	}
381}
382
383macro_rules! impl_from_value_unsigned
384{	($ty:ty) =>
385	{	impl TryFrom<$ty> for Value
386		{	type Error = ();
387
388			fn try_from(value: $ty) -> Result<Self, Self::Error>
389			{	Ok(Value::Number(value.try_into().map_err(|_| ())?, 0, false))
390			}
391		}
392	}
393}
394
395impl_from_value_signed!(isize);
396impl_from_value_signed!(i64);
397impl_from_value_signed!(i32);
398impl_from_value_signed!(i16);
399impl_from_value_signed!(i8);
400impl_from_value_unsigned!(usize);
401impl_from_value_unsigned!(u64);
402impl_from_value_unsigned!(u32);
403impl_from_value_unsigned!(u16);
404impl_from_value_unsigned!(u8);
405
406impl TryFrom<()> for Value
407{	type Error = ();
408
409	fn try_from(_value: ()) -> Result<Self, Self::Error>
410	{	Ok(Value::Null)
411	}
412}
413
414impl TryFrom<bool> for Value
415{	type Error = ();
416
417	fn try_from(value: bool) -> Result<Self, Self::Error>
418	{	Ok(Value::Bool(value))
419	}
420}
421
422impl TryFrom<char> for Value
423{	type Error = ();
424
425	fn try_from(value: char) -> Result<Self, Self::Error>
426	{	Ok(Value::String(value.to_string()))
427	}
428}
429
430impl TryFrom<String> for Value
431{	type Error = ();
432
433	fn try_from(value: String) -> Result<Self, Self::Error>
434	{	Ok(Value::String(value))
435	}
436}
437
438impl FromStr for Value
439{	type Err = ();
440
441	fn from_str(value: &str) -> Result<Self, Self::Err>
442	{	Ok(Value::String(value.to_string()))
443	}
444}
445
446impl TryFrom<Vec<Value>> for Value
447{	type Error = ();
448
449	fn try_from(value: Vec<Value>) -> Result<Self, Self::Error>
450	{	Ok(Value::Array(value))
451	}
452}
453
454macro_rules! impl_from_vec
455{	($ty:ty) =>
456	{	impl TryFrom<Vec<$ty>> for Value
457		{	type Error = ();
458
459			fn try_from(value: Vec<$ty>) -> Result<Self, Self::Error>
460			{	let mut vec = Vec::with_capacity(value.len());
461				for v in value
462				{	vec.push(Value::try_from(v)?);
463				}
464				Ok(Value::Array(vec))
465			}
466		}
467	}
468}
469
470macro_rules! impl_from_linked_list
471{	($ty:ty) =>
472	{	impl TryFrom<LinkedList<$ty>> for Value
473		{	type Error = ();
474
475			fn try_from(value: LinkedList<$ty>) -> Result<Self, Self::Error>
476			{	let mut vec = Vec::with_capacity(value.len());
477				for v in value
478				{	vec.push(Value::try_from(v)?);
479				}
480				Ok(Value::Array(vec))
481			}
482		}
483	}
484}
485
486macro_rules! impl_from_vec_deque
487{	($ty:ty) =>
488	{	impl TryFrom<VecDeque<$ty>> for Value
489		{	type Error = ();
490
491			fn try_from(value: VecDeque<$ty>) -> Result<Self, Self::Error>
492			{	let mut vec = Vec::with_capacity(value.len());
493				for v in value
494				{	vec.push(Value::try_from(v)?);
495				}
496				Ok(Value::Array(vec))
497			}
498		}
499	}
500}
501
502impl_from_vec!(isize);
503impl_from_vec!(i64);
504impl_from_vec!(i32);
505impl_from_vec!(i16);
506impl_from_vec!(i8);
507impl_from_vec!(usize);
508impl_from_vec!(u64);
509impl_from_vec!(u32);
510impl_from_vec!(u16);
511impl_from_vec!(u8);
512impl_from_vec!(bool);
513impl_from_vec!(char);
514impl_from_vec!(());
515impl_from_vec!(String);
516
517impl_from_linked_list!(isize);
518impl_from_linked_list!(i64);
519impl_from_linked_list!(i32);
520impl_from_linked_list!(i16);
521impl_from_linked_list!(i8);
522impl_from_linked_list!(usize);
523impl_from_linked_list!(u64);
524impl_from_linked_list!(u32);
525impl_from_linked_list!(u16);
526impl_from_linked_list!(u8);
527impl_from_linked_list!(bool);
528impl_from_linked_list!(char);
529impl_from_linked_list!(());
530impl_from_linked_list!(String);
531
532impl_from_vec_deque!(isize);
533impl_from_vec_deque!(i64);
534impl_from_vec_deque!(i32);
535impl_from_vec_deque!(i16);
536impl_from_vec_deque!(i8);
537impl_from_vec_deque!(usize);
538impl_from_vec_deque!(u64);
539impl_from_vec_deque!(u32);
540impl_from_vec_deque!(u16);
541impl_from_vec_deque!(u8);
542impl_from_vec_deque!(bool);
543impl_from_vec_deque!(char);
544impl_from_vec_deque!(());
545impl_from_vec_deque!(String);
546
547
548impl TryFrom<HashMap<String, Value>> for Value
549{	type Error = ();
550
551	fn try_from(value: HashMap<String, Value>) -> Result<Self, Self::Error>
552	{	Ok(Value::Object(value))
553	}
554}
555
556macro_rules! impl_from_hash_map
557{	($ty:ty) =>
558	{	impl TryFrom<HashMap<String, $ty>> for Value
559		{	type Error = ();
560
561			fn try_from(value: HashMap<String, $ty>) -> Result<Self, Self::Error>
562			{	let mut obj = HashMap::with_capacity(value.len());
563				for (key, v) in value
564				{	obj.insert(key, Value::try_from(v)?);
565				}
566				Ok(Value::Object(obj))
567			}
568		}
569	}
570}
571
572macro_rules! impl_from_btree_map
573{	($ty:ty) =>
574	{	impl TryFrom<BTreeMap<String, $ty>> for Value
575		{	type Error = ();
576
577			fn try_from(value: BTreeMap<String, $ty>) -> Result<Self, Self::Error>
578			{	let mut obj = HashMap::with_capacity(value.len());
579				for (key, v) in value
580				{	obj.insert(key, Value::try_from(v)?);
581				}
582				Ok(Value::Object(obj))
583			}
584		}
585	}
586}
587
588impl_from_hash_map!(isize);
589impl_from_hash_map!(i64);
590impl_from_hash_map!(i32);
591impl_from_hash_map!(i16);
592impl_from_hash_map!(i8);
593impl_from_hash_map!(usize);
594impl_from_hash_map!(u64);
595impl_from_hash_map!(u32);
596impl_from_hash_map!(u16);
597impl_from_hash_map!(u8);
598impl_from_hash_map!(bool);
599impl_from_hash_map!(char);
600impl_from_hash_map!(());
601impl_from_hash_map!(String);
602
603impl_from_btree_map!(isize);
604impl_from_btree_map!(i64);
605impl_from_btree_map!(i32);
606impl_from_btree_map!(i16);
607impl_from_btree_map!(i8);
608impl_from_btree_map!(usize);
609impl_from_btree_map!(u64);
610impl_from_btree_map!(u32);
611impl_from_btree_map!(u16);
612impl_from_btree_map!(u8);
613impl_from_btree_map!(bool);
614impl_from_btree_map!(char);
615impl_from_btree_map!(());
616impl_from_btree_map!(String);
617
618
619impl<'a> Index<&'a str> for Value
620{	type Output = Value;
621
622	fn index(&self, index: &'a str) -> &Self::Output
623	{	match *self
624		{	Value::Null => &Value::Null,
625			Value::Bool(ref _v) => &Value::Null,
626			Value::Number(ref _mantissa, ref _exponent, ref _is_negative) => &Value::Null,
627			Value::String(ref _v) => &Value::Null,
628			Value::Array(ref _v) => &Value::Null,
629			Value::Object(ref v) =>
630			{	v.get(index).unwrap_or(&Value::Null)
631			}
632		}
633	}
634}