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
use std::{
	borrow::Borrow,
	fmt,
	ops::{Add, Div, Mul, Sub},
	str::FromStr,
};

use num_bigint::{BigInt, TryFromBigIntError};
use num_traits::{Signed, Zero};

use crate::{
	impl_integer_arithmetic,
	lexical::{self, LexicalFormOf},
	value::decimal::{U16_MAX, U32_MAX, U64_MAX, U8_MAX},
	Datatype, Integer, NonNegativeIntegerDatatype, ParseXsd, UnsignedIntDatatype,
	UnsignedLongDatatype, UnsignedShortDatatype, XsdValue,
};

use super::Sign;

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct NonNegativeInteger(BigInt);

impl NonNegativeInteger {
	/// Create a new non negative integer from a `BigInt`.
	///
	/// # Safety
	///
	/// The input number must be non negative.
	pub unsafe fn new_unchecked(n: BigInt) -> Self {
		Self(n)
	}

	/// Creates a non negative integer from its unsigned big endian bytes
	/// representation.
	pub fn from_bytes_be(bytes: &[u8]) -> Self {
		Self(BigInt::from_bytes_be(Sign::Plus, bytes))
	}

	/// Creates a non negative integer from its unsigned little endian bytes
	/// representation.
	pub fn from_bytes_le(bytes: &[u8]) -> Self {
		Self(BigInt::from_bytes_le(Sign::Plus, bytes))
	}

	/// Creates a non negative integer from its signed big endian bytes
	/// representation.
	///
	/// # Safety
	///
	/// The represented number must be non negative.
	pub unsafe fn from_signed_bytes_be_unchecked(bytes: &[u8]) -> Self {
		Self(BigInt::from_signed_bytes_be(bytes))
	}

	/// Creates a non negative integer from its signed little endian bytes
	/// representation.
	///
	/// # Safety
	///
	/// The represented number must be non negative.
	pub unsafe fn from_signed_bytes_le_unchecked(bytes: &[u8]) -> Self {
		Self(BigInt::from_signed_bytes_le(bytes))
	}

	pub fn from_signed_bytes_be(bytes: &[u8]) -> Result<Self, IntegerIsNegative> {
		Integer::from_signed_bytes_be(bytes).try_into()
	}

	pub fn from_signed_bytes_le(bytes: &[u8]) -> Result<Self, IntegerIsNegative> {
		Integer::from_signed_bytes_le(bytes).try_into()
	}

	#[inline(always)]
	pub fn into_big_int(self) -> BigInt {
		self.0
	}

	#[inline(always)]
	pub fn zero() -> Self {
		Self(BigInt::zero())
	}

	#[inline(always)]
	pub fn is_zero(&self) -> bool {
		self.0.is_zero()
	}

	pub fn non_negative_integer_type(&self) -> NonNegativeIntegerDatatype {
		if self.0 > BigInt::zero() {
			if self.0 <= *U8_MAX {
				UnsignedShortDatatype::UnsignedByte.into()
			} else if self.0 <= *U16_MAX {
				UnsignedShortDatatype::UnsignedShort.into()
			} else if self.0 <= *U32_MAX {
				UnsignedIntDatatype::UnsignedInt.into()
			} else if self.0 <= *U64_MAX {
				UnsignedLongDatatype::UnsignedLong.into()
			} else {
				NonNegativeIntegerDatatype::PositiveInteger
			}
		} else {
			NonNegativeIntegerDatatype::NonNegativeInteger
		}
	}

	/// Returns a lexical representation of this non negative integer.
	#[inline(always)]
	pub fn lexical_representation(&self) -> lexical::NonNegativeIntegerBuf {
		unsafe {
			// This is safe because the `Display::fmt` method matches the
			// XSD lexical representation.
			lexical::NonNegativeIntegerBuf::new_unchecked(format!("{}", self))
		}
	}

	pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
		self.0.to_bytes_be()
	}

	pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
		self.0.to_bytes_le()
	}

	pub fn to_signed_bytes_be(&self) -> Vec<u8> {
		self.0.to_signed_bytes_be()
	}

	pub fn to_signed_bytes_le(&self) -> Vec<u8> {
		self.0.to_signed_bytes_le()
	}
}

impl XsdValue for NonNegativeInteger {
	fn datatype(&self) -> Datatype {
		self.non_negative_integer_type().into()
	}
}

impl ParseXsd for NonNegativeInteger {
	type LexicalForm = lexical::NonNegativeInteger;
}

impl LexicalFormOf<NonNegativeInteger> for lexical::NonNegativeInteger {
	type ValueError = std::convert::Infallible;

	fn try_as_value(&self) -> Result<NonNegativeInteger, Self::ValueError> {
		Ok(self.value())
	}
}

impl From<NonNegativeInteger> for BigInt {
	fn from(value: NonNegativeInteger) -> Self {
		value.0
	}
}

