buff-rs 0.2.0

BUFF: Decomposed bounded floats for fast compression and queries
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
//! Optional interop with the `decimal-bytes` crate.
//!
//! This module provides conversion traits between `buff_rs` and `decimal_bytes` types.
//!
//! ## Supported Types
//!
//! - **`Decimal`**: Arbitrary precision decimals (variable-length)
//! - **`Decimal64`**: Fixed 8-byte decimals with embedded scale (≤16 digits)
//!
//! **Important**: Converting between BUFF and Decimal types involves precision loss because:
//! - BUFF uses bounded floating-point representation
//! - Decimal types use exact fixed-point representation
//!
//! ## Usage
//!
//! Enable the `decimal` feature in your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! buff-rs = { version = "0.1", features = ["decimal"] }
//! ```
//!
//! ### With Decimal (arbitrary precision)
//!
//! ```ignore
//! use buff_rs::BuffCodec;
//! use decimal_bytes::Decimal;
//!
//! let codec = BuffCodec::new(1000);
//!
//! // Convert Decimal array to BUFF-encoded bytes
//! let decimals: Vec<Decimal> = vec![
//!     "1.234".parse().unwrap(),
//!     "5.678".parse().unwrap(),
//! ];
//! let encoded = codec.encode_decimals(&decimals).unwrap();
//!
//! // Decode back to Decimal
//! let decoded: Vec<Decimal> = codec.decode_to_decimals(&encoded).unwrap();
//! ```
//!
//! ### With Decimal64 (fixed-size, ≤16 digits)
//!
//! ```ignore
//! use buff_rs::BuffCodec;
//! use decimal_bytes::Decimal64;
//!
//! let codec = BuffCodec::new(1000);
//!
//! // Convert Decimal64 array to BUFF-encoded bytes
//! let decimals: Vec<Decimal64> = vec![
//!     Decimal64::new("1.234", 3).unwrap(),
//!     Decimal64::new("5.678", 3).unwrap(),
//! ];
//! let encoded = codec.encode_decimal64s(&decimals).unwrap();
//!
//! // Decode back to Decimal64 (specify output scale)
//! let decoded: Vec<Decimal64> = codec.decode_to_decimal64s(&encoded, 3).unwrap();
//! ```

use crate::codec::{classify_float, BuffCodec};
use crate::error::BuffError;
use decimal_bytes::{Decimal, Decimal64};

impl BuffCodec {
    /// Encode an array of `decimal_bytes::Decimal` values.
    ///
    /// **Warning**: This involves precision loss. Decimal values are converted
    /// to f64 for BUFF encoding. Use this only when the precision loss is acceptable
    /// for your use case (e.g., analytics on time-series data).
    ///
    /// Special values (Infinity, -Infinity, NaN) in the Decimal are handled
    /// and stored separately.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use buff_rs::BuffCodec;
    /// use decimal_bytes::Decimal;
    ///
    /// let codec = BuffCodec::new(1000);
    /// let decimals: Vec<Decimal> = vec![
    ///     "1.234".parse().unwrap(),
    ///     "5.678".parse().unwrap(),
    /// ];
    /// let encoded = codec.encode_decimals(&decimals).unwrap();
    /// ```
    pub fn encode_decimals(&self, data: &[Decimal]) -> Result<Vec<u8>, BuffError> {
        if data.is_empty() {
            return Err(BuffError::EmptyInput);
        }

        // Convert decimals to f64
        let floats: Vec<f64> = data
            .iter()
            .map(|d| {
                if d.is_nan() {
                    f64::NAN
                } else if d.is_infinity() {
                    if d.is_negative() {
                        f64::NEG_INFINITY
                    } else {
                        f64::INFINITY
                    }
                } else {
                    // Parse decimal to f64 (involves precision loss)
                    d.to_string().parse::<f64>().unwrap_or(0.0)
                }
            })
            .collect();

        // Check if any special values exist
        let has_special = floats.iter().any(|v| classify_float(*v).is_some());

        if has_special {
            self.encode_with_special(&floats)
        } else {
            self.encode(&floats)
        }
    }

