pax_global_header00006660000000000000000000000064146361123560014521gustar00rootroot0000000000000052 comment=d664bbf2cdbe3436d10b42d088a78b6fcd3bf6fe iter_fixed-0.4.0/000077500000000000000000000000001463611235600136445ustar00rootroot00000000000000iter_fixed-0.4.0/.github/000077500000000000000000000000001463611235600152045ustar00rootroot00000000000000iter_fixed-0.4.0/.github/workflows/000077500000000000000000000000001463611235600172415ustar00rootroot00000000000000iter_fixed-0.4.0/.github/workflows/miri.yml000066400000000000000000000006101463611235600207210ustar00rootroot00000000000000on: [push, pull_request] name: Miri jobs: test: name: Test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true components: miri - uses: actions-rs/cargo@v1 with: command: miri args: test iter_fixed-0.4.0/.github/workflows/nightly.yml000066400000000000000000000026051463611235600214450ustar00rootroot00000000000000on: [push, pull_request] name: Nightly jobs: check: name: Check runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true - uses: actions-rs/cargo@v1 with: command: check test: name: Test Suite runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true - uses: actions-rs/cargo@v1 with: command: test fmt: name: Rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true - run: rustup component add rustfmt - uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true - run: rustup component add clippy - uses: actions-rs/cargo@v1 with: command: clippy args: -- -D warnings iter_fixed-0.4.0/.github/workflows/stable.yml000066400000000000000000000022651463611235600212430ustar00rootroot00000000000000on: [push, pull_request] name: Stable jobs: check: name: Check runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: actions-rs/cargo@v1 with: command: check args: --no-default-features readme: name: Readme runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - name: Install cargo-readme run: cargo install cargo-readme - name: Generate Readme for comparison run: cargo readme > README_.md - name: Check if readme is up to date run: diff README.md README_.md test: name: Test Suite runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: actions-rs/cargo@v1 with: command: test args: --no-default-featuresiter_fixed-0.4.0/.gitignore000066400000000000000000000000231463611235600156270ustar00rootroot00000000000000/target Cargo.lock iter_fixed-0.4.0/Cargo.toml000066400000000000000000000010501463611235600155700ustar00rootroot00000000000000[package] name = "iter_fixed" version = "0.4.0" authors = ["Albin Hedman "] edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/usbalbin/iter_fixed/" description = "Iterator of fixed length" keywords = ["iterator", "array", "data-structure", "zip"] categories = ["rust-patterns", "no-std"] [badges] maintenance = { status = "experimental" } # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] default = [] nightly_features = [] [dependencies] iter_fixed-0.4.0/LICENSE-APACHE000066400000000000000000000261351463611235600155770ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. iter_fixed-0.4.0/LICENSE-MIT000066400000000000000000000020551463611235600153020ustar00rootroot00000000000000MIT License Copyright (c) 2021 Albin Hedman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. iter_fixed-0.4.0/README.md000066400000000000000000000052221463611235600151240ustar00rootroot00000000000000![Maintenance](https://img.shields.io/badge/maintenance-experimental-blue.svg) [![crates.io](https://img.shields.io/crates/v/iter_fixed.svg)](https://crates.io/crates/iter_fixed) [![docs.rs](https://docs.rs/iter_fixed/badge.svg)](https://docs.rs/iter_fixed/) [![dependency status](https://deps.rs/crate/iter_fixed/0.3.0/status.svg)](https://deps.rs/crate/iter_fixed/0.3.0) ![Stable](https://github.com/usbalbin/iter_fixed/actions/workflows/stable.yml/badge.svg) ![Nightly](https://github.com/usbalbin/iter_fixed/actions/workflows/nightly.yml/badge.svg) ![Miri](https://github.com/usbalbin/iter_fixed/actions/workflows/miri.yml/badge.svg) # iter_fixed Provides a type and traits for turning collections of fixed size, like arrays, into [`IteratorFixed`] which can be used a bit like an ordinary [`Iterator`] but with a compile time guaranteed length. This enables us to turn them back into collections of fixed size without having to perform unnecessary checks during run time. [`IteratorFixed`] provides on stable methods like `map`, `inspect`, `enumerate`, `zip`, `rev`, `copied`, `cloned`, with nightly `skip`, `step_by`, `chain`, `take`, `flatten`. However it does not and will never be able to support methods like `filter` or `take_while` which will affect the length during runtime. ## ⚠️ Experimental *This code is currently very experimental, type names, function names, trait bounds etc. are all very much subject to change.* ## Origin *This project is inspired by @leonardo-m 's idea * ## Examples: ```rust // simply reverse an Array let rev_array: [_; 4] = [1, 3, 2, 7] .into_iter_fixed() .rev() .collect(); assert_eq!(rev_array, [7, 2, 3, 1]); // .. and compute sum with values of a second array multiplied by 10 let sum_array: [_; 4] = rev_array .into_iter_fixed() .zip([4,1,3,7]) .map(|(a, b)| a + (b * 10)) .collect(); assert_eq!(sum_array, [47, 12, 33, 71]); ``` You can also take a look at examples : [`matrix.rs`] and [`vector.rs`] [`matrix.rs`]: source/examples/matrix.rs [`vector.rs`]: source/examples/vector.rs Current version: 0.4.0 ## no_std This crate should work without the full standard library Some additional info here # License : MIT OR Apache-2.0 `iter_fixed` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE, and LICENSE-MIT for details. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in iter_fixed by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. iter_fixed-0.4.0/README.tpl000066400000000000000000000022001463611235600153140ustar00rootroot00000000000000{{badges}} [![crates.io](https://img.shields.io/crates/v/iter_fixed.svg)](https://crates.io/crates/iter_fixed) [![docs.rs](https://docs.rs/iter_fixed/badge.svg)](https://docs.rs/iter_fixed/) [![dependency status](https://deps.rs/crate/iter_fixed/0.3.0/status.svg)](https://deps.rs/crate/iter_fixed/0.3.0) ![Stable](https://github.com/usbalbin/iter_fixed/actions/workflows/stable.yml/badge.svg) ![Nightly](https://github.com/usbalbin/iter_fixed/actions/workflows/nightly.yml/badge.svg) ![Miri](https://github.com/usbalbin/iter_fixed/actions/workflows/miri.yml/badge.svg) # {{crate}} {{readme}} Current version: {{version}} ## no_std This crate should work without the full standard library Some additional info here # License : {{license}} `iter_fixed` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE, and LICENSE-MIT for details. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in iter_fixed by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. iter_fixed-0.4.0/examples/000077500000000000000000000000001463611235600154625ustar00rootroot00000000000000iter_fixed-0.4.0/examples/matrix.rs000066400000000000000000000012361463611235600173360ustar00rootroot00000000000000extern crate iter_fixed; use iter_fixed::IntoIteratorFixed; #[derive(Clone, Copy)] struct Matrix { rows: [[T; K]; R], } impl Matrix { fn get_col(&self, col_id: usize) -> [&T; R] { (&self.rows) .into_iter_fixed() .map(|row| &row[col_id]) .collect() } fn get_row(&self, row_id: usize) -> [&T; K] { (&self.rows[row_id]).into_iter_fixed().collect() } } fn main() { let m = Matrix { rows: [[1, 2, 3], [4, 5, 6]], }; assert_eq!(m.get_row(0), [&1, &2, &3]); assert_eq!(m.get_col(0), [&1, &4]); } iter_fixed-0.4.0/examples/vector.rs000066400000000000000000000022431463611235600173330ustar00rootroot00000000000000extern crate iter_fixed; use iter_fixed::IntoIteratorFixed; use std::ops::{Add, Mul}; #[derive(Clone, Copy)] struct Vector { elements: [T; N], } impl Vector where T: Mul + std::iter::Sum, { fn new(elements: [T; N]) -> Self { Vector { elements } } } impl Vector where T: Mul + std::iter::Sum + Clone, { fn length2(self) -> T { self.elements .into_iter_fixed() .into_iter() .map(|x| x.clone() * x) .sum() } } impl Add> for Vector where A: Add, { type Output = Vector<>::Output, N>; fn add(self, other: Vector) -> Self::Output { Vector { elements: self .elements .into_iter_fixed() .zip(other.elements) .map(|(a, b)| a + b) .collect(), } } } fn main() { let a = Vector::new([1, 2, 3]); let b = Vector::new([1, 1, 1]); assert_eq!((a + b).elements, [2, 3, 4]); assert_eq!(b.length2(), 3); } iter_fixed-0.4.0/src/000077500000000000000000000000001463611235600144335ustar00rootroot00000000000000iter_fixed-0.4.0/src/from.rs000066400000000000000000000044461463611235600157540ustar00rootroot00000000000000use crate::IteratorFixed; /// Conversion from an [`IteratorFixed`]. /// /// By implementing `FromIteratorFixed` for a type, you define how it will be /// created from an iterator of fixed size. /// /// [`FromIteratorFixed::from_iter_fixed()`] is rarely called explicitly, and is instead /// used through [`IteratorFixed::collect()`] method. See [`IteratorFixed::collect()`]'s /// documentation for more examples. /// /// See also: [`crate::IntoIteratorFixed`]. pub trait FromIteratorFixed { /// Creates a value from a fixed size iterator. /// /// Basic usage: /// ``` /// use iter_fixed::{IntoIteratorFixed, FromIteratorFixed}; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a = <[i32; 3]>::from_iter_fixed(two_four_six); /// assert_eq!(a, [2, 4, 6]); /// ``` /// /// Using `IteratorFixed::collect()` to implicitly use `FromIteratorFixed`: /// ``` /// use iter_fixed::IntoIteratorFixed; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a: [i32; 3] = two_four_six.collect(); /// assert_eq!(a, [2, 4, 6]); /// ``` fn from_iter_fixed>(iter_fixed: IteratorFixed) -> Self; } impl FromIteratorFixed for [T; N] { /// Creates an array from a fixed size iterator. /// /// Basic usage: /// ``` /// use iter_fixed::{IntoIteratorFixed, FromIteratorFixed}; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a = <[i32; 3]>::from_iter_fixed(two_four_six); /// assert_eq!(a, [2, 4, 6]); /// ``` /// /// Using `IteratorFixed::collect()` to implicitly use `FromIteratorFixed`: /// ``` /// use iter_fixed::IntoIteratorFixed; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a: [i32; 3] = two_four_six.collect(); /// assert_eq!(a, [2, 4, 6]); /// ``` #[inline] fn from_iter_fixed>(iter_fixed: IteratorFixed) -> Self { let IteratorFixed { inner: mut it } = iter_fixed; // We know that it will yield N elements due to it originating from an IteratorFixed // of size N [(); N].map(|()| it.next().unwrap()) } } iter_fixed-0.4.0/src/helpers.rs000066400000000000000000000006511463611235600164450ustar00rootroot00000000000000#[cfg(feature = "nightly_features")] pub const fn min(a: usize, b: usize) -> usize { if a < b { a } else { b } } #[cfg(feature = "nightly_features")] pub const fn sub_or_zero(a: usize, b: usize) -> usize { if a > b { a - b } else { 0 } } #[cfg(feature = "nightly_features")] pub const fn ceiling_div(x: usize, d: usize) -> usize { x / d + (x % d != 0) as usize } iter_fixed-0.4.0/src/into.rs000066400000000000000000000116441463611235600157600ustar00rootroot00000000000000use crate::IteratorFixed; use core::{array, iter, slice}; /// Conversion into an [`IteratorFixed`]. /// /// By implementing `IntoIteratorFixed` for a type, you define how it will be /// converted to an iterator of fixed size. /// /// See also: [`crate::FromIteratorFixed`]. /// /// # Safety /// Implementer has to guarantee that the inner iterator will always yield exactly N elements pub unsafe trait IntoIteratorFixed { /// The type of the elements being iterated over. type Item; /// What will be the underlaying iterator for the [`IteratorFixed`] that we are turning this into? type IntoIter: Iterator; /// Creates a fixed size iterator from a value. /// /// Basic usage: /// ``` /// use iter_fixed::IntoIteratorFixed; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a: [i32; 3] = two_four_six.collect(); /// assert_eq!(a, [2, 4, 6]); /// ``` fn into_iter_fixed(self) -> IteratorFixed; } // IteratorFixed implements IntoIteratorFixed unsafe impl IntoIteratorFixed for IteratorFixed where Self: IntoIterator, { type Item = I::Item; type IntoIter = I; /// `IteratorFixed` implements `IntoIteratorFixed` as a no op. This allows passing an /// `IteratorFixed` where an `IntoIteratorFixed` was expected /// /// Basic usage with zip which expects an `IntoIteratorFixed` as its argument: /// ``` /// use iter_fixed::IntoIteratorFixed; /// let one_one = [1, 1].into_iter_fixed(); /// let zipped: [_; 2] = [1, 2].into_iter_fixed().zip(one_one).collect(); /// /// assert_eq!(zipped, [(1, 1), (2, 1)]); /// ``` #[inline] fn into_iter_fixed(self) -> IteratorFixed { self } } unsafe impl IntoIteratorFixed for [T; N] { type Item = T; type IntoIter = array::IntoIter; /// Creates a fixed size iterator from an array. /// /// Basic usage: /// ``` /// use iter_fixed::IntoIteratorFixed; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a: [i32; 3] = two_four_six.collect(); /// assert_eq!(a, [2, 4, 6]); /// ``` #[inline] fn into_iter_fixed(self) -> IteratorFixed, N> { // Safety: array::IntoIter::new([T; N]) always yields N elements unsafe { IteratorFixed::from_iter(<[T; N] as IntoIterator>::into_iter(self)) } } } unsafe impl<'a, T, const N: usize> IntoIteratorFixed for &'a [T; N] { type Item = &'a T; type IntoIter = slice::Iter<'a, T>; /// Creates a fixed size iterator from a borrowed array. /// /// Basic usage: /// ``` /// use iter_fixed::IntoIteratorFixed; /// fn double(array: &[i32; N]) -> [i32; N] { /// let two_four_six = array.into_iter_fixed().map(|&x| 2 * x); /// /// two_four_six.collect() /// } /// assert_eq!(double(&[1, 2, 3]), [2, 4, 6]); /// ``` #[inline] fn into_iter_fixed(self) -> IteratorFixed { // Safety: [T; N]::iter always yields N elements unsafe { IteratorFixed::from_iter(self.iter()) } } } unsafe impl<'a, T, const N: usize> IntoIteratorFixed for &'a mut [T; N] { type Item = &'a mut T; type IntoIter = slice::IterMut<'a, T>; /// Creates a fixed size iterator from a mutably borrowed array. /// /// Basic usage: /// ``` /// use iter_fixed::IntoIteratorFixed; /// /// // Update `array` in place to element wise x * 2 /// // return the initial value of the array /// fn double(array: &mut [i32; N]) -> [i32; N] { /// let fixed_iter = array.into_iter_fixed().map(|x| { /// let old = *x; /// *x = 2 * *x; /// old /// }); /// fixed_iter.collect() /// } /// let mut a = [1, 2, 3]; /// assert_eq!(double(&mut a), [1, 2, 3]); /// assert_eq!(a, [2, 4, 6]); /// ``` #[inline] fn into_iter_fixed(self) -> IteratorFixed { // Safety: [T; N]::iter always yields N elements unsafe { IteratorFixed::from_iter(self.iter_mut()) } } } unsafe impl IntoIteratorFixed for iter::Repeat { type Item = T; type IntoIter = iter::Take; /// Creates a fixed size iterator from an [`core::iter::Repeat`] /// /// Basic usage: /// ``` /// use core::iter; /// use iter_fixed::IntoIteratorFixed; /// /// let one_one_one = iter::repeat(1).into_iter_fixed(); /// /// let a: [i32; 3] = one_one_one.collect(); /// assert_eq!(a, [1, 1, 1]); /// ``` #[inline] fn into_iter_fixed(self) -> IteratorFixed, N> { // Safety: iter::repeat(_).take(N) always yields N elements unsafe { IteratorFixed::from_iter(self.take(N)) } } } iter_fixed-0.4.0/src/lib.rs000066400000000000000000000242571463611235600155610ustar00rootroot00000000000000//! Provides a type and traits for turning collections of fixed size, like arrays, //! into [`IteratorFixed`] which can be used a bit like an ordinary [`Iterator`] but //! with a compile time guaranteed length. This enables us to turn them back into //! collections of fixed size without having to perform unnecessary checks during //! run time. //! //! [`IteratorFixed`] provides on stable methods like `map`, `inspect`, `enumerate`, //! `zip`, `rev`, `copied`, `cloned`, with nightly `skip`, `step_by`, `chain`, `take`, //! `flatten`. //! //! However it does not and will never be able to support methods like //! `filter` or `take_while` which will affect the length during runtime. //! //! # ⚠️ Experimental //! *This code is currently very experimental, type names, function names, trait bounds etc. are all very much subject to change.* //! //! # Origin //! *This project is inspired by @leonardo-m 's idea * //! //! # Examples: //! ``` //! # use crate::iter_fixed::IntoIteratorFixed; //! // simply reverse an Array //! let rev_array: [_; 4] = [1, 3, 2, 7] //! .into_iter_fixed() //! .rev() //! .collect(); //! assert_eq!(rev_array, [7, 2, 3, 1]); //! //! // .. and compute sum with values of a second array multiplied by 10 //! let sum_array: [_; 4] = rev_array //! .into_iter_fixed() //! .zip([4,1,3,7]) //! .map(|(a, b)| a + (b * 10)) //! .collect(); //! assert_eq!(sum_array, [47, 12, 33, 71]); //! ``` //! //! You can also take a look at examples : [`matrix.rs`] and [`vector.rs`] //! //! [`matrix.rs`]: source/examples/matrix.rs //! [`vector.rs`]: source/examples/vector.rs //! #![no_std] #![allow(stable_features)] #![cfg_attr(feature = "nightly_features", allow(incomplete_features))] #![cfg_attr(feature = "nightly_features", feature(generic_const_exprs))] // enable additionnal lints #![warn(clippy::doc_markdown)] #![warn(clippy::ignored_unit_patterns)] #![warn(clippy::missing_inline_in_public_items)] #![warn(clippy::use_self)] use core::iter; mod from; mod helpers; mod into; #[cfg(feature = "nightly_features")] use helpers::{ceiling_div, min, sub_or_zero}; pub use from::FromIteratorFixed; pub use into::IntoIteratorFixed; /// Iterator of fixed size /// /// A type that can be usen a bit like an ordinary Iterator but with a compile time guaranteed /// length. This enables us to turn them back into collections of fixed size without having to /// perform unnecessary checks during run time. /// /// Just like [`Iterator`], [`IteratorFixed`] provides a lot of methods like: /// - available on stable rust: /// [`map`], [`inspect`], [`enumerate`], [`zip`], [`rev`], [`copied`], [`cloned`] /// /// - requires nightly compiler and enable `nightly_features`: /// [`skip`], [`step_by`], [`chain`], [`take`], [`flatten`] /// /// however it does not support methods like `filter` or `take_while` which will affect the length during runtime. /// /// [`map`]: IteratorFixed::map /// [`inspect`]: IteratorFixed::inspect /// [`enumerate`]: IteratorFixed::enumerate /// [`zip`]: IteratorFixed::zip /// [`rev`]: IteratorFixed::rev /// [`copied`]: IteratorFixed::copied /// [`cloned`]: IteratorFixed::cloned /// [`skip`]: IteratorFixed::skip /// [`step_by`]: IteratorFixed::step_by /// [`chain`]: IteratorFixed::chain /// [`take`]: IteratorFixed::take /// [`flatten`]: IteratorFixed::flatten pub struct IteratorFixed { inner: I, } /// Creates a new iterator of fixed size where each iteration calls the provided closure F: FnMut(usize) -> T /// /// This allows very simple initialization of types that implement [`FromIteratorFixed`] such as arrays. /// /// Note: This function is quite similar to [`iter::from_fn`] however note that in contrast to [`iter::from_fn`], /// in `IteratorFixed::from_fn` the provided function does not have any say in the number of elements. /// The length is entirely determined by `N`. /// /// Basic usage: /// ``` /// let zero_two_four: [usize; 3] = iter_fixed::from_fn(|i| 2 * i).collect(); /// /// assert_eq!(zero_two_four, [0, 2, 4]); /// ``` #[inline] pub fn from_fn<'a, F, T: 'a, const N: usize>( mut f: F, ) -> IteratorFixed + 'a, N> where F: FnMut(usize) -> T + 'a, { [(); N] .into_iter_fixed() .enumerate() .map(move |(i, ())| f(i)) } impl IteratorFixed where I: Iterator, { /// # Safety /// Caller has to guarantee that the given iterator will yield exactly N elements /// // TODO: Would it be ok if it generated more elements? #[inline] pub unsafe fn from_iter>(i: II) -> Self { Self { inner: i.into_iter(), } } /// See [`core::iter::Iterator::map`] #[inline] pub fn map::Item) -> U>( self, p: F, ) -> IteratorFixed, N> { IteratorFixed { inner: self.inner.map(p), } } /// See [`core::iter::Iterator::inspect`] #[inline] pub fn inspect::Item)>( self, p: F, ) -> IteratorFixed, N> { IteratorFixed { inner: self.inner.inspect(p), } } // TODO: what should happen when SKIP > N? /// See [`core::iter::Iterator::skip`] #[cfg(feature = "nightly_features")] #[inline] pub fn skip( self, ) -> IteratorFixed, { sub_or_zero(N, SKIP) }> { IteratorFixed { inner: self.inner.skip(SKIP), } } /// See [`core::iter::Iterator::step_by`] #[cfg(feature = "nightly_features")] #[inline] pub fn step_by( self, ) -> IteratorFixed, { ceiling_div(N, STEP) }> { IteratorFixed { inner: self.inner.step_by(STEP), } } /// See [`core::iter::Iterator::chain`] #[cfg(feature = "nightly_features")] #[inline] pub fn chain( self, other: IIF, ) -> IteratorFixed, { N + M }> where IIF: IntoIteratorFixed, { IteratorFixed { inner: self.inner.chain(other.into_iter_fixed().inner), } } /// See [`core::iter::Iterator::enumerate`] #[inline] pub fn enumerate(self) -> IteratorFixed, N> { IteratorFixed { inner: self.inner.enumerate(), } } /// See [`core::iter::Iterator::take`] #[cfg(feature = "nightly_features")] #[inline] pub fn take( self, ) -> IteratorFixed, { min(TAKE, N) }> { IteratorFixed { inner: self.inner.take(TAKE), } } /// See [`core::iter::Iterator::zip`] #[inline] pub fn zip( self, other: IIF, ) -> IteratorFixed, N> where IIF: IntoIteratorFixed, { IteratorFixed { inner: self.inner.zip(other.into_iter_fixed().inner), } } /* pub fn unzip(self) -> (FromA, FromB) where I: Iterator, FromA: FromIteratorFixed, FromB: FromIteratorFixed, { unimplemented!() } */ /// See [`core::iter::Iterator::rev`] #[inline] pub fn rev(self) -> IteratorFixed, N> where I: iter::DoubleEndedIterator, { IteratorFixed { inner: self.inner.rev(), } } #[cfg(feature = "nightly_features")] #[inline] pub fn flatten( self, ) -> IteratorFixed, { M * N }> where I: Iterator, IIF: IntoIteratorFixed, { // The call to into_iter_fixed is needed because we cannot trust that // let x: I::Item; // x.into_iterator() == x.into_iter_fixed().into_iterator() IteratorFixed { inner: self.inner.flat_map(IntoIteratorFixed::into_iter_fixed), } } #[cfg(feature = "nightly_features")] #[inline] pub fn flat_map( self, mut f: F, ) -> IteratorFixed, { M * N }> where F: FnMut(I::Item) -> IIF, IIF: IntoIteratorFixed, { // The call to into_iter_fixed is needed because we cannot trust that // let x: I::Item; // x.into_iterator() == x.into_iter_fixed().into_iterator() IteratorFixed { inner: self.inner.flat_map(move |x| f(x).into_iter_fixed()), } } /// Transforms a fixed size iterator into a collection of compile time known size. /// /// Basic usage: /// ``` /// use iter_fixed::IntoIteratorFixed; /// /// let two_four_six = [1, 2, 3].into_iter_fixed().map(|x| 2 * x); /// /// let a: [i32; 3] = two_four_six.collect(); /// assert_eq!(a, [2, 4, 6]); /// ``` #[inline] pub fn collect>(self) -> U { U::from_iter_fixed(self) } } impl<'a, I, T: 'a, const N: usize> IteratorFixed where I: Iterator, { /// See [`core::iter::Iterator::copied`] #[inline] pub fn copied(self) -> IteratorFixed, N> where T: Copy, { IteratorFixed { inner: self.inner.copied(), } } /// See [`core::iter::Iterator::cloned`] #[inline] pub fn cloned(self) -> IteratorFixed, N> where T: Clone, { IteratorFixed { inner: self.inner.cloned(), } } } /// Convert the fixed size iterator into an ordinary [`core::iter::Iterator`] /// allowing it to be used with for loop syntax impl, const N: usize> IntoIterator for IteratorFixed { type Item = T; type IntoIter = I; /// Convert the fixed size iterator into an ordinary [`core::iter::Iterator`] #[inline] fn into_iter(self) -> I { self.inner } } iter_fixed-0.4.0/tests/000077500000000000000000000000001463611235600150065ustar00rootroot00000000000000iter_fixed-0.4.0/tests/test.rs000066400000000000000000000034641463611235600163420ustar00rootroot00000000000000#![cfg_attr(feature = "nightly_features", allow(incomplete_features))] #![cfg_attr(feature = "nightly_features", feature(generic_const_exprs))] extern crate iter_fixed; use iter_fixed::IntoIteratorFixed; #[test] fn test() { let res: [_; 4] = [1u32, 2, 3, 4] .into_iter_fixed() .zip([4u32, 3, 2, 1]) .map(|(a, b)| a + b) .collect(); assert_eq!(res, [5, 5, 5, 5]); let res: [(_, _); 3] = [1, 2, 3] .into_iter_fixed() .zip(core::iter::repeat(42)) .collect(); assert_eq!(res, [(1, 42), (2, 42), (3, 42)]); } #[cfg(feature = "nightly_features")] #[test] fn test_changing_length() { let res: [_; 3] = [1, 2, 3, 4].into_iter_fixed().skip::<1>().collect(); assert_eq!(res, [2, 3, 4]); let res: [_; 3] = [1, 2, 3, 4, 5].into_iter_fixed().step_by::<2>().collect(); assert_eq!(res, [1, 3, 5]); let res: [_; 3] = [1, 2, 3, 4, 5, 6] .into_iter_fixed() .step_by::<2>() .collect(); assert_eq!(res, [1, 3, 5]); let res: [_; 4] = [1, 2, 3, 4, 5, 6, 7] .into_iter_fixed() .step_by::<2>() .collect(); assert_eq!(res, [1, 3, 5, 7]); let res: [_; 4] = [1, 2].into_iter_fixed().chain([3, 4]).collect(); assert_eq!(res, [1, 2, 3, 4]); let res: [_; 2] = [1, 2, 3, 4].into_iter_fixed().take::<2>().collect(); assert_eq!(res, [1, 2]); let res: [_; 4] = [[1, 2], [3, 4]].into_iter_fixed().flatten().collect(); assert_eq!(res, [1, 2, 3, 4]); let res: [_; 6] = [1, 2, 3].into_iter_fixed().flat_map(|x| [x, x]).collect(); assert_eq!(res, [1, 1, 2, 2, 3, 3]); let res: [_; 6] = [1, 2, 3] .into_iter_fixed() .flat_map(|x| IntoIteratorFixed::<2>::into_iter_fixed(core::iter::repeat(x))) .collect(); assert_eq!(res, [1, 1, 2, 2, 3, 3]); }