impl<'a> From<&'a lexical::NonNegativeInteger> for NonNegativeInteger {
	#[inline(always)]
	fn from(value: &'a lexical::NonNegativeInteger) -> Self {
		Self(value.as_str().parse().unwrap())
	}
}

impl From<lexical::NonNegativeIntegerBuf> for NonNegativeInteger {
	#[inline(always)]
	fn from(value: lexical::NonNegativeIntegerBuf) -> Self {
		value.as_non_negative_integer().into()
	}
}

impl FromStr for NonNegativeInteger {
	type Err = lexical::InvalidNonNegativeInteger;

	#[inline(always)]
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let l = lexical::NonNegativeInteger::new(s)?;
		Ok(l.into())
	}
}

impl fmt::Display for NonNegativeInteger {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl AsRef<BigInt> for NonNegativeInteger {
	#[inline(always)]
	fn as_ref(&self) -> &BigInt {
		&self.0
	}
}

impl Borrow<BigInt> for NonNegativeInteger {
	#[inline(always)]
	fn borrow(&self) -> &BigInt {
		&self.0
	}
}

#[derive(Debug, thiserror::Error)]
#[error("integer {0} is negative")]
pub struct IntegerIsNegative(Integer);

impl TryFrom<Integer> for NonNegativeInteger {
	type Error = IntegerIsNegative;

	fn try_from(value: Integer) -> Result<Self, Self::Error> {
		if value.is_negative() {
			Err(IntegerIsNegative(value))
		} else {
			Ok(Self(value.into()))
		}
	}
}

macro_rules! from {
	{ $( $ty:ty ),* } => {
		$(
			impl From<$ty> for NonNegativeInteger {
				fn from(value: $ty) -> Self {
					Self(value.into())
				}
			}
		)*
	};
}

from!(u8, u16, u32, u64, usize);

#[derive(Debug, thiserror::Error)]
#[error("integer out of supported bounds: {0}")]
pub struct NonNegativeIntegerOutOfTargetBounds(pub NonNegativeInteger);

macro_rules! try_into {
	{ $( $ty:ty ),* } => {
		$(
			impl TryFrom<NonNegativeInteger> for $ty {
				type Error = NonNegativeIntegerOutOfTargetBounds;

				fn try_from(value: NonNegativeInteger) -> Result<Self, Self::Error> {
					value.0.try_into().map_err(|e: TryFromBigIntError<BigInt>| NonNegativeIntegerOutOfTargetBounds(NonNegativeInteger(e.into_original())))
				}
			}
		)*
	};
}

try_into!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);

impl_integer_arithmetic!(
	for NonNegativeInteger where r ( !r.is_negative() ) {
		Integer [.0],
		NonNegativeInteger [.0],
		PositiveInteger [.0],
		super::NonPositiveInteger [.into_big_int()],
		super::NegativeInteger [.into_big_int()],
		i8,
		i16,
		i32,
		i64,
		isize,
		u8,
		u16,
		u32,
		u64,
		usize
	}
);

pub type UnsignedLong = u64;

pub trait XsdUnsignedLong {
	fn unsigned_long_type(&self) -> UnsignedLongDatatype;
}

impl XsdUnsignedLong for UnsignedLong {
	fn unsigned_long_type(&self) -> UnsignedLongDatatype {
		if *self <= u8::MAX as u64 {
			UnsignedShortDatatype::UnsignedByte.into()
		} else if *self <= u16::MAX as u64 {
			UnsignedShortDatatype::UnsignedShort.into()
		} else if *self <= u32::MAX as u64 {
			UnsignedIntDatatype::UnsignedInt.into()
		} else {
			UnsignedLongDatatype::UnsignedLong
		}
	}
}

impl XsdValue for UnsignedLong {
	fn datatype(&self) -> Datatype {
		self.unsigned_long_type().into()
	}
}

impl ParseXsd for UnsignedLong {
	type LexicalForm = lexical::NonNegativeInteger;
}

impl LexicalFormOf<UnsignedLong> for lexical::NonNegativeInteger {
	type ValueError = NonNegativeIntegerOutOfTargetBounds;

	fn try_as_value(&self) -> Result<UnsignedLong, Self::ValueError> {
		self.value().try_into()
	}
}

pub type UnsignedInt = u32;

pub trait XsdUnsignedInt {
	fn unsigned_int_type(&self) -> UnsignedIntDatatype;
}

impl XsdUnsignedInt for UnsignedInt {
	fn unsigned_int_type(&self) -> UnsignedIntDatatype {
		if *self <= u8::MAX as u32 {
			UnsignedShortDatatype::UnsignedByte.into()
		} else if *self <= u16::MAX as u32 {
			UnsignedShortDatatype::UnsignedShort.into()
		} else {
			UnsignedIntDatatype::UnsignedInt
		}
	}
}

impl XsdValue for UnsignedInt {
	fn datatype(&self) -> Datatype {
		self.unsigned_int_type().into()
	}
}

impl ParseXsd for UnsignedInt {
	type LexicalForm = lexical::NonNegativeInteger;
}

