1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! This is a simple library for parsing and storing JSON numbers according
//! to the [JSON specification](https://www.json.org/json-en.html).
//! It provides two types, the unsized `Number` type acting like `str`,
//! and the `NumberBuf<B>` type owning the data inside the `B` type
//! (by default `Vec<u8>`).
//!
//! # Features
//!
//! ## Store small owned numbers on the stack
//!
//! By enabling the `smallnumberbuf` feature, the `SmallNumberBuf<LEN>` type is
//! defined as `NumberBuf<SmallVec<[u8; LEN]>>` (where `LEN=8` by default)
//! thanks to the [`smallvec`](https://crates.io/crates/smallvec) crate.
//!
//! ## Serde support
//!
//! Enable the `serde` feature to add `Serialize`, `Deserialize` and
//! `Deserializer` implementations to `NumberBuf`.
use std::borrow::{Borrow, ToOwned};
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;

/// Serde support.
#[cfg(feature = "serde")]
pub mod serde;

#[cfg(feature = "smallnumberbuf")]
mod smallnumberbuf {
	use super::*;
	use smallvec::SmallVec;

	/// JSON number buffer based on [`SmallVec`](smallvec::SmallVec).
	pub type SmallNumberBuf<const LEN: usize = 8> = NumberBuf<SmallVec<[u8; LEN]>>;

	unsafe impl<A: smallvec::Array<Item = u8>> crate::Buffer for SmallVec<A> {
		fn from_vec(bytes: Vec<u8>) -> Self {
			bytes.into()
		}

		fn from_bytes(bytes: &[u8]) -> Self {
			bytes.into()
		}
	}
}

#[cfg(feature = "smallnumberbuf")]
pub use smallnumberbuf::*;

/// Invalid number error.
///
/// The inner value is the data failed to be parsed.
#[derive(Clone, Copy, Debug)]
pub struct InvalidNumber<T>(T);

/// Number sign.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Sign {
	Negative,
	Zero,
	Positive,
}

impl Sign {
	/// Checks if the number is zero.
	#[inline(always)]
	pub fn is_zero(&self) -> bool {
		matches!(self, Self::Zero)
	}

	/// Checks if the number is non positive (negative or zero).
	#[inline(always)]
	pub fn is_non_positive(&self) -> bool {
		matches!(self, Self::Negative | Self::Zero)
	}

	/// Checks if the number is non negative (positive or zero).
	#[inline(always)]
	pub fn is_non_negative(&self) -> bool {
		matches!(self, Self::Positive | Self::Zero)
	}

	/// Checks if the number is strictly positive (non zero nor negative).
	#[inline(always)]
	pub fn is_positive(&self) -> bool {
		matches!(self, Self::Positive)
	}

	/// Checks if the number is strictly negative (non zero nor positive).
	#[inline(always)]
	pub fn is_negative(&self) -> bool {
		matches!(self, Self::Negative)
	}
}

/// Lexical JSON number.
///
/// This hold the lexical representation of a JSON number.
/// All the comparison operations are done on this *lexical* representation,
/// meaning that `1` is actually greater than `0.1e+80` for instance.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Number {
	data: [u8],
}

