Skip to content

Commit

Permalink
Add index and find operations for VarRange
Browse files Browse the repository at this point in the history
  • Loading branch information
Dekker1 committed Feb 15, 2024
1 parent df287e1 commit 8d70ef3
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion crates/pindakaas/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{
cmp::max,
collections::HashSet,
iter::FusedIterator,
num::NonZeroI32,
ops::{Bound, RangeBounds, RangeInclusive},
};

Expand Down Expand Up @@ -208,9 +209,34 @@ pub struct VarRange {
}

impl VarRange {
/// Create a range starting from [`start`] and ending at [`end`] (inclusive)
pub fn new(start: Var, end: Var) -> Self {
Self { start, end }
}

/// Performs the indexing operation into the variable range
pub fn index(&self, index: usize) -> Var {
if index >= self.len() {
panic!("out of bounds access");
}
if index == 0 {
self.start
} else {
let index = NonZeroI32::new(index as i32).unwrap();
self.start.checked_add(index).unwrap()
}
}

/// Find the index of a variable within the range
pub fn find(&self, var: Var) -> Option<usize> {
if !self.contains(&var) {
None
} else {
let offset = (var.0.get() - self.start.0.get()) as usize;
debug_assert!(offset <= self.len());
Some(offset)
}
}
}

impl Iterator for VarRange {
Expand All @@ -226,7 +252,7 @@ impl Iterator for VarRange {
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = max(self.end.0.get() - self.start.0.get(), 0) as usize;
let size = max(self.end.0.get() - self.start.0.get() + 1, 0) as usize;
(size, Some(size))
}
fn count(self) -> usize {
Expand Down

0 comments on commit 8d70ef3

Please sign in to comment.