impl LexicalFormOf<UnsignedInt> for lexical::NonNegativeInteger {
	type ValueError = NonNegativeIntegerOutOfTargetBounds;

	fn try_as_value(&self) -> Result<UnsignedInt, Self::ValueError> {
		self.value().try_into()
	}
}

pub type UnsignedShort = u16;

pub trait XsdUnsignedShort {
	fn unsigned_short_type(&self) -> UnsignedShortDatatype;
}

impl XsdUnsignedShort for UnsignedShort {
	fn unsigned_short_type(&self) -> UnsignedShortDatatype {
		if *self <= u8::MAX as u16 {
			UnsignedShortDatatype::UnsignedByte
		} else {
			UnsignedShortDatatype::UnsignedShort
		}
	}
}

impl XsdValue for UnsignedShort {
	fn datatype(&self) -> Datatype {
		self.unsigned_short_type().into()
	}
}

impl ParseXsd for UnsignedShort {
	type LexicalForm = lexical::NonNegativeInteger;
}

impl LexicalFormOf<UnsignedShort> for lexical::NonNegativeInteger {
	type ValueError = NonNegativeIntegerOutOfTargetBounds;

	fn try_as_value(&self) -> Result<UnsignedShort, Self::ValueError> {
		self.value().try_into()
	}
}

pub type UnsignedByte = u8;

impl XsdValue for UnsignedByte {
	fn datatype(&self) -> Datatype {
		UnsignedShortDatatype::UnsignedByte.into()
	}
}

impl ParseXsd for UnsignedByte {
	type LexicalForm = lexical::NonNegativeInteger;
}

impl LexicalFormOf<UnsignedByte> for lexical::NonNegativeInteger {
	type ValueError = NonNegativeIntegerOutOfTargetBounds;

	fn try_as_value(&self) -> Result<UnsignedByte, Self::ValueError> {
		self.value().try_into()
	}
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PositiveInteger(BigInt);

impl PositiveInteger {
	/// Creates a new positive integer from the given `BigInt`.
	///
	/// # Safety
	///
	/// The input value *must* but a positive integer.
	pub unsafe fn new_unchecked(n: BigInt) -> Self {
		Self(n)
	}

	/// Creates a positive integer from its unsigned big endian bytes
	/// representation.
	pub fn from_bytes_be(bytes: &[u8]) -> Self {
		Self(BigInt::from_bytes_be(Sign::Plus, bytes))
	}

	/// Creates a positive integer from its unsigned little endian bytes
	/// representation.
	pub fn from_bytes_le(bytes: &[u8]) -> Self {
		Self(BigInt::from_bytes_le(Sign::Plus, bytes))
	}

	/// Creates a positive integer from its unsigned big endian bytes
	/// representation.
	///
	/// # Safety
	///
	/// The represented number must be positive.
	pub unsafe fn from_signed_bytes_be_unchecked(bytes: &[u8]) -> Self {
		Self(BigInt::from_signed_bytes_be(bytes))
	}

	/// Creates a positive integer from its unsigned little endian bytes
	/// representation.
	///
	/// # Safety
	///
	/// The represented number must be positive.
	pub unsafe fn from_signed_bytes_le_unchecked(bytes: &[u8]) -> Self {
		Self(BigInt::from_signed_bytes_le(bytes))
	}

	pub fn into_big_int(self) -> BigInt {
		self.0
	}

	pub fn is_one(&self) -> bool {
		matches!(u8::try_from(&self.0), Ok(1))
	}

	pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
		self.0.to_bytes_be()
	}

	pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
		self.0.to_bytes_le()
	}

	pub fn to_signed_bytes_be(&self) -> Vec<u8> {
		self.0.to_signed_bytes_be()
	}

	pub fn to_signed_bytes_le(&self) -> Vec<u8> {
		self.0.to_signed_bytes_le()
	}
}

impl XsdValue for PositiveInteger {
	fn datatype(&self) -> Datatype {
		NonNegativeIntegerDatatype::PositiveInteger.into()
	}
}

impl ParseXsd for PositiveInteger {
	type LexicalForm = lexical::PositiveInteger;
}

impl LexicalFormOf<PositiveInteger> for lexical::PositiveInteger {
	type ValueError = std::convert::Infallible;

	fn try_as_value(&self) -> Result<PositiveInteger, Self::ValueError> {
		Ok(self.value())
	}
}

impl fmt::Display for PositiveInteger {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl From<PositiveInteger> for BigInt {
	fn from(value: PositiveInteger) -> Self {
		value.into_big_int()
	}
}

impl_integer_arithmetic!(
	for PositiveInteger where r ( r.is_positive() ) {
		Integer [.0],
		NonNegativeInteger [.0],
		PositiveInteger [.0],
		super::NonPositiveInteger [.into_big_int()],
		super::NegativeInteger [.into_big_int()],
		i8,
		i16,
		i32,
		i64,
		isize,
		u8,
		u16,
		u32,
		u64,
		usize
	}
);