├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | rust_version: 20 | - stable 21 | - 1.51 # MSRV (Minimum Supported Rust Version) 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - uses: dtolnay/rust-toolchain@master 26 | with: 27 | toolchain: ${{matrix.rust_version}} 28 | - name: Build 29 | run: cargo build --verbose 30 | - name: Run tests 31 | run: cargo test --verbose 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | os: 7 | - linux 8 | 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | 9 | ## 2.1.0 10 | ### Added 11 | - Introduced an MSRV: Rust 1.51 12 | - Added `map_array_init` function ([#38](https://github.com/Manishearth/array-init/pull/38)) 13 | 14 | ## v2.0.1 (2022-06-24) 15 | ### Added 16 | - Added `from_iter_reversed` function ([#30](https://github.com/Manishearth/array-init/issues/30)) 17 | 18 | ## v2.0.0 (2021-03-29) 19 | ### Breaking 20 | - Removed `IsArray` trait (not necessary anymore with const generics) 21 | 22 | ## v1.1.0 (yanked) 23 | ### Breaking 24 | - Removed `const-generics` feature flag. The MSRV is now rust 1.51 25 | 26 | ## v1.0.0 (2020-10-14) 27 | ### Added 28 | - Added a `try_array_init` function which initializes an array with a callable that may fail. 29 | - Added a `const-generics` feature which uses rust (unstable) `const-generics` feature to implement the initializer functions for all array sizes. 30 | - Added documentation 31 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ 3 | "Manish Goregaokar ", 4 | "Michal 'vorner' Vaner ", 5 | ] 6 | name = "array-init" 7 | version = "2.1.0" 8 | license = "MIT OR Apache-2.0" 9 | edition = "2018" 10 | description = "Safe wrapper for initializing fixed-size arrays" 11 | readme = "README.md" 12 | repository = "https://github.com/Manishearth/array-init/" 13 | documentation = "https://docs.rs/crate/array-init" 14 | 15 | keywords = ["abstraction", "initialization", "no_std"] 16 | categories = ["data-structures", "no-std"] 17 | exclude = [".travis.yml"] 18 | 19 | [package.metadata] 20 | # to be replaced by `package.rust-version` once we increase the msrv beyond 1.56 21 | msrv = "1.51" 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017-2020 The array-init developers 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017-2020 The array-init developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # array-init 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/array-init?style=flat-square)](https://crates.io/crates/array-init) 4 | [![Docs](https://img.shields.io/badge/docs-doc.rs-blue?style=flat-square)](https://docs.rs/array-init) 5 | 6 | The `array-init` crate allows you to initialize arrays 7 | with an initializer closure that will be called 8 | once for each element until the array is filled. 9 | 10 | This way you do not need to default-fill an array 11 | before running initializers. Rust currently only 12 | lets you either specify all initializers at once, 13 | individually (`[a(), b(), c(), ...]`), or specify 14 | one initializer for a `Copy` type (`[a(); N]`), 15 | which will be called once with the result copied over. 16 | 17 | Care is taken not to leak memory shall the initialization 18 | fail. 19 | 20 | ## Examples: 21 | 22 | ```rust 23 | // Initialize an array of length 50 containing 24 | // successive squares 25 | 26 | let arr: [usize; 50] = array_init::array_init(|i| i * i); 27 | 28 | // Initialize an array from an iterator 29 | // producing an array of [1,2,3,4] repeated 30 | 31 | let four = [1,2,3,4]; 32 | let mut iter = four.iter().copied().cycle(); 33 | let arr: [u32; 50] = array_init::from_iter(iter).unwrap(); 34 | 35 | // Closures can also mutate state. We guarantee that they will be called 36 | // in order from lower to higher indices. 37 | 38 | let mut last = 1u64; 39 | let mut secondlast = 0; 40 | let fibonacci: [u64; 50] = array_init::array_init(|_| { 41 | let this = last + secondlast; 42 | secondlast = last; 43 | last = this; 44 | this 45 | }); 46 | ``` 47 | 48 | ## Minimum Supported Rust Version (MSRV) 49 | 50 | `array-init` will only increase the MSRV on a new major 51 | or minor release, but not for patch releases. 52 | Any changes of the MSRV will be announced in the changelog. 53 | When increasing the MSRV, the new Rust version must have been 54 | released at least six months ago. The current MSRV is 1.51.0. 55 | MSRV changes can be expected to happen conservatively. 56 | 57 | ## Licensing 58 | 59 | Licensed under either of Apache License, Version 2.0 or MIT license at your option. 60 | 61 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 62 | 63 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | //! The `array-init` crate allows you to initialize arrays 4 | //! with an initializer closure that will be called 5 | //! once for each element until the array is filled. 6 | //! 7 | //! This way you do not need to default-fill an array 8 | //! before running initializers. Rust currently only 9 | //! lets you either specify all initializers at once, 10 | //! individually (`[a(), b(), c(), ...]`), or specify 11 | //! one initializer for a `Copy` type (`[a(); N]`), 12 | //! which will be called once with the result copied over. 13 | //! 14 | //! Care is taken not to leak memory shall the initialization 15 | //! fail. 16 | //! 17 | //! # Examples: 18 | //! ```rust 19 | //! # #![allow(unused)] 20 | //! # extern crate array_init; 21 | //! # 22 | //! // Initialize an array of length 50 containing 23 | //! // successive squares 24 | //! 25 | //! let arr: [u32; 50] = array_init::array_init(|i: usize| (i * i) as u32); 26 | //! 27 | //! // Initialize an array from an iterator 28 | //! // producing an array of [1,2,3,4] repeated 29 | //! 30 | //! let four = [1,2,3,4]; 31 | //! let mut iter = four.iter().copied().cycle(); 32 | //! let arr: [u32; 50] = array_init::from_iter(iter).unwrap(); 33 | //! 34 | //! // Closures can also mutate state. We guarantee that they will be called 35 | //! // in order from lower to higher indices. 36 | //! 37 | //! let mut last = 1u64; 38 | //! let mut secondlast = 0; 39 | //! let fibonacci: [u64; 50] = array_init::array_init(|_| { 40 | //! let this = last + secondlast; 41 | //! secondlast = last; 42 | //! last = this; 43 | //! this 44 | //! }); 45 | //! ``` 46 | 47 | use ::core::{ 48 | mem::{self, MaybeUninit}, 49 | ptr, slice, 50 | }; 51 | 52 | #[inline] 53 | /// Initialize an array given an initializer expression. 54 | /// 55 | /// The initializer is given the index of the element. It is allowed 56 | /// to mutate external state; we will always initialize the elements in order. 57 | /// 58 | /// # Examples 59 | /// 60 | /// ```rust 61 | /// # #![allow(unused)] 62 | /// # extern crate array_init; 63 | /// # 64 | /// // Initialize an array of length 50 containing 65 | /// // successive squares 66 | /// let arr: [usize; 50] = array_init::array_init(|i| i * i); 67 | /// 68 | /// assert!(arr.iter().enumerate().all(|(i, &x)| x == i * i)); 69 | /// ``` 70 | pub fn array_init(mut initializer: F) -> [T; N] 71 | where 72 | F: FnMut(usize) -> T, 73 | { 74 | enum Unreachable {} 75 | 76 | try_array_init( 77 | // monomorphise into an infallible version 78 | move |i| -> Result { Ok(initializer(i)) }, 79 | ) 80 | .unwrap_or_else( 81 | // zero-cost unwrap 82 | |unreachable| match unreachable { /* ! */ }, 83 | ) 84 | } 85 | 86 | #[inline] 87 | /// Initialize an array given an iterator 88 | /// 89 | /// We will iterate until the array is full or the iterator is exhausted. Returns 90 | /// `None` if the iterator is exhausted before we can fill the array. 91 | /// 92 | /// - Once the array is full, extra elements from the iterator (if any) 93 | /// won't be consumed. 94 | /// 95 | /// # Examples 96 | /// 97 | /// ```rust 98 | /// # #![allow(unused)] 99 | /// # extern crate array_init; 100 | /// # 101 | /// // Initialize an array from an iterator 102 | /// // producing an array of [1,2,3,4] repeated 103 | /// 104 | /// let four = [1,2,3,4]; 105 | /// let mut iter = four.iter().copied().cycle(); 106 | /// let arr: [u32; 10] = array_init::from_iter(iter).unwrap(); 107 | /// assert_eq!(arr, [1, 2, 3, 4, 1, 2, 3, 4, 1, 2]); 108 | /// ``` 109 | pub fn from_iter(iterable: Iterable) -> Option<[T; N]> 110 | where 111 | Iterable: IntoIterator, 112 | { 113 | try_array_init_impl::<_, _, T, N, 1>({ 114 | let mut iterator = iterable.into_iter(); 115 | move |_| iterator.next().ok_or(()) 116 | }) 117 | .ok() 118 | } 119 | 120 | #[inline] 121 | /// Initialize an array in reverse given an iterator 122 | /// 123 | /// We will iterate until the array is full or the iterator is exhausted. Returns 124 | /// `None` if the iterator is exhausted before we can fill the array. 125 | /// 126 | /// - Once the array is full, extra elements from the iterator (if any) 127 | /// won't be consumed. 128 | /// 129 | /// # Examples 130 | /// 131 | /// ```rust 132 | /// # #![allow(unused)] 133 | /// # extern crate array_init; 134 | /// # 135 | /// // Initialize an array from an iterator 136 | /// // producing an array of [4,3,2,1] repeated, finishing with 1. 137 | /// 138 | /// let four = [1,2,3,4]; 139 | /// let mut iter = four.iter().copied().cycle(); 140 | /// let arr: [u32; 10] = array_init::from_iter_reversed(iter).unwrap(); 141 | /// assert_eq!(arr, [2, 1, 4, 3, 2, 1, 4, 3, 2, 1]); 142 | /// ``` 143 | pub fn from_iter_reversed(iterable: Iterable) -> Option<[T; N]> 144 | where 145 | Iterable: IntoIterator, 146 | { 147 | try_array_init_impl::<_, _, T, N, -1>({ 148 | let mut iterator = iterable.into_iter(); 149 | move |_| iterator.next().ok_or(()) 150 | }) 151 | .ok() 152 | } 153 | 154 | #[inline] 155 | /// Initialize an array given an initializer expression that may fail. 156 | /// 157 | /// The initializer is given the index (between 0 and `N - 1` included) of the element, and returns a `Result,`. It is allowed 158 | /// to mutate external state; we will always initialize from lower to higher indices. 159 | /// 160 | /// # Examples 161 | /// 162 | /// ```rust 163 | /// # #![allow(unused)] 164 | /// # extern crate array_init; 165 | /// # 166 | /// #[derive(PartialEq,Eq,Debug)] 167 | /// struct DivideByZero; 168 | /// 169 | /// fn inv(i : usize) -> Result { 170 | /// if i == 0 { 171 | /// Err(DivideByZero) 172 | /// } else { 173 | /// Ok(1./(i as f64)) 174 | /// } 175 | /// } 176 | /// 177 | /// // If the initializer does not fail, we get an initialized array 178 | /// let arr: [f64; 3] = array_init::try_array_init(|i| inv(3-i)).unwrap(); 179 | /// assert_eq!(arr,[1./3., 1./2., 1./1.]); 180 | /// 181 | /// // The initializer fails 182 | /// let res : Result<[f64;4], DivideByZero> = array_init::try_array_init(|i| inv(3-i)); 183 | /// assert_eq!(res,Err(DivideByZero)); 184 | /// ``` 185 | pub fn try_array_init(initializer: F) -> Result<[T; N], Err> 186 | where 187 | F: FnMut(usize) -> Result, 188 | { 189 | try_array_init_impl::(initializer) 190 | } 191 | 192 | #[inline] 193 | /// Initialize an array given a source array and a mapping expression. The size of the source array 194 | /// is the same as the size of the returned array. 195 | /// 196 | /// The mapper is given an element from the source array and maps it to an element in the 197 | /// destination. 198 | /// 199 | /// # Examples 200 | /// 201 | /// ```rust 202 | /// # #![allow(unused)] 203 | /// # extern crate array_init; 204 | /// # 205 | /// // Initialize an array of length 50 containing successive squares 206 | /// let arr: [usize; 50] = array_init::array_init(|i| i * i); 207 | /// 208 | /// // Map each usize element to a u64 element. 209 | /// let u64_arr: [u64; 50] = array_init::map_array_init(&arr, |element| *element as u64); 210 | /// 211 | /// assert!(u64_arr.iter().enumerate().all(|(i, &x)| x == (i * i) as u64)); 212 | /// ``` 213 | pub fn map_array_init(source: &[U; N], mut mapper: M) -> [T; N] 214 | where 215 | M: FnMut(&U) -> T, 216 | { 217 | // # Safety 218 | // - The array size is known at compile time so we are certain that both the source and 219 | // desitination have the same size. If the two arrays are of the same size we know that a 220 | // valid index for one would be a valid index for the other. 221 | array_init(|index| unsafe { mapper(source.get_unchecked(index)) }) 222 | } 223 | 224 | #[inline] 225 | fn try_array_init_impl( 226 | mut initializer: F, 227 | ) -> Result<[T; N], Err> 228 | where 229 | F: FnMut(usize) -> Result, 230 | { 231 | // The implementation differentiates two cases: 232 | // A) `T` does not need to be dropped. Even if the initializer panics 233 | // or returns `Err` we will not leak memory. 234 | // B) `T` needs to be dropped. We must keep track of which elements have 235 | // been initialized so far, and drop them if we encounter a panic or `Err` midway. 236 | if !mem::needs_drop::() { 237 | let mut array: MaybeUninit<[T; N]> = MaybeUninit::uninit(); 238 | // pointer to array = *mut [T; N] <-> *mut T = pointer to first element 239 | let mut ptr_i = array.as_mut_ptr() as *mut T; 240 | 241 | // # Safety 242 | // 243 | // - for D > 0, we are within the array since we start from the 244 | // beginning of the array, and we have `0 <= i < N`. 245 | // - for D < 0, we start at the end of the array and go back one 246 | // place before writing, going back N times in total, finishing 247 | // at the start of the array. 248 | unsafe { 249 | if D < 0 { 250 | ptr_i = ptr_i.add(N); 251 | } 252 | for i in 0..N { 253 | let value_i = initializer(i)?; 254 | // We overwrite *ptr_i previously undefined value without reading or dropping it. 255 | if D < 0 { 256 | ptr_i = ptr_i.sub(1); 257 | } 258 | ptr_i.write(value_i); 259 | if D > 0 { 260 | ptr_i = ptr_i.add(1); 261 | } 262 | } 263 | Ok(array.assume_init()) 264 | } 265 | } else { 266 | // else: `mem::needs_drop::()` 267 | 268 | /// # Safety 269 | /// 270 | /// - `base_ptr[.. initialized_count]` must be a slice of init elements... 271 | /// 272 | /// - ... that must be sound to `ptr::drop_in_place` if/when 273 | /// `UnsafeDropSliceGuard` is dropped: "symbolic ownership" 274 | struct UnsafeDropSliceGuard { 275 | base_ptr: *mut Item, 276 | initialized_count: usize, 277 | } 278 | 279 | impl Drop for UnsafeDropSliceGuard { 280 | fn drop(self: &'_ mut Self) { 281 | unsafe { 282 | // # Safety 283 | // 284 | // - the contract of the struct guarantees that this is sound 285 | ptr::drop_in_place(slice::from_raw_parts_mut( 286 | self.base_ptr, 287 | self.initialized_count, 288 | )); 289 | } 290 | } 291 | } 292 | 293 | // If the `initializer(i)` call panics, `panic_guard` is dropped, 294 | // dropping `array[.. initialized_count]` => no memory leak! 295 | // 296 | // # Safety 297 | // 298 | // 1. - For D > 0, by construction, array[.. initiliazed_count] only 299 | // contains init elements, thus there is no risk of dropping 300 | // uninit data; 301 | // - For D < 0, by construction, array[N - initialized_count..] only 302 | // contains init elements. 303 | // 304 | // 2. - for D > 0, we are within the array since we start from the 305 | // beginning of the array, and we have `0 <= i < N`. 306 | // - for D < 0, we start at the end of the array and go back one 307 | // place before writing, going back N times in total, finishing 308 | // at the start of the array. 309 | // 310 | unsafe { 311 | let mut array: MaybeUninit<[T; N]> = MaybeUninit::uninit(); 312 | // pointer to array = *mut [T; N] <-> *mut T = pointer to first element 313 | let mut ptr_i = array.as_mut_ptr() as *mut T; 314 | if D < 0 { 315 | ptr_i = ptr_i.add(N); 316 | } 317 | let mut panic_guard = UnsafeDropSliceGuard { 318 | base_ptr: ptr_i, 319 | initialized_count: 0, 320 | }; 321 | 322 | for i in 0..N { 323 | // Invariant: `i` elements have already been initialized 324 | panic_guard.initialized_count = i; 325 | // If this panics or fails, `panic_guard` is dropped, thus 326 | // dropping the elements in `base_ptr[.. i]` for D > 0 or 327 | // `base_ptr[N - i..]` for D < 0. 328 | let value_i = initializer(i)?; 329 | // this cannot panic 330 | // the previously uninit value is overwritten without being read or dropped 331 | if D < 0 { 332 | ptr_i = ptr_i.sub(1); 333 | panic_guard.base_ptr = ptr_i; 334 | } 335 | ptr_i.write(value_i); 336 | if D > 0 { 337 | ptr_i = ptr_i.add(1); 338 | } 339 | } 340 | // From now on, the code can no longer `panic!`, let's take the 341 | // symbolic ownership back 342 | mem::forget(panic_guard); 343 | 344 | Ok(array.assume_init()) 345 | } 346 | } 347 | } 348 | 349 | #[cfg(test)] 350 | mod tests { 351 | use super::*; 352 | 353 | #[test] 354 | fn seq() { 355 | let seq: [usize; 5] = array_init(|i| i); 356 | assert_eq!(&[0, 1, 2, 3, 4], &seq); 357 | } 358 | 359 | #[test] 360 | fn array_from_iter() { 361 | let array = [0, 1, 2, 3, 4]; 362 | let seq: [usize; 5] = from_iter(array.iter().copied()).unwrap(); 363 | assert_eq!(array, seq,); 364 | } 365 | 366 | #[test] 367 | fn array_init_no_drop() { 368 | DropChecker::with(|drop_checker| { 369 | let result: Result<[_; 5], ()> = try_array_init(|i| { 370 | if i < 3 { 371 | Ok(drop_checker.new_element()) 372 | } else { 373 | Err(()) 374 | } 375 | }); 376 | assert!(result.is_err()); 377 | }); 378 | } 379 | 380 | #[test] 381 | fn from_iter_no_drop() { 382 | DropChecker::with(|drop_checker| { 383 | let iterator = (0..3).map(|_| drop_checker.new_element()); 384 | let result: Option<[_; 5]> = from_iter(iterator); 385 | assert!(result.is_none()); 386 | }); 387 | } 388 | 389 | #[test] 390 | fn from_iter_reversed_no_drop() { 391 | DropChecker::with(|drop_checker| { 392 | let iterator = (0..3).map(|_| drop_checker.new_element()); 393 | let result: Option<[_; 5]> = from_iter_reversed(iterator); 394 | assert!(result.is_none()); 395 | }); 396 | } 397 | 398 | #[test] 399 | fn test_513_seq() { 400 | let seq: [usize; 513] = array_init(|i| i); 401 | assert_eq!( 402 | [ 403 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 404 | 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 405 | 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 406 | 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 407 | 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 408 | 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 409 | 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 410 | 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 411 | 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 412 | 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 413 | 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 414 | 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 415 | 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 416 | 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 417 | 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 418 | 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 419 | 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 420 | 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 421 | 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 422 | 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 423 | 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 424 | 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 425 | 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 426 | 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 427 | 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 428 | 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 429 | 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 430 | 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 431 | 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 432 | 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 433 | 505, 506, 507, 508, 509, 510, 511, 512 434 | ], 435 | seq 436 | ); 437 | } 438 | 439 | use self::drop_checker::DropChecker; 440 | mod drop_checker { 441 | use ::core::cell::Cell; 442 | 443 | pub(super) struct DropChecker { 444 | slots: [Cell; 512], 445 | next_uninit_slot: Cell, 446 | } 447 | 448 | pub(super) struct Element<'drop_checker> { 449 | slot: &'drop_checker Cell, 450 | } 451 | 452 | impl Drop for Element<'_> { 453 | fn drop(self: &'_ mut Self) { 454 | assert!(self.slot.replace(false), "Double free!"); 455 | } 456 | } 457 | 458 | impl DropChecker { 459 | pub(super) fn with(f: impl FnOnce(&Self)) { 460 | let drop_checker = Self::new(); 461 | f(&drop_checker); 462 | drop_checker.assert_no_leaks(); 463 | } 464 | 465 | pub(super) fn new_element(self: &'_ Self) -> Element<'_> { 466 | let i = self.next_uninit_slot.get(); 467 | self.next_uninit_slot.set(i + 1); 468 | self.slots[i].set(true); 469 | Element { 470 | slot: &self.slots[i], 471 | } 472 | } 473 | 474 | fn new() -> Self { 475 | Self { 476 | slots: crate::array_init(|_| Cell::new(false)), 477 | next_uninit_slot: Cell::new(0), 478 | } 479 | } 480 | 481 | fn assert_no_leaks(self: Self) { 482 | let leak_count: usize = self.slots[..self.next_uninit_slot.get()] 483 | .iter() 484 | .map(|slot| usize::from(slot.get() as u8)) 485 | .sum(); 486 | assert_eq!(leak_count, 0, "{} elements leaked", leak_count); 487 | } 488 | } 489 | } 490 | } 491 | --------------------------------------------------------------------------------