facet-value 0.50.0-rc.0

Memory-efficient dynamic value type for facet, supporting JSON-like data plus bytes
Documentation
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Number value type with efficient storage for various numeric types.

#[cfg(feature = "alloc")]
use alloc::alloc::{Layout, alloc, dealloc};
use core::cmp::Ordering;
use core::fmt::{self, Debug, Formatter};
use core::hash::{Hash, Hasher};

use crate::value::{TypeTag, Value};

/// Internal representation of number type.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum NumberType {
    /// Signed 64-bit integer
    I64 = 0,
    /// Unsigned 64-bit integer
    U64 = 1,
    /// 64-bit floating point
    F64 = 2,
    /// Signed 128-bit integer
    I128 = 3,
    /// Unsigned 128-bit integer
    U128 = 4,
}

/// Header for heap-allocated numbers.
#[repr(C, align(8))]
struct NumberHeader {
    /// Type discriminant
    type_: NumberType,
    /// Padding
    _pad: [u8; 7],
    /// The actual number data (i64, u64, or f64)
    data: NumberData,
}

#[repr(C)]
union NumberData {
    i: i64,
    u: u64,
    f: f64,
    i128: i128,
    u128: u128,
}

/// A JSON number value.
///
/// `VNumber` can represent integers (signed and unsigned) and floating point numbers.
/// It stores the number in the most appropriate internal format.
#[repr(transparent)]
#[derive(Clone)]
pub struct VNumber(pub(crate) Value);

impl VNumber {
    const fn layout() -> Layout {
        Layout::new::<NumberHeader>()
    }

    #[cfg(feature = "alloc")]
    fn alloc(type_: NumberType) -> *mut NumberHeader {
        unsafe {
            let ptr = alloc(Self::layout()).cast::<NumberHeader>();
            (*ptr).type_ = type_;
            ptr
        }
    }

    #[cfg(feature = "alloc")]
    fn dealloc(ptr: *mut NumberHeader) {
        unsafe {
            dealloc(ptr.cast::<u8>(), Self::layout());
        }
    }

    fn header(&self) -> &NumberHeader {
        unsafe { &*(self.0.heap_ptr() as *const NumberHeader) }
    }

    #[allow(dead_code)]
    fn header_mut(&mut self) -> &mut NumberHeader {
        unsafe { &mut *(self.0.heap_ptr_mut() as *mut NumberHeader) }
    }

