xsd-schema 0.1.0

XML Schema (XSD 1.0/1.1) validator with PSVI and a built-in XPath 2.0 engine
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
//! XPath 2.0 numeric functions.
//!
//! This module implements numeric functions from the XPath 2.0 specification:
//! - fn:abs
//! - fn:ceiling
//! - fn:floor
//! - fn:round
//! - fn:round-half-to-even

use num_bigint::BigInt;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::Decimal;

use crate::types::value::{XmlAtomicValue, XmlValue, XmlValueKind};
use crate::types::XmlTypeCode;
use crate::xpath::context::DynamicContext;
use crate::xpath::error::XPathError;
use crate::xpath::DomNavigator;

use super::{atomize_to_single_opt, XPathValue};

/// Check if a type code is an integer-derived type.
fn is_integer_type(code: XmlTypeCode) -> bool {
    matches!(
        code,
        XmlTypeCode::Integer
            | XmlTypeCode::NonPositiveInteger
            | XmlTypeCode::NegativeInteger
            | XmlTypeCode::Long
            | XmlTypeCode::Int
            | XmlTypeCode::Short
            | XmlTypeCode::Byte
            | XmlTypeCode::NonNegativeInteger
            | XmlTypeCode::UnsignedLong
            | XmlTypeCode::UnsignedInt
            | XmlTypeCode::UnsignedShort
            | XmlTypeCode::UnsignedByte
            | XmlTypeCode::PositiveInteger
    )
}

/// Extract float value from XmlValue.
fn get_float(value: &XmlValue) -> Option<f32> {
    match &value.value {
        XmlValueKind::Atomic(XmlAtomicValue::Float(f)) => Some(*f),
        _ => None,
    }
}

// ============================================================================
// fn:abs($arg as numeric?) as numeric?
// ============================================================================

/// Implements fn:abs - returns the absolute value of the argument.
///
/// The function preserves the numeric type of the input.
pub fn abs<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments("abs", 1, args.len()));
    }

    let arg = args.remove(0);
    let value = match atomize_to_single_opt(arg)? {
        None => return Ok(XPathValue::Empty),
        Some(v) => v,
    };

    let result = numeric_abs(&value)?;
    Ok(XPathValue::from_atomic(result))
}

fn numeric_abs(value: &XmlValue) -> Result<XmlValue, XPathError> {
    match value.type_code {
        XmlTypeCode::Double => {
            let d = value.as_double().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:double".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::double(d.abs()))
        }
        XmlTypeCode::Float => {
            let f = get_float(value).ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:float".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::float(f.abs()))
        }
        XmlTypeCode::Decimal => {
            let d = value.as_decimal().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:decimal".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::decimal(d.abs()))
        }
        _ if is_integer_type(value.type_code) => {
            let i = value.as_integer().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:integer".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            // For BigInt, we need to handle negative numbers
            let abs_val = if *i < BigInt::from(0) {
                -i.clone()
            } else {
                i.clone()
            };
            Ok(XmlValue::integer(abs_val))
        }
        _ => Err(XPathError::XPTY0004 {
            expected: "xs:numeric".to_string(),
            found: format!("{:?}", value.type_code),
        }),
    }
}

// ============================================================================
// fn:ceiling($arg as numeric?) as numeric?
// ============================================================================

/// Implements fn:ceiling - returns the smallest integer greater than or equal to the argument.
///
/// The function preserves the numeric type of the input.
pub fn ceiling<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "ceiling",
            1,
            args.len(),
        ));
    }

    let arg = args.remove(0);
    let value = match atomize_to_single_opt(arg)? {
        None => return Ok(XPathValue::Empty),
        Some(v) => v,
    };

    let result = numeric_ceiling(&value)?;
    Ok(XPathValue::from_atomic(result))
}

fn numeric_ceiling(value: &XmlValue) -> Result<XmlValue, XPathError> {
    match value.type_code {
        XmlTypeCode::Double => {
            let d = value.as_double().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:double".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::double(d.ceil()))
        }
        XmlTypeCode::Float => {
            let f = get_float(value).ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:float".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::float(f.ceil()))
        }
        XmlTypeCode::Decimal => {
            let d = value.as_decimal().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:decimal".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            // Decimal doesn't have ceil(), use manual calculation
            let truncated = d.trunc();
            let result = if d > truncated {
                truncated + Decimal::ONE
            } else {
                truncated
            };
            Ok(XmlValue::decimal(result))
        }
        _ if is_integer_type(value.type_code) => {
            // For integers, ceiling is identity
            Ok(value.clone())
        }
        _ => Err(XPathError::XPTY0004 {
            expected: "xs:numeric".to_string(),
            found: format!("{:?}", value.type_code),
        }),
    }
}