impl Number {
	/// Creates a new number by parsing the given input `data`.
	pub fn new<B: AsRef<[u8]> + ?Sized>(data: &B) -> Result<&Number, InvalidNumber<&B>> {
		let s = data.as_ref();

		enum State {
			Init,
			FirstDigit,
			Zero,
			NonZero,
			FractionalFirst,
			FractionalRest,
			ExponentSign,
			ExponentFirst,
			ExponentRest,
		}

		let mut state = State::Init;

		for b in s {
			match state {
				State::Init => match *b {
					b'-' => state = State::FirstDigit,
					b'0' => state = State::Zero,
					b'1'..=b'9' => state = State::NonZero,
					_ => return Err(InvalidNumber(data)),
				},
				State::FirstDigit => match *b {
					b'0' => state = State::Zero,
					b'1'..=b'9' => state = State::NonZero,
					_ => return Err(InvalidNumber(data)),
				},
				State::Zero => match *b {
					b'.' => state = State::FractionalFirst,
					b'e' | b'E' => state = State::ExponentSign,
					_ => return Err(InvalidNumber(data)),
				},
				State::NonZero => match *b {
					b'0'..=b'9' => state = State::NonZero,
					b'.' => state = State::FractionalFirst,
					b'e' | b'E' => state = State::ExponentSign,
					_ => return Err(InvalidNumber(data)),
				},
				State::FractionalFirst => match *b {
					b'0'..=b'9' => state = State::FractionalRest,
					_ => return Err(InvalidNumber(data)),
				},
				State::FractionalRest => match *b {
					b'0'..=b'9' => state = State::FractionalRest,
					b'e' | b'E' => state = State::ExponentSign,
					_ => return Err(InvalidNumber(data)),
				},
				State::ExponentSign => match *b {
					b'+' | b'-' => state = State::ExponentFirst,
					b'0'..=b'9' => state = State::ExponentRest,
					_ => return Err(InvalidNumber(data)),
				},
				State::ExponentFirst => match *b {
					b'0'..=b'9' => state = State::ExponentRest,
					_ => return Err(InvalidNumber(data)),
				},
				State::ExponentRest => match *b {
					b'0'..=b'9' => state = State::ExponentRest,
					_ => return Err(InvalidNumber(data)),
				},
			}
		}

		if matches!(
			state,
			State::Zero | State::NonZero | State::FractionalRest | State::ExponentRest
		) {
			Ok(unsafe { Self::new_unchecked(s) })
		} else {
			Err(InvalidNumber(data))
		}
	}

	/// Creates a new number without parsing the given input `data`.
	///
	/// ## Safety
	///
	/// The `data` input **must** be a valid JSON number.
	#[inline(always)]
	pub unsafe fn new_unchecked<B: AsRef<[u8]> + ?Sized>(data: &B) -> &Number {
		std::mem::transmute(data.as_ref())
	}

	#[inline(always)]
	pub fn as_str(&self) -> &str {
		unsafe {
			// safe because `self.data` is always a valid UTF-8 sequence.
			std::str::from_utf8_unchecked(&self.data)
		}
	}

	/// Checks if the number is equal to zero (`0`).
	///
	/// This include every lexical representation where
	/// the decimal and fraction part are composed of only
	/// `0`, maybe preceded with `-`, and an arbitrary exponent part.
	#[inline(always)]
	pub fn is_zero(&self) -> bool {
		for b in &self.data {
			match b {
				b'-' | b'0' | b'.' => (),
				b'e' | b'E' => break,
				_ => return false,
			}
		}

		true
	}

	/// Returns the sign of the number.
	pub fn sign(&self) -> Sign {
		let mut non_negative = true;

		for b in &self.data {
			match b {
				b'-' => non_negative = false,
				b'0' | b'.' => (),
				b'e' | b'E' => break,
				_ => {
					return if non_negative {
						Sign::Positive
					} else {
						Sign::Negative
					}
				}
			}
		}

		Sign::Zero
	}

	/// Checks if the number is non positive (negative or zero).
	#[inline(always)]
	pub fn is_non_positive(&self) -> bool {
		self.sign().is_non_positive()
	}

	/// Checks if the number is non negative (positive or zero).
	#[inline(always)]
	pub fn is_non_negative(&self) -> bool {
		self.sign().is_non_negative()
	}

	/// Checks if the number is strictly positive (non zero nor negative).
	#[inline(always)]
	pub fn is_positive(&self) -> bool {
		self.sign().is_positive()
	}

	/// Checks if the number is strictly negative (non zero nor positive).
	#[inline(always)]
	pub fn is_negative(&self) -> bool {
		self.sign().is_negative()
	}

	/// Checks if the number has a decimal point.
	#[inline(always)]
	pub fn has_decimal_point(&self) -> bool {
		self.data.contains(&b'.')
	}

	/// Checks if the number has a fraction part.
	///
	/// This is an alias for [`has_decimal_point`](Self::has_decimal_point).
	#[inline(always)]
	pub fn has_fraction(&self) -> bool {
		self.has_decimal_point()
	}