    /// Creates a number from an i64.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_i64(v: i64) -> Self {
        unsafe {
            let ptr = Self::alloc(NumberType::I64);
            (*ptr).data.i = v;
            VNumber(Value::new_ptr(ptr.cast(), TypeTag::Number))
        }
    }

    /// Creates a number from a u64.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_u64(v: u64) -> Self {
        // If it fits in i64, use that for consistency
        if let Ok(i) = i64::try_from(v) {
            Self::from_i64(i)
        } else {
            unsafe {
                let ptr = Self::alloc(NumberType::U64);
                (*ptr).data.u = v;
                VNumber(Value::new_ptr(ptr.cast(), TypeTag::Number))
            }
        }
    }

    /// Creates a number from an f64.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_f64(v: f64) -> Self {
        unsafe {
            let ptr = Self::alloc(NumberType::F64);
            (*ptr).data.f = v;
            VNumber(Value::new_ptr(ptr.cast(), TypeTag::Number))
        }
    }

    /// Creates a number from an i128, canonicalizing to the smallest representation.
    ///
    /// Magnitude canonicalization keeps the representations over disjoint ranges so
    /// that equal values always share a single internal form:
    /// `I64=[i64::MIN, i64::MAX]`, `U64=(i64::MAX, u64::MAX]`,
    /// `U128=(u64::MAX, u128::MAX]`, `I128=[i128::MIN, i64::MIN)`.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_i128(v: i128) -> Self {
        if let Ok(i) = i64::try_from(v) {
            Self::from_i64(i)
        } else if v >= 0 {
            if let Ok(u) = u64::try_from(v) {
                Self::from_u64(u)
            } else {
                // v > u64::MAX and positive: store as u128
                unsafe {
                    let ptr = Self::alloc(NumberType::U128);
                    (*ptr).data.u128 = v as u128;
                    VNumber(Value::new_ptr(ptr.cast(), TypeTag::Number))
                }
            }
        } else {
            // v < i64::MIN: store as i128
            unsafe {
                let ptr = Self::alloc(NumberType::I128);
                (*ptr).data.i128 = v;
                VNumber(Value::new_ptr(ptr.cast(), TypeTag::Number))
            }
        }
    }

    /// Creates a number from a u128, canonicalizing to the smallest representation.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_u128(v: u128) -> Self {
        if let Ok(u) = u64::try_from(v) {
            Self::from_u64(u)
        } else {
            unsafe {
                let ptr = Self::alloc(NumberType::U128);
                (*ptr).data.u128 = v;
                VNumber(Value::new_ptr(ptr.cast(), TypeTag::Number))
            }
        }
    }

    /// Returns the number zero.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn zero() -> Self {
        Self::from_i64(0)
    }

    /// Returns the number one.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn one() -> Self {
        Self::from_i64(1)
    }

    /// Converts to i64 if it can be represented exactly.
    #[must_use]
    pub fn to_i64(&self) -> Option<i64> {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => Some(hd.data.i),
                NumberType::U64 => i64::try_from(hd.data.u).ok(),
                NumberType::I128 => i64::try_from(hd.data.i128).ok(),
                NumberType::U128 => i64::try_from(hd.data.u128).ok(),
                NumberType::F64 => {
                    let f = hd.data.f;
                    // Check if in range and is a whole number via round-trip cast
                    if f >= i64::MIN as f64 && f <= i64::MAX as f64 {
                        let i = f as i64;
                        if i as f64 == f {
                            return Some(i);
                        }
                    }
                    None
                }
            }
        }
    }

    /// Converts to u64 if it can be represented exactly.
    #[must_use]
    pub fn to_u64(&self) -> Option<u64> {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => u64::try_from(hd.data.i).ok(),
                NumberType::U64 => Some(hd.data.u),
                NumberType::I128 => u64::try_from(hd.data.i128).ok(),
                NumberType::U128 => u64::try_from(hd.data.u128).ok(),
                NumberType::F64 => {
                    let f = hd.data.f;
                    // Check if in range and is a whole number via round-trip cast
                    if f >= 0.0 && f <= u64::MAX as f64 {
                        let u = f as u64;
                        if u as f64 == f {
                            return Some(u);
                        }
                    }
                    None
                }
            }
        }
    }

    /// Converts to i128 if it can be represented exactly.
    #[must_use]
    pub fn to_i128(&self) -> Option<i128> {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => Some(i128::from(hd.data.i)),
                NumberType::U64 => Some(i128::from(hd.data.u)),
                NumberType::I128 => Some(hd.data.i128),
                NumberType::U128 => i128::try_from(hd.data.u128).ok(),
                NumberType::F64 => {
                    let f = hd.data.f;
                    // Check if in range and is a whole number via round-trip cast
                    if f >= i128::MIN as f64 && f <= i128::MAX as f64 {
                        let i = f as i128;
                        if i as f64 == f {
                            return Some(i);
                        }
                    }
                    None
                }
            }
        }
    }

    /// Converts to u128 if it can be represented exactly.
    #[must_use]
    pub fn to_u128(&self) -> Option<u128> {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => u128::try_from(hd.data.i).ok(),
                NumberType::U64 => Some(u128::from(hd.data.u)),
                NumberType::I128 => u128::try_from(hd.data.i128).ok(),
                NumberType::U128 => Some(hd.data.u128),
                NumberType::F64 => {
                    let f = hd.data.f;
                    // Check if in range and is a whole number via round-trip cast
                    if f >= 0.0 && f <= u128::MAX as f64 {
                        let u = f as u128;
                        if u as f64 == f {
                            return Some(u);
                        }
                    }
                    None
                }
            }
        }
    }

    /// Converts to f64 if it can be represented exactly.
    #[must_use]
    pub fn to_f64(&self) -> Option<f64> {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => {
                    let i = hd.data.i;
                    let f = i as f64;
                    if f as i64 == i { Some(f) } else { None }
                }
                NumberType::U64 => {
                    let u = hd.data.u;
                    let f = u as f64;
                    if f as u64 == u { Some(f) } else { None }
                }
                NumberType::I128 => {
                    let i = hd.data.i128;
                    let f = i as f64;
                    if f as i128 == i { Some(f) } else { None }
                }
                NumberType::U128 => {
                    let u = hd.data.u128;
                    let f = u as f64;
                    if f as u128 == u { Some(f) } else { None }
                }
                NumberType::F64 => Some(hd.data.f),
            }
        }
    }

    /// Converts to f64, potentially losing precision.
    #[must_use]
    pub fn to_f64_lossy(&self) -> f64 {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => hd.data.i as f64,
                NumberType::U64 => hd.data.u as f64,
                NumberType::I128 => hd.data.i128 as f64,
                NumberType::U128 => hd.data.u128 as f64,
                NumberType::F64 => hd.data.f,
            }
        }
    }

    /// Converts to i32 if it can be represented exactly.
    #[must_use]
    pub fn to_i32(&self) -> Option<i32> {
        self.to_i64().and_then(|v| i32::try_from(v).ok())
    }

    /// Converts to u32 if it can be represented exactly.
    #[must_use]
    pub fn to_u32(&self) -> Option<u32> {
        self.to_u64().and_then(|v| u32::try_from(v).ok())
    }

    /// Converts to f32 if it can be represented exactly.
    #[must_use]
    pub fn to_f32(&self) -> Option<f32> {
        self.to_f64().and_then(|f| {
            let f32_val = f as f32;
            if f32_val as f64 == f {
                Some(f32_val)
            } else {
                None
            }
        })
    }

    /// Returns true if this number was created from a floating point value.
    #[must_use]
    pub fn is_float(&self) -> bool {
        self.header().type_ == NumberType::F64
    }

    /// Returns true if this number is an integer (signed or unsigned).
    #[must_use]
    pub fn is_integer(&self) -> bool {
        matches!(
            self.header().type_,
            NumberType::I64 | NumberType::U64 | NumberType::I128 | NumberType::U128
        )
    }

    pub(crate) fn clone_impl(&self) -> Value {
        let hd = self.header();
        unsafe {
            match hd.type_ {
                NumberType::I64 => Self::from_i64(hd.data.i).0,
                NumberType::U64 => {
                    let ptr = Self::alloc(NumberType::U64);
                    (*ptr).data.u = hd.data.u;
                    Value::new_ptr(ptr.cast(), TypeTag::Number)
                }
                NumberType::I128 => {
                    let ptr = Self::alloc(NumberType::I128);
                    (*ptr).data.i128 = hd.data.i128;
                    Value::new_ptr(ptr.cast(), TypeTag::Number)
                }
                NumberType::U128 => {
                    let ptr = Self::alloc(NumberType::U128);
                    (*ptr).data.u128 = hd.data.u128;
                    Value::new_ptr(ptr.cast(), TypeTag::Number)
                }
                NumberType::F64 => Self::from_f64(hd.data.f).0,
            }
        }
    }

    pub(crate) fn drop_impl(&mut self) {
        unsafe {
            Self::dealloc(self.0.heap_ptr_mut().cast());
        }
    }
}