// ============================================================================
// fn:floor($arg as numeric?) as numeric?
// ============================================================================

/// Implements fn:floor - returns the largest integer less than or equal to the argument.
///
/// The function preserves the numeric type of the input.
pub fn floor<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "floor",
            1,
            args.len(),
        ));
    }

    let arg = args.remove(0);
    let value = match atomize_to_single_opt(arg)? {
        None => return Ok(XPathValue::Empty),
        Some(v) => v,
    };

    let result = numeric_floor(&value)?;
    Ok(XPathValue::from_atomic(result))
}

fn numeric_floor(value: &XmlValue) -> Result<XmlValue, XPathError> {
    match value.type_code {
        XmlTypeCode::Double => {
            let d = value.as_double().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:double".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::double(d.floor()))
        }
        XmlTypeCode::Float => {
            let f = get_float(value).ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:float".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::float(f.floor()))
        }
        XmlTypeCode::Decimal => {
            let d = value.as_decimal().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:decimal".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            // Decimal doesn't have floor(), use manual calculation
            let truncated = d.trunc();
            let result = if d < truncated {
                truncated - Decimal::ONE
            } else {
                truncated
            };
            Ok(XmlValue::decimal(result))
        }
        _ if is_integer_type(value.type_code) => {
            // For integers, floor is identity
            Ok(value.clone())
        }
        _ => Err(XPathError::XPTY0004 {
            expected: "xs:numeric".to_string(),
            found: format!("{:?}", value.type_code),
        }),
    }
}

// ============================================================================
// fn:round($arg as numeric?) as numeric?
// ============================================================================

/// Implements fn:round - returns the nearest integer to the argument.
///
/// Rounds half values away from zero (e.g., 0.5 -> 1, -0.5 -> -1).
/// The function preserves the numeric type of the input.
pub fn round<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "round",
            1,
            args.len(),
        ));
    }

    let arg = args.remove(0);
    let value = match atomize_to_single_opt(arg)? {
        None => return Ok(XPathValue::Empty),
        Some(v) => v,
    };

    let result = numeric_round(&value)?;
    Ok(XPathValue::from_atomic(result))
}

fn numeric_round(value: &XmlValue) -> Result<XmlValue, XPathError> {
    match value.type_code {
        XmlTypeCode::Double => {
            let d = value.as_double().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:double".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            // XPath round() rounds half away from zero
            Ok(XmlValue::double(round_half_away_from_zero_f64(d)))
        }
        XmlTypeCode::Float => {
            let f = get_float(value).ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:float".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::float(round_half_away_from_zero_f32(f)))
        }
        XmlTypeCode::Decimal => {
            let d = value.as_decimal().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:decimal".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::decimal(round_half_away_from_zero_decimal(d)))
        }
        _ if is_integer_type(value.type_code) => {
            // For integers, round is identity
            Ok(value.clone())
        }
        _ => Err(XPathError::XPTY0004 {
            expected: "xs:numeric".to_string(),
            found: format!("{:?}", value.type_code),
        }),
    }
}

/// Round half away from zero for f64 (XPath round semantics).
fn round_half_away_from_zero_f64(d: f64) -> f64 {
    if d.is_nan() || d.is_infinite() {
        return d;
    }
    // For positive numbers: floor(x + 0.5)
    // For negative numbers: ceil(x - 0.5)
    if d >= 0.0 {
        (d + 0.5).floor()
    } else {
        (d - 0.5).ceil()
    }
}

/// Round half away from zero for f32.
fn round_half_away_from_zero_f32(f: f32) -> f32 {
    if f.is_nan() || f.is_infinite() {
        return f;
    }
    if f >= 0.0 {
        (f + 0.5).floor()
    } else {
        (f - 0.5).ceil()
    }
}

/// Round half away from zero for Decimal.
fn round_half_away_from_zero_decimal(d: Decimal) -> Decimal {
    let half = Decimal::new(5, 1); // 0.5
    let truncated = d.trunc();
    let frac = d - truncated;

    if d >= Decimal::ZERO {
        if frac >= half {
            truncated + Decimal::ONE
        } else {
            truncated
        }
    } else if frac <= -half {
        truncated - Decimal::ONE
    } else {
        truncated
    }
}

// ============================================================================
// fn:round-half-to-even($arg as numeric?, $precision as integer?) as numeric?
// ============================================================================