	/// Checks if the number has an exponent part.
	#[inline(always)]
	pub fn has_exponent(&self) -> bool {
		for b in &self.data {
			if matches!(b, b'e' | b'E') {
				return true;
			}
		}

		false
	}

	#[inline(always)]
	pub fn is_i32(&self) -> bool {
		self.as_i32().is_some()
	}

	#[inline(always)]
	pub fn is_i64(&self) -> bool {
		self.as_i64().is_some()
	}

	#[inline(always)]
	pub fn is_u32(&self) -> bool {
		self.as_u32().is_some()
	}

	#[inline(always)]
	pub fn is_u64(&self) -> bool {
		self.as_u64().is_some()
	}

	#[inline(always)]
	pub fn as_i32(&self) -> Option<i32> {
		self.as_str().parse().ok()
	}

	#[inline(always)]
	pub fn as_i64(&self) -> Option<i64> {
		self.as_str().parse().ok()
	}

	#[inline(always)]
	pub fn as_u32(&self) -> Option<u32> {
		self.as_str().parse().ok()
	}

	#[inline(always)]
	pub fn as_u64(&self) -> Option<u64> {
		self.as_str().parse().ok()
	}

	#[inline(always)]
	pub fn as_f32_lossy(&self) -> f32 {
		lexical::parse_with_options::<_, _, { lexical::format::JSON }>(
			self.as_bytes(),
			&LOSSY_PARSE_FLOAT,
		)
		.unwrap()
	}

	#[inline(always)]
	pub fn as_f64_lossy(&self) -> f64 {
		lexical::parse_with_options::<_, _, { lexical::format::JSON }>(
			self.as_bytes(),
			&LOSSY_PARSE_FLOAT,
		)
		.unwrap()
	}

	/// Returns the canonical representation of this number according to
	/// [RFC8785](https://www.rfc-editor.org/rfc/rfc8785#name-serialization-of-numbers).
	#[cfg(feature = "canonical")]
	pub fn canonical_with<'b>(&self, buffer: &'b mut ryu_js::Buffer) -> &'b Number {
		unsafe { Number::new_unchecked(buffer.format_finite(self.as_f64_lossy())) }
	}

	/// Returns the canonical representation of this number according to
	/// [RFC8785](https://www.rfc-editor.org/rfc/rfc8785#name-serialization-of-numbers).
	#[cfg(feature = "canonical")]
	pub fn canonical(&self) -> NumberBuf {
		let mut buffer = ryu_js::Buffer::new();
		self.canonical_with(&mut buffer).to_owned()
	}
}

const LOSSY_PARSE_FLOAT: lexical::ParseFloatOptions = unsafe {
	lexical::ParseFloatOptions::builder()
		.lossy(true)
		.build_unchecked()
};

impl Deref for Number {
	type Target = str;

	#[inline(always)]
	fn deref(&self) -> &str {
		self.as_str()
	}
}

impl AsRef<str> for Number {
	#[inline(always)]
	fn as_ref(&self) -> &str {
		self.as_str()
	}
}

impl Borrow<str> for Number {
	#[inline(always)]
	fn borrow(&self) -> &str {
		self.as_str()
	}
}

impl AsRef<[u8]> for Number {
	#[inline(always)]
	fn as_ref(&self) -> &[u8] {
		self.as_bytes()
	}
}

impl Borrow<[u8]> for Number {
	#[inline(always)]
	fn borrow(&self) -> &[u8] {
		self.as_bytes()
	}
}

impl<'a> TryFrom<&'a str> for &'a Number {
	type Error = InvalidNumber<&'a str>;

	#[inline(always)]
	fn try_from(s: &'a str) -> Result<&'a Number, InvalidNumber<&'a str>> {
		Number::new(s)
	}
}

impl ToOwned for Number {
	type Owned = NumberBuf;

	fn to_owned(&self) -> Self::Owned {
		unsafe { NumberBuf::new_unchecked(self.as_bytes().to_owned()) }
	}
}

impl fmt::Display for Number {
	#[inline(always)]
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		self.as_str().fmt(f)
	}
}

