konst/iter.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
//! Const equivalent of iterators with a specific `next` function signature.
//!
//! The docs for [`IntoIterKind`] has more information on
//! const equivalents of IntoIterator and Iterator.
//!
#[cfg(any(not(doctest), feature = "rust_1_56"))]
pub mod iterator_dsl;
/// Iterates over all elements of an [iterator](crate::iter#iterator),
/// const equivalent of [`Iterator::for_each`]
///
/// # Iterator methods
///
/// This macro supports emulating iterator methods by expanding to equivalent code.
///
/// The supported iterator methods are documented in the [`iterator_dsl`] module,
/// because they are also supported by other `konst::iter` macros.
///
/// # Examples
///
/// ### Custom iterator
///
/// ```rust
/// use konst::iter::{IntoIterKind, IsIteratorKind};
///
/// struct Upto10(u8);
///
/// impl IntoIterKind for Upto10 { type Kind = IsIteratorKind; }
///
/// impl Upto10 {
/// const fn next(mut self) -> Option<(u8, Self)> {
/// if self.0 < 10 {
/// let ret = self.0;
/// self.0 += 1;
/// Some((ret, self))
/// } else {
/// None
/// }
/// }
/// }
///
/// const N: u32 = {
/// let mut n = 0u32;
/// konst::iter::for_each!{elem in Upto10(7) =>
/// n = n * 10 + elem as u32;
/// }
/// n
/// };
///
/// assert_eq!(N, 789);
///
/// ```
///
/// ### Summing pairs
///
/// This example requires the `"rust_1_51"` feature, because it uses const generics.
///
#[cfg_attr(feature = "rust_1_51", doc = "```rust")]
#[cfg_attr(not(feature = "rust_1_51"), doc = "```ignore")]
/// use konst::iter::for_each;
///
/// const fn add_pairs<const N: usize>(l: [u32; N], r: [u32; N]) -> [u32; N] {
/// let mut out = [0u32; N];
///
/// for_each!{(i, val) in &l,zip(&r),map(|(l, r)| *l + *r),enumerate() =>
/// out[i] = val;
/// }
///
/// out
/// }
///
/// assert_eq!(add_pairs([], []), []);
/// assert_eq!(add_pairs([3], [5]), [8]);
/// assert_eq!(add_pairs([3, 5], [8, 13]), [11, 18]);
///
/// ```
///
/// [`iterator_dsl`]: crate::iter::iterator_dsl
pub use konst_macro_rules::for_each;
/// Wrapper for `IntoIterKind` implementors,
/// that defines different methods depending on the
/// value of `<T as IntoIterKind>::Kind`.
#[doc(inline)]
pub use konst_macro_rules::into_iter::IntoIterWrapper;
/// Marker type for proving that `T: IntoIterKind<Kind = K>`
#[doc(inline)]
pub use konst_macro_rules::into_iter::IsIntoIterKind;
/// Macro for converting [`IntoIterKind`] implementors into const iterators.
///
#[doc(inline)]
pub use konst_macro_rules::into_iter_macro as into_iter;
/// Const analog of the [`IntoIterator`] trait.
///
/// # Implementor
///
/// Implementors are expected to be:
///
/// - [Types that have an associated iterator](#isnoniteratorkind),
/// that have [`IsNonIteratorKind`](crate::iter::IsNonIteratorKind)
/// as the [`IntoIterKind::Kind`] associated type.
///
/// - [Iterators themselves](#isiteratorkind),
/// that have [`IsIteratorKind`](crate::iter::IsIteratorKind)
/// as the [`IntoIterKind::Kind`] associated type.
///
/// - Standard library types, of the [`IsStdKind`] kind
///
/// ### `IsNonIteratorKind`
///
/// These types are expected to define this inherent method for converting to
/// a const iterator:
///
/// ```rust
/// # struct II;
/// # struct SomeIterator;
/// # impl II {
/// const fn const_into_iter(self) -> SomeIterator {
/// # loop{}
/// # }
/// # }
/// ```
///
/// [full example below](#non-iter-example)
///
/// ### `IsIteratorKind`
///
/// These types are expected to have this inherent method:
///
/// ```rust
/// # struct SomeIterator;
/// # type Item = u8;
/// # impl SomeIterator {
/// // Equivalent to `Iterator::next`
/// const fn next(self) -> Option<(Item, Self)> {
/// # loop{}
/// # }
/// # }
/// ```
/// Where `Item` can be any type.
///
/// These are other methods that you can optionaly define,
/// which most iterators from the `konst` crate define:
/// ```rust
/// # struct SomeIterator;
/// # struct SomeIteratorRev;
/// # type Item = u8;
/// # impl SomeIterator {
/// // equivalent to `DoubleEndedÃŒterator::mext_back`
/// const fn next_back(self) -> Option<(Item, Self)> {
/// # loop{}
/// // ... some code...
/// }
///
/// // Reverses the itereator, equivalent to `Iterator::rev`
/// const fn rev(self) -> SomeIteratorRev {
/// # loop{}
/// // ... some code...
/// }
///
/// // Clones the iterator, equivalent to `Clone::clone`
/// const fn copy(&self) -> Self {
/// # loop{}
/// // ... some code...
/// }
/// # }
/// ```
/// Where `SomeIteratorRev` should be a `IntoIterKind<Kind = IsIteratorKind>`
/// which has the same inherent methods for iteration.
///
/// [full example below](#iter-example)
///
/// # Examples
///
/// <span id = "non-iter-example"></span>
/// ### Implementing for a non-iterator
///
/// ```rust
/// use konst::{iter, slice};
///
/// struct GetSlice<'a, T>{
/// slice: &'a [T],
/// up_to: usize,
/// }
///
/// impl<T> iter::IntoIterKind for GetSlice<'_, T> {
/// type Kind = iter::IsNonIteratorKind;
/// }
///
/// impl<'a, T> GetSlice<'a, T> {
/// const fn const_into_iter(self) -> konst::slice::Iter<'a, T> {
/// slice::iter(slice::slice_up_to(self.slice, self.up_to))
/// }
/// }
///
/// const fn sum_powers(up_to: usize) -> u64 {
/// let gs = GetSlice{slice: &[1, 2, 4, 8, 16, 32, 64, 128], up_to};
///
/// iter::eval!(gs,fold(0, |l, &r| l + r))
/// }
///
/// assert_eq!(sum_powers(0), 0);
/// assert_eq!(sum_powers(1), 1);
/// assert_eq!(sum_powers(2), 3);
/// assert_eq!(sum_powers(3), 7);
/// assert_eq!(sum_powers(4), 15);
/// assert_eq!(sum_powers(5), 31);
///
/// ```
///
/// <span id = "iter-example"></span>
/// ### Implementing for an iterator
///
/// This example requires Rust 1.47.0 (because of `u8::checked_sub`)
///
#[cfg_attr(feature = "rust_1_51", doc = "```rust")]
#[cfg_attr(not(feature = "rust_1_51"), doc = "```ignore")]
/// use konst::iter::{self, IntoIterKind};
///
/// struct Countdown(u8);
///
/// impl IntoIterKind for Countdown { type Kind = iter::IsIteratorKind; }
///
/// impl Countdown {
/// const fn next(mut self) -> Option<(u8, Self)> {
/// konst::option::map!(self.0.checked_sub(1), |ret| {
/// self.0 = ret;
/// (ret, self)
/// })
/// }
/// }
///
/// const fn sum(initial: u8) -> u16 {
/// iter::eval!(Countdown(initial),fold(0u16, |accum, elem| accum + elem as u16))
/// }
///
/// assert_eq!(sum(0), 0);
/// assert_eq!(sum(1), 0);
/// assert_eq!(sum(2), 1);
/// assert_eq!(sum(3), 3);
/// assert_eq!(sum(4), 6);
/// assert_eq!(sum(5), 10);
///
/// ```
///
/// ### Implementing for a double-ended iterator
///
/// ```rust
/// use konst::iter;
///
/// assert_eq!(HOURS, [1, 2, 3, 4, 5, 6, 12, 11, 10, 9, 8, 7]);
///
/// const HOURS: [u8; 12] = {
/// let mut arr = [0; 12];
/// let hours = Hours::new();
///
/// iter::for_each!{(i, hour) in 0..6,zip(hours.copy()) =>
/// arr[i] = hour;
/// }
/// iter::for_each!{(i, hour) in 6..12,zip(hours.rev()) =>
/// arr[i] = hour;
/// }
///
/// arr
/// };
///
///
/// struct Hours{
/// start: u8,
/// end: u8,
/// }
///
/// impl iter::IntoIterKind for Hours {
/// type Kind = iter::IsIteratorKind;
/// }
///
/// impl Hours {
/// const fn new() -> Self {
/// Self {start: 1, end: 13}
/// }
///
/// const fn next(mut self) -> Option<(u8, Self)> {
/// if self.start == self.end {
/// None
/// } else {
/// let ret = self.start;
/// self.start += 1;
/// Some((ret, self))
/// }
/// }
///
/// const fn next_back(mut self) -> Option<(u8, Self)> {
/// if self.start == self.end {
/// None
/// } else {
/// self.end -= 1;
/// Some((self.end, self))
/// }
/// }
///
/// const fn rev(self) -> HoursRev {
/// HoursRev(self)
/// }
///
/// /// Since `Clone::clone` isn't const callable on stable,
/// /// clonable iterators must define an inherent method to be cloned
/// const fn copy(&self) -> Self {
/// let Self{start, end} = *self;
/// Self{start, end}
/// }
/// }
///
/// struct HoursRev(Hours);
///
/// impl iter::IntoIterKind for HoursRev {
/// type Kind = iter::IsIteratorKind;
/// }
///
/// impl HoursRev {
/// const fn next(self) -> Option<(u8, Self)> {
/// konst::option::map!(self.0.next_back(), |(a, h)| (a, HoursRev(h)))
/// }
///
/// const fn next_back(self) -> Option<(u8, Self)> {
/// konst::option::map!(self.0.next(), |(a, h)| (a, HoursRev(h)))
/// }
///
/// const fn rev(self) -> Hours {
/// self.0
/// }
///
/// const fn copy(&self) -> Self {
/// Self(self.0.copy())
/// }
/// }
///
///
/// ```
///
#[doc(inline)]
pub use konst_macro_rules::into_iter::IntoIterKind;
/// For marking some type as being from std
/// in its [`IntoIterKind::Kind`] associated type.
#[doc(inline)]
pub use konst_macro_rules::into_iter::IsStdKind;
/// For marking some type as being convertible to an iterator
/// in its [`IntoIterKind::Kind`] associated type.
#[doc(inline)]
pub use konst_macro_rules::into_iter::IsNonIteratorKind;
/// For marking some type as being an iterator
/// in its [`IntoIterKind::Kind`] associated type.
#[doc(inline)]
pub use konst_macro_rules::into_iter::IsIteratorKind;
include! {"./iter/collect_const.rs"}
include! {"./iter/iter_eval.rs"}