impl PartialEq for VNumber {
    fn eq(&self, other: &Self) -> bool {
        self.partial_cmp(other) == Some(Ordering::Equal)
    }
}

impl PartialOrd for VNumber {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let h1 = self.header();
        let h2 = other.header();

        unsafe {
            // Fast path: same type
            if h1.type_ == h2.type_ {
                match h1.type_ {
                    NumberType::I64 => Some(h1.data.i.cmp(&h2.data.i)),
                    NumberType::U64 => Some(h1.data.u.cmp(&h2.data.u)),
                    NumberType::I128 => Some(h1.data.i128.cmp(&h2.data.i128)),
                    NumberType::U128 => Some(h1.data.u128.cmp(&h2.data.u128)),
                    NumberType::F64 => h1.data.f.partial_cmp(&h2.data.f),
                }
            } else if h1.type_ == NumberType::F64 || h2.type_ == NumberType::F64 {
                // If either operand is a float, fall back to lossy f64 comparison.
                // This preserves int == whole-float equality and NaN -> None.
                self.to_f64_lossy().partial_cmp(&other.to_f64_lossy())
            } else {
                // Both are integers: compare exactly.
                match (self.to_i128(), other.to_i128()) {
                    (Some(a), Some(b)) => Some(a.cmp(&b)),
                    // Exactly one is None means it's a U128 exceeding i128::MAX,
                    // so that side is the greater value.
                    (None, Some(_)) => Some(Ordering::Greater),
                    (Some(_), None) => Some(Ordering::Less),
                    // Both None: both exceed i128::MAX, compare via u128.
                    (None, None) => Some(self.to_u128().unwrap().cmp(&other.to_u128().unwrap())),
                }
            }
        }
    }
}

