Skip to content

Instantly share code, notes, and snippets.

@DutchGhost
Created June 1, 2022 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DutchGhost/87eb0095e91ad9f9acbd981619b10f57 to your computer and use it in GitHub Desktop.
Save DutchGhost/87eb0095e91ad9f9acbd981619b10f57 to your computer and use it in GitHub Desktop.
maybe this will work out one day?
#![feature(const_slice_index)]
#![feature(inline_const)]
#![feature(strict_provenance)]
#![feature(const_raw_ptr_comparison)]
#![feature(const_mut_refs)]
#![feature(const_trait_impl)]
use core::marker::PhantomData;
trait ConstIterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
fn map<F, U>(self, f: F) -> Map<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> U,
{
Map { iter: self, f: f }
}
}
trait ConstIntoIterator {
type Item;
type Iter: ConstIterator<Item = Self::Item>;
fn into_const_iter(self) -> Self::Iter;
}
impl<'a, T> const ConstIntoIterator for &'a [T] {
type Item = &'a T;
type Iter = Iter<'a, T>;
fn into_const_iter(self) -> Self::Iter {
Iter {
slice: self,
idx: 0,
}
}
}
struct Iter<'a, T> {
slice: &'a [T],
idx: usize,
}
impl<'a, T> const ConstIterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.idx < self.slice.len() {
let elem = Some(&self.slice[self.idx]);
self.idx += 1;
elem
} else {
None
}
}
}
struct Map<I, F> {
iter: I,
f: F,
}
impl<I, F, U> const ConstIterator for Map<I, F>
where
I: ~const ConstIterator,
F: ~const FnMut(I::Item) -> U,
<I as ConstIterator>::Item: Copy,
{
type Item = U;
fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
Some(v) => Some((self.f)(v)),
None => None,
}
}
}
macro_rules! const_for {
($v:ident in $e:expr => $b:block) => {
while let Some($v) = $e.next() {
$b
}
};
}
fn main() {
let mut sum = const {
let mut s = 0;
const_for!(v in [1, 2, 3, 4, 5][..].into_const_iter().map(|elem| elem * 5) => {
s += v;
});
s
};
dbg!(sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment