-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chunks_exact variant with const generic argument #60735
Comments
This also applies to the |
We should actually be able to implement this and test it out unstably now. |
Im willing to give this a shot in the weekend and next week! |
@rustbot assign @DutchGhost |
So, a simple PoC fails to compile horribly Backtrace
|
Notice that a freestanding function does work: #![feature(const_generics)]
fn const_chunks_exact<T, const N: usize>(slice: &[T]) -> ConstChunksExact<'_, T, { N }> {
assert!(N != 0);
let rem = slice.len() % N;
let len = slice.len() - rem;
let (fst, snd) = slice.split_at(len);
ConstChunksExact::<T, { N }> { v: fst, rem: snd }
}
struct ConstChunksExact<'a, T: 'a, const N: usize> {
v: &'a [T],
rem: &'a [T],
}
impl<'a, T: 'a, const N: usize> Iterator for ConstChunksExact<'a, T, { N }> {
type Item = &'a [T; N];
fn next(&mut self) -> Option<Self::Item> {
if self.v.len() < N {
None
} else {
let (fst, snd) = self.v.split_at(N);
self.v = snd;
let ptr = fst.as_ptr() as *const [T; N];
// SAFETY: ok because we just checked that the length fits
unsafe { Some(&*ptr) }
}
}
}
fn main() {
let mut slice = const_chunks_exact::<_, 3>(&[1, 2, 3, 4, 5, 6i32]);
for [a, b, c] in slice {
dbg!(a, b, c);
}
} |
Keep going on, those bugs/limitations are worth fixing anyway :) |
to_array() could be a new function related to take(), it collects the first N items of an iterator into an array of length given as const generic argument (it panics if the iterator isn't long enough). Usable like this (using iterate() from itertools):
|
EDIT: This is already PR'd: #69985 |
We need a good built-in static_assert that works with constant generics too :) |
In the stdlib I'd like an iterator like chunks_exact that yields fixed-sized arrays, using a const usize argument (mostly useful for short arrays).
Those arrays could allow better optimizations and also better pattern matching.
This issue has been assigned to @DutchGhost via this comment.
The text was updated successfully, but these errors were encountered: