├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── azure-pipelines.yml ├── benches └── len.rs ├── src ├── errors.rs ├── iter.rs ├── lib.rs ├── macros.rs └── traits.rs └── tests └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "arrav" 3 | version = "0.2.0" 4 | authors = ["Jon Gjengset "] 5 | edition = "2018" 6 | license = "MIT OR Apache-2.0" 7 | 8 | readme = "README.md" 9 | description = "Sentinel-based heapless vector" 10 | repository = "https://github.com/jonhoo/arrav.git" 11 | 12 | keywords = ["vector","array","const"] 13 | categories = ["data-structures", "no-std"] 14 | 15 | [badges] 16 | azure-devops = { project = "jonhoo/jonhoo", pipeline = "arrav", build = "21" } 17 | codecov = { repository = "jonhoo/arrav", branch = "master", service = "github" } 18 | maintenance = { status = "experimental" } 19 | 20 | [features] 21 | std = [] 22 | specialization = [] 23 | default = ["std", "specialization"] 24 | 25 | [dependencies] 26 | 27 | [dev-dependencies] 28 | criterion = "0.3" 29 | 30 | [[bench]] 31 | name = "len" 32 | harness = false 33 | -------------------------------------------------------------------------------- /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 2020 Jon Gjengset 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 | MIT License 2 | 3 | Copyright (c) 2020 Jon Gjengset 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Crates.io](https://img.shields.io/crates/v/arrav.svg)](https://crates.io/crates/arrav) 2 | [![Documentation](https://docs.rs/arrav/badge.svg)](https://docs.rs/arrav/) 3 | [![Build Status](https://dev.azure.com/jonhoo/jonhoo/_apis/build/status/arrav?branchName=master)](https://dev.azure.com/jonhoo/jonhoo/_build/latest?definitionId=21&branchName=master) 4 | [![Codecov](https://codecov.io/github/jonhoo/arrav/coverage.svg?branch=master)](https://codecov.io/gh/jonhoo/arrav) 5 | 6 | A sentinel-based, heapless, `Vec`-like type. 7 | 8 | Arrays are great, because they do not require allocation. 9 | But arrays are fixed-size. 10 | 11 | Slices are great, because you can make them smaller. 12 | But slices aren't `Sized`. 13 | 14 | Vectors are great, because you can make them bigger. 15 | But vectors require allocation. 16 | 17 | This type provides a type that acts like a vector but is represented 18 | exactly like an array. Unlike other array-backed vector-like types, but 19 | like C-style strings and arrays, `Arrav` uses a sentinel value to 20 | indicate unoccupied elements. This makes `push` and `pop` a little 21 | slower, but avoids having to store the length separately. The trade-off 22 | is that the sentinel value can no longer be stored in the array. 23 | 24 | `Arrav` is intended for when you have a _small_ but variable number of 25 | _small_ values that you want to store compactly (e.g., because they're 26 | going to be stored in a large number of elements). This is also why the 27 | "search" for the sentinel value to determine the array's length (and 28 | thus for `push` and `pop`) is unlikely to matter in practice. 29 | 30 | Unlike C-style strings and arrays, which use `NULL` as the sentinel, 31 | `Arrav` uses the _max_ value of the type (like `std::u8::MAX`). This 32 | means that unless you are saturating the type's range, you won't even 33 | notice the sentinel. 34 | 35 | ## License 36 | 37 | Licensed under either of 38 | 39 | * Apache License, Version 2.0 40 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 41 | * MIT license 42 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 43 | 44 | at your option. 45 | 46 | ## Contribution 47 | 48 | Unless you explicitly state otherwise, any contribution intentionally submitted 49 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 50 | dual licensed as above, without any additional terms or conditions. 51 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | - job: style 3 | displayName: Style linting 4 | pool: 5 | vmImage: ubuntu-latest 6 | continueOnError: true 7 | steps: 8 | - template: install-rust.yml@templates 9 | parameters: 10 | rust: nightly 11 | components: 12 | - rustfmt 13 | - clippy 14 | - script: cargo fmt --all -- --check 15 | displayName: cargo fmt --check 16 | - script: cargo clippy --all 17 | displayName: cargo clippy -- -D warnings 18 | - job: main 19 | displayName: Compile and test 20 | dependsOn: [] 21 | strategy: 22 | matrix: 23 | Linux: 24 | vmImage: ubuntu-latest 25 | rust: nightly 26 | MacOS: 27 | vmImage: macOS-10.15 28 | rust: nightly 29 | Windows: 30 | vmImage: windows-2019 31 | rust: nightly 32 | pool: 33 | vmImage: $(vmImage) 34 | continueOnError: true 35 | steps: 36 | - template: install-rust.yml@templates 37 | parameters: 38 | rust: $(rust) 39 | - script: cargo check 40 | displayName: cargo check 41 | - script: cargo check --no-default-features 42 | displayName: cargo check --no-default-features 43 | - script: cargo check --all-features 44 | displayName: cargo check --all-features 45 | - script: cargo test --no-default-features --features std 46 | displayName: cargo test (no specialization) 47 | - script: cargo test --all-features 48 | displayName: cargo test 49 | - script: cargo doc --no-deps 50 | displayName: cargo doc 51 | - template: coverage.yml@templates 52 | parameters: 53 | token: $(CODECOV_TOKEN_SECRET) 54 | nightly: true 55 | doctests: true 56 | - job: no_std 57 | dependsOn: [] 58 | displayName: "Compile-check on no_std target" 59 | pool: 60 | vmImage: ubuntu-latest 61 | steps: 62 | - template: install-rust.yml@templates 63 | parameters: 64 | rust: nightly 65 | targets: 66 | - thumbv7m-none-eabi 67 | - bash: cargo check --target thumbv7m-none-eabi --no-default-features 68 | displayName: cargo check 69 | # TODO: MSRV (once not nightly-only) 70 | 71 | resources: 72 | repositories: 73 | - repository: templates 74 | type: github 75 | name: crate-ci/azure-pipelines 76 | ref: refs/heads/v0.4 77 | endpoint: jonhoo 78 | -------------------------------------------------------------------------------- /benches/len.rs: -------------------------------------------------------------------------------- 1 | use arrav::Arrav; 2 | use criterion::{black_box, criterion_main, BenchmarkId, Criterion}; 3 | 4 | macro_rules! bench_len { 5 | ($c:ident, $t:ty, $width:expr) => {{ 6 | let mut group = $c.benchmark_group(concat!(stringify!($t), "x", stringify!($width))); 7 | let lens = if $width == 4 { 8 | &[0, 1, 2, 3, 4][..] 9 | } else { 10 | assert!($width > 4); 11 | assert!($width % 4 == 0); 12 | &[ 13 | 0, 14 | 1, 15 | $width / 4, 16 | $width / 2, 17 | 3 * $width / 4, 18 | $width - 1, 19 | $width, 20 | ][..] 21 | }; 22 | for len in lens { 23 | group.bench_with_input(BenchmarkId::from_parameter(len), len, |b, &len| { 24 | let mut av = Arrav::<$t, $width>::repeat(black_box(5)).unwrap(); 25 | while av.len() != len { 26 | av.pop().unwrap(); 27 | } 28 | b.iter(|| av.len()); 29 | }); 30 | } 31 | group.finish(); 32 | }}; 33 | } 34 | 35 | pub fn len() { 36 | use std::time::Duration; 37 | let mut c = Criterion::default() 38 | .configure_from_args() 39 | .warm_up_time(Duration::from_secs(1)) 40 | .sample_size(20) 41 | .measurement_time(Duration::from_secs(1)); 42 | bench_len!(c, u8, 32); 43 | bench_len!(c, u8, 24); 44 | bench_len!(c, u8, 16); 45 | bench_len!(c, u16, 16); 46 | bench_len!(c, u16, 8); 47 | bench_len!(c, u16, 4); 48 | bench_len!(c, u32, 8); 49 | bench_len!(c, u32, 4); 50 | } 51 | 52 | criterion_main!(len); 53 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | /// The provided value was `T`'s [sentinel value](Sentinel). 4 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] 5 | pub struct IsSentinel(pub T); 6 | 7 | #[cfg(feature = "std")] 8 | impl std::error::Error for IsSentinel {} 9 | impl fmt::Display for IsSentinel { 10 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 11 | write!( 12 | f, 13 | "value is the type's sentinel value, which cannot be represented" 14 | ) 15 | } 16 | } 17 | 18 | /// The reason why a call to [`Arrav::try_push`] failed. 19 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] 20 | pub enum PushErrorKind { 21 | /// The `Arrav` was already at capacity. 22 | Full, 23 | /// The value provided to `try_push` was the pushed type's [sentinel value](Sentinel). 24 | IsSentinel, 25 | } 26 | 27 | /// An error that occurred on a call to [`Arrav::try_push`]. 28 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] 29 | pub struct PushError { 30 | /// The item provided to `try_push` that could not be pushed. 31 | pub item: T, 32 | /// The reason the item could not be pushed. 33 | pub kind: PushErrorKind, 34 | } 35 | 36 | #[cfg(feature = "std")] 37 | impl std::error::Error for PushError {} 38 | impl fmt::Display for PushError { 39 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 40 | match self.kind { 41 | PushErrorKind::Full => write!(f, "Arrav was full"), 42 | PushErrorKind::IsSentinel => write!(f, "pushed item had sentinel value"), 43 | } 44 | } 45 | } 46 | 47 | #[inline(never)] 48 | #[cold] 49 | pub(super) fn index_len_fail(index: usize, len: usize) -> ! { 50 | panic!("index {} out of range for Arrav of length {}", index, len); 51 | } 52 | 53 | #[inline(never)] 54 | #[cold] 55 | pub(super) fn index_order_fail(index: usize, end: usize) -> ! { 56 | panic!("Arrav index starts at {} but ends at {}", index, end); 57 | } 58 | -------------------------------------------------------------------------------- /src/iter.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | /// Immutable `Arrav` iterator 4 | /// 5 | /// This struct is created using [`Arrav::iter`]. 6 | #[derive(Debug, Copy, Clone)] 7 | pub struct ArravIter 8 | where 9 | T: Copy + Sentinel, 10 | [T; N]: core::array::LengthAtMost32, 11 | { 12 | v: Arrav, 13 | at: usize, 14 | } 15 | 16 | impl IntoIterator for Arrav 17 | where 18 | T: Copy + Sentinel, 19 | [T; N]: core::array::LengthAtMost32, 20 | { 21 | type IntoIter = ArravIter; 22 | type Item = T; 23 | fn into_iter(self) -> Self::IntoIter { 24 | ArravIter::new(self) 25 | } 26 | } 27 | 28 | impl ArravIter 29 | where 30 | T: Copy + Sentinel, 31 | [T; N]: core::array::LengthAtMost32, 32 | { 33 | pub(crate) const fn new(v: Arrav) -> Self { 34 | Self { v, at: 0 } 35 | } 36 | } 37 | 38 | impl Iterator for ArravIter 39 | where 40 | T: Copy + Sentinel, 41 | [T; N]: core::array::LengthAtMost32, 42 | { 43 | type Item = T; 44 | fn next(&mut self) -> Option { 45 | let t = *self.v.get(self.at)?; 46 | self.at += 1; 47 | Some(t) 48 | } 49 | } 50 | 51 | impl<'a, T, const N: usize> IntoIterator for &'a Arrav 52 | where 53 | T: Copy + Sentinel, 54 | [T; N]: core::array::LengthAtMost32, 55 | { 56 | type IntoIter = ArravIter; 57 | type Item = T; 58 | fn into_iter(self) -> Self::IntoIter { 59 | Arrav::into_iter(*self) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A sentinel-based, heapless, `Vec`-like type. 2 | //! 3 | //! Arrays are great, because they do not require allocation. 4 | //! But arrays are fixed-size. 5 | //! 6 | //! Slices are great, because you can make them smaller. 7 | //! But slices aren't `Sized`. 8 | //! 9 | //! Vectors are great, because you can make them bigger. 10 | //! But vectors require allocation. 11 | //! 12 | //! This type provides a type that acts like a vector but is represented exactly like an array. 13 | //! Unlike other array-backed vector-like types, but like C-style strings and arrays, `Arrav` uses 14 | //! a sentinel value (dictated by [`Sentinel`]) to indicate unoccupied elements. This makes `push` 15 | //! and `pop` a little slower, but avoids having to store the length separately. The trade-off is 16 | //! that the sentinel value can no longer be stored in the array. 17 | //! 18 | //! `Arrav` is intended for when you have a _small_ but variable number of _small_ values that you 19 | //! want to store compactly (e.g., because they're going to be stored in a large number of 20 | //! elements). This is also why the "search" for the sentinel value to determine the array's length 21 | //! (and thus for `push` and `pop`) is unlikely to matter in practice. 22 | //! 23 | //! Unlike C-style strings and arrays, which use `NULL` as the sentinel, `Arrav` uses the _max_ 24 | //! value of the type (like `std::u8::MAX`). This means that unless you are saturating the type's 25 | //! range, you won't even notice the sentinel. 26 | //! 27 | //! # Semi-Important Tidbits 28 | //! 29 | //! **This crate uses the highly experimental const generics feature, and requires nightly.** 30 | //! 31 | //! The crate supports `no_std` environments without `alloc`. Just turn off the `std` feature. 32 | //! 33 | //! Wondering why the name? Arrav looks like the word "Array", but with "a bit chopped off" 🤷 34 | //! 35 | //! # Examples 36 | //! 37 | //! ``` 38 | //! use arrav::Arrav; 39 | //! let mut av = Arrav::<_, 4>::new(); 40 | //! assert_eq!(av.capacity(), 4); 41 | //! assert!(av.is_empty()); 42 | //! 43 | //! av.try_push(1).unwrap(); 44 | //! av.try_push(2).unwrap(); 45 | //! av.try_push(std::i32::MAX).unwrap_err(); 46 | //! 47 | //! assert_eq!(av.len(), 2); 48 | //! assert_eq!(av[0], 1); 49 | //! 50 | //! assert_eq!(av.pop(), Some(2)); 51 | //! assert_eq!(av.len(), 1); 52 | //! 53 | //! av.set(0, 7).unwrap(); 54 | //! assert_eq!(av[0], 7); 55 | //! 56 | //! av.extend([1, 2, 3].iter().copied()); 57 | //! 58 | //! for x in &av { 59 | //! println!("{}", x); 60 | //! } 61 | //! assert_eq!(av, [7, 1, 2, 3]); 62 | //! 63 | //! assert_eq!(av.len(), av.capacity()); 64 | //! av.try_push(3).unwrap_err(); 65 | //! ``` 66 | //! 67 | //! The [`avec!`] macro is provided to make initialization more convenient: 68 | //! 69 | //! ``` 70 | //! use arrav::avec; 71 | //! let av = avec![1, 2, 3]; 72 | //! assert_eq!(av.capacity(), 3); 73 | //! assert_eq!(av, [1, 2, 3]); 74 | //! ``` 75 | //! 76 | //! It can also initialize each element of a `Arrav` with a given value. 77 | //! This may be more efficient than performing allocation and initialization 78 | //! in separate steps, especially when initializing a vector of zeros: 79 | //! 80 | //! ``` 81 | //! use arrav::{Arrav, avec}; 82 | //! let av = arrav::avec![0; 5]; 83 | //! assert_eq!(av, [0, 0, 0, 0, 0]); 84 | //! 85 | //! // The following is equivalent, but potentially slower: 86 | //! let mut av1: Arrav<_, 5> = Arrav::new(); 87 | //! av1.resize(5, 0); 88 | //! assert_eq!(av, av1); 89 | //! ``` 90 | 91 | #![feature( 92 | const_generics, 93 | const_generic_impls_guard, 94 | const_fn, 95 | const_if_match, 96 | const_panic, 97 | slice_index_methods 98 | )] 99 | #![cfg_attr(feature = "specialization", feature(min_specialization))] 100 | #![allow(incomplete_features)] 101 | #![deny(missing_docs, unreachable_pub)] 102 | #![warn(rust_2018_idioms, intra_doc_link_resolution_failure)] 103 | #![cfg_attr(not(feature = "std"), no_std)] 104 | #![cfg_attr(feature = "std", deny(missing_debug_implementations))] 105 | 106 | /// `Arrav` error types. 107 | pub mod errors; 108 | /// `Arrav` iterator types. 109 | pub mod iter; 110 | mod macros; 111 | mod traits; 112 | 113 | use core::ops; 114 | 115 | /// A `Vec`-like type backed only by an array. 116 | /// 117 | /// # Sentinels 118 | /// 119 | /// `Arrav` uses a [sentinel value](Sentinel) for each type `T` to indicate the end of the 120 | /// array. For this reason, you can never insert a [`T::SENTINEL`](Sentinel::SENTINEL) into an 121 | /// `Arrav` — it would make the list be in an inconsistent state! All safe methods on `Arrav` 122 | /// return an error if you attempt to insert the sentinel value for the array's type, or they panic 123 | /// if no `Result` return type is provided. 124 | /// 125 | /// # Representation 126 | /// 127 | /// In memory, an `Arrav` is represented exactly like a `[T; N]`. 128 | /// 129 | /// # Indexing 130 | /// 131 | /// The `Arrav` type allows to access values by index, because it implements the 132 | /// [`Index`] trait. An example might help: 133 | /// 134 | /// ``` 135 | /// let v = arrav::avec![0, 2, 4, 6]; 136 | /// println!("{}", v[1]); // will display '2' 137 | /// ``` 138 | /// 139 | /// However be careful: if you try to access an index which isn't in the `Arrav`, 140 | /// as your code will panic! You cannot do this: 141 | /// 142 | /// ```no_run,should_panic 143 | /// # // this is no_run since tarpaulin can't handle should_panic doctests 144 | /// let v = arrav::avec![0, 2, 4, 6]; 145 | /// println!("{}", v[6]); // it will panic! 146 | /// ``` 147 | /// 148 | /// Use [`get`] if you want to check whether the index is in the `Arrav`. 149 | /// 150 | /// # Slicing 151 | /// 152 | /// You can slice an `Arrav` just like you would an array. 153 | /// To get a slice, use `&`. Example: 154 | /// 155 | /// ``` 156 | /// fn read_slice(_: &[usize]) { /* .. */ } 157 | /// 158 | /// let v = vec![0, 1]; 159 | /// read_slice(&v); 160 | /// 161 | /// // ... and that's all! 162 | /// // you can also do it like this: 163 | /// let x : &[usize] = &v; 164 | /// ``` 165 | /// 166 | /// You can also get a sub-slice using `&[Range]`: 167 | /// 168 | /// ``` 169 | /// fn read_slice(_: &[usize]) { /* .. */ } 170 | /// 171 | /// let v = vec![0, 1, 2]; 172 | /// read_slice(&v[1..2]); 173 | /// ``` 174 | /// 175 | /// In Rust, it's more common to pass slices as arguments rather than vectors 176 | /// when you just want to provide a read access. 177 | /// 178 | /// # Mutability 179 | /// 180 | /// Since an `Arrav` cannot hold all legal values of `T` (specifically, not the sentinel value), 181 | /// you cannot safely get mutable access to the elements of the arrav. Instead, you must use 182 | /// [`set`], which returns an error if the sentinel value is inserted, or the unsafe [`get_mut`] 183 | /// method. 184 | #[derive(Copy, Clone, Hash)] 185 | #[repr(transparent)] 186 | pub struct Arrav 187 | where 188 | [T; N]: core::array::LengthAtMost32, 189 | { 190 | ts: [T; N], 191 | } 192 | 193 | /// A type that has a sentinel value that can be used to indicate termination in [`Arrav`]. 194 | pub trait Sentinel: PartialEq + Copy { 195 | /// The sentinel value for a type used to indicate termination in [`Arrav`]. 196 | const SENTINEL: Self; 197 | } 198 | 199 | // === constructors === 200 | 201 | impl Arrav 202 | where 203 | T: Copy + Sentinel, 204 | [T; N]: core::array::LengthAtMost32, 205 | { 206 | /// Constructs a new, empty `Arrav`. 207 | /// 208 | /// You will generally want to specify the capacity of the `Arrav` when you construct it: 209 | /// 210 | /// ``` 211 | /// # #![allow(unused_mut)] 212 | /// # use arrav::Arrav; 213 | /// let mut av: Arrav = Arrav::new(); 214 | /// ``` 215 | /// 216 | /// You can often give `_` instead of the type (here `i32`), but this [will not work] for the 217 | /// capacity. 218 | /// 219 | /// [will not work]: https://github.com/rust-lang/rust/issues/70754 220 | pub const fn new() -> Self { 221 | Arrav { 222 | ts: [T::SENTINEL; N], 223 | } 224 | } 225 | 226 | /// Constructs a new `Arrav` and fills it with copies of `e`. 227 | /// 228 | /// You will generally want to specify the capacity of the `Arrav` when you construct it: 229 | /// 230 | /// ``` 231 | /// # #![allow(unused_mut)] 232 | /// # use arrav::Arrav; 233 | /// let mut av: Arrav<_, 4> = Arrav::repeat(3).unwrap(); 234 | /// ``` 235 | // TODO: this can be const once we can match against associated consts 236 | pub fn repeat(e: T) -> Result> 237 | where 238 | T: Copy, 239 | { 240 | match e { 241 | e if e == T::SENTINEL => Err(errors::IsSentinel(e)), 242 | _ => Ok(Arrav { ts: [e; N] }), 243 | } 244 | } 245 | 246 | // TODO: one day this can be const, and then we make it pub 247 | pub(crate) fn from_array(arr: [T; N]) -> Result)> { 248 | for t in &arr { 249 | if t == &T::SENTINEL { 250 | return Err((arr, errors::IsSentinel(*t))); 251 | } 252 | } 253 | Ok(Self { ts: arr }) 254 | } 255 | } 256 | 257 | impl Arrav 258 | where 259 | T: Copy, 260 | [T; N]: core::array::LengthAtMost32, 261 | { 262 | /// Constructs a new `Arrav` directly from a backing array. 263 | /// 264 | /// # Safety 265 | /// 266 | /// This method does not check that `T::SENTINEL` only appears in a suffix of the array's 267 | /// elements. If it appears elsewhere, methods will do strange things. 268 | pub const unsafe fn from_array_unchecked(arr: [T; N]) -> Self { 269 | Self { ts: arr } 270 | } 271 | } 272 | 273 | // === meta === 274 | 275 | impl Arrav 276 | where 277 | T: Copy, 278 | [T; N]: core::array::LengthAtMost32, 279 | { 280 | /// Returns the number of elements the `Arrav` can hold without 281 | /// reallocating. 282 | /// 283 | /// # Examples 284 | /// 285 | /// ``` 286 | /// # use arrav::Arrav; 287 | /// let av: Arrav = Arrav::new(); 288 | /// assert_eq!(av.capacity(), 10); 289 | /// ``` 290 | pub const fn capacity(&self) -> usize { 291 | N 292 | } 293 | } 294 | 295 | impl Arrav 296 | where 297 | T: Copy + Sentinel, 298 | [T; N]: core::array::LengthAtMost32, 299 | { 300 | /// Returns the number of elements in the `Arrav`, also referred to 301 | /// as its 'length'. 302 | /// 303 | /// Since the `Arrav` does not store the number of non-sentinel elements, it must search the 304 | /// elements of the backing array for the first sentinel in order to compute the length. This 305 | /// should be very fast for small `N`, but may become a bottleneck at large `N`. 306 | /// 307 | /// # Examples 308 | /// 309 | /// ``` 310 | /// let av = arrav::avec![1, 2, 3]; 311 | /// assert_eq!(av.len(), 3); 312 | /// ``` 313 | #[inline] 314 | pub fn len(&self) -> usize 315 | where 316 | Self: SpecializedLen, 317 | { 318 | self.fast_len() 319 | } 320 | 321 | /// Returns `true` if the `Arrav` contains no elements. 322 | /// 323 | /// # Examples 324 | /// 325 | /// ``` 326 | /// # use arrav::Arrav; 327 | /// let mut v: Arrav<_, 4> = Arrav::new(); 328 | /// assert!(v.is_empty()); 329 | /// 330 | /// v.try_push(1).unwrap(); 331 | /// assert!(!v.is_empty()); 332 | /// ``` 333 | // TODO: this can be const once we can match on SENTINEL 334 | pub fn is_empty(&self) -> bool { 335 | N == 0 || self.ts[0] == T::SENTINEL 336 | } 337 | 338 | /// Returns an iterator over the elements. 339 | /// 340 | /// # Examples 341 | /// 342 | /// ``` 343 | /// # use arrav::avec; 344 | /// let x = avec![1, 2, 4]; 345 | /// let mut iterator = x.iter(); 346 | /// 347 | /// assert_eq!(iterator.next(), Some(1)); 348 | /// assert_eq!(iterator.next(), Some(2)); 349 | /// assert_eq!(iterator.next(), Some(4)); 350 | /// assert_eq!(iterator.next(), None); 351 | /// ``` 352 | pub const fn iter(&self) -> iter::ArravIter { 353 | iter::ArravIter::new(*self) 354 | } 355 | } 356 | 357 | // === accessors === 358 | 359 | impl Arrav 360 | where 361 | T: Copy + Sentinel, 362 | [T; N]: core::array::LengthAtMost32, 363 | { 364 | /// Gets a reference to the element at position `index`. 365 | /// 366 | /// Returns `None` if `index` is greater than or equal to the arrav's [length](len). 367 | #[inline] 368 | // TODO: once we can match on SENTINEL, this can be const 369 | pub fn get(&self, index: usize) -> Option<&T> { 370 | if index >= self.capacity() { 371 | None 372 | } else { 373 | match unsafe { self.ts.get_unchecked(index) } { 374 | t if *t == T::SENTINEL => None, 375 | t => Some(t), 376 | } 377 | } 378 | } 379 | 380 | /// Gets a reference to the slice of elements whose indices fall in the given range. 381 | /// 382 | /// Returns `None` if the range does not fall within the bounds of the `Arrav`. 383 | #[inline] 384 | pub fn get_range(&self, index: ops::Range) -> Option<&[T]> { 385 | if index.start > index.end 386 | || index.end > self.capacity() 387 | || (index.end != 0 && *unsafe { self.get_unchecked(index.end - 1) } == T::SENTINEL) 388 | { 389 | None 390 | } else { 391 | unsafe { Some(self.get_unchecked_range(index)) } 392 | } 393 | } 394 | 395 | /// Sets the value at `index` to `value`. 396 | /// 397 | /// Returns an error if `value` is the [sentinel value](Sentinel). 398 | /// 399 | /// # Panics 400 | /// 401 | /// Panics if `index` is outside the bounds of the `Arrav`. 402 | #[inline] 403 | // TODO: once we can match on SENTINEL, this can be const 404 | pub fn set(&mut self, index: usize, value: T) -> Result<(), errors::IsSentinel> { 405 | if value == T::SENTINEL { 406 | return Err(errors::IsSentinel(value)); 407 | } 408 | 409 | if index >= self.capacity() { 410 | errors::index_len_fail(index, self.len()); 411 | } else { 412 | match unsafe { self.ts.get_unchecked_mut(index) } { 413 | ot if *ot == T::SENTINEL => { 414 | errors::index_len_fail(index, self.len()); 415 | } 416 | ot => { 417 | *ot = value; 418 | } 419 | } 420 | } 421 | 422 | Ok(()) 423 | } 424 | } 425 | 426 | // === mutators === 427 | 428 | impl Arrav 429 | where 430 | T: Copy + Sentinel, 431 | [T; N]: core::array::LengthAtMost32, 432 | { 433 | /// Appends an element to the back of the `Arrav`. 434 | /// 435 | /// Returns `Err` if the provided value is `T`'s [sentinel value], or if the `Arrav` is already 436 | /// full. 437 | /// 438 | /// [sentinel value](Sentinel) 439 | /// 440 | /// # Examples 441 | /// 442 | /// ``` 443 | /// # use arrav::Arrav; 444 | /// let mut av: Arrav = Arrav::new(); 445 | /// av.try_push(1).unwrap(); 446 | /// av.try_push(2).unwrap(); 447 | /// assert_eq!(av, [1, 2]); 448 | /// 449 | /// // this fails since it is pushing the sentinel value 450 | /// av.try_push(std::i32::MAX).unwrap_err(); 451 | /// 452 | /// // this fills the arrav to capacity 453 | /// av.try_push(3).unwrap(); 454 | /// 455 | /// // this fails since the arrav is full 456 | /// av.try_push(4).unwrap_err(); 457 | /// ``` 458 | #[inline] 459 | pub fn try_push(&mut self, t: T) -> Result<(), errors::PushError> { 460 | if t == T::SENTINEL { 461 | return Err(errors::PushError { 462 | kind: errors::PushErrorKind::IsSentinel, 463 | item: t, 464 | }); 465 | } 466 | let i = self.len(); 467 | if i == self.capacity() { 468 | Err(errors::PushError { 469 | kind: errors::PushErrorKind::Full, 470 | item: t, 471 | }) 472 | } else { 473 | debug_assert!(self.ts[i] == T::SENTINEL); 474 | debug_assert!(i == 0 || self.ts[i - 1] != T::SENTINEL); 475 | self.ts[i] = t; 476 | Ok(()) 477 | } 478 | } 479 | 480 | /// Removes the last element from the `Arrav` and returns it, or [`None`] if it 481 | /// is empty. 482 | /// 483 | /// # Examples 484 | /// 485 | /// ``` 486 | /// # use arrav::avec; 487 | /// let mut av = avec![1, 2, 3]; 488 | /// assert_eq!(av.pop(), Some(3)); 489 | /// assert_eq!(av, [1, 2]); 490 | /// assert_eq!(av.pop(), Some(2)); 491 | /// assert_eq!(av.pop(), Some(1)); 492 | /// assert_eq!(av.pop(), None); 493 | /// ``` 494 | #[inline] 495 | pub fn pop(&mut self) -> Option { 496 | let i = self.len(); 497 | if i == 0 { 498 | None 499 | } else { 500 | let i = i - 1; 501 | debug_assert!(self.ts[i] != T::SENTINEL); 502 | debug_assert!(i == self.capacity() - 1 || self.ts[i + 1] == T::SENTINEL); 503 | Some(core::mem::replace(&mut self.ts[i], T::SENTINEL)) 504 | } 505 | } 506 | 507 | /// Clears the `Arrav`, removing all values. 508 | /// 509 | /// Note that this method has no effect on the allocated capacity 510 | /// of the `Arrav`. 511 | /// 512 | /// # Examples 513 | /// 514 | /// ``` 515 | /// # use arrav::avec; 516 | /// let mut v = avec![1, 2, 3]; 517 | /// 518 | /// v.clear(); 519 | /// 520 | /// assert!(v.is_empty()); 521 | /// ``` 522 | pub fn clear(&mut self) { 523 | for i in 0..self.capacity() { 524 | match unsafe { self.get_unchecked_mut(i) } { 525 | t if t == &T::SENTINEL => break, 526 | t => *t = T::SENTINEL, 527 | } 528 | } 529 | } 530 | 531 | /// Increases the capacity of an `Arrav` by moving to a larger backing array. 532 | /// 533 | /// # Examples 534 | /// 535 | /// ``` 536 | /// # use arrav::{Arrav, avec}; 537 | /// let v = avec![1]; 538 | /// assert_eq!(v.capacity(), 1); 539 | /// let v: Arrav<_, 3> = v.expand(); 540 | /// assert_eq!(v.capacity(), 3); 541 | /// ``` 542 | /// 543 | /// # Panics 544 | /// 545 | /// Panics if `N2 < N`. 546 | /// 547 | /// ```no_run,should_panic 548 | /// # // this is no_run since tarpaulin can't handle should_panic doctests 549 | /// # use arrav::{Arrav, avec}; 550 | /// let v = avec![1, 2, 3]; 551 | /// assert_eq!(v.capacity(), 3); 552 | /// let v: Arrav<_, 1> = v.expand(); 553 | /// ``` 554 | // TODO: one day, this can be const, and the should_panic above can be compile_fail 555 | #[inline] 556 | pub fn expand(self) -> Arrav 557 | where 558 | [T; N2]: core::array::LengthAtMost32, 559 | { 560 | assert!( 561 | N2 >= N, 562 | "cannot expand from {} into smaller array {}", 563 | N, 564 | N2 565 | ); 566 | 567 | let mut new: Arrav = Arrav::new(); 568 | // safety: N2 > N 569 | unsafe { core::intrinsics::copy_nonoverlapping(self.ts.as_ptr(), new.ts.as_mut_ptr(), N) }; 570 | new 571 | } 572 | 573 | /// Resizes the `Arrav` in-place so that `len` is equal to `new_len`. 574 | /// 575 | /// If `new_len` is greater than `len`, the `Arrav` is extended by the 576 | /// difference, with each additional slot filled with `value`. 577 | /// If `new_len` is less than `len`, the `Arrav` is simply truncated. 578 | /// 579 | /// # Examples 580 | /// 581 | /// ``` 582 | /// # use arrav::{Arrav, avec}; 583 | /// let mut v: Arrav<_, 3> = avec![1].expand(); 584 | /// v.resize(3, 2); 585 | /// assert_eq!(v, [1, 2, 2]); 586 | /// 587 | /// let mut v = avec![1, 2, 3, 4]; 588 | /// v.resize(2, 0); 589 | /// assert_eq!(v, [1, 2]); 590 | /// ``` 591 | pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), errors::IsSentinel> { 592 | assert!( 593 | new_len <= self.capacity(), 594 | "asked to resize beyond capacity" 595 | ); 596 | if value == T::SENTINEL { 597 | return Err(errors::IsSentinel(value)); 598 | } 599 | // set everything before new_len 600 | for i in 0..new_len { 601 | let t = unsafe { self.ts.get_unchecked_mut(i) }; 602 | if *t == T::SENTINEL { 603 | *t = value; 604 | } 605 | } 606 | // clear everything beyond new_len 607 | for i in new_len..self.capacity() { 608 | let t = unsafe { self.ts.get_unchecked_mut(i) }; 609 | if *t == T::SENTINEL { 610 | break; 611 | } 612 | *t = T::SENTINEL; 613 | } 614 | 615 | Ok(()) 616 | } 617 | 618 | /// Creates an `Arrav` from an iterator. 619 | /// 620 | /// Returns `Err` if one of the values in the iterator is the sentinel value. 621 | /// 622 | /// # Panics 623 | /// 624 | /// Panics if the iterator yields more than `N` elements. 625 | /// 626 | /// # Examples 627 | /// 628 | /// ``` 629 | /// # use arrav::{Arrav, avec}; 630 | /// use std::iter::FromIterator; 631 | /// let five_fives = std::iter::repeat(5).take(5); 632 | /// let v: Arrav<_, 5> = Arrav::try_from_iter(five_fives).unwrap(); 633 | /// assert_eq!(v, avec![5, 5, 5, 5, 5]); 634 | /// 635 | /// Arrav::<_, 1>::try_from_iter(std::iter::once(std::i32::MAX)).unwrap_err(); 636 | /// ``` 637 | pub fn try_from_iter(iter: I) -> Result> 638 | where 639 | I: IntoIterator, 640 | { 641 | let mut v = Arrav::new(); 642 | let iter = iter.into_iter(); 643 | for (i, t) in iter.enumerate() { 644 | if i == v.capacity() { 645 | panic!("iterator does not fit in Arrav<_, {}>", N) 646 | } else if t == T::SENTINEL { 647 | return Err(errors::IsSentinel(t)); 648 | } else { 649 | v.ts[i] = t; 650 | } 651 | } 652 | Ok(v) 653 | } 654 | 655 | /// Extends an `Arrav` with elements from an iterator. 656 | /// 657 | /// Returns `Err` if one of the values in the iterator is the sentinel value. The values 658 | /// yielded by the iterator _before_ the sentinel value are still pushed. 659 | /// 660 | /// # Panics 661 | /// 662 | /// Panics if the capacity of the `Arrav` is exceeded. 663 | /// 664 | /// # Examples 665 | /// 666 | /// ``` 667 | /// # use arrav::{Arrav, avec}; 668 | /// let mut v: Arrav<_, 5> = Arrav::new(); 669 | /// v.try_push(1).unwrap(); 670 | /// v.try_extend(vec![2, 3, 4]).unwrap(); 671 | /// assert_eq!(v, avec![1, 2, 3, 4]); 672 | /// 673 | /// v.try_extend(vec![5, std::i32::MAX]).unwrap_err(); 674 | /// assert_eq!(v, avec![1, 2, 3, 4, 5]); 675 | /// ``` 676 | pub fn try_extend(&mut self, iter: I) -> Result<(), errors::IsSentinel> 677 | where 678 | I: IntoIterator, 679 | { 680 | let start = self.len(); 681 | let iter = iter.into_iter(); 682 | for (i, t) in iter.enumerate() { 683 | if i == self.capacity() { 684 | panic!("iterator does not fit in Arrav<_, {}>", N) 685 | } else if t == T::SENTINEL { 686 | return Err(errors::IsSentinel(t)); 687 | } else { 688 | self.ts[start + i] = t; 689 | } 690 | } 691 | Ok(()) 692 | } 693 | 694 | /// Removes an element from the `Arrav` and returns it. 695 | /// 696 | /// The removed element is replaced by the last element of the `Arrav`. 697 | /// 698 | /// This does not preserve ordering, but is O(1). 699 | /// 700 | /// # Panics 701 | /// 702 | /// Panics if `index` is out of bounds. 703 | /// 704 | /// # Examples 705 | /// 706 | /// ``` 707 | /// # use arrav::avec; 708 | /// let mut v = avec![1, 2, 3, 4]; 709 | /// 710 | /// assert_eq!(v.swap_remove(1), 2); 711 | /// assert_eq!(v, [1, 4, 3]); 712 | /// 713 | /// assert_eq!(v.swap_remove(0), 1); 714 | /// assert_eq!(v, [3, 4]); 715 | /// ``` 716 | pub fn swap_remove(&mut self, index: usize) -> T { 717 | let t = *self.get(index).unwrap_or_else(|| { 718 | errors::index_len_fail(index, self.len()); 719 | }); 720 | 721 | // find last element to swap with 722 | // starting at index because we know it exists 723 | let mut end = index; 724 | let mut lastt = &t; 725 | while end + 1 < self.capacity() { 726 | let t = unsafe { self.ts.get_unchecked(end + 1) }; 727 | if t == &T::SENTINEL { 728 | break; 729 | } 730 | lastt = t; 731 | end += 1; 732 | } 733 | 734 | if end == index { 735 | // index is last element, so just remove it 736 | *unsafe { self.ts.get_unchecked_mut(index) } = T::SENTINEL; 737 | } else { 738 | // place @end at @index, then delete @end 739 | let lastt = *lastt; 740 | *unsafe { self.ts.get_unchecked_mut(index) } = lastt; 741 | *unsafe { self.ts.get_unchecked_mut(end) } = T::SENTINEL; 742 | } 743 | t 744 | } 745 | } 746 | 747 | // === unsafe accessors === 748 | 749 | impl Arrav 750 | where 751 | T: Copy + Sentinel, 752 | [T; N]: core::array::LengthAtMost32, 753 | { 754 | /// Gets a reference to the element at position `index`. 755 | /// 756 | /// # Safety 757 | /// 758 | /// This method does not perform any bounds checks or sentinel checks on the index. 759 | #[inline] 760 | pub unsafe fn get_unchecked(&self, index: usize) -> &T { 761 | self.ts.get_unchecked(index) 762 | } 763 | 764 | /// Gets a reference to the slice of elements whose indices fall in the given range. 765 | /// 766 | /// # Safety 767 | /// 768 | /// This method does not perform any bounds checks or sentinel checks on the index. 769 | #[inline] 770 | pub unsafe fn get_unchecked_range(&self, index: ops::Range) -> &[T] { 771 | self.ts.get_unchecked(index) 772 | } 773 | 774 | /// Gets an exclusive reference to the element at position `index`. 775 | /// 776 | /// This method _does_ perform bounds and sentinel checks. 777 | /// 778 | /// # Safety 779 | /// 780 | /// This method is unsafe, because you must ensure that you do not use the returned reference 781 | /// to overwrite the `T` with `T`'s sentinel value. 782 | #[inline] 783 | pub unsafe fn get_mut(&mut self, index: usize) -> Option<&mut T> { 784 | if index >= self.capacity() { 785 | None 786 | } else { 787 | match self.ts.get_unchecked_mut(index) { 788 | t if *t == T::SENTINEL => None, 789 | t => Some(t), 790 | } 791 | } 792 | } 793 | 794 | /// Gets an exclusive reference to the element at position `index`. 795 | /// 796 | /// # Safety 797 | /// 798 | /// This method does not perform bounds or sentinel checks. 799 | /// 800 | /// Like [`get_mut`], this method is also unsafe because you must ensure that you do not use 801 | /// the returned reference to overwrite the `T` with `T`'s sentinel value. 802 | #[inline] 803 | pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T { 804 | self.ts.get_unchecked_mut(index) 805 | } 806 | } 807 | 808 | // === specializations === 809 | 810 | // The performance of `Arrav::len` is key to the performance of `Arrav`, so we want to provide 811 | // optimized versions of it wherever we can. Even limited specialization lets us do that: 812 | 813 | #[doc(hidden)] 814 | pub trait SpecializedLen { 815 | fn fast_len(&self) -> usize; 816 | } 817 | 818 | // Provide a fall-back that always applies 819 | impl Arrav 820 | where 821 | T: Copy + Sentinel, 822 | [T; N]: core::array::LengthAtMost32, 823 | { 824 | #[inline] 825 | fn slow_len(&self) -> usize { 826 | match N { 827 | 0 => 0, 828 | 1 => { 829 | if self.ts[0] == T::SENTINEL { 830 | 0 831 | } else { 832 | 1 833 | } 834 | } 835 | _ => self.ts.iter().position(|v| *v == T::SENTINEL).unwrap_or(N), 836 | } 837 | } 838 | } 839 | 840 | impl SpecializedLen for Arrav 841 | where 842 | T: Copy + Sentinel, 843 | [T; N]: core::array::LengthAtMost32, 844 | { 845 | #[cfg(not(feature = "specialization"))] 846 | #[inline] 847 | fn fast_len(&self) -> usize { 848 | self.slow_len() 849 | } 850 | 851 | #[cfg(feature = "specialization")] 852 | #[inline] 853 | default fn fast_len(&self) -> usize { 854 | self.slow_len() 855 | } 856 | } 857 | 858 | macro_rules! specialize { 859 | ($t:ty, $width:expr, $splits:expr, $test:ident) => { 860 | #[cfg(feature = "specialization")] 861 | impl SpecializedLen for Arrav<$t, $width> { 862 | #[inline] 863 | fn fast_len(&self) -> usize { 864 | // binary search for the sentinel 865 | // it'd be nice to use slice::binary_search here, but it could find _any_ sentinel 866 | // value, which isn't very helpful. maybe we could search for SENTINEL - 1, and 867 | // then scan forward, but that gets tricky _fast_. 868 | let empty_at = |i| *unsafe { self.ts.get_unchecked(i) } == <$t>::SENTINEL; 869 | if empty_at($width / 2) { 870 | // len must be < $width/2 871 | if $splits == 1 { 872 | 0 + unsafe { self.ts.get_unchecked(0..($width/2)) } 873 | .iter() 874 | .position(|v| *v == <$t>::SENTINEL).unwrap_or($width / 2) 875 | } else { 876 | if empty_at($width / 4) { 877 | // len must be < $width/4 878 | 0 + unsafe { self.ts.get_unchecked(0..($width/4)) } 879 | .iter() 880 | .position(|v| *v == <$t>::SENTINEL).unwrap_or($width / 4) 881 | } else { 882 | // len must be => $width/4 < $width/2 883 | ($width / 4) + unsafe { self.ts.get_unchecked(($width/4)..($width/2)) } 884 | .iter() 885 | .position(|v| *v == <$t>::SENTINEL).unwrap_or($width / 4) 886 | } 887 | } 888 | } else { 889 | // len must be >= $width/2 890 | if $splits == 1 { 891 | ($width / 2) + unsafe { self.ts.get_unchecked(($width/2)..$width) } 892 | .iter() 893 | .position(|v| *v == <$t>::SENTINEL).unwrap_or($width / 2) 894 | } else { 895 | if empty_at(3 * $width / 4) { 896 | // len must be < 3*$width/4 897 | ($width / 2) + unsafe { self.ts.get_unchecked(($width/2)..(3*$width/4)) } 898 | .iter() 899 | .position(|v| *v == <$t>::SENTINEL).unwrap_or($width / 4) 900 | } else { 901 | // len must be => 3*$width/4 902 | (3 * $width / 4) + unsafe { self.ts.get_unchecked((3*$width/4)..$width) } 903 | .iter() 904 | .position(|v| *v == <$t>::SENTINEL).unwrap_or($width / 4) 905 | } 906 | } 907 | } 908 | } 909 | } 910 | 911 | #[cfg(test)] 912 | mod $test { 913 | use super::*; 914 | 915 | #[cfg_attr(not(feature = "specialization"), test)] 916 | fn test_len() { 917 | let mut v: Arrav<$t, $width> = avec![1; $width]; 918 | for removed in 0..$width { 919 | assert_eq!(v.len(), $width - removed); 920 | assert_eq!(v.pop(), Some(1)); 921 | } 922 | assert_eq!(v.len(), 0); 923 | assert!(v.is_empty()); 924 | assert_eq!(v.pop(), None); 925 | } 926 | 927 | #[cfg(feature = "specialization")] 928 | #[test] 929 | fn test_specialized_len() { 930 | test_len() 931 | } 932 | } 933 | } 934 | } 935 | 936 | // NOTE: don't add a specialization just because it looks cool! 937 | // here's what you do: 938 | // 939 | // 1. add a specialize!() call below for the [T, N] you have in mind. 940 | // 2. add a benchmark to benches/len.rs -- the format should hopefully be obvious. 941 | // 3. run this command to benchmark the non-specialized versions of `len`: 942 | // ```console 943 | // $ cargo bench --no-default-features --features std --bench len -- --save-baseline unoptimized 944 | // ``` 945 | // 4. run this command to benchmark the specialized version and compare to the baseline: 946 | // ```console 947 | // $ cargo bench --bench len -- --baseline unoptimized 948 | // ``` 949 | // 5. look for the "len " benchmark for the specialization you added. 950 | // 6. if the change seems significant, make a commit that contains the output from 951 | // step 4 for your new specialization in the commit message. please place the 952 | // criterion output in a fenced code block (```), check that you don't 953 | // accidentally have any tabs in there, and check that the output is correctly 954 | // aligned. 955 | // 7. repeat if you want to add more specializations. 956 | 957 | specialize!(u8, 32, 2, u8_32); 958 | specialize!(u8, 24, 2, u8_24); 959 | specialize!(u8, 16, 2, u8_16); 960 | specialize!(u16, 16, 2, u16_16); 961 | specialize!(u16, 8, 2, u16_8); 962 | specialize!(u16, 4, 1, u16_4); 963 | specialize!(u32, 8, 2, u32_8); 964 | specialize!(u32, 4, 1, u32_4); 965 | 966 | // copies of the above for signed types, assuming the same benchmark results hold 967 | specialize!(i8, 32, 2, i8_32); 968 | specialize!(i8, 24, 2, i8_24); 969 | specialize!(i8, 16, 2, i8_16); 970 | specialize!(i16, 16, 2, i16_16); 971 | specialize!(i16, 8, 2, i16_8); 972 | specialize!(i16, 4, 1, i16_4); 973 | specialize!(i32, 8, 2, i32_8); 974 | specialize!(i32, 4, 1, i32_4); 975 | 976 | macro_rules! impl_sentinel_by_max { 977 | ($t:tt) => { 978 | impl Sentinel for $t { 979 | const SENTINEL: Self = ::core::$t::MAX; 980 | } 981 | }; 982 | } 983 | 984 | impl_sentinel_by_max!(u8); 985 | impl_sentinel_by_max!(i8); 986 | impl_sentinel_by_max!(u16); 987 | impl_sentinel_by_max!(i16); 988 | impl_sentinel_by_max!(u32); 989 | impl_sentinel_by_max!(i32); 990 | impl_sentinel_by_max!(u64); 991 | impl_sentinel_by_max!(i64); 992 | impl_sentinel_by_max!(u128); 993 | impl_sentinel_by_max!(i128); 994 | impl_sentinel_by_max!(usize); 995 | impl_sentinel_by_max!(isize); 996 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | /// Creates a [`Arrav`] containing the arguments. 2 | /// 3 | /// `avec!` allows `Arrav`s to be defined with the same syntax as array expressions. 4 | /// There are two forms of this macro: 5 | /// 6 | /// - Create a [`Arrav`] containing a given list of elements: 7 | /// 8 | /// ``` 9 | /// let v = arrav::avec![1, 2, 3]; 10 | /// assert_eq!(v[0], 1); 11 | /// assert_eq!(v[1], 2); 12 | /// assert_eq!(v[2], 3); 13 | /// ``` 14 | /// 15 | /// - Create a [`Arrav`] from a given element and size: 16 | /// 17 | /// ``` 18 | /// let v = arrav::avec![1; 3]; 19 | /// assert_eq!(&*v, &[1, 1, 1]); 20 | /// ``` 21 | /// 22 | /// [`Vec`]: ../std/vec/struct.Vec.html 23 | #[macro_export] 24 | macro_rules! avec { 25 | ($elem:expr; $n:expr) => {{ 26 | #[allow(unused_imports)] 27 | use ::core::convert::TryFrom; 28 | $crate::Arrav::<_, $n>::repeat($elem).expect("cannot insert sentinel into Arrav") 29 | }}; 30 | ($($x:expr),*) => {{ 31 | #[allow(unused_imports)] 32 | use ::core::convert::TryFrom; 33 | let v = [ 34 | $({ 35 | // TODO: match on sentinel value directly when supported 36 | match $x { 37 | x if x == $crate::Sentinel::SENTINEL => panic!("cannot insert sentinel into Arrav"), 38 | x => x 39 | } 40 | }),* 41 | ]; 42 | unsafe { $crate::Arrav::<_, { $crate::avec![@count_tts ($($x),*)] }>::from_array_unchecked(v) } 43 | }}; 44 | ($($x:expr,)*) => ($crate::avec![$($x),*]); 45 | 46 | // macros for counting: 47 | // https://danielkeep.github.io/tlborm/book/blk-counting.html#slice-length 48 | // these can't be moved into the macro case below because of 49 | // https://github.com/rust-lang/rust/issues/35853 50 | (@replace_expr ($_t:expr, $sub:expr)) => {$sub}; 51 | (@count_tts ($($e:expr),*)) => {<[()]>::len(&[$($crate::avec!(@replace_expr ($e, ()))),*])}; 52 | } 53 | 54 | /// Produce an [`Arrav`] type that fits in a given container type. 55 | /// 56 | /// Using `ArravOf!`, you can easily write out an `Arrav` type that can contain as many of one type 57 | /// as fit in the size of a different type. This is better explain with examples: 58 | /// 59 | /// ``` 60 | /// #![feature(const_panic, const_if_match)] 61 | /// use arrav::{Arrav, ArravOf}; 62 | /// use std::mem::{size_of, size_of_val}; 63 | /// 64 | /// let v: ArravOf! {u64 as u8} = Arrav::new(); 65 | /// assert_eq!(size_of_val(&v), size_of::()); 66 | /// assert_eq!(v.capacity(), 64 / 8); 67 | /// 68 | /// let v: ArravOf! {usize as u8} = Arrav::new(); 69 | /// assert_eq!(size_of_val(&v), size_of::()); 70 | /// assert_eq!(v.capacity(), size_of_val(&0usize) /* bytes */ * 8 / 8); 71 | /// ``` 72 | /// 73 | /// - Create a [`Arrav`] from a given element and size: 74 | /// 75 | /// ``` 76 | /// let v = arrav::avec![1; 3]; 77 | /// assert_eq!(&*v, &[1, 1, 1]); 78 | /// ``` 79 | /// 80 | /// [`Vec`]: ../std/vec/struct.Vec.html 81 | #[macro_export] 82 | macro_rules! ArravOf { 83 | ($container:ty as $t:ty) => { 84 | $crate::Arrav<$t, { 85 | assert!(::core::mem::size_of::<$container>() >= ::core::mem::size_of::<$t>()); 86 | ::core::mem::size_of::<$container>() / ::core::mem::size_of::<$t>() 87 | }> 88 | } 89 | } 90 | 91 | #[cfg(test)] 92 | use crate::*; 93 | 94 | // test the macros in-crate so we get nice, expanded errors 95 | 96 | #[test] 97 | fn let_tiny_vec() { 98 | let v = ::new(); 99 | assert_eq!(v.len(), 0); 100 | assert_eq!(v.capacity(), 4); 101 | assert!(v.is_empty()); 102 | } 103 | 104 | #[test] 105 | fn arrayof_size() { 106 | use std::mem::size_of; 107 | 108 | assert!(size_of::() <= size_of::()); 109 | assert!(size_of::() <= size_of::()); 110 | assert!(size_of::() <= size_of::()); 111 | assert!(size_of::() <= size_of::()); 112 | assert!(size_of::() <= size_of::()); 113 | assert!(size_of::() <= size_of::()); 114 | 115 | assert!(size_of::() <= size_of::()); 116 | assert!(size_of::() <= size_of::()); 117 | assert!(size_of::() <= size_of::()); 118 | assert!(size_of::() <= size_of::()); 119 | assert!(size_of::() <= size_of::()); 120 | 121 | assert!(size_of::() <= size_of::()); 122 | assert!(size_of::() <= size_of::()); 123 | assert!(size_of::() <= size_of::()); 124 | if size_of::() >= size_of::() { 125 | assert!(size_of::() <= size_of::()); 126 | } 127 | 128 | assert!(size_of::() <= size_of::()); 129 | assert!(size_of::() <= size_of::()); 130 | if size_of::() >= size_of::() { 131 | assert!(size_of::() <= size_of::()); 132 | } 133 | 134 | assert!(size_of::() <= size_of::()); 135 | } 136 | 137 | #[test] 138 | fn avec_elem() { 139 | let v0 = avec![0; 0]; 140 | assert_eq!(v0.len(), 0); 141 | assert!(v0.is_empty()); 142 | 143 | let v1 = avec![0; 1]; 144 | assert_eq!(v1.len(), 1); 145 | assert!(!v1.is_empty()); 146 | 147 | let v2 = avec![0; 2]; 148 | assert_eq!(v2.len(), 2); 149 | assert!(!v2.is_empty()); 150 | } 151 | 152 | #[test] 153 | #[should_panic] 154 | fn avec_elem_fail() { 155 | let _ = avec![std::u8::MAX; 1]; 156 | } 157 | 158 | #[test] 159 | fn avec_enum() { 160 | // NOTE: can't be Arrav b/c of https://github.com/rust-lang/rust/issues/70754 161 | let v0: Arrav = avec![]; 162 | assert_eq!(v0.len(), 0); 163 | assert!(v0.is_empty()); 164 | 165 | let v1 = avec![0]; 166 | assert_eq!(v1.len(), 1); 167 | assert_eq!(v1[0], 0); 168 | assert!(!v1.is_empty()); 169 | 170 | let v2 = avec![0, 1]; 171 | assert_eq!(v2.len(), 2); 172 | assert_eq!(v2[0], 0); 173 | assert_eq!(v2[1], 1); 174 | assert!(!v2.is_empty()); 175 | } 176 | 177 | #[test] 178 | #[should_panic] 179 | fn avec_enum_fail() { 180 | let _ = avec![std::u8::MAX]; 181 | } 182 | 183 | /// ```compile_fail 184 | /// #![feature(const_if_match, const_panic)] 185 | /// // fail to compile if T does not fit in container type 186 | /// let _ = std::mem::size_of::(); 187 | /// ``` 188 | #[allow(dead_code)] 189 | struct NotOk; 190 | -------------------------------------------------------------------------------- /src/traits.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use core::convert::TryFrom; 3 | use core::ops::Index; 4 | use core::{fmt, ops}; 5 | 6 | // === constructors === 7 | 8 | impl Default for Arrav 9 | where 10 | T: Copy + Sentinel, 11 | [T; N]: core::array::LengthAtMost32, 12 | { 13 | fn default() -> Self { 14 | Self::new() 15 | } 16 | } 17 | 18 | impl TryFrom<[T; N]> for Arrav 19 | where 20 | T: Copy + Sentinel, 21 | [T; N]: core::array::LengthAtMost32, 22 | { 23 | type Error = ([T; N], self::errors::IsSentinel); 24 | fn try_from(arr: [T; N]) -> Result { 25 | Self::from_array(arr) 26 | } 27 | } 28 | 29 | impl core::iter::FromIterator for Arrav 30 | where 31 | T: Copy + Sentinel, 32 | [T; N]: core::array::LengthAtMost32, 33 | { 34 | fn from_iter(iter: I) -> Self 35 | where 36 | I: IntoIterator, 37 | { 38 | let mut v = Arrav::new(); 39 | v.extend(iter); 40 | v 41 | } 42 | } 43 | 44 | impl core::iter::Extend for Arrav 45 | where 46 | T: Copy + Sentinel, 47 | [T; N]: core::array::LengthAtMost32, 48 | { 49 | fn extend(&mut self, iter: I) 50 | where 51 | I: IntoIterator, 52 | { 53 | let start = self.len(); 54 | let iter = iter.into_iter(); 55 | for (i, t) in iter.enumerate() { 56 | if i == self.capacity() { 57 | panic!("iterator does not fit in Arrav<_, {}>", N) 58 | } else if t == T::SENTINEL { 59 | panic!("iterator produced sentinel value") 60 | } else { 61 | self.ts[start + i] = t; 62 | } 63 | } 64 | } 65 | } 66 | 67 | // === printers === 68 | 69 | impl fmt::Debug for Arrav 70 | where 71 | T: Copy + Sentinel, 72 | [T; N]: core::array::LengthAtMost32, 73 | { 74 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 75 | f.debug_list().entries(self.iter()).finish() 76 | } 77 | } 78 | 79 | // === derefs === 80 | 81 | impl AsRef<[T]> for Arrav 82 | where 83 | T: Copy + Sentinel, 84 | [T; N]: core::array::LengthAtMost32, 85 | { 86 | fn as_ref(&self) -> &[T] { 87 | let len = self.len(); 88 | &self.ts[..len] 89 | } 90 | } 91 | 92 | impl core::ops::Deref for Arrav 93 | where 94 | T: Copy + Sentinel, 95 | [T; N]: core::array::LengthAtMost32, 96 | { 97 | type Target = [T]; 98 | fn deref(&self) -> &Self::Target { 99 | let len = Self::len(self); 100 | &self.ts[..len] 101 | } 102 | } 103 | 104 | // NOTE: we cannot safely implement DerefMut or IndexMut, since the user might override 105 | // the value with the sentinel, which would invalidate the data structure's integrity! 106 | 107 | impl PartialEq> for Arrav 108 | where 109 | T: PartialEq + Copy + Sentinel, 110 | [T; N1]: core::array::LengthAtMost32, 111 | [T; N2]: core::array::LengthAtMost32, 112 | { 113 | fn eq(&self, rhs: &Arrav) -> bool { 114 | let mut rhs = rhs.iter(); 115 | for t in self.iter() { 116 | match rhs.next() { 117 | Some(rhs) if rhs == t => {} 118 | _ => return false, 119 | } 120 | } 121 | rhs.next().is_none() 122 | } 123 | } 124 | 125 | impl Eq for Arrav 126 | where 127 | T: Eq + Copy + Sentinel, 128 | [T; N]: core::array::LengthAtMost32, 129 | { 130 | } 131 | 132 | impl PartialOrd> for Arrav 133 | where 134 | T: PartialOrd + Copy + Sentinel, 135 | [T; N1]: core::array::LengthAtMost32, 136 | [T; N2]: core::array::LengthAtMost32, 137 | { 138 | fn partial_cmp(&self, other: &Arrav) -> Option { 139 | self.iter().partial_cmp(other.iter()) 140 | } 141 | } 142 | 143 | impl Ord for Arrav 144 | where 145 | T: Ord + Copy + Sentinel, 146 | [T; N]: core::array::LengthAtMost32, 147 | { 148 | fn cmp(&self, other: &Self) -> core::cmp::Ordering { 149 | self.iter().cmp(other.iter()) 150 | } 151 | } 152 | 153 | impl PartialEq<[T]> for Arrav 154 | where 155 | T: Copy + Sentinel, 156 | [T; N]: core::array::LengthAtMost32, 157 | { 158 | fn eq(&self, rhs: &[T]) -> bool { 159 | if rhs.len() > N { 160 | // can't possibly be == 161 | return false; 162 | } 163 | 164 | let mut rhs = rhs.iter(); 165 | for t in self.iter() { 166 | match rhs.next() { 167 | Some(rhs) if rhs == &t => {} 168 | _ => return false, 169 | } 170 | } 171 | rhs.next().is_none() 172 | } 173 | } 174 | 175 | impl PartialEq<[T; AN]> for Arrav 176 | where 177 | T: Copy + Sentinel, 178 | [T; N]: core::array::LengthAtMost32, 179 | { 180 | fn eq(&self, rhs: &[T; AN]) -> bool { 181 | self == &rhs[..] 182 | } 183 | } 184 | 185 | // === accessors === 186 | 187 | impl Index for Arrav 188 | where 189 | T: Copy + Sentinel, 190 | [T; N]: core::array::LengthAtMost32, 191 | { 192 | type Output = T; 193 | fn index(&self, idx: usize) -> &Self::Output { 194 | self.get(idx) 195 | .unwrap_or_else(move || errors::index_len_fail(idx, self.len())) 196 | } 197 | } 198 | 199 | impl Index> for Arrav 200 | where 201 | T: Copy + Sentinel, 202 | [T; N]: core::array::LengthAtMost32, 203 | { 204 | type Output = [T]; 205 | fn index(&self, idx: ops::Range) -> &Self::Output { 206 | if idx.start > idx.end { 207 | errors::index_order_fail(idx.start, idx.end) 208 | } else if idx.end > self.capacity() 209 | || (idx.end != 0 && *unsafe { self.get_unchecked(idx.end - 1) } == T::SENTINEL) 210 | { 211 | errors::index_len_fail(idx.end, self.len()) 212 | } 213 | unsafe { self.get_unchecked_range(idx) } 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /tests/main.rs: -------------------------------------------------------------------------------- 1 | use arrav::Arrav; 2 | 3 | #[test] 4 | fn basics() { 5 | let mut v: Arrav = Default::default(); 6 | assert_eq!(v.len(), 0); 7 | assert_eq!(v.capacity(), 4); 8 | assert!(v.is_empty()); 9 | 10 | v.try_push(0).unwrap(); 11 | } 12 | --------------------------------------------------------------------------------