    /// Decode BUFF-encoded data to `decimal_bytes::Decimal` values.
    ///
    /// **Warning**: The decoded Decimals have the precision determined by the
    /// codec's scale, not the original Decimal precision.
    ///
    /// Special values are converted to `Decimal::nan()`, `Decimal::infinity()`,
    /// or `Decimal::neg_infinity()` as appropriate.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use buff_rs::BuffCodec;
    /// use decimal_bytes::Decimal;
    ///
    /// let codec = BuffCodec::new(1000);
    /// let data = vec![1.234, 5.678];
    /// let encoded = codec.encode(&data).unwrap();
    /// let decimals: Vec<Decimal> = codec.decode_to_decimals(&encoded).unwrap();
    /// ```
    pub fn decode_to_decimals(&self, bytes: &[u8]) -> Result<Vec<Decimal>, BuffError> {
        let floats = self.decode(bytes)?;

        floats
            .into_iter()
            .map(|f| {
                if f.is_nan() {
                    Ok(Decimal::nan())
                } else if f == f64::INFINITY {
                    Ok(Decimal::infinity())
                } else if f == f64::NEG_INFINITY {
                    Ok(Decimal::neg_infinity())
                } else {
                    // Convert f64 to Decimal string representation
                    let precision = self.precision() as u32;
                    let formatted = format!("{:.prec$}", f, prec = precision as usize);
                    formatted.parse::<Decimal>().map_err(|e| {
                        BuffError::InvalidData(format!("failed to parse decimal: {}", e))
                    })
                }
            })
            .collect()
    }

    /// Convert a single f64 to `decimal_bytes::Decimal`.
    ///
    /// This is a convenience method for single-value conversions.
    pub fn f64_to_decimal(&self, value: f64) -> Result<Decimal, BuffError> {
        if value.is_nan() {
            Ok(Decimal::nan())
        } else if value == f64::INFINITY {
            Ok(Decimal::infinity())
        } else if value == f64::NEG_INFINITY {
            Ok(Decimal::neg_infinity())
        } else {
            let precision = self.precision() as usize;
            let formatted = format!("{:.prec$}", value, prec = precision);
            formatted
                .parse::<Decimal>()
                .map_err(|e| BuffError::InvalidData(format!("failed to parse decimal: {}", e)))
        }
    }

    /// Convert a `decimal_bytes::Decimal` to f64.
    ///
    /// This is a convenience method for single-value conversions.
    ///
    /// **Warning**: This involves precision loss for high-precision decimals.
    pub fn decimal_to_f64(&self, decimal: &Decimal) -> f64 {
        if decimal.is_nan() {
            f64::NAN
        } else if decimal.is_infinity() {
            if decimal.is_negative() {
                f64::NEG_INFINITY
            } else {
                f64::INFINITY
            }
        } else {
            decimal.to_string().parse::<f64>().unwrap_or(0.0)
        }
    }

    // ==================== Decimal64 Methods ====================

    /// Encode an array of `decimal_bytes::Decimal64` values.
    ///
    /// `Decimal64` values are converted to f64 for BUFF encoding. Since Decimal64
    /// has a maximum of 16 significant digits, precision loss is minimal for most
    /// use cases.
    ///
    /// Special values (Infinity, -Infinity, NaN) are handled and stored separately.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use buff_rs::BuffCodec;
    /// use decimal_bytes::Decimal64;
    ///
    /// let codec = BuffCodec::new(1000);
    /// let decimals: Vec<Decimal64> = vec![
    ///     Decimal64::new("1.234", 3).unwrap(),
    ///     Decimal64::new("5.678", 3).unwrap(),
    /// ];
    /// let encoded = codec.encode_decimal64s(&decimals).unwrap();
    /// ```
    pub fn encode_decimal64s(&self, data: &[Decimal64]) -> Result<Vec<u8>, BuffError> {
        if data.is_empty() {
            return Err(BuffError::EmptyInput);
        }

        // Convert Decimal64 to f64
        let floats: Vec<f64> = data.iter().map(decimal64_to_f64).collect();

        // Check if any special values exist
        let has_special = floats.iter().any(|v| classify_float(*v).is_some());

        if has_special {
            self.encode_with_special(&floats)
        } else {
            self.encode(&floats)
        }
    }