impl Hash for VNumber {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash based on the "canonical" representation. The chain mirrors the
        // canonicalization order so that equal values (including whole floats
        // equal to an integer) always land in the same bucket.
        if let Some(i) = self.to_i64() {
            0u8.hash(state); // discriminant for integer
            i.hash(state);
        } else if let Some(u) = self.to_u64() {
            1u8.hash(state); // discriminant for large unsigned
            u.hash(state);
        } else if let Some(i) = self.to_i128() {
            3u8.hash(state); // discriminant for 128-bit signed
            i.hash(state);
        } else if let Some(u) = self.to_u128() {
            4u8.hash(state); // discriminant for 128-bit unsigned
            u.hash(state);
        } else if let Some(f) = self.to_f64() {
            2u8.hash(state); // discriminant for float
            f.to_bits().hash(state);
        }
    }
}

impl Debug for VNumber {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Some(i) = self.to_i64() {
            Debug::fmt(&i, f)
        } else if let Some(u) = self.to_u64() {
            Debug::fmt(&u, f)
        } else if let Some(i) = self.to_i128() {
            Debug::fmt(&i, f)
        } else if let Some(u) = self.to_u128() {
            Debug::fmt(&u, f)
        } else if let Some(fl) = self.to_f64() {
            Debug::fmt(&fl, f)
        } else {
            f.write_str("NaN")
        }
    }
}

impl Default for VNumber {
    fn default() -> Self {
        Self::zero()
    }
}

// === From implementations ===

macro_rules! impl_from_int {
    ($($t:ty => $method:ident),* $(,)?) => {
        $(
            #[cfg(feature = "alloc")]
            impl From<$t> for VNumber {
                fn from(v: $t) -> Self {
                    Self::$method(v as _)
                }
            }

            #[cfg(feature = "alloc")]
            impl From<$t> for Value {
                fn from(v: $t) -> Self {
                    VNumber::from(v).0
                }
            }
        )*
    };
}

impl_from_int! {
    i8 => from_i64,
    i16 => from_i64,
    i32 => from_i64,
    i64 => from_i64,
    isize => from_i64,
    u8 => from_i64,
    u16 => from_i64,
    u32 => from_i64,
    u64 => from_u64,
    usize => from_u64,
}

// 128-bit integers must NOT go through the `as _` cast in `impl_from_int!`
// (that would be lossy), so they get explicit impls calling the dedicated
// canonicalizing constructors.