impl fmt::Debug for Number {
	#[inline(always)]
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		self.as_str().fmt(f)
	}
}

/// Buffer type.
///
/// # Safety
///
/// The `AsRef<[u8]>` implementation *must* return the bytes provided using
/// the `from_bytes` and `from_vec` constructor functions.
pub unsafe trait Buffer: AsRef<[u8]> {
	fn from_bytes(bytes: &[u8]) -> Self;

	fn from_vec(bytes: Vec<u8>) -> Self;
}

unsafe impl Buffer for Vec<u8> {
	fn from_bytes(bytes: &[u8]) -> Self {
		bytes.into()
	}

	fn from_vec(bytes: Vec<u8>) -> Self {
		bytes
	}
}

/// JSON number buffer.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NumberBuf<B = Vec<u8>> {
	data: B,
}

impl<B> NumberBuf<B> {
	/// Creates a new number buffer by parsing the given input `data` buffer.
	#[inline(always)]
	pub fn new(data: B) -> Result<Self, InvalidNumber<B>>
	where
		B: AsRef<[u8]>,
	{
		match Number::new(&data) {
			Ok(_) => Ok(NumberBuf { data }),
			Err(_) => Err(InvalidNumber(data)),
		}
	}

	/// Creates a new number buffer from the given input `data` buffer.
	///
	/// ## Safety
	///
	/// The input `data` **must** hold a valid JSON number string.
	#[inline(always)]
	pub unsafe fn new_unchecked(data: B) -> Self {
		NumberBuf { data }
	}

	/// Creates a number buffer from the given `number`.
	#[inline(always)]
	pub fn from_number(n: &Number) -> Self
	where
		B: FromIterator<u8>,
	{
		unsafe { NumberBuf::new_unchecked(n.bytes().collect()) }
	}
}

impl<B: Buffer> NumberBuf<B> {
	#[inline(always)]
	pub fn as_number(&self) -> &Number {
		unsafe { Number::new_unchecked(&self.data) }
	}
}

impl<B: Buffer> FromStr for NumberBuf<B> {
	type Err = InvalidNumber<B>;

	#[inline(always)]
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::new(B::from_bytes(s.as_bytes()))
	}
}

impl<B: Buffer> Deref for NumberBuf<B> {
	type Target = Number;

	#[inline(always)]
	fn deref(&self) -> &Number {
		self.as_number()
	}
}

impl<B: Buffer> AsRef<Number> for NumberBuf<B> {
	#[inline(always)]
	fn as_ref(&self) -> &Number {
		self.as_number()
	}
}

impl<B: Buffer> Borrow<Number> for NumberBuf<B> {
	#[inline(always)]
	fn borrow(&self) -> &Number {
		self.as_number()
	}
}

impl<B: Buffer> AsRef<str> for NumberBuf<B> {
	#[inline(always)]
	fn as_ref(&self) -> &str {
		self.as_str()
	}
}

impl<B: Buffer> Borrow<str> for NumberBuf<B> {
	#[inline(always)]
	fn borrow(&self) -> &str {
		self.as_str()
	}
}

impl<B: Buffer> AsRef<[u8]> for NumberBuf<B> {
	#[inline(always)]
	fn as_ref(&self) -> &[u8] {
		self.as_bytes()
	}
}

impl<B: Buffer> Borrow<[u8]> for NumberBuf<B> {
	#[inline(always)]
	fn borrow(&self) -> &[u8] {
		self.as_bytes()
	}
}

impl<B: Buffer> fmt::Display for NumberBuf<B> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		self.as_str().fmt(f)
	}
}

impl<B: Buffer> fmt::Debug for NumberBuf<B> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		self.as_str().fmt(f)
	}
}

macro_rules! impl_from_int {
	($($ty:ty),*) => {
		$(
			impl<B: Buffer> From<$ty> for NumberBuf<B> {
				#[inline(always)]
				fn from(i: $ty) -> Self {
					unsafe {
						Self::new_unchecked(B::from_vec(lexical::to_string(i).into_bytes()))
					}
				}
			}
		)*
	};
}