/// Implements fn:round-half-to-even - banker's rounding.
///
/// Rounds to the specified precision using half-to-even rounding mode.
/// If precision is omitted, rounds to the nearest integer.
pub fn round_half_to_even<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.is_empty() || args.len() > 2 {
        return Err(XPathError::wrong_number_of_arguments(
            "round-half-to-even",
            1,
            args.len(),
        ));
    }

    // Get precision (default 0)
    let precision: i32 = if args.len() == 2 {
        let prec_arg = args.remove(1);
        match atomize_to_single_opt(prec_arg)? {
            None => return Ok(XPathValue::Empty),
            Some(v) => {
                v.as_integer()
                    .and_then(|i| i.to_i32())
                    .ok_or_else(|| XPathError::XPTY0004 {
                        expected: "xs:integer".to_string(),
                        found: format!("{:?}", v.type_code),
                    })?
            }
        }
    } else {
        0
    };

    let arg = args.remove(0);
    let value = match atomize_to_single_opt(arg)? {
        None => return Ok(XPathValue::Empty),
        Some(v) => v,
    };

    let result = numeric_round_half_to_even(&value, precision)?;
    Ok(XPathValue::from_atomic(result))
}

fn numeric_round_half_to_even(value: &XmlValue, precision: i32) -> Result<XmlValue, XPathError> {
    match value.type_code {
        XmlTypeCode::Double => {
            let d = value.as_double().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:double".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::double(round_half_to_even_f64(d, precision)))
        }
        XmlTypeCode::Float => {
            let f = get_float(value).ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:float".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::float(round_half_to_even_f32(f, precision)))
        }
        XmlTypeCode::Decimal => {
            let d = value.as_decimal().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:decimal".to_string(),
                found: format!("{:?}", value.type_code),
            })?;
            Ok(XmlValue::decimal(round_half_to_even_decimal(d, precision)?))
        }
        _ if is_integer_type(value.type_code) => {
            // For integers with non-negative precision, return as-is
            if precision >= 0 {
                return Ok(value.clone());
            }

            // For negative precision, round to powers of 10
            let i = value.as_integer().ok_or_else(|| XPathError::XPTY0004 {
                expected: "xs:integer".to_string(),
                found: format!("{:?}", value.type_code),
            })?;

            let result = round_half_to_even_integer(i, precision);
            Ok(XmlValue::integer(result))
        }
        _ => Err(XPathError::XPTY0004 {
            expected: "xs:numeric".to_string(),
            found: format!("{:?}", value.type_code),
        }),
    }
}

/// Round half to even for f64 with given precision.
fn round_half_to_even_f64(d: f64, precision: i32) -> f64 {
    if d.is_nan() || d.is_infinite() {
        return d;
    }

    if precision < 0 {
        // Round to powers of 10 (e.g., precision -1 rounds to nearest 10)
        let scale = 10_f64.powi(-precision);
        let scaled = d / scale;
        // Use round_ties_even
        round_ties_even_f64(scaled) * scale
    } else {
        let scale = 10_f64.powi(precision);
        let scaled = d * scale;
        round_ties_even_f64(scaled) / scale
    }
}

/// Round ties to even for f64 (banker's rounding).
fn round_ties_even_f64(d: f64) -> f64 {
    let floored = d.floor();
    let frac = d - floored;

    if frac < 0.5 {
        floored
    } else if frac > 0.5 {
        floored + 1.0
    } else {
        // Exactly 0.5 - round to even
        if floored as i64 % 2 == 0 {
            floored
        } else {
            floored + 1.0
        }
    }
}

/// Round half to even for f32 with given precision.
fn round_half_to_even_f32(f: f32, precision: i32) -> f32 {
    if f.is_nan() || f.is_infinite() {
        return f;
    }

    if precision < 0 {
        let scale = 10_f32.powi(-precision);
        let scaled = f / scale;
        round_ties_even_f32(scaled) * scale
    } else {
        let scale = 10_f32.powi(precision);
        let scaled = f * scale;
        round_ties_even_f32(scaled) / scale
    }
}

/// Round ties to even for f32.
fn round_ties_even_f32(f: f32) -> f32 {
    let floored = f.floor();
    let frac = f - floored;

    if frac < 0.5 {
        floored
    } else if frac > 0.5 {
        floored + 1.0
    } else if floored as i32 % 2 == 0 {
        floored
    } else {
        floored + 1.0
    }
}