    /// Decode BUFF-encoded data to `decimal_bytes::Decimal64` values.
    ///
    /// The decoded Decimal64 values will have the specified `scale`.
    ///
    /// Special values are converted to `Decimal64::nan()`, `Decimal64::infinity()`,
    /// or `Decimal64::neg_infinity()` as appropriate.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The BUFF-encoded data
    /// * `scale` - The scale for the output Decimal64 values (0-18)
    ///
    /// # Example
    ///
    /// ```ignore
    /// use buff_rs::BuffCodec;
    /// use decimal_bytes::Decimal64;
    ///
    /// let codec = BuffCodec::new(1000);
    /// let data = vec![1.234, 5.678];
    /// let encoded = codec.encode(&data).unwrap();
    /// let decimals: Vec<Decimal64> = codec.decode_to_decimal64s(&encoded, 3).unwrap();
    /// ```
    pub fn decode_to_decimal64s(
        &self,
        bytes: &[u8],
        scale: u8,
    ) -> Result<Vec<Decimal64>, BuffError> {
        let floats = self.decode(bytes)?;

        floats
            .into_iter()
            .map(|f| {
                if f.is_nan() {
                    Ok(Decimal64::nan())
                } else if f == f64::INFINITY {
                    Ok(Decimal64::infinity())
                } else if f == f64::NEG_INFINITY {
                    Ok(Decimal64::neg_infinity())
                } else {
                    // Convert f64 to Decimal64 with the specified scale
                    f64_to_decimal64(f, scale).map_err(|e| {
                        BuffError::InvalidData(format!("failed to create Decimal64: {}", e))
                    })
                }
            })
            .collect()
    }

    /// Convert a single f64 to `decimal_bytes::Decimal64`.
    ///
    /// # Arguments
    ///
    /// * `value` - The f64 value to convert
    /// * `scale` - The scale for the output Decimal64 (0-18)
    pub fn f64_to_decimal64(&self, value: f64, scale: u8) -> Result<Decimal64, BuffError> {
        if value.is_nan() {
            Ok(Decimal64::nan())
        } else if value == f64::INFINITY {
            Ok(Decimal64::infinity())
        } else if value == f64::NEG_INFINITY {
            Ok(Decimal64::neg_infinity())
        } else {
            f64_to_decimal64(value, scale)
                .map_err(|e| BuffError::InvalidData(format!("failed to create Decimal64: {}", e)))
        }
    }

    /// Convert a `decimal_bytes::Decimal64` to f64.
    ///
    /// This is a convenience method for single-value conversions.
    /// Since Decimal64 has ≤16 significant digits, precision loss is minimal.
    pub fn decimal64_to_f64(&self, decimal: &Decimal64) -> f64 {
        decimal64_to_f64(decimal)
    }
}

// ==================== Helper Functions ====================

/// Convert a Decimal64 to f64.
fn decimal64_to_f64(d: &Decimal64) -> f64 {
    if d.is_nan() {
        f64::NAN
    } else if d.is_pos_infinity() {
        f64::INFINITY
    } else if d.is_neg_infinity() {
        f64::NEG_INFINITY
    } else {
        // Get the raw value and scale
        let value = d.value();
        let scale = d.scale();

        if scale == 0 {
            value as f64
        } else {
            value as f64 / 10f64.powi(scale as i32)
        }
    }
}

/// Convert f64 to Decimal64 with specified scale.
fn f64_to_decimal64(value: f64, scale: u8) -> Result<Decimal64, decimal_bytes::DecimalError> {
    // Format with appropriate precision
    let precision = scale as usize;
    let formatted = format!("{:.prec$}", value, prec = precision);
    Decimal64::new(&formatted, scale)
}

/// Extension trait for converting Decimal arrays to f64 for BUFF encoding.
pub trait DecimalArrayExt {
    /// Convert to f64 array for BUFF encoding.
    fn to_f64_array(&self) -> Vec<f64>;
}

impl DecimalArrayExt for [Decimal] {
    fn to_f64_array(&self) -> Vec<f64> {
        self.iter()
            .map(|d| {
                if d.is_nan() {
                    f64::NAN
                } else if d.is_infinity() {
                    if d.is_negative() {
                        f64::NEG_INFINITY
                    } else {
                        f64::INFINITY
                    }
                } else {
                    d.to_string().parse::<f64>().unwrap_or(0.0)
                }
            })
            .collect()
    }
}

/// Extension trait for converting Decimal64 arrays to f64 for BUFF encoding.
pub trait Decimal64ArrayExt {
    /// Convert Decimal64 array to f64 array for BUFF encoding.
    fn decimal64s_to_f64_array(&self) -> Vec<f64>;
}