#[cfg(feature = "alloc")]
impl From<i128> for VNumber {
    fn from(v: i128) -> Self {
        Self::from_i128(v)
    }
}

#[cfg(feature = "alloc")]
impl From<i128> for Value {
    fn from(v: i128) -> Self {
        VNumber::from_i128(v).0
    }
}

#[cfg(feature = "alloc")]
impl From<u128> for VNumber {
    fn from(v: u128) -> Self {
        Self::from_u128(v)
    }
}

#[cfg(feature = "alloc")]
impl From<u128> for Value {
    fn from(v: u128) -> Self {
        VNumber::from_u128(v).0
    }
}

#[cfg(feature = "alloc")]
impl From<f32> for VNumber {
    fn from(v: f32) -> Self {
        Self::from_f64(f64::from(v))
    }
}

#[cfg(feature = "alloc")]
impl From<f64> for VNumber {
    fn from(v: f64) -> Self {
        Self::from_f64(v)
    }
}

#[cfg(feature = "alloc")]
impl From<f32> for Value {
    fn from(v: f32) -> Self {
        VNumber::from_f64(f64::from(v)).into_value()
    }
}

#[cfg(feature = "alloc")]
impl From<f64> for Value {
    fn from(v: f64) -> Self {
        VNumber::from_f64(v).into_value()
    }
}

// === Conversion traits ===

impl AsRef<Value> for VNumber {
    fn as_ref(&self) -> &Value {
        &self.0
    }
}

impl AsMut<Value> for VNumber {
    fn as_mut(&mut self) -> &mut Value {
        &mut self.0
    }
}

impl From<VNumber> for Value {
    fn from(n: VNumber) -> Self {
        n.0
    }
}