/// Round half to even for Decimal with given precision.
fn round_half_to_even_decimal(d: Decimal, precision: i32) -> Result<Decimal, XPathError> {
    if precision < 0 {
        // For negative precision, we need to round to powers of 10
        let abs_precision = (-precision) as u32;
        let scale = Decimal::from_i64(10_i64.pow(abs_precision))
            .ok_or_else(|| XPathError::internal("Failed to create decimal scale"))?;

        // Divide, round, multiply
        let scaled = d / scale;
        let rounded =
            scaled.round_dp_with_strategy(0, rust_decimal::RoundingStrategy::MidpointNearestEven);
        Ok(rounded * scale)
    } else {
        Ok(d.round_dp_with_strategy(
            precision as u32,
            rust_decimal::RoundingStrategy::MidpointNearestEven,
        ))
    }
}

/// Round half to even for BigInt with negative precision.
fn round_half_to_even_integer(i: &BigInt, precision: i32) -> BigInt {
    if precision >= 0 {
        return i.clone();
    }

    // For negative precision, round to powers of 10
    let abs_precision = (-precision) as u32;
    let scale = BigInt::from(10).pow(abs_precision);
    let half_scale = &scale / 2;

    // Compute: round(i / scale) * scale using half-to-even
    let (quotient, remainder) = (i / &scale, i % &scale);
    let abs_remainder = if remainder < BigInt::from(0) {
        -&remainder
    } else {
        remainder.clone()
    };

    let rounded = if abs_remainder < half_scale {
        quotient.clone()
    } else if abs_remainder > half_scale {
        if *i >= BigInt::from(0) {
            &quotient + 1
        } else {
            &quotient - 1
        }
    } else {
        // Exactly half - round to even
        if &quotient % 2 == BigInt::from(0) {
            quotient.clone()
        } else if *i >= BigInt::from(0) {
            &quotient + 1
        } else {
            &quotient - 1
        }
    };

    rounded * scale
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::namespace::table::NameTable;
    use crate::xpath::context::XPathContext;
    use crate::xpath::RoXmlNavigator;

    fn make_context<'a>() -> DynamicContext<'a, RoXmlNavigator<'a>> {
        let table = Box::leak(Box::new(NameTable::new()));
        let xpath_ctx = Box::leak(Box::new(XPathContext::new(table)));
        DynamicContext::new(xpath_ctx, 0)
    }

    #[test]
    fn test_abs_double() {
        let mut ctx = make_context();
        let args = vec![XPathValue::double(-3.5)];
        let result = abs(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), 3.5);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }

    #[test]
    fn test_abs_empty() {
        let mut ctx = make_context();
        let args = vec![XPathValue::Empty];
        let result = abs(&mut ctx, args).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_ceiling_double() {
        let mut ctx = make_context();
        let args = vec![XPathValue::double(3.2)];
        let result = ceiling(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), 4.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }

    #[test]
    fn test_floor_double() {
        let mut ctx = make_context();
        let args = vec![XPathValue::double(3.8)];
        let result = floor(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), 3.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }

    #[test]
    fn test_round_double() {
        let mut ctx = make_context();

        // Test 2.5 -> 3 (round half away from zero)
        let args = vec![XPathValue::double(2.5)];
        let result = round(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), 3.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }

        // Test -2.5 -> -3 (round half away from zero)
        let args = vec![XPathValue::double(-2.5)];
        let result = round(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), -3.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }

    #[test]
    fn test_round_half_to_even_double() {
        let mut ctx = make_context();

        // Test 2.5 -> 2 (half to even)
        let args = vec![XPathValue::double(2.5)];
        let result = round_half_to_even(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), 2.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }

        // Test 3.5 -> 4 (half to even)
        let args = vec![XPathValue::double(3.5)];
        let result = round_half_to_even(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    assert_eq!(v.as_double().unwrap(), 4.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }

    #[test]
    fn test_round_half_to_even_with_precision() {
        let mut ctx = make_context();

        // Test 3.567 with precision 2 -> 3.57
        let args = vec![XPathValue::double(3.567), XPathValue::integer(2)];
        let result = round_half_to_even(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    let d = v.as_double().unwrap();
                    assert!((d - 3.57).abs() < 0.001);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }

    #[test]
    fn test_round_half_to_even_negative_precision() {
        let mut ctx = make_context();

        // Test 35612 with precision -2 -> 35600
        let args = vec![XPathValue::double(35612.0), XPathValue::integer(-2)];
        let result = round_half_to_even(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(item) => {
                if let crate::xpath::iterator::XmlItem::Atomic(v) = item {
                    let d = v.as_double().unwrap();
                    assert_eq!(d, 35600.0);
                } else {
                    panic!("Expected atomic value");
                }
            }
            _ => panic!("Expected single item"),
        }
    }
}