Skip to main content

nu_protocol/value/
range.rs

1//! A Range is an iterator over integers or floats.
2
3use crate::{ShellError, Signals, Span, Value, ast::RangeInclusion};
4use core::ops::Bound;
5use serde::{Deserialize, Serialize};
6use std::{cmp::Ordering, fmt::Display, str::FromStr};
7use winnow::Parser;
8
9mod int_range {
10    use crate::{FromValue, ShellError, Signals, Span, Value, ast::RangeInclusion};
11    use serde::{Deserialize, Serialize};
12    use std::{
13        cmp::Ordering,
14        fmt::Display,
15        hash::{Hash, Hasher},
16        ops::Bound,
17    };
18
19    use super::Range;
20
21    #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
22    pub struct IntRange {
23        pub(crate) start: i64,
24        pub(crate) step: i64,
25        pub(crate) end: Bound<i64>,
26    }
27
28    impl IntRange {
29        pub fn new(
30            start: Value,
31            next: Value,
32            end: Value,
33            inclusion: RangeInclusion,
34            span: Span,
35        ) -> Result<Self, ShellError> {
36            fn to_int(value: Value) -> Result<Option<i64>, ShellError> {
37                match value {
38                    Value::Int { val, .. } => Ok(Some(val)),
39                    Value::Nothing { .. } => Ok(None),
40                    val => Err(ShellError::CantConvert {
41                        to_type: "int".into(),
42                        from_type: val.get_type().to_string(),
43                        span: val.span(),
44                        help: None,
45                    }),
46                }
47            }
48
49            let start = to_int(start)?.unwrap_or(0);
50
51            let next_span = next.span();
52            let next = to_int(next)?;
53            if next.is_some_and(|next| next == start) {
54                return Err(ShellError::CannotCreateRange { span: next_span });
55            }
56
57            let end = to_int(end)?;
58
59            let step = match (next, end) {
60                (Some(next), Some(end)) => {
61                    if (next < start) != (end < start) {
62                        None
63                    } else {
64                        next.checked_sub(start)
65                    }
66                }
67                (Some(next), None) => next.checked_sub(start),
68                (None, Some(end)) => Some(if end < start { -1 } else { 1 }),
69                (None, None) => Some(1),
70            }
71            .ok_or(ShellError::CannotCreateRange { span })?;
72
73            let end = if let Some(end) = end {
74                match inclusion {
75                    RangeInclusion::Inclusive => Bound::Included(end),
76                    RangeInclusion::RightExclusive => Bound::Excluded(end),
77                }
78            } else {
79                Bound::Unbounded
80            };
81
82            Ok(Self { start, step, end })
83        }
84
85        pub fn start(&self) -> i64 {
86            self.start
87        }
88
89        // Resolves the absolute start position given the length of the input value
90        pub fn absolute_start(&self, len: u64) -> u64 {
91            match self.start {
92                start if start < 0 => len.saturating_sub(start.unsigned_abs()),
93                start => len.min(start.unsigned_abs()),
94            }
95        }
96
97        /// Returns the distance between the start and end of the range
98        /// The result will always be 0 or positive
99        pub fn distance(&self) -> Bound<u64> {
100            match self.end {
101                Bound::Unbounded => Bound::Unbounded,
102                Bound::Included(end) | Bound::Excluded(end) if self.start > end => {
103                    Bound::Excluded(0)
104                }
105                Bound::Included(end) => Bound::Included((end - self.start) as u64),
106                Bound::Excluded(end) => Bound::Excluded((end - self.start) as u64),
107            }
108        }
109
110        pub fn end(&self) -> Bound<i64> {
111            self.end
112        }
113
114        pub fn absolute_end(&self, len: u64) -> Bound<u64> {
115            match self.end {
116                Bound::Unbounded => Bound::Unbounded,
117                Bound::Included(i) => match i {
118                    _ if len == 0 => Bound::Excluded(0),
119                    i if i < 0 => Bound::Excluded(len.saturating_sub((i + 1).unsigned_abs())),
120                    i => Bound::Included((len.saturating_sub(1)).min(i.unsigned_abs())),
121                },
122                Bound::Excluded(i) => Bound::Excluded(match i {
123                    i if i < 0 => len.saturating_sub(i.unsigned_abs()),
124                    i => len.min(i.unsigned_abs()),
125                }),
126            }
127        }
128
129        pub fn absolute_bounds(&self, len: usize) -> (usize, Bound<usize>) {
130            let start = self.absolute_start(len as u64) as usize;
131            let end = self.absolute_end(len as u64).map(|e| e as usize);
132            match end {
133                Bound::Excluded(end) | Bound::Included(end) if end < start => {
134                    (start, Bound::Excluded(start))
135                }
136                Bound::Excluded(end) => (start, Bound::Excluded(end)),
137                Bound::Included(end) => (start, Bound::Included(end)),
138                Bound::Unbounded => (start, Bound::Unbounded),
139            }
140        }
141
142        pub fn step(&self) -> i64 {
143            self.step
144        }
145
146        pub fn is_unbounded(&self) -> bool {
147            self.end == Bound::Unbounded
148        }
149
150        pub fn is_relative(&self) -> bool {
151            self.is_start_relative() || self.is_end_relative()
152        }
153
154        pub fn is_start_relative(&self) -> bool {
155            self.start < 0
156        }
157
158        pub fn is_end_relative(&self) -> bool {
159            match self.end {
160                Bound::Included(end) | Bound::Excluded(end) => end < 0,
161                _ => false,
162            }
163        }
164
165        pub fn contains(&self, value: i64) -> bool {
166            if self.step < 0 {
167                // Decreasing range
168                if value > self.start {
169                    return false;
170                }
171                match self.end {
172                    Bound::Included(end) if value < end => return false,
173                    Bound::Excluded(end) if value <= end => return false,
174                    _ => {}
175                };
176            } else {
177                // Increasing range
178                if value < self.start {
179                    return false;
180                }
181                match self.end {
182                    Bound::Included(end) if value > end => return false,
183                    Bound::Excluded(end) if value >= end => return false,
184                    _ => {}
185                };
186            }
187            (value - self.start) % self.step == 0
188        }
189
190        pub fn into_range_iter(self, signals: Signals) -> Iter {
191            Iter {
192                current: Some(self.start),
193                step: self.step,
194                end: self.end,
195                signals,
196            }
197        }
198    }
199
200    impl Ord for IntRange {
201        fn cmp(&self, other: &Self) -> Ordering {
202            // Ranges are compared roughly according to their list representation.
203            // Compare in order:
204            // - the head element (start)
205            // - the tail elements (step)
206            // - the length (end)
207            self.start
208                .cmp(&other.start)
209                .then(self.step.cmp(&other.step))
210                .then_with(|| match (self.end, other.end) {
211                    (Bound::Included(l), Bound::Included(r))
212                    | (Bound::Excluded(l), Bound::Excluded(r)) => {
213                        let ord = l.cmp(&r);
214                        if self.step < 0 { ord.reverse() } else { ord }
215                    }
216                    (Bound::Included(l), Bound::Excluded(r)) => match l.cmp(&r) {
217                        Ordering::Equal => Ordering::Greater,
218                        ord if self.step < 0 => ord.reverse(),
219                        ord => ord,
220                    },
221                    (Bound::Excluded(l), Bound::Included(r)) => match l.cmp(&r) {
222                        Ordering::Equal => Ordering::Less,
223                        ord if self.step < 0 => ord.reverse(),
224                        ord => ord,
225                    },
226                    (Bound::Included(_), Bound::Unbounded) => Ordering::Less,
227                    (Bound::Excluded(_), Bound::Unbounded) => Ordering::Less,
228                    (Bound::Unbounded, Bound::Included(_)) => Ordering::Greater,
229                    (Bound::Unbounded, Bound::Excluded(_)) => Ordering::Greater,
230                    (Bound::Unbounded, Bound::Unbounded) => Ordering::Equal,
231                })
232        }
233    }
234
235    impl PartialOrd for IntRange {
236        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
237            Some(self.cmp(other))
238        }
239    }
240
241    impl PartialEq for IntRange {
242        fn eq(&self, other: &Self) -> bool {
243            self.start == other.start && self.step == other.step && self.end == other.end
244        }
245    }
246
247    impl Eq for IntRange {}
248
249    impl Hash for IntRange {
250        fn hash<H: Hasher>(&self, state: &mut H) {
251            self.start.hash(state);
252            self.step.hash(state);
253            self.end.hash(state);
254        }
255    }
256
257    impl Display for IntRange {
258        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
259            write!(f, "{}..", self.start)?;
260            if self.step != 1 {
261                write!(f, "{}..", self.start + self.step)?;
262            }
263            match self.end {
264                Bound::Included(end) => write!(f, "{end}"),
265                Bound::Excluded(end) => write!(f, "<{end}"),
266                Bound::Unbounded => Ok(()),
267            }
268        }
269    }
270
271    impl FromValue for IntRange {
272        fn from_value(v: Value) -> Result<Self, ShellError> {
273            let span = v.span();
274            let range = Range::from_value(v)?;
275            match range {
276                Range::IntRange(v) => Ok(v),
277                Range::FloatRange(_) => Err(ShellError::TypeMismatch {
278                    err_message: "expected an int range".into(),
279                    span,
280                }),
281            }
282        }
283    }
284
285    pub struct Iter {
286        current: Option<i64>,
287        step: i64,
288        end: Bound<i64>,
289        signals: Signals,
290    }
291
292    impl Iterator for Iter {
293        type Item = i64;
294
295        fn next(&mut self) -> Option<Self::Item> {
296            if let Some(current) = self.current {
297                let not_end = match (self.step < 0, self.end) {
298                    (true, Bound::Included(end)) => current >= end,
299                    (true, Bound::Excluded(end)) => current > end,
300                    (false, Bound::Included(end)) => current <= end,
301                    (false, Bound::Excluded(end)) => current < end,
302                    (_, Bound::Unbounded) => true, // will stop once integer overflows
303                };
304
305                if not_end && !self.signals.interrupted() {
306                    self.current = current.checked_add(self.step);
307                    Some(current)
308                } else {
309                    self.current = None;
310                    None
311                }
312            } else {
313                None
314            }
315        }
316    }
317}
318
319mod float_range {
320    use crate::{IntRange, Range, ShellError, Signals, Span, Value, ast::RangeInclusion, hash_f64};
321    use nu_utils::ObviousFloat;
322    use serde::{Deserialize, Serialize};
323    use std::{
324        cmp::Ordering,
325        fmt::Display,
326        hash::{Hash, Hasher},
327        ops::Bound,
328    };
329
330    #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
331    pub struct FloatRange {
332        pub(crate) start: f64,
333        pub(crate) step: f64,
334        pub(crate) end: Bound<f64>,
335    }
336
337    impl FloatRange {
338        pub fn new(
339            start: Value,
340            next: Value,
341            end: Value,
342            inclusion: RangeInclusion,
343            span: Span,
344        ) -> Result<Self, ShellError> {
345            fn to_float(value: Value) -> Result<Option<f64>, ShellError> {
346                match value {
347                    Value::Float { val, .. } => Ok(Some(val)),
348                    Value::Int { val, .. } => Ok(Some(val as f64)),
349                    Value::Nothing { .. } => Ok(None),
350                    val => Err(ShellError::CantConvert {
351                        to_type: "float".into(),
352                        from_type: val.get_type().to_string(),
353                        span: val.span(),
354                        help: None,
355                    }),
356                }
357            }
358
359            // `start` must be finite (not NaN or infinity).
360            // `next` must be finite and not equal to `start`.
361            // `end` must not be NaN (but can be infinite).
362            //
363            // TODO: better error messages for the restrictions above
364
365            let start_span = start.span();
366            let start = to_float(start)?.unwrap_or(0.0);
367            if !start.is_finite() {
368                return Err(ShellError::CannotCreateRange { span: start_span });
369            }
370
371            let end_span = end.span();
372            let end = to_float(end)?;
373            if end.is_some_and(f64::is_nan) {
374                return Err(ShellError::CannotCreateRange { span: end_span });
375            }
376
377            let next_span = next.span();
378            let next = to_float(next)?;
379            if next.is_some_and(|next| next == start || !next.is_finite()) {
380                return Err(ShellError::CannotCreateRange { span: next_span });
381            }
382
383            let step = match (next, end) {
384                (Some(next), Some(end)) => {
385                    if (next < start) != (end < start) {
386                        return Err(ShellError::CannotCreateRange { span });
387                    }
388                    next - start
389                }
390                (Some(next), None) => next - start,
391                (None, Some(end)) => {
392                    let diff = end - start;
393                    if diff == 0.0 {
394                        return Err(ShellError::CannotCreateRange { span });
395                    }
396                    if diff.abs() < 1.0 {
397                        // For float ranges with small differences, compute a natural
398                        // step based on the order of magnitude of the difference,
399                        // so that `0.1..0.3` yields 0.1, 0.2, 0.3.
400                        let magnitude = 10.0_f64.powf(diff.abs().log10().floor());
401                        diff.signum() * magnitude
402                    } else if diff > 0.0 {
403                        1.0
404                    } else {
405                        -1.0
406                    }
407                }
408                (None, None) => 1.0,
409            };
410
411            let end = if let Some(end) = end {
412                if end.is_infinite() {
413                    Bound::Unbounded
414                } else {
415                    match inclusion {
416                        RangeInclusion::Inclusive => Bound::Included(end),
417                        RangeInclusion::RightExclusive => Bound::Excluded(end),
418                    }
419                }
420            } else {
421                Bound::Unbounded
422            };
423
424            Ok(Self { start, step, end })
425        }
426
427        pub fn start(&self) -> f64 {
428            self.start
429        }
430
431        pub fn end(&self) -> Bound<f64> {
432            self.end
433        }
434
435        pub fn step(&self) -> f64 {
436            self.step
437        }
438
439        pub fn is_unbounded(&self) -> bool {
440            self.end == Bound::Unbounded
441        }
442
443        pub fn contains(&self, value: f64) -> bool {
444            if self.step < 0.0 {
445                // Decreasing range
446                if value > self.start {
447                    return false;
448                }
449                match self.end {
450                    Bound::Included(end) if value < end => return false,
451                    Bound::Excluded(end) if value <= end => return false,
452                    _ => {}
453                };
454            } else {
455                // Increasing range
456                if value < self.start {
457                    return false;
458                }
459                match self.end {
460                    Bound::Included(end) if value > end => return false,
461                    Bound::Excluded(end) if value >= end => return false,
462                    _ => {}
463                };
464            }
465            ((value - self.start) % self.step).abs() < f64::EPSILON
466        }
467
468        pub fn into_range_iter(self, signals: Signals) -> Iter {
469            // Determine rounding factor from the step's decimal precision.
470            // Only applies when step < 1.0 (fractional steps) to clean up
471            // floating-point artifacts like 0.30000000000000004.
472            let round_factor = if self.step.abs() >= 1.0 || self.step == 0.0 {
473                0.0 // sentinel: no rounding
474            } else {
475                let precision = (-self.step.abs().log10()).max(0.0).ceil() as i32;
476                10.0_f64.powi(precision)
477            };
478            Iter {
479                start: self.start,
480                step: self.step,
481                end: self.end,
482                iter: Some(0),
483                round_factor,
484                signals,
485            }
486        }
487    }
488
489    impl Ord for FloatRange {
490        fn cmp(&self, other: &Self) -> Ordering {
491            fn float_cmp(a: f64, b: f64) -> Ordering {
492                // There is no way a `FloatRange` can have NaN values:
493                // - `FloatRange::new` ensures no values are NaN.
494                // - `From<IntRange> for FloatRange` cannot give NaNs either.
495                // - There are no other ways to create a `FloatRange`.
496                // - There is no way to modify values of a `FloatRange`.
497                a.partial_cmp(&b).expect("not NaN")
498            }
499
500            // Ranges are compared roughly according to their list representation.
501            // Compare in order:
502            // - the head element (start)
503            // - the tail elements (step)
504            // - the length (end)
505            float_cmp(self.start, other.start)
506                .then(float_cmp(self.step, other.step))
507                .then_with(|| match (self.end, other.end) {
508                    (Bound::Included(l), Bound::Included(r))
509                    | (Bound::Excluded(l), Bound::Excluded(r)) => {
510                        let ord = float_cmp(l, r);
511                        if self.step < 0.0 { ord.reverse() } else { ord }
512                    }
513                    (Bound::Included(l), Bound::Excluded(r)) => match float_cmp(l, r) {
514                        Ordering::Equal => Ordering::Greater,
515                        ord if self.step < 0.0 => ord.reverse(),
516                        ord => ord,
517                    },
518                    (Bound::Excluded(l), Bound::Included(r)) => match float_cmp(l, r) {
519                        Ordering::Equal => Ordering::Less,
520                        ord if self.step < 0.0 => ord.reverse(),
521                        ord => ord,
522                    },
523                    (Bound::Included(_), Bound::Unbounded) => Ordering::Less,
524                    (Bound::Excluded(_), Bound::Unbounded) => Ordering::Less,
525                    (Bound::Unbounded, Bound::Included(_)) => Ordering::Greater,
526                    (Bound::Unbounded, Bound::Excluded(_)) => Ordering::Greater,
527                    (Bound::Unbounded, Bound::Unbounded) => Ordering::Equal,
528                })
529        }
530    }
531
532    impl PartialOrd for FloatRange {
533        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
534            Some(self.cmp(other))
535        }
536    }
537
538    impl PartialEq for FloatRange {
539        fn eq(&self, other: &Self) -> bool {
540            self.start == other.start && self.step == other.step && self.end == other.end
541        }
542    }
543
544    impl Eq for FloatRange {}
545
546    impl Hash for FloatRange {
547        /// Consistent with [`PartialEq`], which compares the fields with `f64 ==`.
548        fn hash<H: Hasher>(&self, state: &mut H) {
549            hash_f64(self.start, state);
550            hash_f64(self.step, state);
551            std::mem::discriminant(&self.end).hash(state);
552            if let Bound::Included(v) | Bound::Excluded(v) = self.end {
553                hash_f64(v, state);
554            }
555        }
556    }
557
558    impl Display for FloatRange {
559        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
560            write!(f, "{}..", ObviousFloat(self.start))?;
561            if self.step != 1f64 {
562                write!(f, "{}..", ObviousFloat(self.start + self.step))?;
563            }
564            match self.end {
565                Bound::Included(end) => write!(f, "{}", ObviousFloat(end)),
566                Bound::Excluded(end) => write!(f, "<{}", ObviousFloat(end)),
567                Bound::Unbounded => Ok(()),
568            }
569        }
570    }
571
572    impl From<IntRange> for FloatRange {
573        fn from(range: IntRange) -> Self {
574            Self {
575                start: range.start as f64,
576                step: range.step as f64,
577                end: match range.end {
578                    Bound::Included(b) => Bound::Included(b as f64),
579                    Bound::Excluded(b) => Bound::Excluded(b as f64),
580                    Bound::Unbounded => Bound::Unbounded,
581                },
582            }
583        }
584    }
585
586    impl From<Range> for FloatRange {
587        fn from(range: Range) -> Self {
588            match range {
589                Range::IntRange(range) => range.into(),
590                Range::FloatRange(range) => range,
591            }
592        }
593    }
594
595    pub struct Iter {
596        start: f64,
597        step: f64,
598        end: Bound<f64>,
599        iter: Option<u64>,
600        round_factor: f64,
601        signals: Signals,
602    }
603
604    impl Iterator for Iter {
605        type Item = f64;
606
607        fn next(&mut self) -> Option<Self::Item> {
608            if let Some(iter) = self.iter {
609                let current = self.start + self.step * iter as f64;
610
611                // Snap only tiny floating-point drift (quotient very close to integer).
612                let quotient = current / self.step;
613                let value = if (quotient - quotient.round()).abs() < 1e-10 {
614                    quotient.round() * self.step
615                } else {
616                    current
617                };
618
619                // Round to step's decimal precision if applicable, to avoid
620                // displaying artifacts like 0.30000000000000004.
621                let value = if self.round_factor > 0.0 {
622                    (value * self.round_factor).round() / self.round_factor
623                } else {
624                    value
625                };
626
627                // Use an epsilon tolerance to handle floating-point precision
628                // issues in the end-bound comparison.
629                const EPS: f64 = f64::EPSILON * 100.0;
630                let not_end = match (self.step < 0.0, self.end) {
631                    (true, Bound::Included(end)) => value + EPS >= end,
632                    (true, Bound::Excluded(end)) => value - EPS > end,
633                    (false, Bound::Included(end)) => value <= end + EPS,
634                    (false, Bound::Excluded(end)) => value < end - EPS,
635                    (_, Bound::Unbounded) => value.is_finite(),
636                };
637
638                if not_end && !self.signals.interrupted() {
639                    self.iter = iter.checked_add(1);
640                    Some(value)
641                } else {
642                    self.iter = None;
643                    None
644                }
645            } else {
646                None
647            }
648        }
649    }
650}
651
652pub use float_range::FloatRange;
653pub use int_range::IntRange;
654
655#[derive(Debug, Clone, Copy)]
656pub enum Range {
657    IntRange(IntRange),
658    FloatRange(FloatRange),
659}
660
661impl Range {
662    pub fn new(
663        start: Value,
664        next: Value,
665        end: Value,
666        inclusion: RangeInclusion,
667        span: Span,
668    ) -> Result<Self, ShellError> {
669        // promote to float range if any Value is float
670        if matches!(start, Value::Float { .. })
671            || matches!(next, Value::Float { .. })
672            || matches!(end, Value::Float { .. })
673        {
674            FloatRange::new(start, next, end, inclusion, span).map(Self::FloatRange)
675        } else {
676            IntRange::new(start, next, end, inclusion, span).map(Self::IntRange)
677        }
678    }
679
680    pub fn new_int(
681        start: impl Into<Option<i64>>,
682        next: impl Into<Option<i64>>,
683        end: impl Into<Option<Bound<i64>>>,
684    ) -> Self {
685        let start = start.into().unwrap_or(0);
686        let end = end.into().unwrap_or(Bound::Unbounded);
687        let step = next.into().map(|next| next - start).unwrap_or(match end {
688            Bound::Unbounded => 1,
689            Bound::Included(end) | Bound::Excluded(end) if start <= end => 1,
690            _ => -1,
691        });
692        Range::IntRange(IntRange { start, step, end })
693    }
694
695    pub fn new_float(
696        start: impl Into<Option<f64>>,
697        next: impl Into<Option<f64>>,
698        end: impl Into<Option<Bound<f64>>>,
699    ) -> Self {
700        let start = start.into().unwrap_or(0.0);
701        let end = end.into().unwrap_or(Bound::Unbounded);
702        let step = next.into().map(|next| next - start).unwrap_or(match end {
703            Bound::Unbounded => 1.0,
704            Bound::Included(end) | Bound::Excluded(end) if start <= end => 1.0,
705            _ => -1.0,
706        });
707        Range::FloatRange(FloatRange { start, step, end })
708    }
709
710    pub fn contains(&self, value: &Value) -> bool {
711        match (self, value) {
712            (Self::IntRange(range), Value::Int { val, .. }) => range.contains(*val),
713            (Self::IntRange(range), Value::Float { val, .. }) => {
714                FloatRange::from(*range).contains(*val)
715            }
716            (Self::FloatRange(range), Value::Int { val, .. }) => range.contains(*val as f64),
717            (Self::FloatRange(range), Value::Float { val, .. }) => range.contains(*val),
718            _ => false,
719        }
720    }
721
722    pub fn is_bounded(&self) -> bool {
723        match self {
724            Range::IntRange(range) => range.end() != Bound::<i64>::Unbounded,
725            Range::FloatRange(range) => range.end() != Bound::<f64>::Unbounded,
726        }
727    }
728
729    pub fn into_range_iter(self, span: Span, signals: Signals) -> Iter {
730        match self {
731            Range::IntRange(range) => Iter::IntIter(range.into_range_iter(signals), span),
732            Range::FloatRange(range) => Iter::FloatIter(range.into_range_iter(signals), span),
733        }
734    }
735
736    /// Returns an estimate of the memory size used by this Range in bytes
737    pub fn memory_size(&self) -> usize {
738        std::mem::size_of::<Self>()
739    }
740}
741
742impl Ord for Range {
743    fn cmp(&self, other: &Self) -> Ordering {
744        match (self, other) {
745            (Range::IntRange(l), Range::IntRange(r)) => l.cmp(r),
746            (Range::FloatRange(l), Range::FloatRange(r)) => l.cmp(r),
747            (Range::IntRange(int), Range::FloatRange(float)) => FloatRange::from(*int).cmp(float),
748            (Range::FloatRange(float), Range::IntRange(int)) => float.cmp(&FloatRange::from(*int)),
749        }
750    }
751}
752
753impl PartialOrd for Range {
754    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
755        Some(self.cmp(other))
756    }
757}
758
759impl PartialEq for Range {
760    fn eq(&self, other: &Self) -> bool {
761        match (self, other) {
762            (Range::IntRange(l), Range::IntRange(r)) => l == r,
763            (Range::FloatRange(l), Range::FloatRange(r)) => l == r,
764            (Range::IntRange(int), Range::FloatRange(float)) => FloatRange::from(*int) == *float,
765            (Range::FloatRange(float), Range::IntRange(int)) => *float == FloatRange::from(*int),
766        }
767    }
768}
769
770impl Eq for Range {}
771
772impl Display for Range {
773    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
774        match self {
775            Range::IntRange(range) => write!(f, "{range}"),
776            Range::FloatRange(range) => write!(f, "{range}"),
777        }
778    }
779}
780
781#[derive(Debug, thiserror::Error)]
782#[error("could not parse range {attempted:?}")]
783pub struct ParseRangeError {
784    attempted: String,
785}
786
787impl FromStr for Range {
788    type Err = ParseRangeError;
789
790    fn from_str(s: &str) -> Result<Self, Self::Err> {
791        parse::range.parse(s).map_err(|_| ParseRangeError {
792            attempted: s.to_owned(),
793        })
794    }
795}
796
797impl Serialize for Range {
798    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
799    where
800        S: serde::Serializer,
801    {
802        self.to_string().serialize(serializer)
803    }
804}
805
806impl<'de> Deserialize<'de> for Range {
807    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
808    where
809        D: serde::Deserializer<'de>,
810    {
811        let s = String::deserialize(deserializer)?;
812        Range::from_str(&s).map_err(serde::de::Error::custom)
813    }
814}
815
816impl From<IntRange> for Range {
817    fn from(range: IntRange) -> Self {
818        Self::IntRange(range)
819    }
820}
821
822impl From<FloatRange> for Range {
823    fn from(range: FloatRange) -> Self {
824        Self::FloatRange(range)
825    }
826}
827
828pub enum Iter {
829    IntIter(int_range::Iter, Span),
830    FloatIter(float_range::Iter, Span),
831}
832
833impl Iterator for Iter {
834    type Item = Value;
835
836    fn next(&mut self) -> Option<Self::Item> {
837        match self {
838            Iter::IntIter(iter, span) => iter.next().map(|val| Value::int(val, *span)),
839            Iter::FloatIter(iter, span) => iter.next().map(|val| Value::float(val, *span)),
840        }
841    }
842}
843
844mod parse {
845    use super::*;
846    use winnow::{
847        Result,
848        ascii::*,
849        combinator::*,
850        error::{StrContext, StrContextValue},
851    };
852
853    #[derive(Copy, Clone)]
854    enum Number {
855        Int(i64),
856        Float(f64),
857    }
858
859    // only simple numbers for now
860    fn number(input: &mut &str) -> Result<Number> {
861        fn float(input: &mut &str) -> Result<f64> {
862            (opt("-"), digit0, ".", digit1)
863                .take()
864                .parse_to()
865                .parse_next(input)
866        }
867
868        alt((float.map(Number::Float), dec_int.map(Number::Int))).parse_next(input)
869    }
870
871    struct Components {
872        start: Option<Number>,
873        step: Option<Number>,
874        end: Option<Number>,
875        exclusive: bool,
876    }
877
878    fn components(input: &mut &str) -> Result<Components> {
879        let start = opt(number).parse_next(input)?;
880        "..".parse_next(input)?;
881        if opt("<").parse_next(input)?.is_some() {
882            let end = opt(number).parse_next(input)?;
883            eof.parse_next(input)?;
884            return Ok(Components {
885                start,
886                step: None,
887                end,
888                exclusive: true,
889            });
890        }
891
892        if opt(eof).parse_next(input)?.is_some() {
893            return Ok(Components {
894                start,
895                step: None,
896                end: None,
897                exclusive: false,
898            });
899        }
900
901        let step_or_end = number.parse_next(input)?;
902        if opt(eof).parse_next(input)?.is_some() {
903            return Ok(Components {
904                start,
905                step: None,
906                end: step_or_end.into(),
907                exclusive: false,
908            });
909        }
910
911        "..".parse_next(input)?;
912        if opt("<").parse_next(input)?.is_some() {
913            let end = opt(number).parse_next(input)?;
914            eof.parse_next(input)?;
915            return Ok(Components {
916                start,
917                step: step_or_end.into(),
918                end,
919                exclusive: true,
920            });
921        }
922
923        let end = opt(number).parse_next(input)?;
924        eof.parse_next(input)?;
925        Ok(Components {
926            start,
927            step: step_or_end.into(),
928            end,
929            exclusive: false,
930        })
931    }
932
933    pub fn range(input: &mut &str) -> Result<Range> {
934        let components = components.parse_next(input)?;
935        if components.start.is_none() && components.end.is_none() {
936            fail.context(StrContext::Expected(StrContextValue::Description(
937                "needs bound either at start or end",
938            )))
939            .parse_next(input)?;
940        }
941
942        let use_float = matches!(components.start, Some(Number::Float(_)))
943            || matches!(components.step, Some(Number::Float(_)))
944            || matches!(components.end, Some(Number::Float(_)));
945
946        let span = Span::unknown();
947        let value = |number| match number {
948            Some(Number::Float(i)) => Value::float(i, span),
949            Some(Number::Int(i)) => Value::int(i, span),
950            None => Value::nothing(span),
951        };
952
953        let start = value(components.start);
954        let step = value(components.step);
955        let end = value(components.end);
956        let inclusion = if components.exclusive {
957            RangeInclusion::RightExclusive
958        } else {
959            RangeInclusion::Inclusive
960        };
961
962        if use_float {
963            match FloatRange::new(start, step, end, inclusion, span) {
964                Ok(i) => Ok(Range::FloatRange(i)),
965                Err(_) => fail
966                    .context(StrContext::Expected(StrContextValue::Description(
967                        "valid range",
968                    )))
969                    .parse_next(input),
970            }
971        } else {
972            match IntRange::new(start, step, end, inclusion, span) {
973                Ok(i) => Ok(Range::IntRange(i)),
974                Err(_) => fail
975                    .context(StrContext::Expected(StrContextValue::Description(
976                        "valid range",
977                    )))
978                    .parse_next(input),
979            }
980        }
981    }
982}
983
984#[cfg(test)]
985mod tests {
986    use super::*;
987    use crate::Signals;
988
989    fn collect_float_range(start: f64, step: f64, end: f64, inclusive: bool) -> Vec<f64> {
990        let end = if inclusive {
991            Bound::Included(end)
992        } else {
993            Bound::Excluded(end)
994        };
995        let range = FloatRange { start, step, end };
996        range
997            .into_range_iter(Signals::empty())
998            .collect::<Vec<f64>>()
999    }
1000
1001    #[test]
1002    fn float_range_small_step_inclusive() {
1003        let result = collect_float_range(0.1, 0.1, 0.3, true);
1004        assert_eq!(result.len(), 3);
1005        assert!((result[0] - 0.1).abs() < 1e-15);
1006        assert!((result[1] - 0.2).abs() < 1e-15);
1007        assert!((result[2] - 0.3).abs() < 1e-15);
1008    }
1009
1010    #[test]
1011    fn float_range_tiny_step_inclusive() {
1012        let result = collect_float_range(0.001, 0.001, 0.005, true);
1013        assert_eq!(result.len(), 5);
1014        assert!((result[0] - 0.001).abs() < 1e-15);
1015        assert!((result[1] - 0.002).abs() < 1e-15);
1016        assert!((result[2] - 0.003).abs() < 1e-15);
1017        assert!((result[3] - 0.004).abs() < 1e-15);
1018        assert!((result[4] - 0.005).abs() < 1e-15);
1019    }
1020
1021    #[test]
1022    fn float_range_integer_step_noninteger_start() {
1023        let result = collect_float_range(1.8, 1.0, 3.8, true);
1024        assert_eq!(result.len(), 3);
1025        assert!((result[0] - 1.8).abs() < 1e-15);
1026        assert!((result[1] - 2.8).abs() < 1e-15);
1027        assert!((result[2] - 3.8).abs() < 1e-15);
1028    }
1029
1030    #[test]
1031    fn float_range_decreasing() {
1032        let result = collect_float_range(0.3, -0.1, 0.1, true);
1033        assert_eq!(result.len(), 3);
1034        assert!((result[0] - 0.3).abs() < 1e-15);
1035        assert!((result[1] - 0.2).abs() < 1e-15);
1036        assert!((result[2] - 0.1).abs() < 1e-15);
1037    }
1038
1039    #[test]
1040    fn float_range_explicit_step_clean_values() {
1041        let result = collect_float_range(0.1, 0.2, 0.3, false);
1042        assert_eq!(result.len(), 1);
1043        assert!((result[0] - 0.1).abs() < 1e-15);
1044    }
1045
1046    #[test]
1047    fn float_range_rounds_last_value() {
1048        // 0.1 + 0.1*2 = 0.30000000000000004 without rounding;
1049        // verify rounding produces exactly 0.3
1050        let result = collect_float_range(0.1, 0.1, 0.3, true);
1051        assert_eq!(result[2], 0.3);
1052    }
1053
1054    #[test]
1055    fn float_range_clean_serialization() {
1056        // Verify all values in a small-step range are clean (no floating-point artifacts)
1057        let result = collect_float_range(0.0, 0.1, 0.5, true);
1058        assert_eq!(result.len(), 6);
1059        for (i, &val) in result.iter().enumerate() {
1060            let expected = i as f64 * 0.1;
1061            assert!(
1062                (val - expected).abs() < 1e-15,
1063                "at index {i}: expected {expected}, got {val}"
1064            );
1065        }
1066    }
1067}