impl Decimal64ArrayExt for [Decimal64] {
    fn decimal64s_to_f64_array(&self) -> Vec<f64> {
        self.iter().map(decimal64_to_f64).collect()
    }
}

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

    #[test]
    fn test_encode_decode_decimals() {
        let codec = BuffCodec::new(1000);

        let decimals: Vec<Decimal> = vec![
            "1.234".parse().unwrap(),
            "5.678".parse().unwrap(),
            "9.012".parse().unwrap(),
        ];

        let encoded = codec.encode_decimals(&decimals).unwrap();
        let decoded = codec.decode_to_decimals(&encoded).unwrap();

        assert_eq!(decoded.len(), 3);
        // Check approximate equality (precision loss expected)
        for (orig, dec) in decimals.iter().zip(decoded.iter()) {
            let orig_f: f64 = orig.to_string().parse().unwrap();
            let dec_f: f64 = dec.to_string().parse().unwrap();
            assert!((orig_f - dec_f).abs() < 0.001, "orig={}, dec={}", orig, dec);
        }
    }

    #[test]
    fn test_special_values_decimal() {
        let codec = BuffCodec::new(1000);

        let decimals: Vec<Decimal> = vec![
            "1.0".parse().unwrap(),
            Decimal::infinity(),
            "2.0".parse().unwrap(),
            Decimal::nan(),
            Decimal::neg_infinity(),
        ];

        let encoded = codec.encode_decimals(&decimals).unwrap();
        let decoded = codec.decode_to_decimals(&encoded).unwrap();

        assert_eq!(decoded.len(), 5);
        assert!(!decoded[0].is_special());
        assert!(decoded[1].is_infinity() && !decoded[1].is_negative());
        assert!(!decoded[2].is_special());
        assert!(decoded[3].is_nan());
        assert!(decoded[4].is_infinity() && decoded[4].is_negative());
    }

    #[test]
    fn test_f64_to_decimal_conversion() {
        let codec = BuffCodec::new(1000);

        let dec = codec.f64_to_decimal(3.14159).unwrap();
        let f = codec.decimal_to_f64(&dec);

        assert!((f - 3.142).abs() < 0.001); // Rounded to 3 decimal places
    }

    #[test]
    fn test_decimal_array_ext() {
        let decimals: Vec<Decimal> = vec![
            "1.5".parse().unwrap(),
            Decimal::infinity(),
            "2.5".parse().unwrap(),
        ];

        let floats = decimals.to_f64_array();

        assert!((floats[0] - 1.5).abs() < f64::EPSILON);
        assert!(floats[1].is_infinite() && floats[1].is_sign_positive());
        assert!((floats[2] - 2.5).abs() < f64::EPSILON);
    }

    // ==================== Decimal64 Tests ====================

    #[test]
    fn test_encode_decode_decimal64s() {
        let codec = BuffCodec::new(1000);

        let decimals: Vec<Decimal64> = vec![
            Decimal64::new("1.234", 3).unwrap(),
            Decimal64::new("5.678", 3).unwrap(),
            Decimal64::new("9.012", 3).unwrap(),
        ];

        let encoded = codec.encode_decimal64s(&decimals).unwrap();
        let decoded = codec.decode_to_decimal64s(&encoded, 3).unwrap();

        assert_eq!(decoded.len(), 3);
        // Check approximate equality (precision loss expected)
        for (orig, dec) in decimals.iter().zip(decoded.iter()) {
            let orig_f = decimal64_to_f64(orig);
            let dec_f = decimal64_to_f64(dec);
            assert!((orig_f - dec_f).abs() < 0.001, "orig={}, dec={}", orig, dec);
        }
    }

    #[test]
    fn test_special_values_decimal64() {
        let codec = BuffCodec::new(1000);

        let decimals: Vec<Decimal64> = vec![
            Decimal64::new("1.0", 1).unwrap(),
            Decimal64::infinity(),
            Decimal64::new("2.0", 1).unwrap(),
            Decimal64::nan(),
            Decimal64::neg_infinity(),
        ];

        let encoded = codec.encode_decimal64s(&decimals).unwrap();
        let decoded = codec.decode_to_decimal64s(&encoded, 1).unwrap();

        assert_eq!(decoded.len(), 5);
        assert!(!decoded[0].is_special());
        assert!(decoded[1].is_pos_infinity());
        assert!(!decoded[2].is_special());
        assert!(decoded[3].is_nan());
        assert!(decoded[4].is_neg_infinity());
    }

    #[test]
    fn test_f64_to_decimal64_conversion() {
        let codec = BuffCodec::new(1000);

        let d64 = codec.f64_to_decimal64(3.14159, 3).unwrap();
        let f = codec.decimal64_to_f64(&d64);

        assert!((f - 3.142).abs() < 0.001); // Rounded to 3 decimal places
    }

    #[test]
    fn test_decimal64_array_ext() {
        let decimals: Vec<Decimal64> = vec![
            Decimal64::new("1.5", 1).unwrap(),
            Decimal64::infinity(),
            Decimal64::new("2.5", 1).unwrap(),
        ];

        let floats = decimals.decimal64s_to_f64_array();

        assert!((floats[0] - 1.5).abs() < f64::EPSILON);
        assert!(floats[1].is_infinite() && floats[1].is_sign_positive());
        assert!((floats[2] - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_decimal64_direct_conversion() {
        // Test direct value/scale conversion without string parsing
        let d64 = Decimal64::new("123.45", 2).unwrap();
        let f = decimal64_to_f64(&d64);
        assert!((f - 123.45).abs() < f64::EPSILON);

        let d64_neg = Decimal64::new("-99.99", 2).unwrap();
        let f_neg = decimal64_to_f64(&d64_neg);
        assert!((f_neg - (-99.99)).abs() < f64::EPSILON);
    }

    #[test]
    fn test_decimal64_roundtrip_various_scales() {
        let codec = BuffCodec::new(10000); // 4 decimal places

        // Test with different scales
        for scale in [0u8, 1, 2, 3, 4] {
            let value = format!("{:.prec$}", 123.456789, prec = scale as usize);
            let d64 = Decimal64::new(&value, scale).unwrap();

            let encoded = codec.encode_decimal64s(&[d64]).unwrap();
            let decoded = codec.decode_to_decimal64s(&encoded, scale).unwrap();

            let orig_f = decimal64_to_f64(&d64);
            let dec_f = decimal64_to_f64(&decoded[0]);

            assert!(
                (orig_f - dec_f).abs() < 0.0001,
                "scale={}, orig={}, decoded={}",
                scale,
                orig_f,
                dec_f
            );
        }
    }

    #[test]
    fn test_encode_decimals_empty() {
        let codec = BuffCodec::new(1000);
        let result = codec.encode_decimals(&[]);
        assert!(matches!(result, Err(BuffError::EmptyInput)));
    }

    #[test]
    fn test_encode_decimal64s_empty() {
        let codec = BuffCodec::new(1000);
        let result = codec.encode_decimal64s(&[]);
        assert!(matches!(result, Err(BuffError::EmptyInput)));
    }

    #[test]
    fn test_decimal_to_f64_special_values() {
        let codec = BuffCodec::new(1000);

        // Test NaN
        let nan = Decimal::nan();
        let f_nan = codec.decimal_to_f64(&nan);
        assert!(f_nan.is_nan());

        // Test +Infinity
        let inf = Decimal::infinity();
        let f_inf = codec.decimal_to_f64(&inf);
        assert!(f_inf.is_infinite() && f_inf.is_sign_positive());

        // Test -Infinity
        let neg_inf = Decimal::neg_infinity();
        let f_neg_inf = codec.decimal_to_f64(&neg_inf);
        assert!(f_neg_inf.is_infinite() && f_neg_inf.is_sign_negative());
    }

    #[test]
    fn test_f64_to_decimal_special_values() {
        let codec = BuffCodec::new(1000);

        // Test NaN
        let dec_nan = codec.f64_to_decimal(f64::NAN).unwrap();
        assert!(dec_nan.is_nan());

        // Test +Infinity
        let dec_inf = codec.f64_to_decimal(f64::INFINITY).unwrap();
        assert!(dec_inf.is_infinity() && !dec_inf.is_negative());

        // Test -Infinity
        let dec_neg_inf = codec.f64_to_decimal(f64::NEG_INFINITY).unwrap();
        assert!(dec_neg_inf.is_infinity() && dec_neg_inf.is_negative());
    }

    #[test]
    fn test_f64_to_decimal64_special_values() {
        let codec = BuffCodec::new(1000);

        // Test NaN
        let d64_nan = codec.f64_to_decimal64(f64::NAN, 3).unwrap();
        assert!(d64_nan.is_nan());

        // Test +Infinity
        let d64_inf = codec.f64_to_decimal64(f64::INFINITY, 3).unwrap();
        assert!(d64_inf.is_pos_infinity());

        // Test -Infinity
        let d64_neg_inf = codec.f64_to_decimal64(f64::NEG_INFINITY, 3).unwrap();
        assert!(d64_neg_inf.is_neg_infinity());
    }

    #[test]
    fn test_decimal64_to_f64_scale_zero() {
        // Test with scale=0 (integer)
        let d64 = Decimal64::new("12345", 0).unwrap();
        let f = decimal64_to_f64(&d64);
        assert!((f - 12345.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_decimal64_to_f64_nan() {
        let d64 = Decimal64::nan();
        let f = decimal64_to_f64(&d64);
        assert!(f.is_nan());
    }

    #[test]
    fn test_decimal64_to_f64_pos_infinity() {
        let d64 = Decimal64::infinity();
        let f = decimal64_to_f64(&d64);
        assert!(f.is_infinite() && f.is_sign_positive());
    }

    #[test]
    fn test_decimal64_to_f64_neg_infinity() {
        let d64 = Decimal64::neg_infinity();
        let f = decimal64_to_f64(&d64);
        assert!(f.is_infinite() && f.is_sign_negative());
    }

    #[test]
    fn test_decimal_array_ext_neg_infinity() {
        let decimals: Vec<Decimal> = vec!["1.0".parse().unwrap(), Decimal::neg_infinity()];

        let floats = decimals.to_f64_array();

        assert!((floats[0] - 1.0).abs() < f64::EPSILON);
        assert!(floats[1].is_infinite() && floats[1].is_sign_negative());
    }

    #[test]
    fn test_decimal_array_ext_nan() {
        let decimals: Vec<Decimal> = vec!["1.0".parse().unwrap(), Decimal::nan()];

        let floats = decimals.to_f64_array();

        assert!((floats[0] - 1.0).abs() < f64::EPSILON);
        assert!(floats[1].is_nan());
    }

    #[test]
    fn test_decimal64_array_ext_special() {
        let decimals: Vec<Decimal64> = vec![Decimal64::nan(), Decimal64::neg_infinity()];

        let floats = decimals.decimal64s_to_f64_array();

        assert!(floats[0].is_nan());
        assert!(floats[1].is_infinite() && floats[1].is_sign_negative());
    }

    #[test]
    fn test_negative_decimals() {
        let codec = BuffCodec::new(1000);

        let decimals: Vec<Decimal> = vec![
            "-1.234".parse().unwrap(),
            "-5.678".parse().unwrap(),
            "0.0".parse().unwrap(),
        ];

        let encoded = codec.encode_decimals(&decimals).unwrap();
        let decoded = codec.decode_to_decimals(&encoded).unwrap();

        assert_eq!(decoded.len(), 3);
        for (orig, dec) in decimals.iter().zip(decoded.iter()) {
            let orig_f: f64 = orig.to_string().parse().unwrap();
            let dec_f: f64 = dec.to_string().parse().unwrap();
            assert!((orig_f - dec_f).abs() < 0.001, "orig={}, dec={}", orig, dec);
        }
    }

    #[test]
    fn test_negative_decimal64s() {
        let codec = BuffCodec::new(1000);

        let decimals: Vec<Decimal64> = vec![
            Decimal64::new("-1.234", 3).unwrap(),
            Decimal64::new("-5.678", 3).unwrap(),
            Decimal64::new("0.0", 3).unwrap(),
        ];

        let encoded = codec.encode_decimal64s(&decimals).unwrap();
        let decoded = codec.decode_to_decimal64s(&encoded, 3).unwrap();

        assert_eq!(decoded.len(), 3);
        for (orig, dec) in decimals.iter().zip(decoded.iter()) {
            let orig_f = decimal64_to_f64(orig);
            let dec_f = decimal64_to_f64(dec);
            assert!((orig_f - dec_f).abs() < 0.001, "orig={}, dec={}", orig, dec);
        }
    }
}