1use crate::nat;
5use crate::object::{box_, dec, Obj};
6use std::cmp::Ordering;
7use std::fmt;
8use std::str::FromStr;
9
10pub struct Nat(Obj);
25
26unsafe impl Send for Nat {}
31unsafe impl Sync for Nat {}
32
33impl Nat {
34 #[doc(hidden)]
42 pub unsafe fn from_raw(raw: Obj) -> Nat {
43 Nat(raw)
44 }
45
46 #[doc(hidden)]
52 #[inline]
53 pub unsafe fn owning(raw: Obj) -> Nat {
54 Nat(nat::owned(raw))
55 }
56
57 #[doc(hidden)]
59 pub fn as_raw(&self) -> Obj {
60 self.0
61 }
62
63 #[doc(hidden)]
65 pub fn into_raw(self) -> Obj {
66 let raw = self.0;
67 std::mem::forget(self);
68 raw
69 }
70}
71
72impl Clone for Nat {
73 #[inline]
74 fn clone(&self) -> Nat {
75 Nat(unsafe { nat::unshared(self.0) })
76 }
77}
78
79impl Drop for Nat {
80 #[inline]
81 fn drop(&mut self) {
82 unsafe { dec(self.0) };
83 }
84}
85
86impl Default for Nat {
87 fn default() -> Nat {
88 Nat(box_(0))
89 }
90}
91
92impl From<&Nat> for Nat {
93 fn from(value: &Nat) -> Nat {
94 value.clone()
95 }
96}
97
98impl From<u128> for Nat {
99 fn from(value: u128) -> Nat {
100 Nat(nat::of_u128(value))
101 }
102}
103
104macro_rules! conversions {
105 ($($ty:ty),*) => {$(
106 impl From<$ty> for Nat {
107 fn from(value: $ty) -> Nat {
108 Nat(nat::uint64_to_nat(value as u64))
109 }
110 }
111
112 impl TryFrom<&Nat> for $ty {
113 type Error = TooLarge;
114
115 fn try_from(value: &Nat) -> Result<$ty, TooLarge> {
116 u128::try_from(value)?.try_into().map_err(|_| TooLarge)
117 }
118 }
119
120 impl TryFrom<Nat> for $ty {
121 type Error = TooLarge;
122
123 fn try_from(value: Nat) -> Result<$ty, TooLarge> {
124 <$ty>::try_from(&value)
125 }
126 }
127 )*};
128}
129
130conversions!(u8, u16, u32, u64, usize);
131
132impl TryFrom<&Nat> for u128 {
133 type Error = TooLarge;
134
135 fn try_from(value: &Nat) -> Result<u128, TooLarge> {
136 unsafe { nat::to_u128(value.0) }.ok_or(TooLarge)
137 }
138}
139
140impl TryFrom<Nat> for u128 {
141 type Error = TooLarge;
142
143 fn try_from(value: Nat) -> Result<u128, TooLarge> {
144 u128::try_from(&value)
145 }
146}
147
148impl Nat {
149 pub fn from_limbs(limbs: &[u64]) -> Nat {
157 Nat(nat::of_limbs(limbs))
158 }
159
160 pub fn to_limbs(&self) -> Vec<u64> {
162 unsafe { nat::with_limbs(self.0, <[u64]>::to_vec) }
163 }
164}
165
166impl<const N: usize> From<[u64; N]> for Nat {
167 fn from(limbs: [u64; N]) -> Nat {
169 Nat::from_limbs(&limbs)
170 }
171}
172
173impl<const N: usize> TryFrom<&Nat> for [u64; N] {
174 type Error = TooLarge;
175
176 fn try_from(value: &Nat) -> Result<[u64; N], TooLarge> {
178 unsafe { nat::with_limbs(value.0, crate::codec::fixed_limbs) }.ok_or(TooLarge)
179 }
180}
181
182impl<const N: usize> TryFrom<Nat> for [u64; N] {
183 type Error = TooLarge;
184
185 fn try_from(value: Nat) -> Result<[u64; N], TooLarge> {
186 <[u64; N]>::try_from(&value)
187 }
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub struct TooLarge;
193
194impl fmt::Display for TooLarge {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 f.write_str("the natural number does not fit the integer type")
197 }
198}
199
200impl std::error::Error for TooLarge {}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub struct ParseNatError;
205
206impl fmt::Display for ParseNatError {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 f.write_str("expected a natural number in decimal digits")
209 }
210}
211
212impl std::error::Error for ParseNatError {}
213
214impl FromStr for Nat {
215 type Err = ParseNatError;
216
217 fn from_str(text: &str) -> Result<Nat, ParseNatError> {
218 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
219 return Err(ParseNatError);
220 }
221 Ok(Nat(nat::cstr_to_nat(text)))
222 }
223}
224
225impl fmt::Display for Nat {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.pad_integral(true, "", &unsafe { nat::to_decimal(self.0) })
228 }
229}
230
231impl fmt::Debug for Nat {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 fmt::Display::fmt(self, f)
234 }
235}
236
237impl PartialEq for Nat {
238 fn eq(&self, other: &Nat) -> bool {
239 self.cmp(other) == Ordering::Equal
240 }
241}
242
243impl Eq for Nat {}
244
245impl PartialOrd for Nat {
246 fn partial_cmp(&self, other: &Nat) -> Option<Ordering> {
247 Some(self.cmp(other))
248 }
249}
250
251impl Ord for Nat {
252 fn cmp(&self, other: &Nat) -> Ordering {
253 unsafe { nat::ordering(self.0, other.0) }
254 }
255}
256
257impl std::hash::Hash for Nat {
258 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
259 unsafe { nat::with_limbs(self.0, |limbs| limbs.hash(state)) }
261 }
262}
263
264pub struct Int(Obj);
278
279unsafe impl Send for Int {}
281unsafe impl Sync for Int {}
282
283impl Int {
284 #[doc(hidden)]
289 pub unsafe fn from_raw(raw: Obj) -> Int {
290 Int(raw)
291 }
292
293 #[doc(hidden)]
299 #[inline]
300 pub unsafe fn owning(raw: Obj) -> Int {
301 Int(nat::owned(raw))
302 }
303
304 #[doc(hidden)]
306 pub fn as_raw(&self) -> Obj {
307 self.0
308 }
309
310 #[doc(hidden)]
312 pub fn into_raw(self) -> Obj {
313 let raw = self.0;
314 std::mem::forget(self);
315 raw
316 }
317}
318
319impl Clone for Int {
320 #[inline]
321 fn clone(&self) -> Int {
322 Int(unsafe { nat::unshared(self.0) })
323 }
324}
325
326impl Drop for Int {
327 #[inline]
328 fn drop(&mut self) {
329 unsafe { dec(self.0) };
330 }
331}
332
333impl Default for Int {
334 fn default() -> Int {
335 Int(box_(0))
336 }
337}
338
339impl From<&Int> for Int {
340 fn from(value: &Int) -> Int {
341 value.clone()
342 }
343}
344
345impl From<i128> for Int {
346 fn from(value: i128) -> Int {
347 Int(crate::int::of_i128(value))
348 }
349}
350
351impl From<Nat> for Int {
352 fn from(value: Nat) -> Int {
353 Int(unsafe { crate::int::nat_to_int(value.into_raw()) })
354 }
355}
356
357macro_rules! int_conversions {
358 ($($ty:ty),*) => {$(
359 impl From<$ty> for Int {
360 fn from(value: $ty) -> Int {
361 Int(crate::int::of_i128(value as i128))
362 }
363 }
364
365 impl TryFrom<&Int> for $ty {
366 type Error = TooLarge;
367
368 fn try_from(value: &Int) -> Result<$ty, TooLarge> {
369 i128::try_from(value)?.try_into().map_err(|_| TooLarge)
370 }
371 }
372
373 impl TryFrom<Int> for $ty {
374 type Error = TooLarge;
375
376 fn try_from(value: Int) -> Result<$ty, TooLarge> {
377 <$ty>::try_from(&value)
378 }
379 }
380 )*};
381}
382
383int_conversions!(i8, i16, i32, i64, isize);
384
385impl TryFrom<&Int> for i128 {
386 type Error = TooLarge;
387
388 fn try_from(value: &Int) -> Result<i128, TooLarge> {
389 unsafe { crate::int::to_i128(value.0) }.ok_or(TooLarge)
390 }
391}
392
393impl TryFrom<Int> for i128 {
394 type Error = TooLarge;
395
396 fn try_from(value: Int) -> Result<i128, TooLarge> {
397 i128::try_from(&value)
398 }
399}
400
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub struct ParseIntError;
404
405impl fmt::Display for ParseIntError {
406 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407 f.write_str("expected an integer in decimal digits")
408 }
409}
410
411impl std::error::Error for ParseIntError {}
412
413impl FromStr for Int {
414 type Err = ParseIntError;
415
416 fn from_str(text: &str) -> Result<Int, ParseIntError> {
417 let (negative, digits) = match text.strip_prefix('-') {
418 Some(digits) => (true, digits),
419 None => (false, text),
420 };
421 crate::int::from_decimal(negative, digits).map(Int).ok_or(ParseIntError)
422 }
423}
424
425impl fmt::Display for Int {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 let text = unsafe { crate::int::to_decimal(self.0) };
428 match text.strip_prefix('-') {
429 Some(digits) => f.pad_integral(false, "", digits),
430 None => f.pad_integral(true, "", &text),
431 }
432 }
433}
434
435impl fmt::Debug for Int {
436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437 fmt::Display::fmt(self, f)
438 }
439}
440
441impl PartialEq for Int {
442 fn eq(&self, other: &Int) -> bool {
443 self.cmp(other) == Ordering::Equal
444 }
445}
446
447impl Eq for Int {}
448
449impl PartialOrd for Int {
450 fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
451 Some(self.cmp(other))
452 }
453}
454
455impl Ord for Int {
456 fn cmp(&self, other: &Int) -> Ordering {
457 unsafe { crate::int::ordering(self.0, other.0) }
458 }
459}
460
461impl std::hash::Hash for Int {
462 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
463 unsafe { crate::int::hash(self.0, state) }
464 }
465}
466
467pub struct Generic<'a, const N: usize>(Obj, std::marker::PhantomData<&'a ()>);
485
486impl<const N: usize> Generic<'_, N> {
487 #[doc(hidden)]
490 #[inline(always)]
491 pub unsafe fn from_raw(raw: Obj) -> Self {
492 Generic(raw, std::marker::PhantomData)
493 }
494
495 #[doc(hidden)]
497 #[inline(always)]
498 pub fn into_raw(self) -> Obj {
499 let raw = self.0;
500 std::mem::forget(self);
501 raw
502 }
503}
504
505impl<const N: usize> Clone for Generic<'_, N> {
506 #[inline]
507 fn clone(&self) -> Self {
508 unsafe { crate::object::inc(self.0) };
509 Generic(self.0, std::marker::PhantomData)
510 }
511}
512
513impl<const N: usize> Drop for Generic<'_, N> {
514 #[inline]
515 fn drop(&mut self) {
516 unsafe { dec(self.0) };
517 }
518}