Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add Field::shifted_powers and some iterator niceties #1599

Merged
merged 3 commits into from
Jun 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion field/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,9 +427,13 @@ pub trait Field:
}

fn powers(&self) -> Powers<Self> {
self.shifted_powers(Self::ONE)
}

fn shifted_powers(&self, start: Self) -> Powers<Self> {
Powers {
base: *self,
current: Self::ONE,
current: start,
}
}

Expand Down Expand Up @@ -563,6 +567,7 @@ pub trait PrimeField64: PrimeField + Field64 {
}

/// An iterator over the powers of a certain base element `b`: `b^0, b^1, b^2, ...`.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[derive(Clone, Debug)]
pub struct Powers<F: Field> {
base: F,
Expand All @@ -577,6 +582,24 @@ impl<F: Field> Iterator for Powers<F> {
self.current *= self.base;
Some(result)
}

fn size_hint(&self) -> (usize, Option<usize>) {
(usize::MAX, None)
}

fn nth(&mut self, n: usize) -> Option<F> {
let result = self.current * self.base.exp_u64(n.try_into().unwrap());
self.current = result * self.base;
Some(result)
}

fn last(self) -> Option<F> {
panic!("called `Iterator::last()` on an infinite sequence")
}

fn count(self) -> usize {
panic!("called `Iterator::count()` on an infinite sequence")
}
}

impl<F: Field> Powers<F> {
Expand All @@ -592,3 +615,26 @@ impl<F: Field> Powers<F> {
}
}
}

#[cfg(test)]
mod tests {
use super::Field;
use crate::goldilocks_field::GoldilocksField;

#[test]
fn test_powers_nth() {
type F = GoldilocksField;

const N: usize = 10;
let powers_of_two: Vec<F> = F::TWO.powers().take(N).collect();

for (n, &expect) in powers_of_two.iter().enumerate() {
let mut iter = F::TWO.powers();
assert_eq!(iter.nth(n), Some(expect));

for &expect_next in &powers_of_two[n + 1..] {
assert_eq!(iter.next(), Some(expect_next));
}
}
}
}