/// Float conversion error.
#[derive(Clone, Copy, Debug)]
pub enum TryFromFloatError {
	/// The float was Nan, which is not a JSON number.
	Nan,

	/// The float was not finite, and hence not a JSON number.
	Infinite,
}

const WRITE_FLOAT: lexical::WriteFloatOptions = unsafe {
	lexical::WriteFloatOptions::builder()
		.trim_floats(true)
		.exponent(b'e')
		.build_unchecked()
};

macro_rules! impl_try_from_float {
	($($ty:ty),*) => {
		$(
			impl<B: Buffer> TryFrom<$ty> for NumberBuf<B> {
				type Error = TryFromFloatError;

				#[inline(always)]
				fn try_from(f: $ty) -> Result<Self, Self::Error> {
					if f.is_finite() {
						Ok(unsafe {
							Self::new_unchecked(B::from_vec(lexical::to_string_with_options::<_, {lexical::format::JSON}>(f, &WRITE_FLOAT).into_bytes()))
						})
					} else if f.is_nan() {
						Err(TryFromFloatError::Nan)
					} else {
						Err(TryFromFloatError::Infinite)
					}
				}
			}
		)*
	};
}

impl_from_int!(u8, i8, u16, i16, u32, i32, u64, i64, usize, isize);
impl_try_from_float!(f32, f64);

#[cfg(test)]
mod tests {
	use super::*;

	macro_rules! positive_tests {
		{ $($id:ident: $input:literal),* } => {
			$(
				#[test]
				fn $id () {
					assert!(Number::new($input).is_ok())
				}
			)*
		};
	}

	macro_rules! negative_tests {
		{ $($id:ident: $input:literal),* } => {
			$(
				#[test]
				fn $id () {
					assert!(Number::new($input).is_err())
				}
			)*
		};
	}

	macro_rules! sign_tests {
		{ $($id:ident: $input:literal => $sign:ident),* } => {
			$(
				#[test]
				fn $id () {
					assert_eq!(Number::new($input).unwrap().sign(), Sign::$sign)
				}
			)*
		};
	}

	macro_rules! canonical_tests {
		{ $($id:ident: $input:literal => $output:literal),* } => {
			$(
				#[cfg(feature="canonical")]
				#[test]
				fn $id () {
					assert_eq!(Number::new($input).unwrap().canonical().as_number(), Number::new($output).unwrap())
				}
			)*
		};
	}

	positive_tests! {
		pos_01: "0",
		pos_02: "-0",
		pos_03: "123",
		pos_04: "1.23",
		pos_05: "-12.34",
		pos_06: "12.34e+56",
		pos_07: "12.34E-56",
		pos_08: "0.0000"
	}

	negative_tests! {
		neg_01: "",
		neg_02: "00",
		neg_03: "01",
		neg_04: "-00",
		neg_05: "-01",
		neg_06: "0.000e+-1",
		neg_07: "12.34E-56abc",
		neg_08: "1.",
		neg_09: "12.34e",
		neg_10: "12.34e+",
		neg_11: "12.34E-"
	}

	sign_tests! {
		sign_zero_01: "0" => Zero,
		sign_zero_02: "-0" => Zero,
		sign_zero_03: "0.0" => Zero,
		sign_zero_04: "0.0e12" => Zero,
		sign_zero_05: "-0.0E-12" => Zero,
		sign_zero_06: "-0.00000" => Zero
	}

	sign_tests! {
		sign_pos_01: "1" => Positive,
		sign_pos_02: "0.1" => Positive,
		sign_pos_03: "0.01e23" => Positive,
		sign_pos_04: "1.0E-23" => Positive,
		sign_pos_05: "0.00001" => Positive
	}

	sign_tests! {
		sign_neg_01: "-1" => Negative,
		sign_neg_02: "-0.1" => Negative,
		sign_neg_03: "-0.01e23" => Negative,
		sign_neg_04: "-1.0E-23" => Negative,
		sign_neg_05: "-0.00001" => Negative
	}

	canonical_tests! {
		canonical_01: "-0.0000" => "0",
		canonical_02: "0.00000000028" => "2.8e-10"
	}
}