impl VNumber {
    /// Converts this VNumber into a Value, consuming self.
    #[inline]
    pub fn into_value(self) -> Value {
        self.0
    }
}

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

    #[test]
    fn test_i64() {
        let n = VNumber::from_i64(42);
        assert_eq!(n.to_i64(), Some(42));
        assert_eq!(n.to_u64(), Some(42));
        assert_eq!(n.to_f64(), Some(42.0));
        assert!(n.is_integer());
        assert!(!n.is_float());
    }

    #[test]
    fn test_negative() {
        let n = VNumber::from_i64(-100);
        assert_eq!(n.to_i64(), Some(-100));
        assert_eq!(n.to_u64(), None);
        assert_eq!(n.to_f64(), Some(-100.0));
    }

    #[test]
    fn test_large_u64() {
        let v = u64::MAX;
        let n = VNumber::from_u64(v);
        assert_eq!(n.to_u64(), Some(v));
        assert_eq!(n.to_i64(), None);
    }

    #[test]
    fn test_f64() {
        let n = VNumber::from_f64(2.5);
        assert_eq!(n.to_f64(), Some(2.5));
        assert_eq!(n.to_i64(), None); // has fractional part
        assert!(n.is_float());
        assert!(!n.is_integer());
    }

    #[test]
    fn test_f64_whole() {
        let n = VNumber::from_f64(42.0);
        assert_eq!(n.to_f64(), Some(42.0));
        assert_eq!(n.to_i64(), Some(42)); // whole number
    }

    #[test]
    fn test_nan_roundtrip() {
        assert!(VNumber::from_f64(f64::NAN).to_f64().unwrap().is_nan());
        assert_eq!(
            VNumber::from_f64(f64::INFINITY).to_f64().unwrap(),
            f64::INFINITY
        );
        assert_eq!(
            VNumber::from_f64(f64::NEG_INFINITY).to_f64().unwrap(),
            f64::NEG_INFINITY
        );
    }

    #[test]
    fn test_equality() {
        let a = VNumber::from_i64(42);
        let b = VNumber::from_i64(42);
        let c = VNumber::from_f64(42.0);
        let nan = VNumber::from_f64(f64::NAN);

        assert_eq!(a, b);
        assert_eq!(a, c); // integer 42 equals float 42.0

        // nan should != any value including itself
        assert_ne!(c, nan);
        assert_ne!(nan, nan);
    }

    #[test]
    fn test_ordering() {
        let a = VNumber::from_i64(1);
        let b = VNumber::from_i64(2);
        let c = VNumber::from_f64(1.5);
        let nan = VNumber::from_f64(f64::NAN);
        let inf = VNumber::from_f64(f64::INFINITY);

        assert!(a < b);
        assert!(a < c);
        assert!(c < b);
        assert!(b < inf);
        assert!(c.partial_cmp(&nan).is_none());
    }

    #[test]
    fn test_u128_max_roundtrip() {
        let n = VNumber::from_u128(u128::MAX);
        assert_eq!(n.to_u128(), Some(u128::MAX));
        // u128::MAX exceeds i128::MAX, so to_i128 must be None.
        assert_eq!(n.to_i128(), None);
        assert_eq!(n.to_u64(), None);
        assert!(n.is_integer());
    }

    #[test]
    fn test_i128_min_roundtrip() {
        let n = VNumber::from_i128(i128::MIN);
        assert_eq!(n.to_i128(), Some(i128::MIN));
        assert_eq!(n.to_u128(), None);
        assert_eq!(n.to_i64(), None);
        assert!(n.is_integer());
    }

    #[test]
    fn test_above_u64_max_roundtrip() {
        let v = u128::from(u64::MAX) + 1;
        let n = VNumber::from_u128(v);
        assert_eq!(n.to_u128(), Some(v));
        assert_eq!(n.to_i128(), Some(v as i128));
        assert_eq!(n.to_u64(), None);
    }

    #[test]
    fn test_128_canonicalization() {
        // Small values canonicalize down to I64.
        assert_eq!(VNumber::from_i128(5), VNumber::from_i64(5));
        assert_eq!(VNumber::from_u128(5), VNumber::from_i64(5));
        // u64::MAX canonicalizes to the same U64 representation.
        assert_eq!(
            VNumber::from_u128(u128::from(u64::MAX)),
            VNumber::from_u64(u64::MAX)
        );
        // A negative value within i64 range canonicalizes to I64.
        assert_eq!(VNumber::from_i128(-42), VNumber::from_i64(-42));
    }

    #[test]
    fn test_128_eq_hash_consistency() {
        use std::collections::HashSet;

        // Equal values built via different constructors must be Eq and hash equal.
        let a = VNumber::from_i128(5);
        let b = VNumber::from_u128(5);
        assert_eq!(a, b);

        let mut set = HashSet::new();
        set.insert(crate::Value::from(a.clone()));
        // Inserting the equal-but-differently-constructed value must collide.
        assert!(!set.insert(crate::Value::from(b.clone())));

        // A big value above u64::MAX, equal across i128/u128 construction.
        let big = u128::from(u64::MAX) + 12345;
        let x = VNumber::from_u128(big);
        let y = VNumber::from_i128(big as i128);
        assert_eq!(x, y);
        let mut set2 = HashSet::new();
        set2.insert(crate::Value::from(x));
        assert!(!set2.insert(crate::Value::from(y)));
    }

    #[test]
    fn test_128_cross_type_ordering() {
        // U128 above i128::MAX must order greater than any i128.
        let huge = VNumber::from_u128(u128::MAX);
        let big_signed = VNumber::from_i128(i128::MAX);
        assert!(big_signed < huge);

        // I128 min is the smallest.
        let small = VNumber::from_i128(i128::MIN);
        assert!(small < big_signed);
        assert!(small < VNumber::from_i64(0));
    }

    #[test]
    fn test_from_128_impls() {
        let v: crate::Value = (u128::MAX).into();
        assert_eq!(v.as_number().unwrap().to_u128(), Some(u128::MAX));
        let v: crate::Value = (i128::MIN).into();
        assert_eq!(v.as_number().unwrap().to_i128(), Some(i128::MIN));
    }
}