Skip to main content

lox_core/
utils.rs

1// SPDX-FileCopyrightText: 2025 Helge Eichhorn <git@helgeeichhorn.de>
2//
3// SPDX-License-Identifier: MPL-2.0
4
5//! General-purpose utilities.
6
7/// An iterator that yields `n` evenly spaced values from `start` to `end` (inclusive).
8pub struct Linspace {
9    start: f64,
10    end: f64,
11    n: usize,
12    current: usize,
13}
14
15impl Linspace {
16    /// Creates a new `Linspace` iterator with `n` points from `start` to `end`.
17    pub fn new(start: f64, end: f64, n: usize) -> Self {
18        Self {
19            start,
20            end,
21            n,
22            current: 0,
23        }
24    }
25}
26
27impl Iterator for Linspace {
28    type Item = f64;
29
30    fn next(&mut self) -> Option<Self::Item> {
31        if self.current >= self.n {
32            return None;
33        }
34
35        let value = if self.n == 1 {
36            self.start
37        } else {
38            let t = self.current as f64 / (self.n - 1) as f64;
39            self.start + t * (self.end - self.start)
40        };
41
42        self.current += 1;
43        Some(value)
44    }
45
46    fn size_hint(&self) -> (usize, Option<usize>) {
47        let remaining = self.n - self.current;
48        (remaining, Some(remaining))
49    }
50}
51
52impl ExactSizeIterator for Linspace {}