├── rust-toolchain.toml ├── .gitignore ├── .github └── workflows │ └── validate-commit.yml ├── tests └── issue_13_tailing_comman.rs ├── LICENSE-MIT ├── CONTRIBUTORS.md ├── Cargo.toml ├── README.md ├── CHANGELOG.md ├── LICENSE-APACHE └── src ├── smallvec_v1.rs ├── shared.rs └── lib.rs /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.71.1" 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | .idea/ 4 | .vscode/ 5 | *.iml 6 | **/*.rs.bk 7 | -------------------------------------------------------------------------------- /.github/workflows/validate-commit.yml: -------------------------------------------------------------------------------- 1 | name: validate commit 2 | 3 | on: [push] 4 | 5 | env: 6 | CARGO_TERM_COLOR: always 7 | 8 | jobs: 9 | 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - run: cargo test --no-default-features --verbose 15 | - run: cargo test --verbose 16 | - run: cargo test --all-features --verbose 17 | -------------------------------------------------------------------------------- /tests/issue_13_tailing_comman.rs: -------------------------------------------------------------------------------- 1 | //! [Issue 13: vec1! macro doesn't accept trailing comma](https://github.com/rustonaut/vec1/issues/13) 2 | //! 3 | 4 | #[macro_use] 5 | extern crate vec1; 6 | 7 | #[test] 8 | fn allow_trailing_comma_in_vec_macro() { 9 | let _ = vec1![1u8,]; 10 | let _ = vec1![1u8, 2u8,]; 11 | let _ = vec1![1u8, 2u8, 3u8,]; 12 | } 13 | 14 | #[test] 15 | fn allow_no_trailing_comma_in_vec_macro() { 16 | let _ = vec1![1u8]; 17 | let _ = vec1![1u8, 2u8]; 18 | let _ = vec1![1u8, 2u8, 3u8]; 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2021 Philipp Korber 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributors 3 | 4 | @name refers to the github nickname. 5 | 6 | Names sorted alphabetically by github nickname. 7 | Contributions ordered by PR number. 8 | 9 | ## Ben Schulz @benschulz 10 | 11 | - [Relax lifetime constraints on mapped_ref and mapped_mut](https://github.com/rustonaut/vec1/pull/30) 12 | 13 | ## dahlbaek @dahlbaek 14 | 15 | - [Reduce rust-version to 1.71.1](https://github.com/rustonaut/vec1/pull/34) 16 | 17 | ## eignnx @eignnx 18 | 19 | - [mention serde support in README](https://github.com/rustonaut/vec1/pull/16) 20 | 21 | ## Erich Gubler @ErichDonGubler 22 | 23 | - [Remove feature flag around `TryFrom`, now that it's landed in Rust 1.34.0 ](https://github.com/rustonaut/vec1/pull/9) 24 | 25 | ## Graham Christensen @grahamc 26 | 27 | - [from_vec: return None](https://github.com/rustonaut/vec1/pull/5) 28 | 29 | ## Jonas Schievink @jonas-schievink 30 | 31 | - [Documentation enhancements ](https://github.com/rustonaut/vec1/pull/3) 32 | 33 | 34 | ## Peter Kolloch @kolloch 35 | 36 | - [README.md: Fix typo in first paragraph #1](https://github.com/rustonaut/vec1/pull/1) 37 | 38 | ## Corentin Henry @little-dude 39 | 40 | - [Use fully qualified path in macro](https://github.com/rustonaut/vec1/pull/23) 41 | 42 | ## Matt Kantor @mkantor 43 | 44 | - [Basic CI workflow using GitHub actions.](https://github.com/rustonaut/vec1/pull/17) 45 | 46 | ## Michael Killough @mjkillough 47 | 48 | - [Add an optional 'serde' feature. ](https://github.com/rustonaut/vec1/pull/4) 49 | 50 | ## Robin Krahl @robinkrahl 51 | 52 | - [Fix typo in doc comment for Vec1](https://github.com/rustonaut/vec1/pull/19) 53 | - [Add split_off_{first,last} methods](https://github.com/rustonaut/vec1/pull/20) 54 | - [Fix typo in try_split_off documentation](https://github.com/rustonaut/vec1/pull/21) 55 | 56 | ## Ryan Wiedemann @Ryan1729 57 | 58 | - [implement `Default` when `T` has a default](https://github.com/rustonaut/vec1/pull/8) 59 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | version = "1.12.1" 3 | authors = ["Philipp Korber "] 4 | categories = ["data-structures"] 5 | description = "a std Vec wrapper assuring that it has at least 1 element" 6 | documentation = "https://docs.rs/vec1" 7 | keywords = ["vec", "min", "length", "1"] 8 | license = "MIT OR Apache-2.0" 9 | name = "vec1" 10 | readme = "./README.md" 11 | repository = "https://github.com/rustonaut/vec1/" 12 | edition = "2021" 13 | rust-version = "1.71.1" 14 | 15 | [features] 16 | default = ["std"] 17 | std = [] 18 | 19 | # Keep feature as to not brake code which used it in the past. 20 | # The Vec1 crate roughly traces rust stable=1 but tries to keep 21 | # as much compatiblility with older compiler versions. But it 22 | # should never require changes to older projects compiled with 23 | # a new enough rust compiler. As such this features needs to 24 | # stay in existence. 25 | unstable-nightly-try-from-impl = [] 26 | 27 | # Provide a `SmallVec1` which works like a `Vec1` but is backed by a `SmallVec` 28 | # it's explicitly v1 as I do not intend to do a braking change once v2 is released. 29 | # Enabling this crates serde features will also enable (de-)serialization for the 30 | # `SmallVec1` (but not for the `SmallVec` if not wrapped into a `SmallVec1`, this 31 | # is necessary as you can't implicitly pull in `smallvec_v1_/serde` if `serde` and 32 | # `smallvec_v1_` are enabled). 33 | # 34 | # To enable `smallvec_v1_/union` import it seperately in your crate with the 35 | # dependency enabled (and using a compatible version). In the future `union` 36 | # might be enabled by default. 37 | smallvec-v1 = ["smallvec_v1_"] 38 | 39 | # Enables the smallvec-v1/write feature 40 | smallvec-v1-write = ["std", "smallvec_v1_/write"] 41 | 42 | [dependencies] 43 | # Is a feature! 44 | serde = { version = "1.0", optional = true, features = ["derive"], default-features=false } 45 | # In the future we will support smallvec v1 and v2 so if we had 46 | # a optional dependency called smallvec people might acidentally 47 | # pull it in as feature and create anoyences wrt. backward compatibility. 48 | 49 | [dependencies.smallvec_v1_] 50 | version = "1.6.1" 51 | package = "smallvec" 52 | optional = true 53 | features = ["const_generics", "const_new"] 54 | 55 | [dev-dependencies] 56 | serde_json = "1.0" 57 | proptest = "1.0" 58 | 59 | [package.metadata.docs.rs] 60 | all-features = true 61 | rustdoc-args = ["--cfg", "docs"] 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | vec1 [![Crates.io](https://img.shields.io/crates/v/vec1.svg)](https://crates.io/crates/vec1) [![vec1](https://docs.rs/vec1/badge.svg)](https://docs.rs/vec1) [![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 2 | ============= 3 | 4 | This crate provides a rust `std::vec::Vec` wrapper with type 5 | guarantees to contain at least 1 element. This is useful if 6 | you build a API which sometimes has such constraints e.g. you 7 | need at least one target server address but there can be more. 8 | 9 | Example 10 | -------- 11 | 12 | ```rust 13 | #[macro_use] 14 | extern crate vec1; 15 | 16 | use vec1::Vec1; 17 | 18 | fn main() { 19 | // vec1![] makes sure there is at least one element 20 | // at compiler time 21 | //let names = vec1! [ ]; 22 | let names = vec1! [ "Liz" ]; 23 | greet(names); 24 | } 25 | 26 | fn greet(names: Vec1<&str>) { 27 | // methods like first/last which return a Option on Vec do 28 | // directly return the value, we know it's possible 29 | let first = names.first(); 30 | println!("hallo {}", first); 31 | for name in names.iter().skip(1) { 32 | println!(" who is also know as {}", name) 33 | } 34 | } 35 | 36 | ``` 37 | 38 | Support for `serde::{Serialize, Deserialize}` 39 | ------------- 40 | 41 | The `Vec1` type supports both of [`serde`](https://serde.rs/)'s `Serialize` and 42 | `Deserialize` traits, but this feature is only enabled when the `"serde"` feature 43 | flag is specified in your project's `Cargo.toml` file: 44 | 45 | ```toml 46 | # Cargo.toml 47 | 48 | [dependencies] 49 | vec1 = { version = "...", features = ["serde"] } 50 | ``` 51 | 52 | Building docs like on docs.rs 53 | ------------- 54 | 55 | To build docs which document all features and contains hints 56 | which functions require which features use following command: 57 | 58 | ```sh 59 | RUSTDOCFLAGS="--cfg docs" cargo +nightly doc --all-features 60 | ``` 61 | 62 | This will document all features and enable the unstable 63 | nightly only `doc_auto_cfg` feature. 64 | 65 | 66 | License 67 | -------- 68 | 69 | Licensed under either of 70 | 71 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 72 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 73 | 74 | at your option. 75 | 76 | Contribution 77 | ------------ 78 | 79 | Unless you explicitly state otherwise, any contribution intentionally submitted 80 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall 81 | be dual licensed as above, without any additional terms or conditions. 82 | 83 | Contributors: [./CONTRIBUTORS.md](./CONTRIBUTORS.md) 84 | 85 | Change Log 86 | ----------- 87 | 88 | See [./CHANGELOG.md](./CHANGELOG.md) -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | # Change Log 3 | 4 | ## Version 1.12.1 (25.05.2024) 5 | 6 | - Reduced minimal rust version to 1.71.1 7 | 8 | ## Version 1.12.0 (27.03.2024) 9 | 10 | - Added `len_nonzero`. 11 | 12 | ## Version 1.11.1 (23.03.2024) 13 | 14 | - Fix `package.rust-version` in `Cargo.toml`. 15 | 16 | ## Version 1.11.0 (23.03.2024) 17 | 18 | - Increased minimal rust version to 1.74. 19 | - Relax lifetime constraints on `{try_,}mapped_{ref,mut}`. 20 | - Added new proxy functions for `Vec` 21 | - `try_reserve` 22 | - `try_reserve_exact` 23 | - `shrink_to` 24 | - `spare_capacity_mut` 25 | - `extend_from_within` 26 | - `retain_mut` 27 | - Added missing proxy trait impls 28 | - `impl TryFrom> for Box<[T; N]>` 29 | - `impl TryFrom<&[T; N]> for Vec1 where T: Clone` 30 | - `impl TryFrom<&mut [T; N]> for Vec1 where T: Clone` 31 | - Removed no longer needed import/impl workaround. 32 | - Added multiple `_nonzero` implementations 33 | - `truncate_nonzero` 34 | - `resize_with_nonzero` 35 | - `resize_nonzero` 36 | 37 | ## Version 1.10.1 (21.10.2022) 38 | 39 | - Improved documentation by using `doc_auto_cfg` on docs.rs. 40 | 41 | ## Version 1.10.0 (21.10.2022) 42 | 43 | - Increased minimal rust version to 1.57. 44 | - Added a length>0 aware `reduce`, `reduce_ref`, `reduce_mut`. 45 | - Added `smallvec1_inline!`. 46 | - Added `SmallVec1::from_array_const()`. 47 | 48 | ## Version 1.9.0 (16.10.2022) 49 | 50 | - Increased minimal rust version to 1.56. 51 | - Added missing LICENSE-MIT,LICENSE-APACHE files. Licensing did not change. 52 | - Added `from_vec_push` and `from_vec_insert` constructors. 53 | - Use edition 2021. 54 | - Impl `TryFrom` for `[T; N]` for `Vec1`/`SmallVec1` using const generic. 55 | 56 | ## Version 1.8.0 (21.04.2021) 57 | 58 | - minimal rust version is now 1.48 59 | - updated documentation 60 | - more tests 61 | - deprecated the `try_` prefix usage as it created ambiguities with 62 | other potential `try_` versions (like try and don't panic if out of 63 | bounds or try and don't panic if allocation fails). 64 | - some missing methods and trait implementations (e.g. `drain) 65 | - fixed bug in `Vec1.splice()` which caused the code to return 66 | a `Size0Error` in a very specific edge case where it should 67 | have panicked due to a out of bounds range like `Vec.splice()` 68 | does. 69 | 70 | ## Version 1.7.0 (11.03.2021) 71 | 72 | - minimal rust version is now 1.47 73 | - support for `SmallVec1` backed by the `smallvec` crate (v>=1.6.1) 74 | - added `no_std` support (making `std` a default feature) 75 | - converted various `Into`/`TryInto` impls into `From`/`TryFrom` impls. 76 | - changes in the documentation for various reasons, some functions 77 | have now less good documentation as they are automatically implemented 78 | for both `Vec1`, and `smallvec-v1::SmallVec1`. 79 | 80 | ## Version 1.6.0 (11.08.2020) 81 | 82 | - Added the `split_off_first` and `split_off_last` methods. 83 | 84 | ## Version 1.5.1 (01.07.2020) 85 | 86 | - Updated project to `edition="2018"` (not that this is 87 | a purely internal change and doesn't affect the API 88 | interface or minimal supported rustc version) 89 | - Added [CONTRIBUTORS.md](./CONTRIBUTORS.md) 90 | - Updated [README.md](./README.md) 91 | 92 | ## Version 1.5.0 (21.05.2020) 93 | 94 | - minimal rust version is now 1.34 95 | - `TryFrom` is no longer feature gated 96 | - `vec1![]` now allows trailing `,` in all cases 97 | - `Size0Error` now no longer has a custom 98 | `std::error::Error::description()` implementation. 99 | - fixed various clippy::pedantic warnings 100 | - updated `Cargo.toml` 101 | - `cargo fmt` 102 | 103 | ## Version 1.4.0 (26.03.2019) 104 | 105 | New trait impl: 106 | - impl Default for Vec1 where T: Default 107 | 108 | ## Version 1.3.0 (21.03.2019) 109 | 110 | New manual proxy methods: 111 | - splice 112 | - to_asci_lowercase 113 | - to_ascii_uppercase 114 | 115 | New Into impl for following types: 116 | - Rc<[T]> 117 | - Arc<[T]> 118 | - Box<[T]> 119 | - VecDeque 120 | 121 | ### Unstable/Nightly features 122 | 123 | New TryFrom impl for following types: 124 | - Box<[T]> 125 | - BinaryHeap 126 | - VecDeque 127 | - String 128 | - &str 129 | - &[T] where T: Clone 130 | - &mut [T] where T: Clone 131 | 132 | ## Version 1.2.0 (20.03.2019) 133 | 134 | - Added new `try_from_vec` which returns a `Result, Size0Error>`. 135 | - Deprecated `from_vec` as it doesn't return a error type as error. 136 | 137 | ### Unstable/Nightly features 138 | 139 | - New `unstable-nightly-try-from-impl` feature which adds a `TryFrom>` implementation. 140 | 141 | 142 | ## Version 1.1.0 143 | 144 | - Addead a `serde` feature implementing `Serialize`/`Deserialize`. 145 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/smallvec_v1.rs: -------------------------------------------------------------------------------- 1 | //! A alternative `Vec1` implementation backed by an `SmallVec1`. 2 | //! 3 | //! # Construction Macro 4 | //! 5 | //! A macro similar to `vec!` or `vec1!` does exist and is 6 | //! re-exported in this module as `smallvec1`. 7 | //! 8 | //! Due to limitations in rust we can't properly document it 9 | //! directly without either giving it strange names or ending 10 | //! up with name collisions once we support smallvec v2 in the 11 | //! future (without introducing a braking change). 12 | //! 13 | //! ## Example 14 | //! 15 | //! ```rust 16 | //! use vec1::smallvec_v1::{smallvec1, SmallVec1}; 17 | //! let v: SmallVec1<[u8; 4]> = smallvec1![1u8, 2]; 18 | //! assert_eq!(&*v, &*vec![1u8,2]); 19 | //! ``` 20 | 21 | use crate::Size0Error; 22 | 23 | #[cfg(feature = "smallvec-v1-write")] 24 | use std::io; 25 | 26 | use alloc::boxed::Box; 27 | use alloc::vec::Vec; 28 | use smallvec::*; 29 | use smallvec_v1_ as smallvec; 30 | 31 | pub use crate::__smallvec1_inline_macro_v1 as smallvec1_inline; 32 | pub use crate::__smallvec1_macro_v1 as smallvec1; 33 | 34 | use smallvec::Drain; 35 | 36 | #[doc(hidden)] 37 | #[macro_export] 38 | macro_rules! __smallvec1_macro_v1 { 39 | () => ( 40 | compile_error!("SmallVec1 needs at least 1 element") 41 | ); 42 | ($first:expr $(, $item:expr)* , ) => ( 43 | $crate::smallvec_v1::smallvec1!($first $(, $item)*) 44 | ); 45 | ($first:expr $(, $item:expr)* ) => ({ 46 | let smallvec = $crate::smallvec_v1_::smallvec!($first $(, $item)*); 47 | $crate::smallvec_v1::SmallVec1::try_from_smallvec(smallvec).unwrap() 48 | }); 49 | } 50 | 51 | #[doc(hidden)] 52 | #[macro_export] 53 | macro_rules! __smallvec1_inline_macro_v1 { 54 | () => ( 55 | compile_error!("SmallVec1 needs at least 1 element") 56 | ); 57 | ($first:expr $(, $item:expr)* , ) => ( 58 | $crate::smallvec_v1::smallvec1_inline!($first $(, $item)*) 59 | ); 60 | ($first:expr $(, $item:expr)* ) => ({ 61 | $crate::smallvec_v1::SmallVec1::from_array_const([$first $(, $item)*]) 62 | }); 63 | } 64 | 65 | shared_impl! { 66 | base_bounds_macro = A: Array, 67 | item_ty_macro = A::Item, 68 | 69 | /// `smallvec::SmallVec` wrapper which guarantees to have at least 1 element. 70 | /// 71 | /// `SmallVec1` dereferences to `&[T]` and `&mut [T]` as functionality 72 | /// exposed through this can not change the length. 73 | /// 74 | /// Methods of `SmallVec` which can be called without reducing the length 75 | /// (e.g. `capacity()`, `reserve()`) are exposed through wrappers 76 | /// with the same function signature. 77 | /// 78 | /// Methods of `SmallVec` which could reduce the length to 0 79 | /// are implemented with a `try_` prefix returning a `Result`. 80 | /// (e.g. `try_pop(&self)`, `try_truncate()`, etc.). 81 | /// 82 | /// Methods with returned `Option` with `None` if the length was 0 83 | /// (and do not reduce the length) now return T. (e.g. `first`, 84 | /// `last`, `first_mut`, etc.). 85 | /// 86 | /// All stable traits and methods implemented on `SmallVec` _should_ also 87 | /// be implemented on `SmallVec1` (except if they make no sense to implement 88 | /// due to the len 1 guarantee). Be aware implementations may lack behind a bit, 89 | /// fell free to open a issue/make a PR, but please search closed and open 90 | /// issues for duplicates first. 91 | pub struct SmallVec1(SmallVec); 92 | } 93 | 94 | impl SmallVec1 95 | where 96 | A: Array, 97 | { 98 | /// Tries to create a new instance from a instance of the wrapped type. 99 | /// 100 | /// # Errors 101 | /// 102 | /// This will fail if the input is empty. 103 | /// The returned error is a `Size0Error` instance, as 104 | /// such this means the _input vector will be dropped if 105 | /// it's empty_. But this is normally fine as it only 106 | /// happens if the `Vec` is empty. 107 | /// 108 | pub fn try_from_smallvec(wrapped: SmallVec) -> Result { 109 | if wrapped.is_empty() { 110 | Err(Size0Error) 111 | } else { 112 | Ok(Self(wrapped)) 113 | } 114 | } 115 | 116 | /// See [`SmallVec::from_buf()`] but fails if the `buf` is empty. 117 | pub fn try_from_buf(buf: A) -> Result { 118 | Self::try_from_smallvec(SmallVec::from_buf(buf)) 119 | } 120 | 121 | /// See [`SmallVec::from_buf_and_len()`] but fails if the buf and len are empty. 122 | /// 123 | /// # Panic 124 | /// 125 | /// Like [`SmallVec::from_buf_and_len()`] this fails if the length is > the 126 | /// size of the buffer. I.e. `SmallVec1::try_from_buf_and_len([] as [u8;0],2)` will 127 | /// panic. 128 | pub fn try_from_buf_and_len(buf: A, len: usize) -> Result { 129 | Self::try_from_smallvec(SmallVec::from_buf_and_len(buf, len)) 130 | } 131 | 132 | /// Converts this instance into the underlying [`$wrapped<$t>`] instance. 133 | pub fn into_smallvec(self) -> SmallVec { 134 | self.0 135 | } 136 | 137 | /// Return a reference to the underlying `$wrapped`. 138 | pub fn as_smallvec(&self) -> &SmallVec { 139 | &self.0 140 | } 141 | 142 | /// Converts this instance into a [`Vec<$item_ty>`] instance. 143 | pub fn into_vec(self) -> Vec { 144 | self.0.into_vec() 145 | } 146 | 147 | /// Converts this instance into the inner most underlying buffer/array. 148 | /// 149 | /// This fails if the `SmallVec` has not the exact length of 150 | /// the underlying buffers/arrays capacity. 151 | /// 152 | /// This matches [`SmallVec::into_inner()`] in that if the 153 | // length is to large or small self is returned as error. 154 | pub fn into_inner(self) -> Result { 155 | self.0.into_inner().map_err(SmallVec1) 156 | } 157 | 158 | /// See [`SmallVec::insert_many()`]. 159 | pub fn insert_many>(&mut self, index: usize, iterable: I) { 160 | self.0.insert_many(index, iterable) 161 | } 162 | } 163 | 164 | impl SmallVec1 165 | where 166 | A: Array, 167 | A::Item: Copy, 168 | { 169 | pub fn try_from_slice(slice: &[A::Item]) -> Result { 170 | if slice.is_empty() { 171 | Err(Size0Error) 172 | } else { 173 | Ok(Self(SmallVec::from_slice(slice))) 174 | } 175 | } 176 | 177 | pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { 178 | self.0.insert_from_slice(index, slice) 179 | } 180 | } 181 | 182 | impl SmallVec1 183 | where 184 | A: Array, 185 | A::Item: Clone, 186 | { 187 | pub fn try_from_elem(element: A::Item, len: usize) -> Result { 188 | if len == 0 { 189 | Err(Size0Error) 190 | } else { 191 | Ok(Self(SmallVec::from_elem(element, len))) 192 | } 193 | } 194 | } 195 | 196 | impl SmallVec1<[T; N]> { 197 | /// Creates a new `SmallVec1` from an array. 198 | /// 199 | /// # Panics 200 | /// 201 | /// This will panic if N==0. 202 | pub const fn from_array_const(val: [T; N]) -> Self { 203 | if N == 0 { 204 | panic!("Empty arrays can not be used for creating a SmallVec1"); 205 | } 206 | Self(SmallVec::from_const(val)) 207 | } 208 | } 209 | 210 | impl_wrapper! { 211 | base_bounds_macro = A: Array, 212 | impl SmallVec1 { 213 | fn inline_size(&self) -> usize; 214 | fn spilled(&self) -> bool; 215 | fn grow(&mut self, len: usize) -> (); 216 | fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr>; 217 | fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr>; 218 | fn try_grow(&mut self, len: usize) -> Result<(), CollectionAllocErr>; 219 | } 220 | } 221 | 222 | impl PartialEq> for SmallVec1 223 | where 224 | A::Item: PartialEq, 225 | A: Array, 226 | B: Array, 227 | { 228 | #[inline] 229 | fn eq(&self, other: &SmallVec1) -> bool { 230 | self.0.eq(&other.0) 231 | } 232 | } 233 | 234 | ///FIXME(v2.0) use `From` and panic on `N==0` instead. 235 | impl TryFrom<[T; N]> for SmallVec1<[T; N]> { 236 | type Error = Size0Error; 237 | fn try_from(vec: [T; N]) -> Result { 238 | Self::try_from_buf(vec) 239 | } 240 | } 241 | 242 | impl TryFrom> for [T; N] { 243 | type Error = SmallVec1<[T; N]>; 244 | fn try_from(vec: SmallVec1<[T; N]>) -> Result> { 245 | vec.into_inner() 246 | } 247 | } 248 | 249 | impl IntoIterator for SmallVec1 250 | where 251 | A: Array, 252 | { 253 | type Item = A::Item; 254 | type IntoIter = smallvec::IntoIter; 255 | 256 | fn into_iter(self) -> Self::IntoIter { 257 | self.0.into_iter() 258 | } 259 | } 260 | 261 | impl From> for Vec 262 | where 263 | A: Array, 264 | { 265 | fn from(vec: SmallVec1) -> Vec { 266 | vec.into_vec() 267 | } 268 | } 269 | 270 | impl TryFrom> for SmallVec1 271 | where 272 | A: Array, 273 | { 274 | type Error = Size0Error; 275 | fn try_from(vec: Vec) -> Result { 276 | Self::try_from_vec(vec) 277 | } 278 | } 279 | 280 | impl From> for Box<[A::Item]> 281 | where 282 | A: Array, 283 | { 284 | fn from(vec: SmallVec1) -> Self { 285 | vec.into_boxed_slice() 286 | } 287 | } 288 | 289 | #[cfg(feature = "smallvec-v1-write")] 290 | impl io::Write for SmallVec1 291 | where 292 | A: Array, 293 | { 294 | #[inline] 295 | fn write(&mut self, buf: &[u8]) -> io::Result { 296 | self.0.write(buf) 297 | } 298 | 299 | #[inline] 300 | fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { 301 | self.0.write_vectored(bufs) 302 | } 303 | 304 | #[inline] 305 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 306 | self.0.write_all(buf) 307 | } 308 | 309 | #[inline] 310 | fn flush(&mut self) -> io::Result<()> { 311 | self.0.flush() 312 | } 313 | } 314 | 315 | #[cfg(test)] 316 | mod tests { 317 | 318 | mod SmallVec1 { 319 | #![allow(non_snake_case)] 320 | use super::super::*; 321 | use core::num::NonZeroUsize; 322 | use std::{ 323 | borrow::{Borrow, BorrowMut, ToOwned}, 324 | cmp::Ordering, 325 | collections::hash_map::DefaultHasher, 326 | format, 327 | hash::{Hash, Hasher}, 328 | panic::catch_unwind, 329 | string::String, 330 | vec, 331 | vec::Vec, 332 | }; 333 | 334 | #[test] 335 | fn Clone() { 336 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 337 | let b = a.clone(); 338 | assert_eq!(a, b); 339 | } 340 | 341 | #[test] 342 | fn Eq() { 343 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 344 | let b: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 345 | let c: SmallVec1<[u8; 4]> = smallvec1![2, 2, 3]; 346 | 347 | assert_eq!(a, b); 348 | assert_ne!(a, c); 349 | //make sure Eq is supported and not only PartialEq 350 | fn cmp() {} 351 | cmp::>(); 352 | } 353 | 354 | #[test] 355 | fn PartialEq() { 356 | let a: SmallVec1<[String; 4]> = smallvec1!["hy".to_owned()]; 357 | let b: SmallVec1<[&'static str; 4]> = smallvec1!["hy"]; 358 | assert_eq!(a, b); 359 | 360 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3, 4, 5]; 361 | let b: SmallVec1<[u8; 8]> = smallvec1![1, 2, 3, 4, 5]; 362 | assert_eq!(a, b); 363 | } 364 | 365 | #[test] 366 | fn Ord() { 367 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 368 | let b: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 369 | assert_eq!(Ord::cmp(&a, &b), Ordering::Less); 370 | } 371 | 372 | #[test] 373 | fn Hash() { 374 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 375 | let b = vec![1u8, 3]; 376 | assert_eq!(compute_hash(&a), compute_hash(&b)); 377 | 378 | /// ------------------- 379 | fn compute_hash(value: &T) -> u64 { 380 | let mut hasher = DefaultHasher::new(); 381 | value.hash(&mut hasher); 382 | hasher.finish() 383 | } 384 | } 385 | 386 | #[test] 387 | fn Debug() { 388 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 389 | assert_eq!(format!("{:?}", a), "[1, 2]"); 390 | } 391 | 392 | #[test] 393 | fn Default() { 394 | let a = SmallVec1::<[u8; 4]>::default(); 395 | assert_eq!(a.as_slice(), &[0u8] as &[u8]); 396 | } 397 | #[test] 398 | fn Deref() { 399 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 400 | let _: &SmallVec<_> = a.as_smallvec(); 401 | let b: &[u8] = &*a; 402 | assert_eq!(b, &[1u8, 2] as &[u8]); 403 | } 404 | 405 | #[test] 406 | fn DerefMut() { 407 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 408 | let b: &mut [u8] = &mut *a; 409 | assert_eq!(b, &[1u8, 2] as &[u8]); 410 | } 411 | 412 | mod IntoIterator { 413 | use super::*; 414 | 415 | #[test] 416 | fn owned() { 417 | let a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 418 | let a_ = a.clone(); 419 | let b = a.into_iter().collect::>(); 420 | assert_eq!(&a_[..], &b[..]); 421 | } 422 | 423 | #[test] 424 | fn by_ref() { 425 | let a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 426 | let a = (&a).into_iter().collect::>(); 427 | assert_eq!(a, vec![&12u8, &23]); 428 | } 429 | 430 | #[test] 431 | fn by_mut() { 432 | let mut a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 433 | let a = (&mut a).into_iter().collect::>(); 434 | assert_eq!(a, vec![&mut 12u8, &mut 23]); 435 | } 436 | } 437 | 438 | #[test] 439 | fn AsRef() { 440 | let a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 441 | let _: &[u8] = a.as_ref(); 442 | let _: &SmallVec<[u8; 4]> = a.as_ref(); 443 | } 444 | 445 | mod AsMut { 446 | use super::{smallvec1, SmallVec1}; 447 | 448 | #[test] 449 | fn os_slice() { 450 | let mut a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 451 | let _: &mut [u8] = a.as_mut(); 452 | } 453 | 454 | #[test] 455 | fn of_self() { 456 | let mut a: SmallVec1<[u8; 4]> = smallvec1![33u8, 123]; 457 | let v: &mut SmallVec1<[u8; 4]> = a.as_mut(); 458 | let mut expected: SmallVec1<[u8; 4]> = smallvec1![33u8, 123]; 459 | assert_eq!(v, &mut expected); 460 | } 461 | } 462 | 463 | #[test] 464 | fn Borrow() { 465 | let a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 466 | let _: &[u8] = a.borrow(); 467 | let _: &SmallVec<[u8; 4]> = a.borrow(); 468 | } 469 | 470 | #[test] 471 | fn BorrowMut() { 472 | let mut a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 473 | let _: &mut [u8] = a.borrow_mut(); 474 | } 475 | 476 | #[test] 477 | fn Extend() { 478 | let mut a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 479 | a.extend(vec![1u8, 2, 3].into_iter()); 480 | assert_eq!(a.as_slice(), &[12u8, 23, 1, 2, 3] as &[u8]); 481 | } 482 | 483 | #[test] 484 | fn Index() { 485 | let a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 486 | assert_eq!(a[0], 12); 487 | } 488 | 489 | #[test] 490 | fn IndexMut() { 491 | let mut a: SmallVec1<[u8; 4]> = smallvec1![12, 23]; 492 | a[0] = 33; 493 | assert_eq!(a[0], 33); 494 | } 495 | 496 | mod TryFrom { 497 | use super::super::super::*; 498 | use std::{borrow::ToOwned, string::String, vec}; 499 | 500 | #[test] 501 | fn slice() { 502 | let a = 503 | SmallVec1::<[String; 4]>::try_from(&["hy".to_owned()] as &[String]).unwrap(); 504 | assert_eq!(a[0], "hy"); 505 | 506 | SmallVec1::<[String; 4]>::try_from(&[] as &[String]).unwrap_err(); 507 | } 508 | 509 | #[test] 510 | fn misc() { 511 | let _ = SmallVec1::<[u8; 4]>::try_from(vec![1, 2, 3]).unwrap(); 512 | let _ = SmallVec1::<[u8; 4]>::try_from(vec![]).unwrap_err(); 513 | let _ = SmallVec1::<[u8; 4]>::try_from(smallvec![1, 2, 3]).unwrap(); 514 | let _ = SmallVec1::<[u8; 4]>::try_from(smallvec![]).unwrap_err(); 515 | let _ = SmallVec1::<[u8; 4]>::try_from([1u8, 2, 3, 4]).unwrap(); 516 | let _ = SmallVec1::<[u8; 0]>::try_from([] as [u8; 0]).unwrap_err(); 517 | } 518 | 519 | #[test] 520 | fn array_try_from_smallvec1() { 521 | let vec: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 522 | <[u8; 4]>::try_from(vec).unwrap(); 523 | 524 | let vec: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2]; 525 | <[u8; 4]>::try_from(vec).unwrap_err(); 526 | } 527 | } 528 | 529 | #[test] 530 | fn new() { 531 | let a = SmallVec1::<[u8; 4]>::new(12); 532 | let b: SmallVec1<[u8; 4]> = smallvec1![12]; 533 | assert_eq!(a, b); 534 | } 535 | 536 | #[test] 537 | fn with_capacity() { 538 | let a = SmallVec1::<[u8; 4]>::with_capacity(32, 21); 539 | assert_eq!(a.is_empty(), false); 540 | assert_eq!(a.capacity(), 21); 541 | 542 | let a = SmallVec1::<[u8; 4]>::with_capacity(32, 1); 543 | assert_eq!(a.is_empty(), false); 544 | assert_eq!(a.capacity(), 4 /*yes 4!*/); 545 | } 546 | 547 | #[test] 548 | fn try_from_vec() { 549 | let a = SmallVec1::<[u8; 4]>::try_from_vec(vec![1, 2, 3]); 550 | assert_eq!(a, Ok(smallvec1![1, 2, 3])); 551 | 552 | let b = SmallVec1::<[u8; 4]>::try_from_vec(vec![]); 553 | assert_eq!(b, Err(Size0Error)); 554 | } 555 | 556 | #[test] 557 | fn try_from_smallvec() { 558 | let a = SmallVec1::<[u8; 4]>::try_from_smallvec(smallvec![32, 2, 3]); 559 | assert_eq!(a, Ok(smallvec1![32, 2, 3])); 560 | 561 | let a = SmallVec1::<[u8; 4]>::try_from_smallvec(smallvec![]); 562 | assert_eq!(a, Err(Size0Error)); 563 | } 564 | 565 | #[test] 566 | fn try_from_buf() { 567 | let a = SmallVec1::try_from_buf([1u8, 2, 3, 4]); 568 | assert_eq!(a, Ok(smallvec1![1, 2, 3, 4])); 569 | 570 | let a = SmallVec1::try_from_buf([] as [u8; 0]); 571 | assert_eq!(a, Err(Size0Error)); 572 | } 573 | 574 | #[test] 575 | fn try_from_buf_and_len() { 576 | let a = SmallVec1::try_from_buf_and_len([1u8, 2, 3, 4, 0, 0, 0, 0], 4); 577 | assert_eq!(a, Ok(smallvec1![1, 2, 3, 4])); 578 | 579 | let a = SmallVec1::try_from_buf_and_len([1u8, 2, 3], 0); 580 | assert_eq!(a, Err(Size0Error)); 581 | } 582 | 583 | #[should_panic] 584 | #[test] 585 | fn try_from_buf_and_len_panic_if_len_gt_size() { 586 | let _ = SmallVec1::try_from_buf_and_len([] as [u8; 0], 3); 587 | } 588 | 589 | #[test] 590 | fn into_smallvec() { 591 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2]; 592 | let a = a.into_smallvec(); 593 | let b: SmallVec<[u8; 4]> = smallvec![1, 3, 2]; 594 | assert_eq!(a, b); 595 | } 596 | 597 | #[test] 598 | fn into_vec() { 599 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2]; 600 | let a: Vec = a.into_vec(); 601 | assert_eq!(a, vec![1, 3, 2]) 602 | } 603 | 604 | #[test] 605 | fn into_inner() { 606 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 607 | let a: [u8; 4] = a.into_inner().unwrap(); 608 | assert_eq!(a, [1, 3, 2, 4]) 609 | } 610 | 611 | #[test] 612 | fn into_boxed_slice() { 613 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 614 | let a: Box<[u8]> = a.into_boxed_slice(); 615 | assert_eq!(&*a, &[1u8, 3, 2, 4] as &[u8]) 616 | } 617 | 618 | #[test] 619 | fn leak() { 620 | let a: SmallVec1<[u8; 32]> = smallvec1![1u8, 3]; 621 | let s: &'static mut [u8] = a.leak(); 622 | assert_eq!(s, &[1u8, 3]); 623 | } 624 | 625 | #[test] 626 | fn reduce() { 627 | assert_eq!(smallvec1_inline![1u8, 2, 4, 3].reduce(std::cmp::max), 4); 628 | assert_eq!(smallvec1_inline![1u8, 2, 2, 3].reduce(|a, b| a + b), 8); 629 | } 630 | 631 | #[test] 632 | fn reduce_ref() { 633 | let a = smallvec1_inline![std::cell::Cell::new(4)]; 634 | a.reduce_ref(std::cmp::max).set(44); 635 | assert_eq!(a, smallvec1_inline![std::cell::Cell::new(44)]); 636 | } 637 | 638 | #[test] 639 | fn reduce_mut() { 640 | let mut a = smallvec1_inline![1u8, 2, 4, 3]; 641 | *a.reduce_mut(std::cmp::max) *= 2; 642 | assert_eq!(a, smallvec1_inline![1u8, 2, 8, 3]); 643 | } 644 | 645 | mod From { 646 | use super::*; 647 | 648 | #[test] 649 | fn boxed_slice_from_smallvec1() { 650 | let vec: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4, 5]; 651 | let _ = Box::<[u8]>::from(vec); 652 | } 653 | 654 | #[test] 655 | fn vec_from_smallvec1() { 656 | let vec: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 657 | let _ = Vec::::from(vec); 658 | } 659 | 660 | #[test] 661 | fn smallvec_from_smallvec1() { 662 | let vec: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 663 | let _ = SmallVec::<[u8; 4]>::from(vec); 664 | } 665 | } 666 | 667 | #[test] 668 | fn last_first_methods_are_shadowed() { 669 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 670 | assert_eq!(a.last(), &4); 671 | assert_eq!(a.last_mut(), &mut 4); 672 | assert_eq!(a.first(), &1); 673 | assert_eq!(a.first_mut(), &mut 1); 674 | } 675 | 676 | #[test] 677 | fn truncate() { 678 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 679 | assert_eq!(a.truncate(0), Err(Size0Error)); 680 | assert_eq!(a.truncate(1), Ok(())); 681 | assert_eq!(a.len(), 1); 682 | } 683 | 684 | #[test] 685 | fn try_truncate() { 686 | #![allow(deprecated)] 687 | 688 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 689 | assert_eq!(a.try_truncate(0), Err(Size0Error)); 690 | assert_eq!(a.try_truncate(1), Ok(())); 691 | assert_eq!(a.len(), 1); 692 | } 693 | 694 | #[test] 695 | fn reserve() { 696 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 697 | a.reserve(4); 698 | assert!(a.capacity() >= 8); 699 | } 700 | 701 | #[test] 702 | fn try_reserve() { 703 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 704 | a.try_reserve(4).unwrap(); 705 | assert!(a.capacity() >= 8); 706 | } 707 | 708 | #[test] 709 | fn reserve_exact() { 710 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 711 | a.reserve_exact(4); 712 | assert_eq!(a.capacity(), 8); 713 | } 714 | 715 | #[test] 716 | fn try_reserve_exact() { 717 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4]; 718 | a.try_reserve_exact(4).unwrap(); 719 | assert_eq!(a.capacity(), 8); 720 | } 721 | 722 | #[test] 723 | fn shrink_to_fit() { 724 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 2, 4, 5]; 725 | a.shrink_to_fit(); 726 | assert_eq!(a.capacity(), 5); 727 | } 728 | 729 | #[test] 730 | fn push() { 731 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 732 | a.push(12); 733 | let b: SmallVec1<[u8; 4]> = smallvec1![1, 3, 12]; 734 | assert_eq!(a, b); 735 | } 736 | 737 | #[test] 738 | fn insert() { 739 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 740 | a.insert(0, 12); 741 | let b: SmallVec1<[u8; 4]> = smallvec1![12, 1, 3]; 742 | assert_eq!(a, b); 743 | } 744 | 745 | #[test] 746 | fn len() { 747 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 748 | assert_eq!(a.len(), 2); 749 | } 750 | 751 | #[test] 752 | fn len_nonzero() { 753 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 754 | assert_eq!(a.len_nonzero(), NonZeroUsize::new(2).unwrap()); 755 | } 756 | 757 | #[test] 758 | fn capacity() { 759 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 760 | assert_eq!(a.capacity(), 4); 761 | } 762 | 763 | #[test] 764 | fn as_slice() { 765 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 766 | assert_eq!(a.as_slice(), &[1u8, 3] as &[u8]); 767 | } 768 | 769 | #[test] 770 | fn as_mut_slice() { 771 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 772 | a.as_mut_slice()[0] = 10; 773 | let b: SmallVec1<[u8; 4]> = smallvec1![10, 3]; 774 | assert_eq!(a, b); 775 | } 776 | 777 | #[test] 778 | fn inline_size() { 779 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 780 | assert_eq!(a.inline_size(), 4); 781 | } 782 | 783 | #[test] 784 | fn spilled() { 785 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 786 | assert_eq!(a.spilled(), false); 787 | 788 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 3, 6, 9, 2]; 789 | assert_eq!(a.spilled(), true); 790 | } 791 | 792 | #[test] 793 | fn pop() { 794 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 795 | assert_eq!(a.pop(), Ok(3)); 796 | assert_eq!(a.pop(), Err(Size0Error)); 797 | } 798 | 799 | #[test] 800 | fn try_pop() { 801 | #![allow(deprecated)] 802 | 803 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 804 | assert_eq!(a.try_pop(), Ok(3)); 805 | assert_eq!(a.try_pop(), Err(Size0Error)); 806 | } 807 | 808 | #[test] 809 | fn append() { 810 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 811 | let mut b: SmallVec<[u8; 4]> = smallvec![53, 12]; 812 | a.append(&mut b); 813 | let c: SmallVec1<[u8; 4]> = smallvec1![1, 3, 53, 12]; 814 | assert_eq!(a, c); 815 | } 816 | 817 | #[test] 818 | fn grow() { 819 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 820 | a.grow(32); 821 | assert_eq!(a.capacity(), 32); 822 | } 823 | 824 | #[test] 825 | fn try_grow() { 826 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 827 | a.try_grow(32).unwrap(); 828 | assert_eq!(a.capacity(), 32); 829 | } 830 | 831 | #[test] 832 | fn swap_remove() { 833 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 834 | assert_eq!(a.swap_remove(0), Ok(1)); 835 | assert_eq!(a.swap_remove(0), Err(Size0Error)); 836 | } 837 | 838 | #[test] 839 | fn try_swap_remove() { 840 | #![allow(deprecated)] 841 | 842 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 843 | assert_eq!(a.try_swap_remove(0), Ok(1)); 844 | assert_eq!(a.try_swap_remove(0), Err(Size0Error)); 845 | } 846 | 847 | #[test] 848 | fn remove() { 849 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 850 | assert_eq!(a.remove(0), Ok(1)); 851 | assert_eq!(a.remove(0), Err(Size0Error)); 852 | 853 | catch_unwind(|| { 854 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 855 | let _ = a.remove(200); 856 | }) 857 | .unwrap_err(); 858 | } 859 | 860 | #[test] 861 | fn try_remove() { 862 | #![allow(deprecated)] 863 | 864 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 865 | assert_eq!(a.try_remove(0), Ok(1)); 866 | assert_eq!(a.try_remove(0), Err(Size0Error)); 867 | } 868 | 869 | #[test] 870 | fn insert_many() { 871 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 3]; 872 | a.insert_many(1, vec![2, 4, 8]); 873 | let b: SmallVec1<[u8; 4]> = smallvec1![1, 2, 4, 8, 3]; 874 | assert_eq!(a, b); 875 | } 876 | 877 | #[test] 878 | fn dedup() { 879 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 1]; 880 | a.dedup(); 881 | assert_eq!(a.as_slice(), &[1u8] as &[u8]); 882 | } 883 | 884 | #[test] 885 | fn dedup_by() { 886 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 1, 4, 4]; 887 | a.dedup_by(|a, b| a == b); 888 | assert_eq!(a.as_slice(), &[1u8, 4] as &[u8]); 889 | } 890 | 891 | #[test] 892 | fn dedup_by_key() { 893 | let mut a: SmallVec1<[(u8, u8); 4]> = smallvec1![(1, 2), (1, 5), (4, 4), (5, 4)]; 894 | a.dedup_by_key(|a| a.0); 895 | assert_eq!(a.as_slice(), &[(1u8, 2u8), (4, 4), (5, 4)] as &[(u8, u8)]); 896 | } 897 | 898 | #[test] 899 | fn resize_with() { 900 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 901 | assert_eq!(a.resize_with(0, Default::default), Err(Size0Error)); 902 | assert_eq!(a.resize_with(4, Default::default), Ok(())); 903 | } 904 | 905 | #[test] 906 | fn try_resize_with() { 907 | #![allow(deprecated)] 908 | 909 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 910 | assert_eq!(a.try_resize_with(0, Default::default), Err(Size0Error)); 911 | assert_eq!(a.try_resize_with(4, Default::default), Ok(())); 912 | } 913 | 914 | #[test] 915 | fn as_ptr() { 916 | let a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 917 | let pa = a.as_ptr(); 918 | let pb = a.as_slice().as_ptr(); 919 | assert_eq!(pa as usize, pb as usize); 920 | } 921 | 922 | #[test] 923 | fn as_mut_ptr() { 924 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 925 | let pa = a.as_mut_ptr(); 926 | let pb = a.as_mut_slice().as_mut_ptr(); 927 | assert_eq!(pa as usize, pb as usize); 928 | } 929 | 930 | #[test] 931 | fn try_from_slice() { 932 | let a = SmallVec1::<[u8; 4]>::try_from_slice(&[1u8, 2, 9]).unwrap(); 933 | assert_eq!(a.as_slice(), &[1u8, 2, 9] as &[u8]); 934 | 935 | SmallVec1::<[u8; 4]>::try_from_slice(&[]).unwrap_err(); 936 | } 937 | 938 | #[test] 939 | fn insert_from_slice() { 940 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 941 | a.insert_from_slice(1, &[3, 9]); 942 | assert_eq!(a.as_slice(), &[1u8, 3, 9, 2] as &[u8]); 943 | } 944 | 945 | #[test] 946 | fn extend_from_slice() { 947 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2]; 948 | a.extend_from_slice(&[3, 9]); 949 | assert_eq!(a.as_slice(), &[1u8, 2, 3, 9] as &[u8]); 950 | } 951 | 952 | #[test] 953 | fn resize() { 954 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 955 | assert_eq!(a.resize(0, 12), Err(Size0Error)); 956 | assert_eq!(a.resize(2, 12), Ok(())); 957 | assert_eq!(a.resize(4, 12), Ok(())); 958 | assert_eq!(a.as_slice(), &[1u8, 2, 12, 12] as &[u8]); 959 | } 960 | 961 | #[test] 962 | fn try_resize() { 963 | #![allow(deprecated)] 964 | 965 | let mut a: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 966 | assert_eq!(a.try_resize(0, 12), Err(Size0Error)); 967 | assert_eq!(a.try_resize(2, 12), Ok(())); 968 | assert_eq!(a.try_resize(4, 12), Ok(())); 969 | assert_eq!(a.as_slice(), &[1u8, 2, 12, 12] as &[u8]); 970 | } 971 | 972 | #[test] 973 | fn try_from_elem() { 974 | let a = SmallVec1::<[u8; 4]>::try_from_elem(1u8, 3).unwrap(); 975 | assert_eq!(a.as_slice(), &[1u8, 1, 1] as &[u8]); 976 | 977 | SmallVec1::<[u8; 4]>::try_from_elem(1u8, 0).unwrap_err(); 978 | } 979 | 980 | #[test] 981 | fn split_off_first() { 982 | let a: SmallVec1<[u8; 4]> = smallvec1![32]; 983 | assert_eq!((32, SmallVec::<[u8; 4]>::new()), a.split_off_first()); 984 | 985 | let a: SmallVec1<[u8; 4]> = smallvec1![32, 43]; 986 | let exp: SmallVec<[u8; 4]> = smallvec![43]; 987 | assert_eq!((32, exp), a.split_off_first()); 988 | } 989 | 990 | #[test] 991 | fn split_off_last() { 992 | let a: SmallVec1<[u8; 4]> = smallvec1![32]; 993 | assert_eq!((SmallVec::<[u8; 4]>::new(), 32), a.split_off_last()); 994 | 995 | let a: SmallVec1<[u8; 4]> = smallvec1![32, 43]; 996 | let exp: SmallVec<[u8; 4]> = smallvec![32]; 997 | assert_eq!((exp, 43), a.split_off_last()); 998 | } 999 | 1000 | #[test] 1001 | fn from_vec_push() { 1002 | let got: SmallVec1<[u8; 4]> = SmallVec1::from_vec_push(std::vec![], 1u8); 1003 | let expected: SmallVec1<[u8; 4]> = smallvec1![1]; 1004 | assert_eq!(got, expected); 1005 | let got: SmallVec1<[u8; 4]> = SmallVec1::from_vec_push(std::vec![1, 2], 3u8); 1006 | let expected: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 1007 | assert_eq!(got, expected); 1008 | } 1009 | 1010 | #[test] 1011 | fn from_vec_insert() { 1012 | let got: SmallVec1<[u8; 4]> = SmallVec1::from_vec_insert(std::vec![], 0, 1u8); 1013 | let expected: SmallVec1<[u8; 4]> = smallvec1![1]; 1014 | assert_eq!(got, expected); 1015 | let got: SmallVec1<[u8; 4]> = SmallVec1::from_vec_insert(std::vec![1, 3], 1, 2u8); 1016 | let expected: SmallVec1<[u8; 4]> = smallvec1![1, 2, 3]; 1017 | assert_eq!(got, expected); 1018 | assert!(catch_unwind(|| { 1019 | SmallVec1::<[u8; 4]>::from_vec_insert(std::vec![1, 3], 3, 2u8); 1020 | }) 1021 | .is_err()); 1022 | } 1023 | 1024 | #[cfg(feature = "serde")] 1025 | mod serde { 1026 | use super::super::super::*; 1027 | 1028 | #[test] 1029 | fn can_be_serialized_and_deserialized() { 1030 | let a: SmallVec1<[u8; 4]> = smallvec1![32, 12, 14, 18, 201]; 1031 | let json_str = serde_json::to_string(&a).unwrap(); 1032 | let b: SmallVec1<[u8; 4]> = serde_json::from_str(&json_str).unwrap(); 1033 | assert_eq!(a, b); 1034 | } 1035 | 1036 | #[test] 1037 | fn array_size_is_not_serialized() { 1038 | let a: SmallVec1<[u8; 4]> = smallvec1![32, 12, 14, 18, 201]; 1039 | let json_str = serde_json::to_string(&a).unwrap(); 1040 | let b: SmallVec1<[u8; 8]> = serde_json::from_str(&json_str).unwrap(); 1041 | assert_eq!(a, b); 1042 | } 1043 | 1044 | #[test] 1045 | fn does_not_allow_empty_deserialization() { 1046 | let a = Vec::::new(); 1047 | let json_str = serde_json::to_string(&a).unwrap(); 1048 | serde_json::from_str::>(&json_str).unwrap_err(); 1049 | } 1050 | } 1051 | } 1052 | 1053 | mod macros { 1054 | use super::super::{smallvec1, smallvec1_inline, SmallVec1}; 1055 | 1056 | #[test] 1057 | fn smallvec1() { 1058 | let _: SmallVec1<[u8; 2]> = smallvec1![1]; 1059 | let _: SmallVec1<[u8; 2]> = smallvec1![1,]; 1060 | let _: SmallVec1<[u8; 2]> = smallvec1![1, 2]; 1061 | let _: SmallVec1<[u8; 2]> = smallvec1![1, 2,]; 1062 | } 1063 | 1064 | #[test] 1065 | fn smallvec1_inline() { 1066 | assert_eq!(smallvec1_inline![1].capacity(), 1); 1067 | assert_eq!(smallvec1_inline![1,].capacity(), 1); 1068 | assert_eq!(smallvec1_inline![1, 2].capacity(), 2); 1069 | assert_eq!(smallvec1_inline![1, 2,].capacity(), 2); 1070 | } 1071 | } 1072 | } 1073 | -------------------------------------------------------------------------------- /src/shared.rs: -------------------------------------------------------------------------------- 1 | use core::ops::{Bound, RangeBounds}; 2 | 3 | /// Returns the boolean pair `(covers_all_of_slice, is_out_of_bounds)`. 4 | /// 5 | /// E.g. given a unbound start of the range, if the end of the range is behind the len of 6 | /// the slice it will cover all of the slice but it also will be out of bounds. 7 | /// 8 | /// E.g. given a bound start at 1 of the range, if the end of the range is behind the len 9 | /// of the slice it will *not* cover all but still be out of bounds. 10 | /// 11 | //FIXME(v2.0): For simplicity we might move the panic into this check (but currently can't as for Vec1::splice we don't panic) 12 | pub(crate) fn range_covers_slice( 13 | range: &impl RangeBounds, 14 | slice_len: usize, 15 | ) -> (bool, bool) { 16 | // As this is only used for vec1 we don't need the if vec_len == 0. 17 | // if vec_len == 0 { return true; } 18 | let (covers_start, oob_start) = range_covers_slice_start(range.start_bound(), slice_len); 19 | let (covers_end, oob_end) = range_covers_slice_end(range.end_bound(), slice_len); 20 | (covers_start && covers_end, oob_start || oob_end) 21 | } 22 | 23 | fn range_covers_slice_start(start_bound: Bound<&usize>, slice_len: usize) -> (bool, bool) { 24 | match start_bound { 25 | Bound::Included(idx) => (*idx == 0, *idx > slice_len), 26 | Bound::Excluded(idx) => (false, *idx >= slice_len), 27 | Bound::Unbounded => (true, false), 28 | } 29 | } 30 | 31 | fn range_covers_slice_end(end_bound: Bound<&usize>, len: usize) -> (bool, bool) { 32 | match end_bound { 33 | Bound::Included(idx) => { 34 | if len == 0 { 35 | (true, true) 36 | } else { 37 | (*idx >= len - 1, *idx >= len) 38 | } 39 | } 40 | Bound::Excluded(idx) => (*idx >= len, *idx > len), 41 | Bound::Unbounded => (true, false), 42 | } 43 | } 44 | 45 | macro_rules! impl_wrapper { 46 | ( 47 | base_bounds_macro = $($tb:ident : $trait:ident)?, 48 | impl <$A:ident> $ty_name:ident<$A_:ident> { 49 | $(fn $fn_name:ident(&$($m:ident)* $(, $param:ident: $tp:ty)*) -> $rt:ty ;)* 50 | } 51 | ) => ( 52 | impl<$A> $ty_name<$A> 53 | where 54 | $($tb : $trait,)? 55 | {$( 56 | /// See [`Vec`] for a rough idea how this method works. 57 | #[inline] 58 | pub fn $fn_name(self: impl_wrapper!{__PRIV_SELF &$($m)*} $(, $param: $tp)*) -> $rt { 59 | (self.0).$fn_name($($param),*) 60 | } 61 | )*} 62 | ); 63 | (__PRIV_SELF &mut self) => (&mut Self); 64 | (__PRIV_SELF &self) => (&Self); 65 | } 66 | 67 | macro_rules! shared_impl { 68 | ( 69 | base_bounds_macro = $($tb:ident : $trait:ident)?, 70 | item_ty_macro = $item_ty:ty, 71 | $(#[$attr:meta])* 72 | $v:vis struct $name:ident<$t:ident>($wrapped:ident<$_t:ident>); 73 | ) => ( 74 | $(#[$attr])* 75 | $v struct $name<$t>($wrapped<$t>) 76 | where 77 | $($tb : $trait,)?; 78 | 79 | const _: () = { 80 | use core::{ 81 | borrow::{Borrow, BorrowMut}, 82 | cmp::{Eq, Ord, Ordering, PartialEq}, 83 | convert::TryFrom, 84 | fmt::{self, Debug}, 85 | hash::{Hash, Hasher}, 86 | ops::{Deref, DerefMut, Index, IndexMut, RangeBounds}, 87 | slice::SliceIndex, 88 | num::NonZeroUsize, 89 | }; 90 | use alloc::{vec::Vec, boxed::Box}; 91 | 92 | impl<$t> $name<$t> 93 | where 94 | $($tb : $trait,)? 95 | { 96 | /// Creates a new instance containing a single element. 97 | pub fn new(first: $item_ty) -> Self { 98 | #![allow(clippy::vec_init_then_push)] 99 | let mut inner = $wrapped::new(); 100 | inner.push(first); 101 | $name(inner) 102 | } 103 | 104 | /// Creates a new instance with a given capacity and a given "first" element. 105 | pub fn with_capacity(first: $item_ty, capacity: usize) -> Self { 106 | let mut vec = $wrapped::with_capacity(capacity); 107 | vec.push(first); 108 | $name(vec) 109 | } 110 | 111 | /// Creates an instance from a normal `Vec` pushing one additional element. 112 | pub fn from_vec_push(mut vec: Vec<$item_ty>, last: $item_ty) -> Self { 113 | vec.push(last); 114 | $name($wrapped::from(vec)) 115 | } 116 | 117 | /// Creates an instance from a normal `Vec` inserting one additional element. 118 | /// 119 | /// # Panics 120 | /// 121 | /// Panics if `index > len`. 122 | pub fn from_vec_insert(mut vec: Vec<$item_ty>, index: usize, item: $item_ty) -> Self { 123 | vec.insert(index, item); 124 | $name($wrapped::from(vec)) 125 | } 126 | 127 | /// Tries to create an instance from a normal `Vec`. 128 | /// 129 | /// # Errors 130 | /// 131 | /// This will fail if the input `Vec` is empty. 132 | /// The returned error is a `Size0Error` instance, as 133 | /// such this means the _input vector will be dropped if 134 | /// it's empty_. But this is normally fine as it only 135 | /// happens if the `Vec` is empty. 136 | /// 137 | pub fn try_from_vec(vec: Vec<$item_ty>) -> Result { 138 | if vec.is_empty() { 139 | Err(Size0Error) 140 | } else { 141 | Ok($name($wrapped::from(vec))) 142 | } 143 | } 144 | 145 | /// Returns a reference to the last element. 146 | /// 147 | /// As `$name` always contains at least one element there is always a last element. 148 | pub fn last(&self) -> &$item_ty { 149 | //UNWRAP_SAFE: len is at least 1 150 | self.0.last().unwrap() 151 | } 152 | 153 | /// Returns a mutable reference to the last element. 154 | /// 155 | /// As `$name` always contains at least one element there is always a last element. 156 | pub fn last_mut(&mut self) -> &mut $item_ty { 157 | //UNWRAP_SAFE: len is at least 1 158 | self.0.last_mut().unwrap() 159 | } 160 | 161 | /// Returns a reference to the first element. 162 | /// 163 | /// As `$name` always contains at least one element there is always a first element. 164 | pub fn first(&self) -> &$item_ty { 165 | //UNWRAP_SAFE: len is at least 1 166 | self.0.first().unwrap() 167 | } 168 | 169 | /// Returns a mutable reference to the first element. 170 | /// 171 | /// As `$name` always contains at least one element there is always a first element. 172 | pub fn first_mut(&mut self) -> &mut $item_ty { 173 | //UNWRAP_SAFE: len is at least 1 174 | self.0.first_mut().unwrap() 175 | } 176 | 177 | 178 | /// Truncates this vector to given length. 179 | /// 180 | /// # Errors 181 | /// 182 | /// If len is 0 an error is returned as the 183 | /// length >= 1 constraint must be uphold. 184 | /// 185 | pub fn truncate(&mut self, len: usize) -> Result<(), Size0Error> { 186 | if len > 0 { 187 | self.0.truncate(len); 188 | Ok(()) 189 | } else { 190 | Err(Size0Error) 191 | } 192 | } 193 | 194 | /// Truncates this vector to given length. 195 | pub fn truncate_nonzero(&mut self, len: NonZeroUsize) { 196 | self.0.truncate(len.get()) 197 | } 198 | 199 | /// Returns the len as a [`NonZeroUsize`] 200 | pub fn len_nonzero(&self) -> NonZeroUsize { 201 | NonZeroUsize::new(self.len()).unwrap() 202 | } 203 | 204 | /// Truncates the `SmalVec1` to given length. 205 | /// 206 | /// # Errors 207 | /// 208 | /// If len is 0 an error is returned as the 209 | /// length >= 1 constraint must be uphold. 210 | /// 211 | #[deprecated( 212 | since = "1.8.0", 213 | note = "try_ prefix created ambiguity use `truncate`" 214 | )] 215 | #[inline(always)] 216 | pub fn try_truncate(&mut self, len: usize) -> Result<(), Size0Error> { 217 | self.truncate(len) 218 | } 219 | 220 | /// Calls `swap_remove` on the inner smallvec if length >= 2. 221 | /// 222 | /// # Errors 223 | /// 224 | /// If len is 1 an error is returned as the 225 | /// length >= 1 constraint must be uphold. 226 | pub fn swap_remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> { 227 | if self.len() > 1 { 228 | Ok(self.0.swap_remove(index)) 229 | } else { 230 | Err(Size0Error) 231 | } 232 | } 233 | 234 | /// Calls `swap_remove` on the inner smallvec if length >= 2. 235 | /// 236 | /// # Errors 237 | /// 238 | /// If len is 1 an error is returned as the 239 | /// length >= 1 constraint must be uphold. 240 | #[deprecated( 241 | since = "1.8.0", 242 | note = "try_ prefix created ambiguity use `swap_remove`" 243 | )] 244 | #[inline(always)] 245 | pub fn try_swap_remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> { 246 | self.swap_remove(index) 247 | } 248 | 249 | /// Calls `remove` on the inner smallvec if length >= 2. 250 | /// 251 | /// # Errors 252 | /// 253 | /// If len is 1 an error is returned as the 254 | /// length >= 1 constraint must be uphold. 255 | pub fn remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> { 256 | if self.len() > 1 { 257 | Ok(self.0.remove(index)) 258 | } else { 259 | Err(Size0Error) 260 | } 261 | } 262 | 263 | /// Calls `remove` on the inner smallvec if length >= 2. 264 | /// 265 | /// # Errors 266 | /// 267 | /// If len is 1 an error is returned as the 268 | /// length >= 1 constraint must be uphold. 269 | /// 270 | /// # Panics 271 | /// 272 | /// If `index` is greater or equal then `len`. 273 | #[deprecated( 274 | since = "1.8.0", 275 | note = "try_ prefix created ambiguity use `remove`, also try_remove PANICS on out of bounds" 276 | )] 277 | #[inline(always)] 278 | pub fn try_remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> { 279 | self.remove(index) 280 | } 281 | 282 | /// If calls `drain` on the underlying vector if it will not empty the vector. 283 | /// 284 | /// # Error 285 | /// 286 | /// If calling `drain` would empty the vector an `Err(Size0Error)` is returned 287 | /// **instead** of draining the vector. 288 | /// 289 | /// # Panic 290 | /// 291 | /// Like [`Vec::drain()`] panics if: 292 | /// 293 | /// - The starting point is greater than the end point. 294 | /// - The end point is greater than the length of the vector. 295 | /// 296 | pub fn drain(&mut self, range: R) -> Result, Size0Error> 297 | where 298 | R: RangeBounds 299 | { 300 | let (covers_all, out_of_bounds) = crate::shared::range_covers_slice(&range, self.len()); 301 | // To make sure we get the same panic we do call drain if it will cause a panic. 302 | if covers_all && !out_of_bounds { 303 | Err(Size0Error) 304 | } else { 305 | Ok(self.0.drain(range)) 306 | } 307 | } 308 | 309 | /// Removes all elements except the ones which the predicate says need to be retained. 310 | /// 311 | /// The moment the last element would be removed this will instead fail, not removing 312 | /// the element. **All but the last element will have been removed anyway.** 313 | /// 314 | /// # Panic Behavior 315 | /// 316 | /// The panic behavior is for now unspecified and might change without a 317 | /// major version release. 318 | /// 319 | /// The current implementation does only delete non-retained elements at 320 | /// the end of the `retain` function call. This might change in the future 321 | /// matching `std`s behavior. 322 | /// 323 | /// # Error 324 | /// 325 | /// If the last element would be removed instead of removing it a `Size0Error` is 326 | /// returned. 327 | /// 328 | /// # Example 329 | /// 330 | /// Is for `Vec1` but similar code works with `SmallVec1`, too. 331 | /// 332 | /// ``` 333 | /// # use vec1::vec1; 334 | /// 335 | /// let mut vec = vec1![1, 7, 8, 9, 10]; 336 | /// vec.retain(|v| *v % 2 == 1).unwrap(); 337 | /// assert_eq!(vec, vec1![1, 7, 9]); 338 | /// let Size0Error = vec.retain(|_| false).unwrap_err(); 339 | /// assert_eq!(vec.len(), 1); 340 | /// assert_eq!(vec.last(), &9); 341 | /// ``` 342 | pub fn retain(&mut self, mut f: F) -> Result<(), Size0Error> 343 | where 344 | F: FnMut(&$item_ty) -> bool 345 | { 346 | self.retain_mut(|e| f(e)) 347 | } 348 | 349 | /// Removes all elements except the ones which the predicate says need to be retained. 350 | /// 351 | /// The moment the last element would be removed this will instead fail, not removing 352 | /// the element. **All other non retained elements will still be removed.** This means 353 | /// you have to be more careful compared to `Vec::retain_mut` about how you modify 354 | /// non retained elements in the closure. 355 | /// 356 | /// # Panic Behavior 357 | /// 358 | /// The panic behavior is for now unspecified and might change without a 359 | /// major version release. 360 | /// 361 | /// The current implementation does only delete non-retained elements at 362 | /// the end of the `retain` function call. This might change in the future 363 | /// matching `std`s behavior. 364 | /// 365 | /// # Error 366 | /// 367 | /// If the last element would be removed instead of removing it a `Size0Error` is 368 | /// returned. 369 | /// 370 | /// # Example 371 | /// 372 | /// Is for `Vec1` but similar code works with `SmallVec1`, too. 373 | /// 374 | /// ``` 375 | /// # use vec1::vec1; 376 | /// 377 | /// let mut vec = vec1![1, 7, 8, 9, 10]; 378 | /// vec.retain_mut(|v| { 379 | /// *v += 2; 380 | /// *v % 2 == 1 381 | /// }).unwrap(); 382 | /// assert_eq!(vec, vec1![3, 9, 11]); 383 | /// let Size0Error = vec.retain_mut(|_| false).unwrap_err(); 384 | /// assert_eq!(vec.len(), 1); 385 | /// assert_eq!(vec.last(), &11); 386 | /// ``` 387 | pub fn retain_mut(&mut self, mut f: F) -> Result<(), Size0Error> 388 | where 389 | F: FnMut(&mut $item_ty) -> bool 390 | { 391 | // Code is based on the code in the standard library, but not the newest version 392 | // as the newest version uses unsafe optimizations. 393 | // Given a local instal of rust v1.50.0 source documentation in rustup: 394 | // /share/doc/rust/html/src/alloc/vec.rs.html#1314-1334 395 | let len = self.len(); 396 | let mut del = 0; 397 | { 398 | let v = &mut **self; 399 | 400 | for i in 0..len { 401 | if !f(&mut v[i]) { 402 | del += 1; 403 | } else if del > 0 { 404 | v.swap(i - del, i); 405 | } 406 | } 407 | } 408 | if del == 0 { 409 | Ok(()) 410 | } else { 411 | if del < len { 412 | self.0.truncate(len - del); 413 | Ok(()) 414 | } else { 415 | // if we would delete all then: 416 | // del == len AND no swap was done 417 | // so retain only last and return error 418 | self.swap(0, len - 1); 419 | self.0.truncate(1); 420 | Err(Size0Error) 421 | } 422 | } 423 | } 424 | 425 | /// Calls `dedup_by_key` on the inner smallvec. 426 | /// 427 | /// While this can remove elements it will 428 | /// never produce a empty vector from an non 429 | /// empty vector. 430 | pub fn dedup_by_key(&mut self, key: F) 431 | where 432 | F: FnMut(&mut $item_ty) -> K, 433 | K: PartialEq, 434 | { 435 | self.0.dedup_by_key(key) 436 | } 437 | 438 | /// Calls `dedup_by_key` on the inner smallvec. 439 | /// 440 | /// While this can remove elements it will 441 | /// never produce a empty vector from an non 442 | /// empty vector. 443 | pub fn dedup_by(&mut self, same_bucket: F) 444 | where 445 | F: FnMut(&mut $item_ty, &mut $item_ty) -> bool, 446 | { 447 | self.0.dedup_by(same_bucket) 448 | } 449 | 450 | /// Remove the last element from this vector, if there is more than one element in it. 451 | /// 452 | /// # Errors 453 | /// 454 | /// If len is 1 an error is returned as the 455 | /// length >= 1 constraint must be uphold. 456 | pub fn pop(&mut self) -> Result<$item_ty, Size0Error> { 457 | if self.len() > 1 { 458 | //UNWRAP_SAFE: pop on len > 1 can not be none 459 | Ok(self.0.pop().unwrap()) 460 | } else { 461 | Err(Size0Error) 462 | } 463 | } 464 | 465 | /// Remove the last element from this vector, if there is more than one element in it. 466 | /// 467 | /// # Errors 468 | /// 469 | /// If len is 1 an error is returned as the 470 | /// length >= 1 constraint must be uphold. 471 | #[deprecated( 472 | since = "1.8.0", 473 | note = "try_ prefix created ambiguity use `pop`" 474 | )] 475 | #[inline(always)] 476 | pub fn try_pop(&mut self) -> Result<$item_ty, Size0Error> { 477 | self.pop() 478 | } 479 | 480 | /// See [`Vec::resize_with()`] but fails if it would resize to length 0. 481 | pub fn resize_with(&mut self, new_len: usize, f: F) -> Result<(), Size0Error> 482 | where 483 | F: FnMut() -> $item_ty 484 | { 485 | if new_len > 0 { 486 | self.0.resize_with(new_len, f); 487 | Ok(()) 488 | } else { 489 | Err(Size0Error) 490 | } 491 | } 492 | 493 | /// See [`Vec::resize_with()`] 494 | pub fn resize_with_nonzero(&mut self, new_len: NonZeroUsize, f: F) 495 | where 496 | F: FnMut() -> $item_ty 497 | { 498 | self.0.resize_with(new_len.get(), f); 499 | } 500 | 501 | /// See [`Vec::resize_with()`] but fails if it would resize to length 0. 502 | #[deprecated( 503 | since = "1.8.0", 504 | note = "try_ prefix created ambiguity use `resize_with`" 505 | )] 506 | #[inline(always)] 507 | pub fn try_resize_with(&mut self, new_len: usize, f: F) -> Result<(), Size0Error> 508 | where 509 | F: FnMut() -> $item_ty 510 | { 511 | self.resize_with(new_len, f) 512 | } 513 | 514 | /// Splits off the first element of this vector and returns it together with the rest of the 515 | /// vector. 516 | /// 517 | pub fn split_off_first(self) -> ($item_ty, $wrapped<$t>) { 518 | let mut smallvec = self.0; 519 | let first = smallvec.remove(0); 520 | (first, smallvec) 521 | } 522 | 523 | /// Splits off the last element of this vector and returns it together with the rest of the 524 | /// vector. 525 | pub fn split_off_last(self) -> ($wrapped<$t>, $item_ty) { 526 | let mut smallvec = self.0; 527 | let last = smallvec.remove(smallvec.len() - 1); 528 | (smallvec, last) 529 | } 530 | 531 | /// Turns this vector into a boxed slice. 532 | /// 533 | /// For `Vec1` this is as cheap as for `Vec` but for 534 | /// `SmallVec1` this will cause an allocation if the 535 | /// on-stack buffer was not yet spilled. 536 | pub fn into_boxed_slice(self) -> Box<[$item_ty]> { 537 | self.into_vec().into_boxed_slice() 538 | } 539 | 540 | /// Leaks the allocation to return a mutable slice reference. 541 | /// 542 | /// This is equivalent to turning this vector into a boxed 543 | /// slice and then leaking that slice. 544 | /// 545 | /// In case of `SmallVec1` calling leak does entail an allocation 546 | /// if the stack-buffer had not yet spilled. 547 | pub fn leak<'a>(self) -> &'a mut [$item_ty] 548 | where 549 | $item_ty: 'a 550 | { 551 | self.into_vec().leak() 552 | } 553 | 554 | /// Like [`Iterator::reduce()`] but does not return an option. 555 | /// 556 | /// This is roughly equivalent with `.into_iter().reduce(f).unwrap()`. 557 | /// 558 | /// # Example 559 | /// 560 | /// ``` 561 | /// # use vec1::vec1; 562 | /// assert_eq!(vec1![1,2,4,3].reduce(std::cmp::max), 4) 563 | /// ``` 564 | /// 565 | /// *Be aware that `reduce` consumes the vector, to get a reference 566 | /// use either `reduce_ref` or `reduce_mut`.* 567 | /// 568 | pub fn reduce(self, f: impl FnMut($item_ty, $item_ty) -> $item_ty) -> $item_ty { 569 | //UNWRAP_SAFE: len is at least 1 570 | self.into_iter().reduce(f).unwrap() 571 | } 572 | 573 | /// Like [`Iterator::reduce()`] but does not return an option. 574 | /// 575 | /// This is roughly equivalent with `.iter().reduce(f).unwrap()`. 576 | /// 577 | /// *Hint: Because of the reduction function returning a reference 578 | /// this method is (in general) only suitable for selecting exactly 579 | /// one element from the vector.* 580 | /// 581 | /// # Example 582 | /// 583 | /// ``` 584 | /// # use vec1::vec1; 585 | /// assert_eq!(vec1![1,2,4,3].reduce_ref(std::cmp::max), &4) 586 | /// ``` 587 | /// 588 | pub fn reduce_ref<'a>(&'a self, f: impl FnMut(&'a $item_ty, &'a $item_ty) -> &'a $item_ty) -> &'a $item_ty { 589 | //UNWRAP_SAFE: len is at least 1 590 | self.iter().reduce(f).unwrap() 591 | } 592 | 593 | /// Like [`Iterator::reduce()`] but does not return an option. 594 | /// 595 | /// This is roughly equivalent with `.iter_mut().reduce(f).unwrap()`. 596 | /// 597 | /// *Hint: Because of the reduction function returning a reference 598 | /// this method is (in general) only suitable for selecting exactly 599 | /// one element from the vector.* 600 | /// 601 | /// # Example 602 | /// 603 | /// ``` 604 | /// # use vec1::vec1; 605 | /// assert_eq!(vec1![1,2,4,3].reduce_mut(std::cmp::max), &mut 4) 606 | /// ``` 607 | /// 608 | pub fn reduce_mut<'a>(&'a mut self, f: impl FnMut(&'a mut $item_ty, &'a mut $item_ty) -> &'a mut $item_ty) -> &'a mut $item_ty { 609 | //UNWRAP_SAFE: len is at least 1 610 | self.iter_mut().reduce(f).unwrap() 611 | } 612 | 613 | } 614 | 615 | // methods in Vec not in &[] which can be directly exposed 616 | impl_wrapper! { 617 | base_bounds_macro = $($tb : $trait)?, 618 | impl<$t> $name<$t> { 619 | fn append(&mut self, other: &mut $wrapped<$t>) -> (); 620 | fn reserve(&mut self, additional: usize) -> (); 621 | fn reserve_exact(&mut self, additional: usize) -> (); 622 | fn shrink_to_fit(&mut self) -> (); 623 | fn as_mut_slice(&mut self) -> &mut [$item_ty]; 624 | fn push(&mut self, value: $item_ty) -> (); 625 | fn insert(&mut self, idx: usize, val: $item_ty) -> (); 626 | fn len(&self) -> usize; 627 | fn capacity(&self) -> usize; 628 | fn as_slice(&self) -> &[$item_ty]; 629 | } 630 | } 631 | 632 | impl<$t> $name<$t> 633 | where 634 | $item_ty: PartialEq<$item_ty>, 635 | $($tb : $trait,)? 636 | { 637 | pub fn dedup(&mut self) { 638 | self.0.dedup() 639 | } 640 | } 641 | 642 | impl<$t> $name<$t> 643 | where 644 | $item_ty: Copy, 645 | $($tb : $trait,)? 646 | { 647 | pub fn extend_from_slice(&mut self, slice: &[$item_ty]) { 648 | self.0.extend_from_slice(slice) 649 | } 650 | } 651 | 652 | impl<$t> $name<$t> 653 | where 654 | $item_ty: Clone, 655 | $($tb : $trait,)? 656 | { 657 | /// See [`Vec::resize()`] but fails if it would resize to length 0. 658 | pub fn resize(&mut self, len: usize, value: $item_ty) -> Result<(), Size0Error> { 659 | if len == 0 { 660 | Err(Size0Error) 661 | } else { 662 | self.0.resize(len, value); 663 | Ok(()) 664 | } 665 | } 666 | 667 | /// See [`Vec::resize()`]. 668 | pub fn resize_nonzero(&mut self, len: NonZeroUsize, value: $item_ty) { 669 | self.0.resize(len.get(), value); 670 | } 671 | 672 | /// See [`Vec::resize()`] but fails if it would resize to length 0. 673 | #[deprecated( 674 | since = "1.8.0", 675 | note = "try_ prefix created ambiguity use `resize_with`" 676 | )] 677 | #[inline(always)] 678 | pub fn try_resize(&mut self, len: usize, value: $item_ty) -> Result<(), Size0Error> { 679 | self.resize(len, value) 680 | } 681 | } 682 | 683 | impl<$t> From<$name<$t>> for $wrapped<$t> 684 | where 685 | $($tb : $trait,)? 686 | { 687 | fn from(vec: $name<$t>) -> $wrapped<$t> { 688 | vec.0 689 | } 690 | } 691 | 692 | 693 | impl<$t> TryFrom<$wrapped<$t>> for $name<$t> 694 | where 695 | $($tb : $trait,)? 696 | { 697 | type Error = Size0Error; 698 | fn try_from(vec: $wrapped<$t>) -> Result { 699 | if vec.is_empty() { 700 | Err(Size0Error) 701 | } else { 702 | Ok(Self(vec)) 703 | } 704 | } 705 | } 706 | 707 | 708 | impl<$t> TryFrom<&'_ [$item_ty]> for $name<$t> 709 | where 710 | $item_ty: Clone, 711 | $($tb : $trait,)? 712 | { 713 | type Error = Size0Error; 714 | fn try_from(slice: &'_ [$item_ty]) -> Result { 715 | if slice.is_empty() { 716 | Err(Size0Error) 717 | } else { 718 | Ok($name($wrapped::from(slice))) 719 | } 720 | } 721 | } 722 | 723 | impl<$t> TryFrom> for $name<$t> 724 | where 725 | $($tb : $trait,)? 726 | { 727 | type Error = Size0Error; 728 | fn try_from(slice: Box<[$item_ty]>) -> Result { 729 | if slice.is_empty() { 730 | Err(Size0Error) 731 | } else { 732 | let vec = Vec::from(slice); 733 | Self::try_from_vec(vec) 734 | } 735 | } 736 | } 737 | 738 | impl<$t> Debug for $name<$t> 739 | where 740 | $item_ty: Debug, 741 | $($tb : $trait,)? 742 | { 743 | #[inline] 744 | fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result { 745 | Debug::fmt(&self.0, fter) 746 | } 747 | } 748 | 749 | impl<$t> Clone for $name<$t> 750 | where 751 | $item_ty: Clone, 752 | $($tb : $trait,)? 753 | { 754 | #[inline] 755 | fn clone(&self) -> Self { 756 | $name(self.0.clone()) 757 | } 758 | } 759 | 760 | impl<$t, B> PartialEq for $name<$t> 761 | where 762 | B: ?Sized, 763 | $wrapped<$t>: PartialEq, 764 | $($tb : $trait,)? 765 | { 766 | #[inline] 767 | fn eq(&self, other: &B) -> bool { 768 | self.0.eq(other) 769 | } 770 | } 771 | 772 | impl<$t> Eq for $name<$t> 773 | where 774 | $item_ty: Eq, 775 | $($tb : $trait,)? 776 | {} 777 | 778 | impl<$t> Hash for $name<$t> 779 | where 780 | $item_ty: Hash, 781 | $($tb : $trait,)? 782 | { 783 | #[inline] 784 | fn hash(&self, state: &mut H) { 785 | self.0.hash(state) 786 | } 787 | } 788 | 789 | impl<$t> PartialOrd for $name<$t> 790 | where 791 | $item_ty: PartialOrd, 792 | $($tb : $trait,)? 793 | { 794 | #[inline] 795 | fn partial_cmp(&self, other: &$name<$t>) -> Option { 796 | self.0.partial_cmp(&other.0) 797 | } 798 | } 799 | 800 | impl<$t> Ord for $name<$t> 801 | where 802 | $item_ty: Ord, 803 | $($tb : $trait,)? 804 | { 805 | #[inline] 806 | fn cmp(&self, other: &$name<$t>) -> Ordering { 807 | self.0.cmp(&other.0) 808 | } 809 | } 810 | 811 | impl<$t> Deref for $name<$t> 812 | where 813 | $($tb : $trait,)? 814 | { 815 | type Target = [$item_ty]; 816 | 817 | fn deref(&self) -> &Self::Target { 818 | &*self.0 819 | } 820 | } 821 | 822 | impl<$t> DerefMut for $name<$t> 823 | where 824 | $($tb : $trait,)? 825 | { 826 | fn deref_mut(&mut self) -> &mut Self::Target { 827 | &mut *self.0 828 | } 829 | } 830 | 831 | impl<'a, $t> IntoIterator for &'a $name<$t> 832 | where 833 | $($tb : $trait,)? 834 | { 835 | type Item = &'a $item_ty; 836 | type IntoIter = core::slice::Iter<'a, $item_ty>; 837 | 838 | fn into_iter(self) -> Self::IntoIter { 839 | (&self.0).into_iter() 840 | } 841 | } 842 | 843 | impl<'a, $t> IntoIterator for &'a mut $name<$t> 844 | where 845 | $($tb : $trait,)? 846 | { 847 | type Item = &'a mut $item_ty; 848 | type IntoIter = core::slice::IterMut<'a, $item_ty>; 849 | 850 | fn into_iter(self) -> Self::IntoIter { 851 | (&mut self.0).into_iter() 852 | } 853 | } 854 | 855 | impl<$t> Default for $name<$t> 856 | where 857 | $item_ty: Default, 858 | $($tb : $trait,)? 859 | { 860 | fn default() -> Self { 861 | $name::new(Default::default()) 862 | } 863 | } 864 | 865 | impl<$t> AsRef<[$item_ty]> for $name<$t> 866 | where 867 | $($tb : $trait,)? 868 | { 869 | fn as_ref(&self) -> &[$item_ty] { 870 | self.0.as_ref() 871 | } 872 | } 873 | 874 | impl<$t> AsMut<[$item_ty]> for $name<$t> 875 | where 876 | $($tb : $trait,)? 877 | { 878 | fn as_mut(&mut self) -> &mut [$item_ty] { 879 | self.0.as_mut() 880 | } 881 | } 882 | 883 | impl<$t> AsRef<$wrapped<$t>> for $name<$t> 884 | where 885 | $($tb : $trait,)? 886 | { 887 | fn as_ref(&self) -> &$wrapped<$t>{ 888 | &self.0 889 | } 890 | } 891 | 892 | impl<$t> AsRef<$name<$t>> for $name<$t> 893 | where 894 | $($tb : $trait,)? 895 | { 896 | fn as_ref(&self) -> &$name<$t> { 897 | self 898 | } 899 | } 900 | 901 | impl<$t> AsMut<$name<$t>> for $name<$t> 902 | where 903 | $($tb : $trait,)? 904 | { 905 | fn as_mut(&mut self) -> &mut $name<$t> { 906 | self 907 | } 908 | } 909 | 910 | 911 | 912 | impl<$t> Borrow<[$item_ty]> for $name<$t> 913 | where 914 | $($tb : $trait,)? 915 | { 916 | fn borrow(&self) -> &[$item_ty] { 917 | self.0.as_ref() 918 | } 919 | } 920 | 921 | 922 | impl<$t> Borrow<$wrapped<$t>> for $name<$t> 923 | where 924 | $($tb : $trait,)? 925 | { 926 | fn borrow(&self) -> &$wrapped<$t>{ 927 | &self.0 928 | } 929 | } 930 | 931 | impl<$t, SI> Index for $name<$t> 932 | where 933 | SI: SliceIndex<[$item_ty]>, 934 | $($tb : $trait,)? 935 | { 936 | type Output = SI::Output; 937 | 938 | fn index(&self, index: SI) -> &SI::Output { 939 | self.0.index(index) 940 | } 941 | } 942 | 943 | impl<$t, SI> IndexMut for $name<$t> 944 | where 945 | SI: SliceIndex<[$item_ty]>, 946 | $($tb : $trait,)? 947 | { 948 | fn index_mut(&mut self, index: SI) -> &mut SI::Output { 949 | self.0.index_mut(index) 950 | } 951 | } 952 | 953 | 954 | impl<$t> BorrowMut<[$item_ty]> for $name<$t> 955 | where 956 | $($tb : $trait,)? 957 | { 958 | fn borrow_mut(&mut self) -> &mut [$item_ty] { 959 | self.0.as_mut() 960 | } 961 | } 962 | 963 | impl<$t> Extend<$item_ty> for $name<$t> 964 | where 965 | $($tb : $trait,)? 966 | { 967 | fn extend>(&mut self, iterable: IT) { 968 | self.0.extend(iterable) 969 | } 970 | } 971 | 972 | //Note: We can not (simply) have if feature serde and feature smallvec enable 973 | // dependency smallvec/serde, but we can mirror the serde implementation. 974 | #[cfg(feature = "serde")] 975 | const _: () = { 976 | use core::marker::PhantomData; 977 | use serde::{ 978 | de::{SeqAccess,Deserialize, Visitor, Deserializer, Error as _}, 979 | ser::{Serialize, Serializer, SerializeSeq} 980 | }; 981 | 982 | impl<$t> Serialize for $name<$t> 983 | where 984 | $item_ty: Serialize, 985 | $($tb : $trait,)? 986 | { 987 | fn serialize(&self, serializer: S) -> Result { 988 | let mut seq_ser = serializer.serialize_seq(Some(self.len()))?; 989 | for item in self { 990 | seq_ser.serialize_element(&item)?; 991 | } 992 | seq_ser.end() 993 | } 994 | } 995 | 996 | impl<'de, $t> Deserialize<'de> for $name<$t> 997 | where 998 | $item_ty: Deserialize<'de>, 999 | $($tb : $trait,)? 1000 | { 1001 | fn deserialize>(deserializer: D) -> Result { 1002 | deserializer.deserialize_seq(SmallVec1Visitor { 1003 | _type_carry: PhantomData, 1004 | }) 1005 | } 1006 | } 1007 | struct SmallVec1Visitor<$t> { 1008 | _type_carry: PhantomData<$t>, 1009 | } 1010 | 1011 | impl<'de, $t> Visitor<'de> for SmallVec1Visitor<$t> 1012 | where 1013 | $item_ty: Deserialize<'de>, 1014 | $($tb : $trait,)? 1015 | { 1016 | type Value = $name<$t>; 1017 | 1018 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 1019 | formatter.write_str("a sequence") 1020 | } 1021 | 1022 | fn visit_seq(self, mut seq: B) -> Result 1023 | where 1024 | B: SeqAccess<'de>, 1025 | { 1026 | let len = seq.size_hint().unwrap_or(0); 1027 | let mut vec = $wrapped::new(); 1028 | //FIXME use try_reserve 1029 | vec.reserve(len); 1030 | 1031 | while let Some(value) = seq.next_element()? { 1032 | vec.push(value); 1033 | } 1034 | 1035 | $name::try_from(vec).map_err(B::Error::custom) 1036 | } 1037 | } 1038 | }; 1039 | }; 1040 | ); 1041 | } 1042 | 1043 | #[cfg(test)] 1044 | mod tests { 1045 | use core::ops::{Bound, RangeBounds}; 1046 | 1047 | #[derive(Debug)] 1048 | struct AnyBound { 1049 | start: Bound, 1050 | end: Bound, 1051 | } 1052 | 1053 | fn bound_as_ref(bound: &Bound) -> Bound<&usize> { 1054 | match bound { 1055 | Bound::Included(v) => Bound::Included(v), 1056 | Bound::Excluded(v) => Bound::Excluded(v), 1057 | Bound::Unbounded => Bound::Unbounded, 1058 | } 1059 | } 1060 | 1061 | impl RangeBounds for AnyBound { 1062 | fn start_bound(&self) -> Bound<&usize> { 1063 | bound_as_ref(&self.start) 1064 | } 1065 | 1066 | fn end_bound(&self) -> Bound<&usize> { 1067 | bound_as_ref(&self.end) 1068 | } 1069 | } 1070 | 1071 | mod range_covers_slice_start { 1072 | use super::super::range_covers_slice_start; 1073 | use core::ops::Bound; 1074 | 1075 | #[test] 1076 | fn included_bound() { 1077 | let cases = &[ 1078 | (1, 10, (false, false)), 1079 | (0, 0, (true, false)), 1080 | (0, 1, (true, false)), 1081 | (1, 0, (false, true)), 1082 | (11, 10, (false, true)), 1083 | (1, 1, (false, false)), 1084 | ]; 1085 | for (start, len, expected_res) in cases { 1086 | let res = range_covers_slice_start(Bound::Included(start), *len); 1087 | assert_eq!( 1088 | res, *expected_res, 1089 | "Failed start=${}, len=${}, res]=${:?}", 1090 | start, len, res 1091 | ); 1092 | } 1093 | } 1094 | 1095 | #[test] 1096 | fn excluded_bound() { 1097 | let cases = &[ 1098 | (1, 10, (false, false)), 1099 | (0, 0, (false, true)), 1100 | (0, 1, (false, false)), 1101 | (1, 0, (false, true)), 1102 | (11, 10, (false, true)), 1103 | (1, 1, (false, true)), 1104 | ]; 1105 | for (start, len, expected_res) in cases { 1106 | let res = range_covers_slice_start(Bound::Excluded(start), *len); 1107 | assert_eq!( 1108 | res, *expected_res, 1109 | "Failed start=${}, len=${}, res]=${:?}", 1110 | start, len, res 1111 | ); 1112 | } 1113 | } 1114 | 1115 | #[test] 1116 | fn unbound_bound() { 1117 | for len in &[0, 1, 100] { 1118 | assert_eq!( 1119 | range_covers_slice_start(Bound::Unbounded, *len), 1120 | (true, false) 1121 | ); 1122 | } 1123 | } 1124 | } 1125 | 1126 | mod range_covers_slice_end { 1127 | use super::super::range_covers_slice_end; 1128 | use core::ops::Bound; 1129 | 1130 | #[test] 1131 | fn included_bound() { 1132 | let cases = &[ 1133 | (5, 6, (true, false)), 1134 | (4, 6, (false, false)), 1135 | (0, 10, (false, false)), 1136 | (6, 6, (true, true)), 1137 | (9, 8, (true, true)), 1138 | (0, 0, (true, true)), 1139 | ]; 1140 | for (end, len, expected_res) in cases { 1141 | let res = range_covers_slice_end(Bound::Included(end), *len); 1142 | assert_eq!( 1143 | res, *expected_res, 1144 | "Failed start=${}, len=${}, res]=${:?}", 1145 | end, len, res 1146 | ); 1147 | } 1148 | } 1149 | 1150 | #[test] 1151 | fn excluded_bound() { 1152 | let cases = &[ 1153 | (5, 6, (false, false)), 1154 | (4, 6, (false, false)), 1155 | (0, 10, (false, false)), 1156 | (6, 6, (true, false)), 1157 | (0, 0, (true, false)), 1158 | (11, 10, (true, true)), 1159 | (1, 0, (true, true)), 1160 | ]; 1161 | for (end, len, expected_res) in cases { 1162 | let res = range_covers_slice_end(Bound::Excluded(end), *len); 1163 | assert_eq!( 1164 | res, *expected_res, 1165 | "Unexpected result: start=${}, len=${}, res=${:?} => ${:?}", 1166 | end, len, res, expected_res 1167 | ); 1168 | } 1169 | } 1170 | 1171 | #[test] 1172 | fn unbound_bound() { 1173 | for len in &[0, 1, 100] { 1174 | assert_eq!( 1175 | range_covers_slice_end(Bound::Unbounded, *len), 1176 | (true, false) 1177 | ); 1178 | } 1179 | } 1180 | } 1181 | 1182 | mod range_covers_slice { 1183 | use super::super::range_covers_slice; 1184 | use super::AnyBound; 1185 | 1186 | #[test] 1187 | fn test_multiple_cases_from_table() { 1188 | use core::ops::Bound::*; 1189 | /* 1190 | start end cover-all oob 1191 | ---------------------------------------------- 1192 | cover cover true false 1193 | cover non-cover false false 1194 | cover cover-oob true true 1195 | non-cover cover false false 1196 | non-cover non-cover false false 1197 | non-cover cover-oob false true 1198 | non-cover-oob cover false true 1199 | non-cover-obb non-cover false true 1200 | non-cover-oob cover-oob false true 1201 | */ 1202 | let len = 3; 1203 | let cases: &[_] = &[ 1204 | (Included(0), Excluded(len), (true, false)), 1205 | (Unbounded, Excluded(len - 1), (false, false)), 1206 | (Included(0), Included(len), (true, true)), 1207 | (Included(1), Included(len - 1), (false, false)), 1208 | (Excluded(0), Included(len - 2), (false, false)), 1209 | (Included(1), Excluded(len + 4), (false, true)), 1210 | (Excluded(len), Excluded(len), (false, true)), 1211 | (Included(len + 1), Excluded(len - 1), (false, true)), 1212 | (Excluded(len), Included(len), (false, true)), 1213 | ]; 1214 | 1215 | for &(start, end, expected_res) in cases.into_iter() { 1216 | let bound = AnyBound { start, end }; 1217 | let res = range_covers_slice(&bound, len); 1218 | assert_eq!( 1219 | res, expected_res, 1220 | "Unexpected result: bound=${:?}, len=${} => ${:?}", 1221 | bound, len, expected_res 1222 | ) 1223 | } 1224 | } 1225 | } 1226 | } 1227 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate provides a `Vec` wrapper (`Vec1`) which guarantees to have at least 1 element. 2 | //! 3 | //! This can be useful if you have a API which accepts one or more of a kind. 4 | //! Instead of accepting a `Vec` and returning an error if it's empty a `Vec1` 5 | //! can be used assuring there is at least 1 element and through this reducing 6 | //! the number of possible error causes. 7 | //! 8 | //! # Example 9 | //! 10 | //! ``` 11 | //! #[macro_use] 12 | //! extern crate vec1; 13 | //! 14 | //! use vec1::Vec1; 15 | //! 16 | //! fn main() { 17 | //! // vec1![] makes sure at compiler time 18 | //! // there is at least one element 19 | //! //let names = vec1! [ ]; 20 | //! let names = vec1! [ "Liz" ]; 21 | //! greet(names); 22 | //! } 23 | //! 24 | //! fn greet(names: Vec1<&str>) { 25 | //! // methods like first/last which return a Option on Vec do 26 | //! // directly return the value, we know it's possible 27 | //! let first = names.first(); 28 | //! println!("hallo {}", first); 29 | //! for name in names.iter().skip(1) { 30 | //! println!(" who is also know as {}", name) 31 | //! } 32 | //! } 33 | //! 34 | //! ``` 35 | //! 36 | //! # Features 37 | //! 38 | //! - `std` (default): If disabled this crate will only use `core` and `alloc` but not `std` as dependencies. 39 | //! Because of this some traits and method are not available if it is disabled. 40 | //! 41 | //! - `serde`: Implements `Serialize` and `Deserialize` for `Vec1`. Also implements it for 42 | //! `SmallVec1` if both `serde` and `smallvec-v1` features are enabled. Note that 43 | //! enabling both `serde` and `smallvec-v1` implements `Serialize` and `Deserialize` 44 | //! for `SmallVec1` but will *not* enable `smallvec/serde` and as such will not 45 | //! implement the `serde` traits for `smallvec::SmallVec`. 46 | //! 47 | //! - `smallvec-v1` : Adds support for a vec1 variation backed by the smallvec crate 48 | //! version 1.x.y. (In the future there will likely be a additional `smallvec-v2`.). 49 | //! Works with no_std, i.e. if the default features are disabled. 50 | //! 51 | //! - `smallvec-v1-write`: Enables `smallvec/write`, this requires std. As we can't tell cargo to 52 | //! automatically enable `smallvec/write` if and only if `smallvec-v1` and 53 | //! `std` are both enabled this needs to be an extra feature. 54 | //! 55 | //! - `unstable-nightly-try-from-impl` (deprecated) : Was used to enable `TryFrom`/`TryInto` implementations 56 | //! before the traits became stable. Doesn't do anything by 57 | //! now, but still exist for compatibility reasons. 58 | //! 59 | //! # Rustdoc 60 | //! 61 | //! To have all intra-(and inter-) doc links working properly it is 62 | //! recommended to generate the documentation with nightly rustdoc. 63 | //! This is _only_ for the links in the documentation, library code 64 | //! and test should run at least on stable-2 (a two versions old stable) 65 | //! and might work on older versions too. 66 | //! 67 | //! # Rust Version / Stability 68 | //! 69 | //! Besides intra-doc links everything else is supposed to work on a 70 | //! two versions old stable release and everything newer, through it 71 | //! might work on older releases. 72 | //! 73 | //! Features which require nightly/beta will be prefixed with `unstable-`. 74 | //! 75 | //! For forwards compatibility the prefixed feature will be kept even if 76 | //! it's no longer unstable, through the code it feature gated is now also 77 | //! either always available or behind a non-prefixed feature gate which the 78 | //! `unstable-` prefixed feature gate enables. 79 | //! 80 | //! While I do try to keep `unstable-` features API stable this might not 81 | //! always be possible so enabling a `unstable-` prefixed features does 82 | //! exclude the stability guarantees normally expected from SemVer for 83 | //! code related to that feature. Still no patch version change will 84 | //! be pushed which brakes any code, even if it's `unstable-` prefixed! 85 | //! 86 | //! Updating dependencies follows following rules 87 | //! 88 | //! SemVer Dep. Update Kind | Publicly exposed dep? | Update of this Crate 89 | //! ------------------------|-----------------------|---------------- 90 | //! patch update | yes | patch (or minor) 91 | //! minor update | yes | minor 92 | //! major update | yes | won't happen, smallvec gets a second feature for v2 93 | //! patch update | no | patch (or minor) 94 | //! minor update | no | minor 95 | //! major update | no | minor 96 | //! 97 | //! If `smallvec` gets a major update a additional feature will be added supporting 98 | //! both major versions of it *without* introducing a major update for this crate. 99 | //! 100 | //! I do my best so that I will never have to release a major version update for this crate as 101 | //! this would lead to API incompatibilities for other crates using this crate in their public API. 102 | #![no_std] 103 | #![cfg_attr(docs, feature(doc_auto_cfg))] 104 | 105 | extern crate alloc; 106 | 107 | #[cfg(any(feature = "std", test))] 108 | extern crate std; 109 | 110 | #[doc(hidden)] 111 | #[cfg(feature = "smallvec-v1")] 112 | pub extern crate smallvec_v1_; 113 | 114 | #[macro_use] 115 | mod shared; 116 | 117 | #[cfg(feature = "smallvec-v1")] 118 | pub mod smallvec_v1; 119 | 120 | use core::{ 121 | fmt, 122 | iter::{DoubleEndedIterator, ExactSizeIterator, Extend, IntoIterator, Peekable}, 123 | mem::MaybeUninit, 124 | ops::RangeBounds, 125 | result::Result as StdResult, 126 | }; 127 | 128 | use alloc::{ 129 | boxed::Box, 130 | collections::{BinaryHeap, TryReserveError, VecDeque}, 131 | rc::Rc, 132 | string::String, 133 | vec::{self, Vec}, 134 | }; 135 | 136 | #[cfg(feature = "std")] 137 | use std::{ 138 | borrow::{Cow, ToOwned}, 139 | ffi::CString, 140 | io, 141 | num::NonZeroU8, 142 | sync::Arc, 143 | }; 144 | 145 | #[cfg(any(feature = "std", test))] 146 | use std::error::Error; 147 | 148 | use alloc::vec::Drain; 149 | 150 | /// Error returned by operations which would cause `Vec1` to have a length of 0. 151 | #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone)] 152 | pub struct Size0Error; 153 | 154 | impl fmt::Display for Size0Error { 155 | fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result { 156 | fter.write_str("Cannot produce a Vec1 with a length of zero.") 157 | } 158 | } 159 | 160 | #[cfg(any(feature = "std", test))] 161 | impl Error for Size0Error {} 162 | 163 | /// A macro similar to `vec!` to create a `Vec1`. 164 | /// 165 | /// If it is called with less then 1 element a 166 | /// compiler error is triggered (using `compile_error` 167 | /// to make sure you know what went wrong). 168 | #[macro_export] 169 | macro_rules! vec1 { 170 | () => ( 171 | compile_error!("Vec1 needs at least 1 element") 172 | ); 173 | ($first:expr $(, $item:expr)* , ) => ( 174 | $crate::vec1!($first $(, $item)*) 175 | ); 176 | ($first:expr $(, $item:expr)* ) => ({ 177 | #[allow(unused_mut)] 178 | let mut tmp = $crate::Vec1::new($first); 179 | $(tmp.push($item);)* 180 | tmp 181 | }); 182 | } 183 | 184 | shared_impl! { 185 | base_bounds_macro = , 186 | item_ty_macro = I, 187 | 188 | /// `std::vec::Vec` wrapper which guarantees to have at least 1 element. 189 | /// 190 | /// `Vec1` dereferences to `&[T]` and `&mut [T]` as functionality 191 | /// exposed through this can not change the length. 192 | /// 193 | /// Methods of `Vec` which can be called without reducing the length 194 | /// (e.g. `capacity()`, `reserve()`) are exposed through wrappers 195 | /// with the same function signature. 196 | /// 197 | /// Methods of `Vec` which could reduce the length to 0 198 | /// are return a `Result` wrapping their normal return type. 199 | /// 200 | /// Methods with returned `Option` with `None` if the length was 0 201 | /// (and do not reduce the length) now return T. (e.g. `first`, 202 | /// `last`, `first_mut`, etc.). 203 | /// 204 | /// All stable traits and methods implemented on `Vec` _should_ also 205 | /// be implemented on `Vec1` (except if they make no sense to implement 206 | /// due to the len 1 guarantee). Be aware implementations may lack behind a bit, 207 | /// fell free to open a issue/make a PR, but please search closed and open 208 | /// issues for duplicates first. 209 | /// 210 | pub struct Vec1(Vec); 211 | } 212 | 213 | impl IntoIterator for Vec1 { 214 | type Item = T; 215 | type IntoIter = vec::IntoIter; 216 | 217 | fn into_iter(self) -> Self::IntoIter { 218 | self.0.into_iter() 219 | } 220 | } 221 | 222 | impl Vec1 { 223 | /// Tries to create a `Vec1` from a `Vec`. 224 | /// 225 | /// The fact that the input is returned _as error_ if it's empty, 226 | /// means that it doesn't work well with the `?` operator. It naming 227 | /// is also semantic sub-optimal as it's not a "from" but "try from" 228 | /// conversion. Which is why this method is now deprecated. Instead 229 | /// use `try_from_vec` and once `TryFrom` is stable it will be possible 230 | /// to use `try_from`, too. 231 | /// 232 | /// # Errors 233 | /// 234 | /// If the input is empty the input is returned _as error_. 235 | #[deprecated( 236 | since = "1.2.0", 237 | note = "does not work with `?` use Vec1::try_from_vec() instead" 238 | )] 239 | pub fn from_vec(vec: Vec) -> StdResult> { 240 | if vec.is_empty() { 241 | Err(vec) 242 | } else { 243 | Ok(Vec1(vec)) 244 | } 245 | } 246 | 247 | /// Turns this `Vec1` into a `Vec`. 248 | pub fn into_vec(self) -> Vec { 249 | self.0 250 | } 251 | 252 | /// Return a reference to the underlying `Vec`. 253 | pub fn as_vec(&self) -> &Vec { 254 | &self.0 255 | } 256 | 257 | /// Create a new `Vec1` by consuming `self` and mapping each element. 258 | /// 259 | /// This is useful as it keeps the knowledge that the length is >= 1, 260 | /// even through the old `Vec1` is consumed and turned into an iterator. 261 | /// 262 | /// # Example 263 | /// 264 | /// ``` 265 | /// # #[macro_use] 266 | /// # extern crate vec1; 267 | /// # use vec1::Vec1; 268 | /// # fn main() { 269 | /// let data = vec1![1u8,2,3]; 270 | /// 271 | /// let data = data.mapped(|x|x*2); 272 | /// assert_eq!(data, vec![2,4,6]); 273 | /// 274 | /// // without mapped 275 | /// let data = Vec1::try_from_vec(data.into_iter().map(|x|x*2).collect::>()).unwrap(); 276 | /// assert_eq!(data, vec![4,8,12]); 277 | /// # } 278 | /// ``` 279 | pub fn mapped(self, map_fn: F) -> Vec1 280 | where 281 | F: FnMut(T) -> N, 282 | { 283 | Vec1(self.into_iter().map(map_fn).collect::>()) 284 | } 285 | 286 | /// Create a new `Vec1` by mapping references to the elements of `self`. 287 | /// 288 | /// The benefit to this compared to `Iterator::map` is that it's known 289 | /// that the length will still be at least 1 when creating the new `Vec1`. 290 | pub fn mapped_ref<'a, F, N>(&'a self, map_fn: F) -> Vec1 291 | where 292 | F: FnMut(&'a T) -> N, 293 | { 294 | Vec1(self.iter().map(map_fn).collect::>()) 295 | } 296 | 297 | /// Create a new `Vec1` by mapping mutable references to the elements of `self`. 298 | /// 299 | /// The benefit to this compared to `Iterator::map` is that it's known 300 | /// that the length will still be at least 1 when creating the new `Vec1`. 301 | pub fn mapped_mut<'a, F, N>(&'a mut self, map_fn: F) -> Vec1 302 | where 303 | F: FnMut(&'a mut T) -> N, 304 | { 305 | Vec1(self.iter_mut().map(map_fn).collect::>()) 306 | } 307 | 308 | /// Create a new `Vec1` by consuming `self` and mapping each element 309 | /// to a `Result`. 310 | /// 311 | /// This is useful as it keeps the knowledge that the length is >= 1, 312 | /// even through the old `Vec1` is consumed and turned into an iterator. 313 | /// 314 | /// As this method consumes self, returning an error means that this 315 | /// vec is dropped. I.e. this method behaves roughly like using a 316 | /// chain of `into_iter()`, `map`, `collect::,E>>` and 317 | /// then converting the `Vec` back to a `Vec1`. 318 | /// 319 | /// 320 | /// # Errors 321 | /// 322 | /// Once any call to `map_fn` returns a error that error is directly 323 | /// returned by this method. 324 | /// 325 | /// # Example 326 | /// 327 | /// ``` 328 | /// # #[macro_use] 329 | /// # extern crate vec1; 330 | /// # use vec1::Vec1; 331 | /// # fn main() { 332 | /// let data = vec1![1,2,3]; 333 | /// 334 | /// let data: Result, &'static str> = data.try_mapped(|x| Err("failed")); 335 | /// assert_eq!(data, Err("failed")); 336 | /// # } 337 | /// ``` 338 | pub fn try_mapped(self, map_fn: F) -> Result, E> 339 | where 340 | F: FnMut(T) -> Result, 341 | { 342 | let mut map_fn = map_fn; 343 | // ::collect>>() is uses the iterators size hint's lower bound 344 | // for with_capacity, which is 0 as it might fail at the first element 345 | let mut out = Vec::with_capacity(self.len()); 346 | for element in self { 347 | out.push(map_fn(element)?); 348 | } 349 | Ok(Vec1(out)) 350 | } 351 | 352 | /// Create a new `Vec1` by mapping references to the elements of `self` 353 | /// to `Result`s. 354 | /// 355 | /// The benefit to this compared to `Iterator::map` is that it's known 356 | /// that the length will still be at least 1 when creating the new `Vec1`. 357 | /// 358 | /// # Errors 359 | /// 360 | /// Once any call to `map_fn` returns a error that error is directly 361 | /// returned by this method. 362 | /// 363 | pub fn try_mapped_ref<'a, F, N, E>(&'a self, map_fn: F) -> Result, E> 364 | where 365 | F: FnMut(&'a T) -> Result, 366 | { 367 | let mut map_fn = map_fn; 368 | let mut out = Vec::with_capacity(self.len()); 369 | for element in self.iter() { 370 | out.push(map_fn(element)?); 371 | } 372 | Ok(Vec1(out)) 373 | } 374 | 375 | /// Create a new `Vec1` by mapping mutable references to the elements of 376 | /// `self` to `Result`s. 377 | /// 378 | /// The benefit to this compared to `Iterator::map` is that it's known 379 | /// that the length will still be at least 1 when creating the new `Vec1`. 380 | /// 381 | /// # Errors 382 | /// 383 | /// Once any call to `map_fn` returns a error that error is directly 384 | /// returned by this method. 385 | /// 386 | pub fn try_mapped_mut<'a, F, N, E>(&'a mut self, map_fn: F) -> Result, E> 387 | where 388 | F: FnMut(&'a mut T) -> Result, 389 | { 390 | let mut map_fn = map_fn; 391 | let mut out = Vec::with_capacity(self.len()); 392 | for element in self.iter_mut() { 393 | out.push(map_fn(element)?); 394 | } 395 | Ok(Vec1(out)) 396 | } 397 | 398 | /// Class `split_off` on the wrapped vector 399 | /// 400 | /// # Panics 401 | /// 402 | /// **If `at` is greater then `len`. (In the same way [`Vec.split_off()`] does.)** 403 | /// 404 | /// # Errors 405 | /// 406 | /// If splitting would result in an empty `Vec1` an error is returned, this happens 407 | /// if `at` is `0` or `at` is equals to `len`. 408 | pub fn split_off(&mut self, at: usize) -> Result, Size0Error> { 409 | if at == 0 || at == self.len() { 410 | Err(Size0Error) 411 | } else { 412 | let out = self.0.split_off(at); 413 | Ok(Vec1(out)) 414 | } 415 | } 416 | 417 | /// Calls `split_off` on the inner vec if both resulting parts have length >= 1. 418 | /// 419 | /// **In difference to `split_off` this also returns a `Size0Error` if `at` is 420 | /// greater then `len`. Which is different to how [`Vec.split_off()`] behaves.** 421 | /// 422 | /// # Errors 423 | /// 424 | /// If after the split any part would be empty an error is returned as the 425 | /// length >= 1 constraint must be uphold. 426 | #[deprecated( 427 | since = "1.8.0", 428 | note = "try_ prefix created ambiguity use `split_off`, `try_split_off doesn't panic on out of bounds `at`" 429 | )] 430 | pub fn try_split_off(&mut self, at: usize) -> Result, Size0Error> { 431 | if at == 0 || at >= self.len() { 432 | Err(Size0Error) 433 | } else { 434 | let out = self.0.split_off(at); 435 | Ok(Vec1(out)) 436 | } 437 | } 438 | 439 | /// Calls `splice` on the underlying vec (only) if it wont produce an empty vec. 440 | /// 441 | /// # Errors 442 | /// 443 | /// If range covers the whole vec and the replacement iterator doesn't yield 444 | /// any value an error is returned **instead of doing any splicing**. 445 | /// 446 | /// **To check if the iterator will yield values we need to turn call next on it 447 | /// once which means that if an error is returned [`Iterator::next()`] is still called once!** 448 | /// 449 | /// # Panics 450 | /// 451 | /// This **will** panic under the same conditions as [`Vec::splice()`], 452 | /// the conditions are: 453 | /// 454 | /// - if the starting point is greater than the end point 455 | /// - if the end point is greater than the length of the vector. 456 | /// 457 | pub fn splice( 458 | &mut self, 459 | range: R, 460 | replace_with: I, 461 | ) -> Result::IntoIter>, Size0Error> 462 | where 463 | I: IntoIterator, 464 | R: RangeBounds, 465 | { 466 | let mut replace_with = replace_with.into_iter().peekable(); 467 | let (range_covers_all, out_of_bounds) = 468 | crate::shared::range_covers_slice(&range, self.len()); 469 | 470 | if out_of_bounds { 471 | panic!("out of bounds range, either start > end or end > len"); 472 | } 473 | 474 | if range_covers_all && replace_with.peek().is_none() { 475 | Err(Size0Error) 476 | } else { 477 | let vec_splice = self.0.splice(range, replace_with); 478 | Ok(Splice { vec_splice }) 479 | } 480 | } 481 | } 482 | 483 | impl_wrapper! { 484 | base_bounds_macro = , 485 | impl Vec1 { 486 | fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>; 487 | fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError>; 488 | fn shrink_to(&mut self, min_capacity: usize) -> (); 489 | fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit]; 490 | } 491 | } 492 | 493 | impl Vec1 494 | where 495 | T: Clone, 496 | { 497 | pub fn extend_from_within(&mut self, src: R) 498 | where 499 | R: RangeBounds, 500 | { 501 | self.0.extend_from_within(src); 502 | } 503 | } 504 | 505 | impl Vec1 { 506 | /// Works like `&[u8].to_ascii_uppercase()` but returns a `Vec1` instead of a `Vec` 507 | pub fn to_ascii_uppercase(&self) -> Vec1 { 508 | Vec1(self.0.to_ascii_uppercase()) 509 | } 510 | 511 | /// Works like `&[u8].to_ascii_lowercase()` but returns a `Vec1` instead of a `Vec` 512 | pub fn to_ascii_lowercase(&self) -> Vec1 { 513 | Vec1(self.0.to_ascii_lowercase()) 514 | } 515 | } 516 | 517 | pub struct Splice<'a, I: Iterator + 'a> { 518 | vec_splice: vec::Splice<'a, Peekable>, 519 | } 520 | 521 | impl<'a, I> fmt::Debug for Splice<'a, I> 522 | where 523 | I: Iterator + 'a, 524 | vec::Splice<'a, Peekable>: fmt::Debug, 525 | { 526 | fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result { 527 | fter.debug_tuple("Splice").field(&self.vec_splice).finish() 528 | } 529 | } 530 | 531 | impl<'a, I> Iterator for Splice<'a, I> 532 | where 533 | I: Iterator, 534 | { 535 | type Item = I::Item; 536 | 537 | fn next(&mut self) -> Option { 538 | self.vec_splice.next() 539 | } 540 | 541 | fn size_hint(&self) -> (usize, Option) { 542 | self.vec_splice.size_hint() 543 | } 544 | } 545 | 546 | impl<'a, I> ExactSizeIterator for Splice<'a, I> where I: Iterator {} 547 | 548 | impl<'a, I> DoubleEndedIterator for Splice<'a, I> 549 | where 550 | I: Iterator, 551 | { 552 | fn next_back(&mut self) -> Option { 553 | self.vec_splice.next_back() 554 | } 555 | } 556 | 557 | impl PartialEq> for Vec1 558 | where 559 | A: PartialEq, 560 | { 561 | fn eq(&self, other: &Vec1) -> bool { 562 | self.0.eq(&other.0) 563 | } 564 | } 565 | 566 | #[cfg(feature = "std")] 567 | impl PartialEq> for Cow<'_, [T]> 568 | where 569 | T: PartialEq + Clone, 570 | { 571 | fn eq(&self, other: &Vec1) -> bool { 572 | self.eq(&other.0) 573 | } 574 | } 575 | 576 | impl PartialEq> for [T] 577 | where 578 | T: PartialEq, 579 | { 580 | fn eq(&self, other: &Vec1) -> bool { 581 | self.eq(&**other) 582 | } 583 | } 584 | 585 | impl PartialEq> for &'_ [T] 586 | where 587 | T: PartialEq, 588 | { 589 | fn eq(&self, other: &Vec1) -> bool { 590 | (**self).eq(&**other) 591 | } 592 | } 593 | 594 | impl PartialEq> for &'_ mut [T] 595 | where 596 | T: PartialEq, 597 | { 598 | fn eq(&self, other: &Vec1) -> bool { 599 | (**self).eq(&**other) 600 | } 601 | } 602 | 603 | impl PartialEq> for VecDeque 604 | where 605 | T: PartialEq, 606 | { 607 | fn eq(&self, other: &Vec1) -> bool { 608 | self.eq(other.as_vec()) 609 | } 610 | } 611 | 612 | impl<'a, T> Extend<&'a T> for Vec1 613 | where 614 | T: 'a + Copy, 615 | { 616 | fn extend(&mut self, iter: I) 617 | where 618 | I: IntoIterator, 619 | { 620 | self.0.extend(iter) 621 | } 622 | } 623 | 624 | macro_rules! wrapper_from_vec1 { 625 | (impl[$($tv:tt)*] From> for $other:ty where $($tail:tt)*) => ( 626 | impl<$($tv)*> From> for $other where $($tail)* { 627 | fn from(vec: Vec1<$tf>) -> Self { 628 | vec.0.into() 629 | } 630 | } 631 | ); 632 | } 633 | 634 | wrapper_from_vec1!(impl[T] From> for Rc<[T]> where); 635 | wrapper_from_vec1!(impl[T] From> for Box<[T]> where); 636 | wrapper_from_vec1!(impl[T] From> for BinaryHeap where T: Ord); 637 | #[cfg(feature = "std")] 638 | wrapper_from_vec1!(impl[T] From> for Arc<[T]> where); 639 | #[cfg(feature = "std")] 640 | wrapper_from_vec1!(impl['a, T] From> for Cow<'a, [T]> where T: Clone); 641 | 642 | #[cfg(feature = "std")] 643 | impl From> for CString { 644 | fn from(vec: Vec1) -> Self { 645 | CString::from(vec.0) 646 | } 647 | } 648 | 649 | impl TryFrom> for Box<[T; N]> { 650 | type Error = Vec1; 651 | 652 | fn try_from(vec: Vec1) -> Result { 653 | vec.0.try_into().map_err(Vec1) 654 | } 655 | } 656 | 657 | macro_rules! wrapper_from_to_try_from { 658 | (impl Into + impl[$($tv:tt)*] TryFrom<$tf:ty> for Vec1<$et:ty> $($tail:tt)*) => ( 659 | 660 | wrapper_from_to_try_from!(impl[$($tv),*] TryFrom<$tf> for Vec1<$et> $($tail)*); 661 | 662 | impl<$($tv)*> From> for $tf $($tail)* { 663 | fn from(vec: Vec1<$et>) -> Self { 664 | vec.0.into() 665 | } 666 | } 667 | ); 668 | (impl[$($tv:tt)*] TryFrom<$tf:ty> for Vec1<$et:ty> $($tail:tt)*) => ( 669 | impl<$($tv)*> TryFrom<$tf> for Vec1<$et> $($tail)* { 670 | type Error = Size0Error; 671 | 672 | fn try_from(inp: $tf) -> StdResult { 673 | if inp.is_empty() { 674 | Err(Size0Error) 675 | } else { 676 | Ok(Vec1(inp.into())) 677 | } 678 | } 679 | } 680 | ); 681 | } 682 | 683 | wrapper_from_to_try_from!(impl[T] TryFrom> for Vec1); 684 | wrapper_from_to_try_from!(impl[] TryFrom for Vec1); 685 | wrapper_from_to_try_from!(impl['a] TryFrom<&'a str> for Vec1); 686 | wrapper_from_to_try_from!(impl['a, T] TryFrom<&'a mut [T]> for Vec1 where T: Clone); 687 | wrapper_from_to_try_from!(impl Into + impl[T] TryFrom> for Vec1); 688 | 689 | #[cfg(feature = "std")] 690 | wrapper_from_to_try_from!(impl['a, T] TryFrom> for Vec1 where [T]: ToOwned>); 691 | 692 | #[cfg(feature = "std")] 693 | impl TryFrom for Vec1 { 694 | type Error = Size0Error; 695 | 696 | /// Like `Vec`'s `From` this will treat the `'\0'` as not part of the string. 697 | fn try_from(string: CString) -> StdResult { 698 | if string.as_bytes().is_empty() { 699 | Err(Size0Error) 700 | } else { 701 | Ok(Vec1(string.into())) 702 | } 703 | } 704 | } 705 | 706 | #[cfg(feature = "std")] 707 | impl io::Write for Vec1 { 708 | #[inline] 709 | fn write(&mut self, buf: &[u8]) -> io::Result { 710 | self.0.write(buf) 711 | } 712 | 713 | #[inline] 714 | fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { 715 | self.0.write_vectored(bufs) 716 | } 717 | 718 | #[inline] 719 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 720 | self.0.write_all(buf) 721 | } 722 | 723 | #[inline] 724 | fn flush(&mut self) -> io::Result<()> { 725 | self.0.flush() 726 | } 727 | } 728 | 729 | impl TryFrom> for [T; N] { 730 | type Error = Vec1; 731 | 732 | fn try_from(value: Vec1) -> StdResult { 733 | <[T; N]>::try_from(value.0).map_err(Vec1) 734 | } 735 | } 736 | 737 | impl TryFrom<[T; N]> for Vec1 { 738 | type Error = [T; N]; 739 | 740 | fn try_from(value: [T; N]) -> StdResult { 741 | if N == 0 { 742 | Err(value) 743 | } else { 744 | Ok(Self(value.into())) 745 | } 746 | } 747 | } 748 | 749 | impl TryFrom<&[T; N]> for Vec1 750 | where 751 | T: Clone, 752 | { 753 | type Error = Size0Error; 754 | 755 | fn try_from(value: &[T; N]) -> StdResult { 756 | if N == 0 { 757 | Err(Size0Error) 758 | } else { 759 | // TODO: as_slice can be removed when MSRV is bumped to 1.74 760 | Ok(Self(value.as_slice().into())) 761 | } 762 | } 763 | } 764 | 765 | impl TryFrom<&mut [T; N]> for Vec1 766 | where 767 | T: Clone, 768 | { 769 | type Error = Size0Error; 770 | 771 | fn try_from(value: &mut [T; N]) -> StdResult { 772 | if N == 0 { 773 | Err(Size0Error) 774 | } else { 775 | // TODO: as_slice can be removed when MSRV is bumped to 1.74 776 | Ok(Self(value.as_slice().into())) 777 | } 778 | } 779 | } 780 | 781 | #[cfg(test)] 782 | mod test { 783 | #![allow(non_snake_case)] 784 | 785 | mod Size0Error { 786 | #![allow(non_snake_case)] 787 | use super::super::*; 788 | use std::error::Error as StdError; 789 | 790 | #[test] 791 | fn implements_std_error() { 792 | fn comp_check() {} 793 | comp_check::(); 794 | } 795 | } 796 | 797 | mod Vec1 { 798 | use core::num::NonZeroUsize; 799 | use proptest::prelude::*; 800 | use std::panic::catch_unwind; 801 | 802 | use super::super::*; 803 | 804 | // prevent a type from causing us to use the wrong type 805 | #[allow(unused_macros)] 806 | macro_rules! vec { 807 | ($($any:tt)*) => { 808 | compile_error!("typo? vec! => vec1!") 809 | }; 810 | } 811 | 812 | #[test] 813 | fn new_vec1_macro() { 814 | let a = vec1![1u8, 10u8, 3u8]; 815 | assert_eq!(a, &[1, 10, 3]); 816 | 817 | let a = vec1![40u8]; 818 | assert_eq!(a, &[40]); 819 | 820 | //TODO comptest vec1![] => compiler error 821 | } 822 | 823 | #[test] 824 | fn new() { 825 | let a = Vec1::new(1u8); 826 | assert_eq!(a.len(), 1); 827 | assert_eq!(a.first(), &1u8); 828 | } 829 | 830 | #[test] 831 | fn with_capacity() { 832 | let a = Vec1::with_capacity(2u8, 10); 833 | assert_eq!(a.len(), 1); 834 | assert_eq!(a.first(), &2u8); 835 | assert_eq!(a.capacity(), 10); 836 | } 837 | 838 | #[test] 839 | fn capacity() { 840 | let a = Vec1::with_capacity(2u8, 123); 841 | assert_eq!(a.capacity(), 123); 842 | } 843 | 844 | #[test] 845 | fn reserve() { 846 | let mut a = Vec1::with_capacity(1u8, 1); 847 | assert_eq!(a.capacity(), 1); 848 | a.reserve(15); 849 | assert!(a.capacity() > 10); 850 | } 851 | 852 | #[test] 853 | fn reserve_exact() { 854 | let mut a = Vec1::with_capacity(1u8, 1); 855 | assert_eq!(a.capacity(), 1); 856 | a.reserve_exact(11); 857 | assert_eq!(a.capacity(), 12); 858 | } 859 | 860 | #[test] 861 | fn shrink_to_fit() { 862 | let mut a = Vec1::with_capacity(1u8, 20); 863 | a.push(13u8); 864 | a.shrink_to_fit(); 865 | assert_eq!(a.capacity(), 2); 866 | } 867 | 868 | #[test] 869 | fn into_boxed_slice() { 870 | let a = vec1![32u8, 12u8]; 871 | let boxed: Box<[u8]> = a.into_boxed_slice(); 872 | assert_eq!(&*boxed, &[32u8, 12u8]); 873 | } 874 | 875 | #[test] 876 | fn truncate() { 877 | let mut a = vec1![42u8, 32, 1]; 878 | a.truncate(1).unwrap(); 879 | assert_eq!(a.len(), 1); 880 | assert_eq!(a, &[42u8]); 881 | 882 | a.truncate(0).unwrap_err(); 883 | } 884 | 885 | #[test] 886 | fn try_truncate() { 887 | #![allow(deprecated)] 888 | 889 | let mut a = vec1![42u8, 32, 1]; 890 | a.try_truncate(1).unwrap(); 891 | assert_eq!(a.len(), 1); 892 | assert_eq!(a, &[42u8]); 893 | 894 | a.try_truncate(0).unwrap_err(); 895 | } 896 | 897 | #[test] 898 | fn as_slice() { 899 | let a = vec1![22u8, 12, 9]; 900 | let b: &[u8] = a.as_slice(); 901 | assert_eq!(b, &[22u8, 12, 9]); 902 | } 903 | 904 | #[test] 905 | fn as_mut_slice() { 906 | let mut a = vec1![22u8, 12, 9]; 907 | let b: &mut [u8] = a.as_mut_slice(); 908 | assert_eq!(b, &mut [22u8, 12, 9]); 909 | } 910 | 911 | #[test] 912 | fn as_ptr() { 913 | let a = vec1![22u8, 12, 9]; 914 | let a_ptr = a.as_ptr(); 915 | let a = a.into_vec(); 916 | let a_ptr2 = a.as_ptr(); 917 | assert_eq!(a_ptr, a_ptr2); 918 | } 919 | 920 | #[test] 921 | fn as_mut_ptr() { 922 | let mut a = vec1![22u8, 12, 9]; 923 | let a_ptr = a.as_mut_ptr(); 924 | let mut a = a.into_vec(); 925 | let a_ptr2 = a.as_mut_ptr(); 926 | assert_eq!(a_ptr, a_ptr2); 927 | } 928 | 929 | #[test] 930 | fn swap_remove() { 931 | let mut a = vec1![1u8, 2, 4]; 932 | a.swap_remove(0).unwrap(); 933 | assert_eq!(a, &[4u8, 2]); 934 | a.swap_remove(0).unwrap(); 935 | assert_eq!(a, &[2u8]); 936 | a.swap_remove(0).unwrap_err(); 937 | } 938 | 939 | #[test] 940 | fn try_swap_remove() { 941 | #![allow(deprecated)] 942 | let mut a = vec1![1u8, 2, 4]; 943 | a.try_swap_remove(0).unwrap(); 944 | assert_eq!(a, &[4u8, 2]); 945 | a.try_swap_remove(0).unwrap(); 946 | assert_eq!(a, &[2u8]); 947 | a.try_swap_remove(0).unwrap_err(); 948 | } 949 | 950 | #[test] 951 | fn insert() { 952 | // we only test that it's there as we only 953 | // forward to the underlying Vec so this test 954 | // is enough 955 | let mut a = vec1![9u8, 7, 3]; 956 | a.insert(1, 22); 957 | assert_eq!(a, &[9u8, 22, 7, 3]); 958 | } 959 | 960 | #[test] 961 | fn remove() { 962 | // we only test that it's there as we only 963 | // forward to the underlying Vec so this test 964 | // is enough 965 | let mut a = vec1![9u8, 7, 3]; 966 | a.remove(1).unwrap(); 967 | assert_eq!(a, &[9u8, 3]); 968 | a.remove(1).unwrap(); 969 | assert_eq!(a, &[9u8]); 970 | a.remove(0).unwrap_err(); 971 | 972 | catch_unwind(|| { 973 | let mut a = vec1![9u8, 7, 3]; 974 | let _ = a.remove(200); 975 | }) 976 | .unwrap_err(); 977 | } 978 | 979 | #[test] 980 | fn try_remove() { 981 | #![allow(deprecated)] 982 | 983 | // we only test that it's there as we only 984 | // forward to the underlying Vec so this test 985 | // is enough 986 | let mut a = vec1![9u8, 7, 3]; 987 | a.try_remove(1).unwrap(); 988 | assert_eq!(a, &[9u8, 3]); 989 | a.try_remove(1).unwrap(); 990 | assert_eq!(a, &[9u8]); 991 | a.try_remove(0).unwrap_err(); 992 | 993 | // try_remove is inconsistent and panics on out of bounds but e.g. try_split_off doesn't! 994 | catch_unwind(|| { 995 | let mut a = vec1![9u8, 7, 3]; 996 | let _ = a.remove(200); 997 | }) 998 | .unwrap_err(); 999 | } 1000 | 1001 | #[test] 1002 | fn retain() { 1003 | let mut a = vec1![9u8, 7, 3]; 1004 | let Size0Error = a.retain(|_| false).unwrap_err(); 1005 | assert_eq!(a.len(), 1); 1006 | assert_eq!(a.first(), &3); 1007 | 1008 | let mut a = vec1![9u8, 4, 3, 8, 9]; 1009 | a.retain(|v| *v % 2 == 0).unwrap(); 1010 | 1011 | assert_eq!(a.len(), 2); 1012 | assert_eq!(a.first(), &4); 1013 | assert_eq!(a.last(), &8); 1014 | } 1015 | 1016 | proptest! { 1017 | #[test] 1018 | fn same_behavior_as_vec_except_when_empty( 1019 | data in (1usize..=20) 1020 | .prop_flat_map(|size| prop::collection::vec(any::(), size..=size)) 1021 | ) { 1022 | use std::convert::TryFrom; 1023 | 1024 | let mut vec = data.clone(); 1025 | let mut vec1 = Vec1::try_from(data).unwrap(); 1026 | let last = *vec1.last(); 1027 | 1028 | vec.retain(|value| *value == true); 1029 | let res = vec1.retain(|value| *value == true); 1030 | 1031 | if vec.is_empty() { 1032 | assert_eq!(res, Err(Size0Error)); 1033 | assert_eq!(vec1.len(), 1); 1034 | assert_eq!(vec1.last(), &last); 1035 | } else { 1036 | assert_eq!(res, Ok(())); 1037 | assert_eq!(&*vec, &*vec1); 1038 | } 1039 | 1040 | } 1041 | } 1042 | 1043 | #[test] 1044 | fn dedup_by_key() { 1045 | let mut a = vec1![0xA3u16, 0x10F, 0x20F]; 1046 | a.dedup_by_key(|f| *f & 0xFF); 1047 | assert_eq!(a, &[0xA3, 0x10F]); 1048 | } 1049 | 1050 | #[test] 1051 | fn dedup_by() { 1052 | let mut a = vec1![1u8, 7u8, 12u8, 10u8]; 1053 | a.dedup_by(|l, r| (*l % 2 == 0) == (*r % 2 == 0)); 1054 | assert_eq!(a, &[1u8, 12u8]); 1055 | } 1056 | 1057 | #[test] 1058 | fn push() { 1059 | let mut a = vec1![1u8, 2, 10]; 1060 | a.push(1); 1061 | assert_eq!(a, &[1u8, 2, 10, 1]); 1062 | } 1063 | 1064 | #[test] 1065 | fn pop() { 1066 | let mut a = vec1![3u8, 10, 2]; 1067 | a.pop().unwrap(); 1068 | assert_eq!(a, &[3u8, 10]); 1069 | a.pop().unwrap(); 1070 | assert_eq!(a, &[3u8]); 1071 | a.pop().unwrap_err(); 1072 | } 1073 | 1074 | #[test] 1075 | fn try_pop() { 1076 | #![allow(deprecated)] 1077 | 1078 | let mut a = vec1![3u8, 10, 2]; 1079 | a.try_pop().unwrap(); 1080 | assert_eq!(a, &[3u8, 10]); 1081 | a.try_pop().unwrap(); 1082 | assert_eq!(a, &[3u8]); 1083 | a.try_pop().unwrap_err(); 1084 | } 1085 | 1086 | #[test] 1087 | fn append() { 1088 | let mut a = vec1![9u8, 12, 93]; 1089 | a.append(&mut std::vec![33, 12]); 1090 | assert_eq!(a, &[9u8, 12, 93, 33, 12]); 1091 | } 1092 | 1093 | macro_rules! do_call_drain { 1094 | ($vec:ident.drain($from:expr, $to:expr, $incl:expr) => $iter:ident => $map:block) => {{ 1095 | match ($from, $to) { 1096 | (Some(from), Some(to)) => { 1097 | if $incl { 1098 | let $iter = $vec.drain(from..=to); 1099 | $map 1100 | } else { 1101 | let $iter = $vec.drain(from..to); 1102 | $map 1103 | } 1104 | } 1105 | (None, Some(to)) => { 1106 | if $incl { 1107 | let $iter = $vec.drain(..=to); 1108 | $map 1109 | } else { 1110 | let $iter = $vec.drain(..to); 1111 | $map 1112 | } 1113 | } 1114 | (Some(from), None) => { 1115 | let $iter = $vec.drain(from..); 1116 | $map 1117 | } 1118 | (None, None) => { 1119 | let $iter = $vec.drain(..); 1120 | $map 1121 | } 1122 | } 1123 | }}; 1124 | } 1125 | 1126 | proptest! { 1127 | 1128 | #[test] 1129 | fn works_as_in_vec_except_if_draining_all( 1130 | data in prop::collection::vec(any::(), 1..=5), 1131 | start in (0usize..7).prop_map(|v| if v == 7 { None } else { Some(v) }), 1132 | end in (0usize..7).prop_map(|v| if v == 7 { None } else { Some(v) }), 1133 | incl in any::() 1134 | ) { 1135 | use std::convert::TryFrom; 1136 | 1137 | let mut data2 = data.clone(); 1138 | let res_vec = catch_unwind(move || { 1139 | let drained = do_call_drain!(data2.drain(start, end, incl) => iter => { iter.collect::>() }); 1140 | (data2, drained) 1141 | }); 1142 | 1143 | let mut data2 = Vec1::try_from(data.clone()).unwrap(); 1144 | let res_vec1 = catch_unwind(move ||{ 1145 | let drained = do_call_drain!(data2.drain(start, end, incl) => iter_res => { iter_res.map(|iter| iter.collect::>()) }); 1146 | (data2, drained) 1147 | }); 1148 | 1149 | match (res_vec, res_vec1) { 1150 | (Err(_), Err(_)) => {/*both paniced (out of bounds)*/}, 1151 | (Ok(_), Err(panic)) => std::panic::resume_unwind(panic), 1152 | (Err(panic), Ok(_)) => std::panic::resume_unwind(panic), 1153 | (Ok((vec, vec_drained)), Ok((vec1, vec1_res))) => { 1154 | if vec.is_empty() { 1155 | assert_eq!(vec1_res, Err(Size0Error)); 1156 | assert_eq!(&*vec1, &*data); 1157 | } else { 1158 | let vec1_drained = vec1_res.unwrap(); 1159 | assert_eq!(vec_drained, vec1_drained); 1160 | assert_eq!(&*vec, &*vec1); 1161 | } 1162 | } 1163 | } 1164 | } 1165 | } 1166 | 1167 | // #[test] 1168 | // fn clear() { 1169 | // //TODO comptest a.clear() must not compile 1170 | // let mut a = vec1![1u8,2,3]; 1171 | // a.clear(); 1172 | // } 1173 | 1174 | #[test] 1175 | fn len() { 1176 | let a = vec1![12u8, 4, 6, 2, 3]; 1177 | assert_eq!(a.len(), 5); 1178 | } 1179 | 1180 | #[test] 1181 | fn len_nonzero() { 1182 | let a = vec1![12u8, 4, 6, 2, 3]; 1183 | assert_eq!(a.len_nonzero(), NonZeroUsize::new(5).unwrap()); 1184 | } 1185 | 1186 | #[test] 1187 | fn is_empty() { 1188 | let a = vec1![12u8]; 1189 | //we don't impl. it but slice does 1190 | assert_eq!(a.is_empty(), false); 1191 | } 1192 | 1193 | #[test] 1194 | fn split_off() { 1195 | let mut left = vec1![88u8, 73, 12, 6]; 1196 | let mut right = left.split_off(1).unwrap(); 1197 | assert_eq!(left, &[88u8]); 1198 | assert_eq!(right, &[73u8, 12, 6]); 1199 | 1200 | right.split_off(0).unwrap_err(); 1201 | right.split_off(right.len()).unwrap_err(); 1202 | 1203 | catch_unwind(|| { 1204 | let mut v = vec1![1u8, 3, 4]; 1205 | let _ = v.split_off(200); 1206 | }) 1207 | .unwrap_err(); 1208 | } 1209 | 1210 | #[test] 1211 | fn try_split_off() { 1212 | #![allow(deprecated)] 1213 | 1214 | let mut left = vec1![88u8, 73, 12, 6]; 1215 | let mut right = left.try_split_off(1).unwrap(); 1216 | assert_eq!(left, &[88u8]); 1217 | assert_eq!(right, &[73u8, 12, 6]); 1218 | 1219 | right.try_split_off(0).unwrap_err(); 1220 | right.try_split_off(right.len()).unwrap_err(); 1221 | 1222 | // Also returns `Size0Error` on out of bounds. 1223 | let Size0Error = right.try_split_off(200).unwrap_err(); 1224 | } 1225 | 1226 | #[test] 1227 | fn resize_with() { 1228 | let mut a = vec1![1u8]; 1229 | a.resize_with(3, || 3u8).unwrap(); 1230 | assert_eq!(a, &[1u8, 3, 3]); 1231 | a.resize_with(0, || 0u8).unwrap_err(); 1232 | } 1233 | 1234 | #[test] 1235 | fn try_resize_with() { 1236 | #![allow(deprecated)] 1237 | 1238 | let mut a = vec1![1u8]; 1239 | a.try_resize_with(3, || 3u8).unwrap(); 1240 | assert_eq!(a, &[1u8, 3, 3]); 1241 | a.try_resize_with(0, || 0u8).unwrap_err(); 1242 | } 1243 | 1244 | #[test] 1245 | fn leak() { 1246 | let a = vec1![1u8, 3]; 1247 | let s: &'static mut [u8] = a.leak(); 1248 | assert_eq!(s, &[1u8, 3]); 1249 | } 1250 | 1251 | #[test] 1252 | fn resize() { 1253 | let mut a = vec1![1u8, 2]; 1254 | a.resize(4, 19).unwrap(); 1255 | assert_eq!(a, &[1u8, 2, 19, 19]); 1256 | a.resize(0, 19).unwrap_err(); 1257 | } 1258 | 1259 | #[test] 1260 | fn try_resize() { 1261 | #![allow(deprecated)] 1262 | 1263 | let mut a = vec1![1u8, 2]; 1264 | a.try_resize(4, 19).unwrap(); 1265 | assert_eq!(a, &[1u8, 2, 19, 19]); 1266 | a.try_resize(0, 19).unwrap_err(); 1267 | } 1268 | 1269 | #[test] 1270 | fn extend_from_slice() { 1271 | let mut a = vec1![1u8]; 1272 | a.extend_from_slice(&[2u8, 3, 4]); 1273 | assert_eq!(a, &[1u8, 2, 3, 4]); 1274 | } 1275 | 1276 | #[test] 1277 | fn dedup() { 1278 | let mut a = vec1![1u8, 1, 2, 2]; 1279 | a.dedup(); 1280 | assert_eq!(a, &[1u8, 2]); 1281 | } 1282 | 1283 | #[test] 1284 | fn splice() { 1285 | let mut a = vec1![1u8, 2, 3, 4]; 1286 | 1287 | let out: Vec = a.splice(1..3, std::vec![11, 12, 13]).unwrap().collect(); 1288 | assert_eq!(a, &[1u8, 11, 12, 13, 4]); 1289 | assert_eq!(out, &[2u8, 3]); 1290 | 1291 | let out: Vec = a.splice(2.., std::vec![7, 8]).unwrap().collect(); 1292 | assert_eq!(a, &[1u8, 11, 7, 8]); 1293 | assert_eq!(out, &[12u8, 13, 4]); 1294 | 1295 | let out: Vec = a.splice(..2, std::vec![100, 200]).unwrap().collect(); 1296 | assert_eq!(a, &[100u8, 200, 7, 8]); 1297 | assert_eq!(out, &[1u8, 11]); 1298 | 1299 | let out: Vec = a.splice(.., std::vec![10, 220]).unwrap().collect(); 1300 | assert_eq!(a, &[10u8, 220]); 1301 | assert_eq!(out, &[100u8, 200, 7, 8]); 1302 | 1303 | let out: Vec = a.splice(1.., Vec::::new()).unwrap().collect(); 1304 | assert_eq!(a, &[10u8]); 1305 | assert_eq!(out, &[220u8]); 1306 | 1307 | a.splice(.., Vec::::new()).unwrap_err(); 1308 | 1309 | assert!(catch_unwind(|| { 1310 | let mut a = vec1![1u8, 2]; 1311 | let _ = a.splice(1..0, std::vec![]); 1312 | }) 1313 | .is_err()); 1314 | 1315 | assert!(catch_unwind(|| { 1316 | let mut a = vec1![1u8, 2]; 1317 | let _ = a.splice(3.., std::vec![]); 1318 | }) 1319 | .is_err()); 1320 | 1321 | assert!(catch_unwind(|| { 1322 | let mut a = vec1![1u8, 2]; 1323 | let _ = a.splice(..3, std::vec![]); 1324 | }) 1325 | .is_err()); 1326 | } 1327 | 1328 | #[test] 1329 | fn first() { 1330 | let a = vec1![12u8, 13]; 1331 | assert_eq!(a.first(), &12u8); 1332 | } 1333 | 1334 | #[test] 1335 | fn first_mut() { 1336 | let mut a = vec1![12u8, 13]; 1337 | assert_eq!(a.first_mut(), &mut 12u8); 1338 | } 1339 | 1340 | #[test] 1341 | fn last() { 1342 | let a = vec1![12u8, 13]; 1343 | assert_eq!(a.last(), &13u8); 1344 | } 1345 | 1346 | #[test] 1347 | fn last_mut() { 1348 | let mut a = vec1![12u8, 13]; 1349 | assert_eq!(a.last_mut(), &mut 13u8); 1350 | } 1351 | 1352 | #[test] 1353 | fn split_off_last() { 1354 | let a = vec1![12u8, 33, 44]; 1355 | let (heads, last): (Vec, u8) = a.split_off_last(); 1356 | assert_eq!(heads, &[12u8, 33]); 1357 | assert_eq!(last, 44); 1358 | } 1359 | 1360 | #[test] 1361 | fn split_off_first() { 1362 | let a = vec1![12u8, 33, 45]; 1363 | let (first, tail): (u8, Vec) = a.split_off_first(); 1364 | assert_eq!(tail, &[33u8, 45]); 1365 | assert_eq!(first, 12); 1366 | } 1367 | 1368 | #[test] 1369 | fn from_vec_push() { 1370 | assert_eq!(Vec1::from_vec_push(std::vec![], 1u8), vec1![1]); 1371 | assert_eq!(Vec1::from_vec_push(std::vec![1, 2], 3u8), vec1![1, 2, 3]); 1372 | } 1373 | 1374 | #[test] 1375 | fn from_vec_insert() { 1376 | assert_eq!(Vec1::from_vec_insert(std::vec![], 0, 1u8), vec1![1]); 1377 | assert_eq!( 1378 | Vec1::from_vec_insert(std::vec![1, 3], 1, 2u8), 1379 | vec1![1, 2, 3] 1380 | ); 1381 | assert!(catch_unwind(|| { 1382 | Vec1::from_vec_insert(std::vec![1, 3], 3, 2u8); 1383 | }) 1384 | .is_err()); 1385 | } 1386 | 1387 | #[test] 1388 | fn reduce() { 1389 | assert_eq!(vec1![1u8, 2, 4, 3].reduce(std::cmp::max), 4); 1390 | assert_eq!(vec1![1u8, 2, 2, 3].reduce(|a, b| a + b), 8); 1391 | } 1392 | 1393 | #[test] 1394 | fn reduce_ref() { 1395 | let a = vec1![std::cell::Cell::new(4)]; 1396 | a.reduce_ref(std::cmp::max).set(44); 1397 | assert_eq!(a, vec1![std::cell::Cell::new(44)]); 1398 | } 1399 | 1400 | #[test] 1401 | fn reduce_mut() { 1402 | let mut a = vec1![1u8, 2, 4, 3]; 1403 | *a.reduce_mut(std::cmp::max) *= 2; 1404 | assert_eq!(a, vec1![1u8, 2, 8, 3]); 1405 | } 1406 | 1407 | #[test] 1408 | fn try_reserve() { 1409 | let mut a = vec1![1u8, 2, 4, 3]; 1410 | a.try_reserve(100).unwrap(); 1411 | assert!(a.capacity() > 100); 1412 | a.try_reserve(usize::MAX).unwrap_err(); 1413 | } 1414 | 1415 | #[test] 1416 | fn try_reserve_exact() { 1417 | let mut a = vec1![1u8, 2, 4, 3]; 1418 | a.try_reserve_exact(124).unwrap(); 1419 | assert_eq!(a.capacity(), 128); 1420 | a.try_reserve(usize::MAX).unwrap_err(); 1421 | } 1422 | 1423 | #[test] 1424 | fn shrink_to() { 1425 | let mut a = Vec1::with_capacity(1, 16); 1426 | a.extend([2, 3, 4]); 1427 | a.shrink_to(16); 1428 | assert_eq!(a.capacity(), 16); 1429 | a.shrink_to(4); 1430 | assert_eq!(a.capacity(), 4); 1431 | a.shrink_to(1); 1432 | assert_eq!(a.capacity(), 4); 1433 | } 1434 | 1435 | #[test] 1436 | fn spare_capacity_mut() { 1437 | let mut a = Vec1::with_capacity(1, 16); 1438 | a.extend([2, 3, 4]); 1439 | assert_eq!(a.spare_capacity_mut().len(), 12); 1440 | } 1441 | 1442 | #[test] 1443 | fn extend_from_within() { 1444 | let mut a = vec1!["a", "b", "c", "d"]; 1445 | a.extend_from_within(1..3); 1446 | assert_eq!(a, ["a", "b", "c", "d", "b", "c"]); 1447 | } 1448 | 1449 | mod AsMut { 1450 | use crate::*; 1451 | 1452 | #[test] 1453 | fn of_slice() { 1454 | let mut a = vec1![33u8, 123]; 1455 | let s: &mut [u8] = a.as_mut(); 1456 | assert_eq!(s, &mut [33u8, 123]); 1457 | } 1458 | 1459 | #[test] 1460 | fn of_self() { 1461 | let mut a = vec1![33u8, 123]; 1462 | let v: &mut Vec1 = a.as_mut(); 1463 | assert_eq!(v, &mut vec1![33u8, 123]); 1464 | } 1465 | 1466 | //TODO comptest AsMut of Vec must not compile 1467 | } 1468 | 1469 | mod AsRef { 1470 | use crate::*; 1471 | 1472 | #[test] 1473 | fn of_slice() { 1474 | let a = vec1![32u8, 103]; 1475 | let s: &[u8] = a.as_ref(); 1476 | assert_eq!(s, &[32u8, 103]); 1477 | } 1478 | 1479 | #[test] 1480 | fn of_vec() { 1481 | let a = vec1![33u8]; 1482 | let v: &Vec = a.as_ref(); 1483 | assert_eq!(v, &std::vec![33u8]); 1484 | } 1485 | 1486 | #[test] 1487 | fn of_self() { 1488 | let a = vec1![211u8]; 1489 | let v: &Vec1 = a.as_ref(); 1490 | assert_eq!(v, &vec1![211u8]); 1491 | } 1492 | } 1493 | 1494 | mod Borrow { 1495 | use core::borrow::Borrow as _; 1496 | 1497 | use crate::*; 1498 | 1499 | #[test] 1500 | fn of_slice() { 1501 | let a = vec1![32u8, 103]; 1502 | let s: &[u8] = a.borrow(); 1503 | assert_eq!(s, &[32u8, 103]); 1504 | } 1505 | 1506 | #[test] 1507 | fn of_vec() { 1508 | let a = vec1![33u8]; 1509 | let v: &Vec = a.borrow(); 1510 | assert_eq!(v, &std::vec![33u8]); 1511 | } 1512 | } 1513 | 1514 | mod BorrowMut { 1515 | use core::borrow::BorrowMut as _; 1516 | 1517 | use crate::*; 1518 | 1519 | #[test] 1520 | fn of_slice() { 1521 | let mut a = vec1![32u8, 103]; 1522 | let s: &mut [u8] = a.borrow_mut(); 1523 | assert_eq!(s, &mut [32u8, 103]); 1524 | } 1525 | } 1526 | 1527 | mod Clone { 1528 | #[test] 1529 | fn clone() { 1530 | let a = vec1![41u8, 12, 33]; 1531 | let b = a.clone(); 1532 | assert_eq!(a, b); 1533 | } 1534 | } 1535 | 1536 | mod Debug { 1537 | #[test] 1538 | fn fmt() { 1539 | let a = vec1![2u8, 3, 1]; 1540 | assert_eq!(std::format!("{:?}", a), "[2, 3, 1]"); 1541 | } 1542 | } 1543 | 1544 | mod Default { 1545 | use crate::*; 1546 | 1547 | #[test] 1548 | fn default() { 1549 | let a = Vec1::::default(); 1550 | assert_eq!(a, &[0u8]); 1551 | } 1552 | } 1553 | 1554 | mod Deref { 1555 | use core::ops::Deref; 1556 | 1557 | use crate::*; 1558 | 1559 | #[test] 1560 | fn deref() { 1561 | let a = vec1![99, 73]; 1562 | let d: &[u8] = as Deref>::deref(&a); 1563 | assert_eq!(d, &[99, 73]); 1564 | } 1565 | } 1566 | 1567 | mod DerefMut { 1568 | use core::ops::DerefMut; 1569 | 1570 | use crate::*; 1571 | 1572 | #[test] 1573 | fn deref() { 1574 | let mut a = vec1![99, 73]; 1575 | let d: &mut [u8] = as DerefMut>::deref_mut(&mut a); 1576 | assert_eq!(d, &mut [99, 73]); 1577 | } 1578 | } 1579 | 1580 | mod Eq { 1581 | use crate::*; 1582 | 1583 | #[test] 1584 | fn eq() { 1585 | let a = vec1![41u8, 12, 33]; 1586 | let b = a.clone(); 1587 | assert_eq!(a, b); 1588 | 1589 | fn impls_eq() {} 1590 | impls_eq::>(); 1591 | } 1592 | } 1593 | 1594 | mod Extend { 1595 | use std::borrow::ToOwned; 1596 | 1597 | #[test] 1598 | fn by_value_ref() { 1599 | let mut a = vec1![0]; 1600 | a.extend(vec1![33u8].iter()); 1601 | assert_eq!(a, &[0, 33]); 1602 | } 1603 | 1604 | #[test] 1605 | fn by_value() { 1606 | let mut a = vec1!["hy".to_owned()]; 1607 | a.extend(vec1!["ho".to_owned()].into_iter()); 1608 | assert_eq!(a, &["hy".to_owned(), "ho".to_owned()]); 1609 | } 1610 | } 1611 | 1612 | mod TryFrom { 1613 | use crate::*; 1614 | use std::{borrow::ToOwned, convert::TryFrom}; 1615 | 1616 | #[test] 1617 | fn from_slice_ref() { 1618 | let slice: &[String] = &["hy".to_owned()]; 1619 | let vec = Vec1::try_from(slice).unwrap(); 1620 | assert_eq!(vec, slice); 1621 | 1622 | let slice: &[String] = &[]; 1623 | Vec1::try_from(slice).unwrap_err(); 1624 | } 1625 | 1626 | #[test] 1627 | fn from_slice_mut() { 1628 | let slice: &mut [String] = &mut ["hy".to_owned()]; 1629 | let vec = Vec1::try_from(&mut *slice).unwrap(); 1630 | assert_eq!(vec, slice); 1631 | 1632 | let slice: &mut [String] = &mut []; 1633 | Vec1::try_from(slice).unwrap_err(); 1634 | } 1635 | 1636 | #[test] 1637 | fn from_str() { 1638 | let vec = Vec1::::try_from("hy").unwrap(); 1639 | assert_eq!(vec, "hy".as_bytes()); 1640 | Vec1::::try_from("").unwrap_err(); 1641 | } 1642 | 1643 | #[test] 1644 | fn from_array() { 1645 | // we just test if there is a impl for a arbitrary len 1646 | // which here is good enough but far from complete coverage! 1647 | let array = [11; 100]; 1648 | let vec = Vec1::try_from(array).unwrap(); 1649 | assert_eq!(vec.iter().sum::(), 1100); 1650 | 1651 | Vec1::try_from([0u8; 0]).unwrap_err(); 1652 | } 1653 | 1654 | #[test] 1655 | fn from_array_ref() { 1656 | // we just test if there is a impl for a arbitrary len 1657 | // which here is good enough but far from complete coverage! 1658 | let array = [11; 100]; 1659 | let vec = Vec1::try_from(&array).unwrap(); 1660 | assert_eq!(vec.iter().sum::(), 1100); 1661 | 1662 | Vec1::try_from([0u8; 0]).unwrap_err(); 1663 | } 1664 | 1665 | #[test] 1666 | fn from_array_mut() { 1667 | // we just test if there is a impl for a arbitrary len 1668 | // which here is good enough but far from complete coverage! 1669 | let mut array = [11; 100]; 1670 | let vec = Vec1::try_from(&mut array).unwrap(); 1671 | assert_eq!(vec.iter().sum::(), 1100); 1672 | 1673 | Vec1::try_from([0u8; 0]).unwrap_err(); 1674 | } 1675 | 1676 | #[test] 1677 | fn from_binary_heap() { 1678 | use std::collections::BinaryHeap; 1679 | let mut heap = BinaryHeap::new(); 1680 | heap.push(1u8); 1681 | heap.push(100); 1682 | heap.push(3); 1683 | 1684 | let vec = Vec1::try_from(heap).unwrap(); 1685 | assert_eq!(vec.len(), 3); 1686 | assert_eq!(vec.first(), &100); 1687 | assert!(vec.contains(&3)); 1688 | assert!(vec.contains(&1)); 1689 | 1690 | Vec1::::try_from(BinaryHeap::new()).unwrap_err(); 1691 | } 1692 | 1693 | #[test] 1694 | fn from_boxed_slice() { 1695 | let boxed = Box::new([20u8; 10]) as Box<[u8]>; 1696 | let vec = Vec1::try_from(boxed).unwrap(); 1697 | assert_eq!(vec, &[20u8; 10]); 1698 | } 1699 | 1700 | #[cfg(feature = "std")] 1701 | #[test] 1702 | fn from_cstring() { 1703 | let cstring = CString::new("ABA").unwrap(); 1704 | let vec = Vec1::::try_from(cstring).unwrap(); 1705 | assert_eq!(vec, &[65, 66, 65]); 1706 | 1707 | let cstring = CString::new("").unwrap(); 1708 | Vec1::::try_from(cstring).unwrap_err(); 1709 | } 1710 | 1711 | #[cfg(feature = "std")] 1712 | #[test] 1713 | fn from_cow() { 1714 | let slice: &[u8] = &[12u8, 33]; 1715 | let cow = Cow::Borrowed(slice); 1716 | let vec = Vec1::try_from(cow).unwrap(); 1717 | assert_eq!(vec, slice); 1718 | 1719 | let slice: &[u8] = &[]; 1720 | let cow = Cow::Borrowed(slice); 1721 | Vec1::try_from(cow).unwrap_err(); 1722 | } 1723 | 1724 | #[test] 1725 | fn from_string() { 1726 | let vec = Vec1::::try_from("ABA".to_owned()).unwrap(); 1727 | assert_eq!(vec, &[65, 66, 65]); 1728 | 1729 | Vec1::::try_from("".to_owned()).unwrap_err(); 1730 | } 1731 | 1732 | #[test] 1733 | fn from_vec_deque() { 1734 | let queue = VecDeque::from(std::vec![1u8, 2, 3]); 1735 | let vec = Vec1::try_from(queue).unwrap(); 1736 | assert_eq!(vec, &[1u8, 2, 3]); 1737 | 1738 | Vec1::::try_from(VecDeque::new()).unwrap_err(); 1739 | } 1740 | } 1741 | 1742 | mod Hash { 1743 | use crate::*; 1744 | use std::{ 1745 | collections::hash_map::DefaultHasher, 1746 | hash::{Hash, Hasher}, 1747 | }; 1748 | 1749 | #[test] 1750 | fn hash() { 1751 | let a = vec1![1u8, 10, 33, 12]; 1752 | let mut hasher = DefaultHasher::new(); 1753 | a.hash(&mut hasher); 1754 | let a_state = hasher.finish(); 1755 | 1756 | let b = a.into_vec(); 1757 | let mut hasher = DefaultHasher::new(); 1758 | b.hash(&mut hasher); 1759 | let b_state = hasher.finish(); 1760 | 1761 | assert_eq!(a_state, b_state); 1762 | } 1763 | 1764 | #[test] 1765 | fn hash_slice() { 1766 | let a: &[_] = &[vec1![1u8, 10, 33, 12], vec1![22, 12]]; 1767 | let mut hasher = DefaultHasher::new(); 1768 | as Hash>::hash_slice(a, &mut hasher); 1769 | let a_state = hasher.finish(); 1770 | 1771 | let b: &[_] = &[std::vec![1u8, 10, 33, 12], std::vec![22, 12]]; 1772 | let mut hasher = DefaultHasher::new(); 1773 | as Hash>::hash_slice(b, &mut hasher); 1774 | let b_state = hasher.finish(); 1775 | 1776 | assert_eq!(a_state, b_state); 1777 | } 1778 | } 1779 | 1780 | mod Index { 1781 | use std::ops::Index; 1782 | 1783 | #[test] 1784 | fn index() { 1785 | let vec = vec1![34u8, 99, 10, 73]; 1786 | assert_eq!(vec.index(1..3), &[99, 10]); 1787 | assert_eq!(&vec[1..3], &[99, 10]); 1788 | assert_eq!(vec[0], 34u8); 1789 | } 1790 | } 1791 | 1792 | mod IndexMut { 1793 | use std::ops::IndexMut; 1794 | 1795 | #[test] 1796 | fn index_mut() { 1797 | let mut vec = vec1![34u8, 99, 10, 73]; 1798 | assert_eq!(vec.index_mut(1..3), &mut [99, 10]); 1799 | assert_eq!(&mut vec[1..3], &mut [99, 10]); 1800 | } 1801 | } 1802 | 1803 | mod IntoIterator { 1804 | #[test] 1805 | fn of_self() { 1806 | let vec = vec1![1u8, 33u8, 57]; 1807 | let mut iter = vec.into_iter(); 1808 | assert_eq!(iter.size_hint(), (3, Some(3))); 1809 | // impl. ExactSizedIterator 1810 | assert_eq!(iter.len(), 3); 1811 | assert_eq!(iter.next(), Some(1)); 1812 | // impl. DoubleEndedIterator 1813 | assert_eq!(iter.next_back(), Some(57)); 1814 | assert_eq!(iter.next(), Some(33)); 1815 | assert_eq!(iter.next(), None); 1816 | } 1817 | 1818 | #[test] 1819 | fn of_self_ref() { 1820 | let vec = vec1![1u8, 33u8, 57]; 1821 | let mut iter = (&vec).into_iter(); 1822 | assert_eq!(iter.size_hint(), (3, Some(3))); 1823 | // impl. ExactSizedIterator 1824 | assert_eq!(iter.len(), 3); 1825 | assert_eq!(iter.next(), Some(&1)); 1826 | // impl. DoubleEndedIterator 1827 | assert_eq!(iter.next_back(), Some(&57)); 1828 | assert_eq!(iter.next(), Some(&33)); 1829 | assert_eq!(iter.next(), None); 1830 | } 1831 | 1832 | #[test] 1833 | fn of_self_mut() { 1834 | let mut vec = vec1![1u8, 33u8, 57]; 1835 | let mut iter = (&mut vec).into_iter(); 1836 | assert_eq!(iter.size_hint(), (3, Some(3))); 1837 | // impl. ExactSizedIterator 1838 | assert_eq!(iter.len(), 3); 1839 | assert_eq!(iter.next(), Some(&mut 1)); 1840 | // impl. DoubleEndedIterator 1841 | assert_eq!(iter.next_back(), Some(&mut 57)); 1842 | assert_eq!(iter.next(), Some(&mut 33)); 1843 | assert_eq!(iter.next(), None); 1844 | } 1845 | } 1846 | 1847 | mod Ord { 1848 | use std::cmp::Ordering; 1849 | 1850 | #[test] 1851 | fn cmp() { 1852 | // just make sure we implemented it 1853 | // we will forward to Vec's impl. anyway 1854 | // so no reasone to test if cmp works correctly 1855 | // (it doing so is desired sue proptest!). 1856 | let a = vec1![1u8, 3, 4]; 1857 | let b = vec1![1u8, 4, 2]; 1858 | assert_eq!(a.cmp(&b), Ordering::Less); 1859 | } 1860 | } 1861 | 1862 | mod PartialEq { 1863 | use crate::*; 1864 | use std::borrow::ToOwned; 1865 | 1866 | #[test] 1867 | fn to_array_ref() { 1868 | let vec = vec1![67u8, 73, 12]; 1869 | let array: &[u8; 3] = &[67, 73, 12]; 1870 | let array2: &[u8; 3] = &[67, 73, 33]; 1871 | assert_eq!(vec.eq(&array), true); 1872 | assert_eq!(vec.eq(&array2), false); 1873 | } 1874 | 1875 | #[test] 1876 | fn to_slice_ref() { 1877 | let vec = vec1![67u8, 73, 12]; 1878 | let array: &[u8] = &[67, 73, 12]; 1879 | let array2: &[u8] = &[67, 73, 33]; 1880 | assert_eq!(vec.eq(&array), true); 1881 | assert_eq!(vec.eq(&array2), false); 1882 | } 1883 | 1884 | #[test] 1885 | fn to_slice_mut() { 1886 | let vec = vec1![67u8, 73, 12]; 1887 | let array: &mut [u8] = &mut [67, 73, 12]; 1888 | let array2: &mut [u8] = &mut [67, 73, 33]; 1889 | assert_eq!(vec.eq(&array), true); 1890 | assert_eq!(vec.eq(&array2), false); 1891 | } 1892 | 1893 | #[test] 1894 | fn to_array() { 1895 | let vec = vec1![67u8, 73, 12]; 1896 | let array: [u8; 3] = [67, 73, 12]; 1897 | let array2: [u8; 3] = [67, 73, 33]; 1898 | assert_eq!(vec.eq(&array), true); 1899 | assert_eq!(vec.eq(&array2), false); 1900 | } 1901 | 1902 | #[test] 1903 | fn to_slice() { 1904 | let vec = vec1![67u8, 73, 12]; 1905 | let array: &[u8] = &[67, 73, 12]; 1906 | let array2: &[u8] = &[67, 73, 33]; 1907 | 1908 | assert_eq!( as PartialEq<[u8]>>::eq(&vec, array), true); 1909 | assert_eq!( as PartialEq<[u8]>>::eq(&vec, array2), false); 1910 | } 1911 | 1912 | #[test] 1913 | fn to_self_kind() { 1914 | let a = vec1!["hy".to_owned()]; 1915 | let b = vec1!["hy"]; 1916 | assert_eq!(a, b); 1917 | } 1918 | } 1919 | 1920 | mod PartialOrd { 1921 | use std::cmp::Ordering; 1922 | 1923 | #[test] 1924 | fn with_self_kind() { 1925 | let a = vec1!["b"]; 1926 | let b = vec1!["a"]; 1927 | assert_eq!(a.partial_cmp(&b), Some(Ordering::Greater)); 1928 | } 1929 | } 1930 | 1931 | #[cfg(feature = "std")] 1932 | mod Write { 1933 | use std::io::Write; 1934 | 1935 | #[test] 1936 | fn for_bytes() { 1937 | let mut v = vec1![1u8]; 1938 | v.write(&[65, 100, 12]).unwrap(); 1939 | assert_eq!(v, &[1u8, 65, 100, 12]); 1940 | } 1941 | } 1942 | 1943 | #[cfg(feature = "serde")] 1944 | mod serde { 1945 | use crate::*; 1946 | 1947 | #[test] 1948 | fn empty() { 1949 | let result: Result, _> = serde_json::from_str("[]"); 1950 | assert!(result.is_err()); 1951 | } 1952 | 1953 | #[test] 1954 | fn one_element() { 1955 | let vec: Vec1 = serde_json::from_str("[1]").unwrap(); 1956 | assert_eq!(vec, vec1![1]); 1957 | let json = serde_json::to_string(&vec).unwrap(); 1958 | assert_eq!(json, "[1]"); 1959 | } 1960 | 1961 | #[test] 1962 | fn multiple_elements() { 1963 | let vec: Vec1 = serde_json::from_str("[1, 2, 3]").unwrap(); 1964 | assert_eq!(vec, vec1![1, 2, 3]); 1965 | let json = serde_json::to_string(&vec).unwrap(); 1966 | assert_eq!(json, "[1,2,3]"); 1967 | } 1968 | } 1969 | } 1970 | 1971 | #[cfg(feature = "std")] 1972 | mod Cow { 1973 | 1974 | mod From { 1975 | use crate::*; 1976 | use std::borrow::{Cow, ToOwned}; 1977 | 1978 | #[test] 1979 | fn from_vec1() { 1980 | let vec = vec1!["ho".to_owned()]; 1981 | match Cow::<'_, [String]>::from(vec.clone()) { 1982 | Cow::Owned(other) => assert_eq!(vec, other), 1983 | Cow::Borrowed(_) => panic!("unexpected conversion"), 1984 | } 1985 | } 1986 | 1987 | //Note: no From<&Vec1<_>> as this would require cloning the vector which 1988 | //is not how it's work for From<&Vec<_>> 1989 | } 1990 | 1991 | mod PartialEq { 1992 | use std::borrow::Cow; 1993 | 1994 | #[test] 1995 | fn to_vec1() { 1996 | let cow: Cow<'_, [u8]> = Cow::Borrowed(&[1u8, 3, 4]); 1997 | assert_eq!(cow.eq(&vec1![1u8, 3, 4]), true); 1998 | assert_eq!(cow.eq(&vec1![2u8, 3, 4]), false); 1999 | } 2000 | } 2001 | } 2002 | 2003 | #[cfg(feature = "std")] 2004 | mod CString { 2005 | mod From { 2006 | use std::{ffi::CString, num::NonZeroU8}; 2007 | 2008 | #[test] 2009 | fn from_vec1_non_zero_u8() { 2010 | let vec = vec1![NonZeroU8::new(67).unwrap()]; 2011 | let cstring = CString::from(vec); 2012 | assert_eq!(cstring, CString::new("C").unwrap()); 2013 | } 2014 | } 2015 | } 2016 | 2017 | mod BoxedSlice { 2018 | 2019 | mod From { 2020 | use std::boxed::Box; 2021 | 2022 | #[test] 2023 | fn from_vec1() { 2024 | let boxed = Box::<[u8]>::from(vec1![99u8, 23, 4]); 2025 | assert_eq!(&*boxed, &[99u8, 23, 4]); 2026 | } 2027 | } 2028 | } 2029 | 2030 | mod BoxedArray { 2031 | 2032 | mod TryFrom { 2033 | use std::boxed::Box; 2034 | 2035 | #[test] 2036 | fn from_vec1() { 2037 | Box::<[u8; 4]>::try_from(vec1![1u8, 2, 3, 4]).unwrap(); 2038 | Box::<[u8; 4]>::try_from(vec1![1u8, 2]).unwrap_err(); 2039 | } 2040 | } 2041 | } 2042 | 2043 | mod BinaryHeap { 2044 | mod From { 2045 | use std::collections::BinaryHeap; 2046 | 2047 | #[test] 2048 | fn from_vec1() { 2049 | let vec = vec1![1u8, 99, 23]; 2050 | let mut heap = BinaryHeap::from(vec); 2051 | assert_eq!(heap.pop(), Some(99)); 2052 | assert_eq!(heap.pop(), Some(23)); 2053 | assert_eq!(heap.pop(), Some(1)); 2054 | assert_eq!(heap.pop(), None); 2055 | } 2056 | } 2057 | } 2058 | 2059 | mod Rc { 2060 | mod From { 2061 | use std::rc::Rc; 2062 | 2063 | #[test] 2064 | fn from_vec1() { 2065 | let rced = Rc::<[u8]>::from(vec1![8u8, 7, 33]); 2066 | assert_eq!(&*rced, &[8u8, 7, 33]); 2067 | } 2068 | } 2069 | } 2070 | 2071 | #[cfg(feature = "std")] 2072 | mod Arc { 2073 | mod From { 2074 | use std::sync::Arc; 2075 | 2076 | #[test] 2077 | fn from_vec1() { 2078 | let arced = Arc::<[u8]>::from(vec1![8u8, 7, 33]); 2079 | assert_eq!(&*arced, &[8u8, 7, 33]); 2080 | } 2081 | } 2082 | } 2083 | 2084 | mod VecDeque { 2085 | 2086 | mod From { 2087 | use alloc::collections::VecDeque; 2088 | 2089 | #[test] 2090 | fn from_vec1() { 2091 | let queue = VecDeque::from(vec1![32u8, 2, 10]); 2092 | assert_eq!(queue, &[32, 2, 10]); 2093 | } 2094 | } 2095 | 2096 | mod PartialEq { 2097 | use alloc::collections::VecDeque; 2098 | 2099 | #[test] 2100 | fn to_vec1() { 2101 | let queue = VecDeque::from(vec1![1u8, 2]); 2102 | 2103 | assert_eq!(queue.eq(&vec1![1u8, 2]), true); 2104 | assert_eq!(queue.eq(&vec1![1u8, 3]), false); 2105 | } 2106 | } 2107 | } 2108 | 2109 | mod slice { 2110 | 2111 | mod PartialEq { 2112 | use crate::*; 2113 | 2114 | #[test] 2115 | fn slice_mut_to_vec1() { 2116 | let slice: &[u8] = &mut [77u8]; 2117 | assert_eq!(slice.eq(&vec1![77u8]), true); 2118 | assert_eq!(slice.eq(&vec1![0u8]), false); 2119 | } 2120 | 2121 | #[test] 2122 | fn slice_to_vec1() { 2123 | let slice: &[u8] = &[77u8]; 2124 | assert_eq!(<[_] as PartialEq>>::eq(slice, &vec1![77u8]), true); 2125 | assert_eq!(<[_] as PartialEq>>::eq(slice, &vec1![1u8]), false); 2126 | } 2127 | 2128 | #[test] 2129 | fn slice_ref_to_vec1() { 2130 | let slice: &[u8] = &[77u8]; 2131 | assert_eq!(<&[_] as PartialEq>>::eq(&slice, &vec1![77u8]), true); 2132 | assert_eq!(<&[_] as PartialEq>>::eq(&slice, &vec1![0u8]), false); 2133 | } 2134 | } 2135 | } 2136 | 2137 | mod array { 2138 | 2139 | mod TryFrom { 2140 | 2141 | #[test] 2142 | fn from_vec1() { 2143 | let v = vec1![1u8, 10, 23]; 2144 | let _ = <[u8; 3]>::try_from(v).unwrap(); 2145 | <[u8; 3]>::try_from(vec1![1u8, 2]).unwrap_err(); 2146 | } 2147 | } 2148 | } 2149 | } 2150 | --------------------------------------------------------------------------------