├── .gitignore ├── README.md ├── Cargo.toml ├── CHANGELOG.md ├── LICENSE ├── .github └── workflows │ └── actions.yml └── src ├── nonzero.rs └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .idea 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Correct by Construction Non-Empty List 2 | 3 | This package exposes a type `NonEmpty` with a data representation 4 | that guarantees non-emptiness statically: 5 | 6 | struct NonEmpty(T, Vec) 7 | 8 | The library is meant to have an interface similar to `std::vec::Vec`: 9 | 10 | use nonempty::NonEmpty; 11 | 12 | let mut l = NonEmpty::new(42); 13 | 14 | assert_eq!(l.first(), &42); 15 | 16 | l.push(36); 17 | l.push(58); 18 | 19 | let v: Vec = l.into(); 20 | assert_eq!(v, vec![42, 36, 58]); 21 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nonempty" 3 | version = "0.12.0" 4 | description = "Correct by construction non-empty vector" 5 | authors = ["Alexis Sellier "] 6 | edition = "2021" 7 | license = "MIT" 8 | repository = "https://github.com/cloudhead/nonempty" 9 | 10 | [dependencies] 11 | serde = { features = ["derive", "alloc"], default-features = false, optional = true, version = "1" } 12 | arbitrary = { features = ["derive"], optional = true, version = "1" } 13 | bincode = { optional = true, version = "2.0.1" } 14 | 15 | [features] 16 | default = ["std"] 17 | std = [] 18 | serialize = ["dep:serde"] 19 | arbitrary = ["dep:arbitrary"] 20 | bincode = ["dep:bincode"] 21 | 22 | [dev-dependencies] 23 | serde_json = "1" 24 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this library will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this library adheres to Rust's notion of 6 | [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## 0.12.0 9 | 10 | ### Added 11 | - `bincode` feature flag to enable the use of `bincode-2.0.0`. 12 | 13 | ### Changed 14 | - `NonEmpty::capacity` returns `NonZeroUsize` 15 | - Fixed the `nonempty!` macro to use the `vec!` macro internally, ensuring that 16 | it compiles with `std` and `no_std`. 17 | 18 | ## 0.11.0 19 | 20 | ### Added 21 | - `std` feature flag; building with `--no-default-features` now enables `no_std` use. 22 | - `NonEmpty::sort` was added. 23 | - `NonEmpty::as_ref` added for converting a `&NonEmpty` to `NonEmpty<&T>`. 24 | 25 | ### Changed 26 | - MSRV is now 1.56 (this is a semver-breaking change). 27 | - `NonEmpty::split` now returns `Option<&T>` for last element. 28 | - `cargo clippy` and `cargo doc` failures are fixed. 29 | 30 | ## [Unreleased] 31 | 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Alexis Sellier 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /.github/workflows/actions.yml: -------------------------------------------------------------------------------- 1 | name: Cargo 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | build: 11 | name: Build and test 12 | strategy: 13 | matrix: 14 | os: ['ubuntu-latest', 'macos-latest'] 15 | runs-on: ${{ matrix.os }} 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Build 19 | run: cargo build --verbose 20 | env: 21 | RUSTFLAGS: -D warnings 22 | - name: Run tests 23 | run: cargo test --all --verbose --features serialize,arbitrary 24 | no-std: 25 | name: no-std build and test 26 | strategy: 27 | matrix: 28 | os: ['ubuntu-latest', 'macos-latest'] 29 | runs-on: ${{ matrix.os }} 30 | steps: 31 | - uses: actions/checkout@v4 32 | - name: Build 33 | run: cargo build --verbose --no-default-features 34 | env: 35 | RUSTFLAGS: -D warnings 36 | - name: Run tests 37 | run: cargo test --all --verbose --no-default-features 38 | 39 | rustfmt_and_clippy: 40 | name: Check rustfmt style && run clippy 41 | runs-on: ubuntu-latest 42 | steps: 43 | - uses: actions/checkout@v4 44 | - uses: actions-rs/toolchain@v1 45 | with: 46 | toolchain: stable 47 | profile: minimal 48 | components: clippy, rustfmt 49 | override: true 50 | - name: Cache cargo registry 51 | uses: actions/cache@v4 52 | with: 53 | path: ~/.cargo/registry 54 | key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} 55 | - name: Run clippy 56 | uses: actions-rs/cargo@v1 57 | with: 58 | command: clippy 59 | args: --all --tests --features serialize,arbitrary 60 | env: 61 | RUSTFLAGS: -D warnings 62 | - name: Check formating 63 | uses: actions-rs/cargo@v1 64 | with: 65 | command: fmt 66 | args: --all -- --check 67 | -------------------------------------------------------------------------------- /src/nonzero.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "arbitrary")] 2 | use arbitrary::Arbitrary; 3 | use core::num::NonZeroUsize; 4 | 5 | /// A non-empty list which statically guarantees certain operations 6 | /// cannot return zero, using [`core::num::NonZeroUsize`]. 7 | /// 8 | /// *Experimental* 9 | /// 10 | #[repr(transparent)] 11 | #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] 12 | #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] 13 | pub struct NonEmpty(super::NonEmpty); 14 | 15 | impl NonEmpty { 16 | /// Get the length of the list. 17 | pub fn len(&self) -> NonZeroUsize { 18 | unsafe { NonZeroUsize::new_unchecked(self.0.tail.len() + 1) } 19 | } 20 | 21 | /// Get the capacity of the list. 22 | pub fn capacity(&self) -> NonZeroUsize { 23 | unsafe { NonZeroUsize::new_unchecked(self.0.tail.capacity() + 1) } 24 | } 25 | 26 | /// Truncate the list to a certain size. 27 | pub fn truncate(&mut self, len: NonZeroUsize) { 28 | self.tail.truncate(usize::from(len) - 1); 29 | } 30 | } 31 | 32 | impl From> for NonEmpty { 33 | fn from(other: super::NonEmpty) -> NonEmpty { 34 | NonEmpty(other) 35 | } 36 | } 37 | 38 | impl core::ops::Deref for NonEmpty { 39 | type Target = super::NonEmpty; 40 | 41 | fn deref(&self) -> &Self::Target { 42 | &self.0 43 | } 44 | } 45 | 46 | impl core::ops::DerefMut for NonEmpty { 47 | fn deref_mut(&mut self) -> &mut Self::Target { 48 | &mut self.0 49 | } 50 | } 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use crate::nonzero; 55 | use crate::NonEmpty; 56 | 57 | use core::convert::TryInto; 58 | 59 | #[test] 60 | fn test_nonzero() { 61 | let nonempty: nonzero::NonEmpty<_> = NonEmpty::from((0, vec![1, 2, 3])).into(); 62 | 63 | assert_eq!(nonempty.len(), 4.try_into().unwrap()); 64 | assert_eq!(nonempty.capacity(), 4.try_into().unwrap()); 65 | } 66 | 67 | #[cfg(feature = "arbitrary")] 68 | mod arbitrary { 69 | use crate::nonzero; 70 | use arbitrary::{Arbitrary, Unstructured}; 71 | 72 | use core::convert::TryInto; 73 | 74 | #[test] 75 | fn test_nonzero_arbitrary_empty_tail() -> arbitrary::Result<()> { 76 | let mut u = Unstructured::new(&[1, 2, 3, 4]); 77 | let nonempty: nonzero::NonEmpty<_> = nonzero::NonEmpty::::arbitrary(&mut u)?; 78 | 79 | assert_eq!(nonempty.len(), 1.try_into().unwrap()); 80 | assert_eq!(nonempty.capacity(), 1.try_into().unwrap()); 81 | 82 | Ok(()) 83 | } 84 | 85 | #[test] 86 | fn test_nonzero_arbitrary_with_tail() -> arbitrary::Result<()> { 87 | let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]); 88 | let nonempty: nonzero::NonEmpty<_> = nonzero::NonEmpty::::arbitrary(&mut u)?; 89 | 90 | assert_eq!(nonempty.len(), 2.try_into().unwrap()); 91 | assert_eq!(nonempty.capacity(), 5.try_into().unwrap()); 92 | 93 | Ok(()) 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A Non-empty growable vector. 2 | //! 3 | //! Non-emptiness can be a powerful guarantee. If your main use of `Vec` is as 4 | //! an `Iterator`, then you may not need to distinguish on emptiness. But there 5 | //! are indeed times when the `Vec` you receive as as function argument needs to 6 | //! be non-empty or your function can't proceed. Similarly, there are times when 7 | //! the `Vec` you return to a calling user needs to promise it actually contains 8 | //! something. 9 | //! 10 | //! With `NonEmpty`, you're freed from the boilerplate of constantly needing to 11 | //! check `is_empty()` or pattern matching before proceeding, or erroring if you 12 | //! can't. So overall, code, type signatures, and logic become cleaner. 13 | //! 14 | //! Consider that unlike `Vec`, [`NonEmpty::first`] and [`NonEmpty::last`] don't 15 | //! return in `Option`, they always succeed. 16 | //! 17 | //! # Examples 18 | //! 19 | //! The simplest way to construct a [`NonEmpty`] is via the [`nonempty`] macro: 20 | //! 21 | //! ``` 22 | //! # extern crate alloc; 23 | //! # use alloc::vec::Vec; 24 | //! use nonempty::{NonEmpty, nonempty}; 25 | //! 26 | //! let l: NonEmpty = nonempty![1, 2, 3]; 27 | //! assert_eq!(l.head, 1); 28 | //! ``` 29 | //! 30 | //! Unlike the familiar `vec!` macro, `nonempty!` requires at least one element: 31 | //! 32 | //! ``` 33 | //! # extern crate alloc; 34 | //! # use alloc::vec::Vec; 35 | //! use nonempty::nonempty; 36 | //! 37 | //! let l = nonempty![1]; 38 | //! 39 | //! // Doesn't compile! 40 | //! // let l = nonempty![]; 41 | //! ``` 42 | //! 43 | //! Like `Vec`, you can also construct a [`NonEmpty`] the old fashioned way with 44 | //! [`NonEmpty::new`] or its constructor: 45 | //! 46 | //! ``` 47 | //! # extern crate alloc; 48 | //! # use alloc::vec::Vec; 49 | //! use nonempty::NonEmpty; 50 | //! 51 | //! let mut l = NonEmpty { head: 42, tail: vec![36, 58] }; 52 | //! assert_eq!(l.head, 42); 53 | //! 54 | //! l.push(9001); 55 | //! assert_eq!(l.last(), &9001); 56 | //! ``` 57 | //! 58 | //! And if necessary, you're free to convert to and from `Vec`: 59 | //! 60 | //! ``` 61 | //! use nonempty::{NonEmpty, nonempty}; 62 | //! 63 | //! let l: NonEmpty = nonempty![42, 36, 58, 9001]; 64 | //! let v: Vec = l.into(); 65 | //! assert_eq!(v, vec![42, 36, 58, 9001]); 66 | //! 67 | //! let u: Option> = NonEmpty::from_vec(v); 68 | //! assert_eq!(Some(nonempty![42, 36, 58, 9001]), u); 69 | //! ``` 70 | //! 71 | //! # Caveats 72 | //! 73 | //! Since `NonEmpty` must have a least one element, it is not possible to 74 | //! implement the [`FromIterator`] trait for it. We can't know, in general, if 75 | //! any given [`Iterator`] actually contains something. 76 | 77 | #![no_std] 78 | 79 | //! # Features 80 | //! 81 | //! * `serialize`: `serde` support. 82 | //! * `arbitrary`: `arbitrary` support. 83 | //! * `bincode`" `bincode` support. 84 | #[cfg(feature = "arbitrary")] 85 | use arbitrary::Arbitrary; 86 | #[cfg(feature = "bincode")] 87 | use bincode::{Decode, Encode}; 88 | #[cfg(feature = "serialize")] 89 | use serde::{ 90 | ser::{SerializeSeq, Serializer}, 91 | Deserialize, Serialize, 92 | }; 93 | 94 | use core::iter; 95 | use core::mem; 96 | use core::{cmp::Ordering, num::NonZeroUsize}; 97 | 98 | #[cfg(feature = "std")] 99 | extern crate std; 100 | 101 | #[cfg_attr(test, macro_use)] 102 | extern crate alloc; 103 | use alloc::vec::{self, Vec}; 104 | 105 | pub mod nonzero; 106 | 107 | #[doc(hidden)] 108 | pub mod __macro_support { 109 | pub use alloc::vec; 110 | } 111 | 112 | /// Like the `vec!` macro, but enforces at least one argument. A nice short-hand 113 | /// for constructing [`NonEmpty`] values. 114 | /// 115 | /// ``` 116 | /// # extern crate alloc; 117 | /// # use alloc::vec::Vec; 118 | /// use nonempty::{NonEmpty, nonempty}; 119 | /// 120 | /// let v = nonempty![1, 2, 3]; 121 | /// assert_eq!(v, NonEmpty { head: 1, tail: vec![2, 3] }); 122 | /// 123 | /// let v = nonempty![1]; 124 | /// assert_eq!(v, NonEmpty { head: 1, tail: Vec::new() }); 125 | /// 126 | /// // Accepts trailing commas 127 | /// let v = nonempty![1,]; 128 | /// assert_eq!(v, NonEmpty { head: 1, tail: Vec::new() }); 129 | /// 130 | /// // Doesn't compile! 131 | /// // let v = nonempty![]; 132 | /// ``` 133 | #[macro_export] 134 | macro_rules! nonempty { 135 | ($h:expr, $( $x:expr ),* $(,)?) => {{ 136 | let tail = $crate::__macro_support::vec![$($x),*]; 137 | $crate::NonEmpty { head: $h, tail } 138 | }}; 139 | ($h:expr) => { 140 | $crate::NonEmpty { 141 | head: $h, 142 | tail: $crate::__macro_support::vec![], 143 | } 144 | }; 145 | } 146 | 147 | /// Non-empty vector. 148 | #[cfg_attr(feature = "serialize", derive(Deserialize))] 149 | #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] 150 | #[cfg_attr(feature = "serialize", serde(try_from = "Vec"))] 151 | #[cfg_attr(feature = "bincode", derive(Encode, Decode))] 152 | #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] 153 | pub struct NonEmpty { 154 | pub head: T, 155 | pub tail: Vec, 156 | } 157 | 158 | // Nb. `Serialize` is implemented manually, as serde's `into` container attribute 159 | // requires a `T: Clone` bound which we'd like to avoid. 160 | #[cfg(feature = "serialize")] 161 | impl Serialize for NonEmpty 162 | where 163 | T: Serialize, 164 | { 165 | fn serialize(&self, serializer: S) -> Result 166 | where 167 | S: Serializer, 168 | { 169 | let mut seq = serializer.serialize_seq(Some(self.len()))?; 170 | for e in self { 171 | seq.serialize_element(e)?; 172 | } 173 | seq.end() 174 | } 175 | } 176 | 177 | pub struct Iter<'a, T> { 178 | head: Option<&'a T>, 179 | tail: &'a [T], 180 | } 181 | 182 | impl<'a, T> Iterator for Iter<'a, T> { 183 | type Item = &'a T; 184 | 185 | fn next(&mut self) -> Option { 186 | if let Some(value) = self.head.take() { 187 | Some(value) 188 | } else if let Some((first, rest)) = self.tail.split_first() { 189 | self.tail = rest; 190 | Some(first) 191 | } else { 192 | None 193 | } 194 | } 195 | } 196 | 197 | impl DoubleEndedIterator for Iter<'_, T> { 198 | fn next_back(&mut self) -> Option { 199 | if let Some((last, rest)) = self.tail.split_last() { 200 | self.tail = rest; 201 | Some(last) 202 | } else if let Some(first_value) = self.head.take() { 203 | Some(first_value) 204 | } else { 205 | None 206 | } 207 | } 208 | } 209 | 210 | impl ExactSizeIterator for Iter<'_, T> { 211 | fn len(&self) -> usize { 212 | self.tail.len() + self.head.map_or(0, |_| 1) 213 | } 214 | } 215 | 216 | impl core::iter::FusedIterator for Iter<'_, T> {} 217 | 218 | impl NonEmpty { 219 | /// Alias for [`NonEmpty::singleton`]. 220 | pub const fn new(e: T) -> Self { 221 | Self::singleton(e) 222 | } 223 | 224 | /// Converts from `&NonEmpty` to `NonEmpty<&T>`. 225 | pub fn as_ref(&self) -> NonEmpty<&T> { 226 | NonEmpty { 227 | head: &self.head, 228 | tail: self.tail.iter().collect(), 229 | } 230 | } 231 | 232 | /// Attempt to convert an iterator into a `NonEmpty` vector. 233 | /// Returns `None` if the iterator was empty. 234 | pub fn collect(iter: I) -> Option> 235 | where 236 | I: IntoIterator, 237 | { 238 | let mut iter = iter.into_iter(); 239 | let head = iter.next()?; 240 | Some(Self { 241 | head, 242 | tail: iter.collect(), 243 | }) 244 | } 245 | 246 | /// Create a new non-empty list with an initial element. 247 | pub const fn singleton(head: T) -> Self { 248 | NonEmpty { 249 | head, 250 | tail: Vec::new(), 251 | } 252 | } 253 | 254 | /// Always returns false. 255 | pub const fn is_empty(&self) -> bool { 256 | false 257 | } 258 | 259 | /// Get the first element. Never fails. 260 | pub const fn first(&self) -> &T { 261 | &self.head 262 | } 263 | 264 | /// Get the mutable reference to the first element. Never fails. 265 | /// 266 | /// # Examples 267 | /// 268 | /// ``` 269 | /// use nonempty::NonEmpty; 270 | /// 271 | /// let mut non_empty = NonEmpty::new(42); 272 | /// let head = non_empty.first_mut(); 273 | /// *head += 1; 274 | /// assert_eq!(non_empty.first(), &43); 275 | /// 276 | /// let mut non_empty = NonEmpty::from((1, vec![4, 2, 3])); 277 | /// let head = non_empty.first_mut(); 278 | /// *head *= 42; 279 | /// assert_eq!(non_empty.first(), &42); 280 | /// ``` 281 | pub fn first_mut(&mut self) -> &mut T { 282 | &mut self.head 283 | } 284 | 285 | /// Get the possibly-empty tail of the list. 286 | /// 287 | /// ``` 288 | /// use nonempty::NonEmpty; 289 | /// 290 | /// let non_empty = NonEmpty::new(42); 291 | /// assert_eq!(non_empty.tail(), &[]); 292 | /// 293 | /// let non_empty = NonEmpty::from((1, vec![4, 2, 3])); 294 | /// assert_eq!(non_empty.tail(), &[4, 2, 3]); 295 | /// ``` 296 | pub fn tail(&self) -> &[T] { 297 | &self.tail 298 | } 299 | 300 | /// Push an element to the end of the list. 301 | pub fn push(&mut self, e: T) { 302 | self.tail.push(e) 303 | } 304 | 305 | /// Pop an element from the end of the list. 306 | pub fn pop(&mut self) -> Option { 307 | self.tail.pop() 308 | } 309 | 310 | /// Inserts an element at position index within the vector, shifting all elements after it to the right. 311 | /// 312 | /// # Panics 313 | /// 314 | /// Panics if index > len. 315 | /// 316 | /// # Examples 317 | /// 318 | /// ``` 319 | /// use nonempty::NonEmpty; 320 | /// 321 | /// let mut non_empty = NonEmpty::from((1, vec![2, 3])); 322 | /// non_empty.insert(1, 4); 323 | /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3]))); 324 | /// non_empty.insert(4, 5); 325 | /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3, 5]))); 326 | /// non_empty.insert(0, 42); 327 | /// assert_eq!(non_empty, NonEmpty::from((42, vec![1, 4, 2, 3, 5]))); 328 | /// ``` 329 | pub fn insert(&mut self, index: usize, element: T) { 330 | let len = self.len(); 331 | assert!(index <= len); 332 | 333 | if index == 0 { 334 | let head = mem::replace(&mut self.head, element); 335 | self.tail.insert(0, head); 336 | } else { 337 | self.tail.insert(index - 1, element); 338 | } 339 | } 340 | 341 | /// Get the length of the list. 342 | pub fn len(&self) -> usize { 343 | self.tail.len() + 1 344 | } 345 | 346 | /// Gets the length of the list as a NonZeroUsize. 347 | pub fn len_nonzero(&self) -> NonZeroUsize { 348 | unsafe { NonZeroUsize::new_unchecked(self.tail.len().saturating_add(1)) } 349 | } 350 | 351 | /// Get the capacity of the list. 352 | pub fn capacity(&self) -> NonZeroUsize { 353 | NonZeroUsize::MIN.saturating_add(self.tail.capacity()) 354 | } 355 | 356 | /// Get the last element. Never fails. 357 | pub fn last(&self) -> &T { 358 | match self.tail.last() { 359 | None => &self.head, 360 | Some(e) => e, 361 | } 362 | } 363 | 364 | /// Get the last element mutably. 365 | pub fn last_mut(&mut self) -> &mut T { 366 | match self.tail.last_mut() { 367 | None => &mut self.head, 368 | Some(e) => e, 369 | } 370 | } 371 | 372 | /// Check whether an element is contained in the list. 373 | /// 374 | /// ``` 375 | /// use nonempty::NonEmpty; 376 | /// 377 | /// let mut l = NonEmpty::from((42, vec![36, 58])); 378 | /// 379 | /// assert!(l.contains(&42)); 380 | /// assert!(!l.contains(&101)); 381 | /// ``` 382 | pub fn contains(&self, x: &T) -> bool 383 | where 384 | T: PartialEq, 385 | { 386 | self.iter().any(|e| e == x) 387 | } 388 | 389 | /// Get an element by index. 390 | pub fn get(&self, index: usize) -> Option<&T> { 391 | if index == 0 { 392 | Some(&self.head) 393 | } else { 394 | self.tail.get(index - 1) 395 | } 396 | } 397 | 398 | /// Get an element by index, mutably. 399 | pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { 400 | if index == 0 { 401 | Some(&mut self.head) 402 | } else { 403 | self.tail.get_mut(index - 1) 404 | } 405 | } 406 | 407 | /// Truncate the list to a certain size. Must be greater than `0`. 408 | pub fn truncate(&mut self, len: usize) { 409 | assert!(len >= 1); 410 | self.tail.truncate(len - 1); 411 | } 412 | 413 | /// ``` 414 | /// use nonempty::NonEmpty; 415 | /// 416 | /// let mut l = NonEmpty::from((42, vec![36, 58])); 417 | /// 418 | /// let mut l_iter = l.iter(); 419 | /// 420 | /// assert_eq!(l_iter.len(), 3); 421 | /// assert_eq!(l_iter.next(), Some(&42)); 422 | /// assert_eq!(l_iter.next(), Some(&36)); 423 | /// assert_eq!(l_iter.next(), Some(&58)); 424 | /// assert_eq!(l_iter.next(), None); 425 | /// ``` 426 | pub fn iter(&self) -> Iter { 427 | Iter { 428 | head: Some(&self.head), 429 | tail: &self.tail, 430 | } 431 | } 432 | 433 | /// ``` 434 | /// use nonempty::NonEmpty; 435 | /// 436 | /// let mut l = NonEmpty::new(42); 437 | /// l.push(36); 438 | /// l.push(58); 439 | /// 440 | /// for i in l.iter_mut() { 441 | /// *i *= 10; 442 | /// } 443 | /// 444 | /// let mut l_iter = l.iter(); 445 | /// 446 | /// assert_eq!(l_iter.next(), Some(&420)); 447 | /// assert_eq!(l_iter.next(), Some(&360)); 448 | /// assert_eq!(l_iter.next(), Some(&580)); 449 | /// assert_eq!(l_iter.next(), None); 450 | /// ``` 451 | pub fn iter_mut(&mut self) -> impl DoubleEndedIterator + '_ { 452 | iter::once(&mut self.head).chain(self.tail.iter_mut()) 453 | } 454 | 455 | /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before 456 | /// proceeding with a computation. Using `from_slice` will give us a proof 457 | /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows 458 | /// the caller to handle the `None` case. 459 | /// 460 | /// # Example Use 461 | /// 462 | /// ``` 463 | /// use nonempty::NonEmpty; 464 | /// 465 | /// let non_empty_vec = NonEmpty::from_slice(&[1, 2, 3, 4, 5]); 466 | /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5])))); 467 | /// 468 | /// let empty_vec: Option> = NonEmpty::from_slice(&[]); 469 | /// assert!(empty_vec.is_none()); 470 | /// ``` 471 | pub fn from_slice(slice: &[T]) -> Option> 472 | where 473 | T: Clone, 474 | { 475 | slice.split_first().map(|(h, t)| NonEmpty { 476 | head: h.clone(), 477 | tail: t.into(), 478 | }) 479 | } 480 | 481 | /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before 482 | /// proceeding with a computation. Using `from_vec` will give us a proof 483 | /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows 484 | /// the caller to handle the `None` case. 485 | /// 486 | /// This version will consume the `Vec` you pass in. If you would rather pass the data as a 487 | /// slice then use `NonEmpty::from_slice`. 488 | /// 489 | /// # Example Use 490 | /// 491 | /// ``` 492 | /// use nonempty::NonEmpty; 493 | /// 494 | /// let non_empty_vec = NonEmpty::from_vec(vec![1, 2, 3, 4, 5]); 495 | /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5])))); 496 | /// 497 | /// let empty_vec: Option> = NonEmpty::from_vec(vec![]); 498 | /// assert!(empty_vec.is_none()); 499 | /// ``` 500 | pub fn from_vec(mut vec: Vec) -> Option> { 501 | if vec.is_empty() { 502 | None 503 | } else { 504 | let head = vec.remove(0); 505 | Some(NonEmpty { head, tail: vec }) 506 | } 507 | } 508 | 509 | /// Deconstruct a `NonEmpty` into its head and tail. 510 | /// This operation never fails since we are guaranteed 511 | /// to have a head element. 512 | /// 513 | /// # Example Use 514 | /// 515 | /// ``` 516 | /// use nonempty::NonEmpty; 517 | /// 518 | /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5])); 519 | /// 520 | /// // Guaranteed to have the head and we also get the tail. 521 | /// assert_eq!(non_empty.split_first(), (&1, &[2, 3, 4, 5][..])); 522 | /// 523 | /// let non_empty = NonEmpty::new(1); 524 | /// 525 | /// // Guaranteed to have the head element. 526 | /// assert_eq!(non_empty.split_first(), (&1, &[][..])); 527 | /// ``` 528 | pub fn split_first(&self) -> (&T, &[T]) { 529 | (&self.head, &self.tail) 530 | } 531 | 532 | /// Deconstruct a `NonEmpty` into its first, last, and 533 | /// middle elements, in that order. 534 | /// 535 | /// If there is only one element then last is `None`. 536 | /// 537 | /// # Example Use 538 | /// 539 | /// ``` 540 | /// use nonempty::NonEmpty; 541 | /// 542 | /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5])); 543 | /// 544 | /// // When there are two or more elements, the last element is represented 545 | /// // as a `Some`. Elements preceding it, except for the first, are returned 546 | /// // in the middle. 547 | /// assert_eq!(non_empty.split(), (&1, &[2, 3, 4][..], Some(&5))); 548 | /// 549 | /// let non_empty = NonEmpty::new(1); 550 | /// 551 | /// // The last element is `None` when there's only one element. 552 | /// assert_eq!(non_empty.split(), (&1, &[][..], None)); 553 | /// ``` 554 | pub fn split(&self) -> (&T, &[T], Option<&T>) { 555 | match self.tail.split_last() { 556 | None => (&self.head, &[], None), 557 | Some((last, middle)) => (&self.head, middle, Some(last)), 558 | } 559 | } 560 | 561 | /// Append a `Vec` to the tail of the `NonEmpty`. 562 | /// 563 | /// # Example Use 564 | /// 565 | /// ``` 566 | /// use nonempty::NonEmpty; 567 | /// 568 | /// let mut non_empty = NonEmpty::new(1); 569 | /// let mut vec = vec![2, 3, 4, 5]; 570 | /// non_empty.append(&mut vec); 571 | /// 572 | /// let mut expected = NonEmpty::from((1, vec![2, 3, 4, 5])); 573 | /// 574 | /// assert_eq!(non_empty, expected); 575 | /// ``` 576 | pub fn append(&mut self, other: &mut Vec) { 577 | self.tail.append(other) 578 | } 579 | 580 | /// A structure preserving `map`. This is useful for when 581 | /// we wish to keep the `NonEmpty` structure guaranteeing 582 | /// that there is at least one element. Otherwise, we can 583 | /// use `nonempty.iter().map(f)`. 584 | /// 585 | /// # Examples 586 | /// 587 | /// ``` 588 | /// use nonempty::NonEmpty; 589 | /// 590 | /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5])); 591 | /// 592 | /// let squares = non_empty.map(|i| i * i); 593 | /// 594 | /// let expected = NonEmpty::from((1, vec![4, 9, 16, 25])); 595 | /// 596 | /// assert_eq!(squares, expected); 597 | /// ``` 598 | pub fn map(self, mut f: F) -> NonEmpty 599 | where 600 | F: FnMut(T) -> U, 601 | { 602 | NonEmpty { 603 | head: f(self.head), 604 | tail: self.tail.into_iter().map(f).collect(), 605 | } 606 | } 607 | 608 | /// A structure preserving, fallible mapping function. 609 | pub fn try_map(self, mut f: F) -> Result, E> 610 | where 611 | F: FnMut(T) -> Result, 612 | { 613 | Ok(NonEmpty { 614 | head: f(self.head)?, 615 | tail: self.tail.into_iter().map(f).collect::>()?, 616 | }) 617 | } 618 | 619 | /// When we have a function that goes from some `T` to a `NonEmpty`, 620 | /// we may want to apply it to a `NonEmpty` but keep the structure flat. 621 | /// This is where `flat_map` shines. 622 | /// 623 | /// # Examples 624 | /// 625 | /// ``` 626 | /// use nonempty::NonEmpty; 627 | /// 628 | /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5])); 629 | /// 630 | /// let windows = non_empty.flat_map(|i| { 631 | /// let mut next = NonEmpty::new(i + 5); 632 | /// next.push(i + 6); 633 | /// next 634 | /// }); 635 | /// 636 | /// let expected = NonEmpty::from((6, vec![7, 7, 8, 8, 9, 9, 10, 10, 11])); 637 | /// 638 | /// assert_eq!(windows, expected); 639 | /// ``` 640 | pub fn flat_map(self, mut f: F) -> NonEmpty 641 | where 642 | F: FnMut(T) -> NonEmpty, 643 | { 644 | let mut heads = f(self.head); 645 | let mut tails = self 646 | .tail 647 | .into_iter() 648 | .flat_map(|t| f(t).into_iter()) 649 | .collect(); 650 | heads.append(&mut tails); 651 | heads 652 | } 653 | 654 | /// Flatten nested `NonEmpty`s into a single one. 655 | /// 656 | /// # Examples 657 | /// 658 | /// ``` 659 | /// use nonempty::NonEmpty; 660 | /// 661 | /// let non_empty = NonEmpty::from(( 662 | /// NonEmpty::from((1, vec![2, 3])), 663 | /// vec![NonEmpty::from((4, vec![5]))], 664 | /// )); 665 | /// 666 | /// let expected = NonEmpty::from((1, vec![2, 3, 4, 5])); 667 | /// 668 | /// assert_eq!(NonEmpty::flatten(non_empty), expected); 669 | /// ``` 670 | pub fn flatten(full: NonEmpty>) -> Self { 671 | full.flat_map(|n| n) 672 | } 673 | 674 | /// Binary searches this sorted non-empty vector for a given element. 675 | /// 676 | /// If the value is found then Result::Ok is returned, containing the index of the matching element. 677 | /// If there are multiple matches, then any one of the matches could be returned. 678 | /// 679 | /// If the value is not found then Result::Err is returned, containing the index where a 680 | /// matching element could be inserted while maintaining sorted order. 681 | /// 682 | /// # Examples 683 | /// 684 | /// ``` 685 | /// use nonempty::NonEmpty; 686 | /// 687 | /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])); 688 | /// assert_eq!(non_empty.binary_search(&0), Ok(0)); 689 | /// assert_eq!(non_empty.binary_search(&13), Ok(9)); 690 | /// assert_eq!(non_empty.binary_search(&4), Err(7)); 691 | /// assert_eq!(non_empty.binary_search(&100), Err(13)); 692 | /// let r = non_empty.binary_search(&1); 693 | /// assert!(match r { Ok(1..=4) => true, _ => false, }); 694 | /// ``` 695 | /// 696 | /// If you want to insert an item to a sorted non-empty vector, while maintaining sort order: 697 | /// 698 | /// ``` 699 | /// use nonempty::NonEmpty; 700 | /// 701 | /// let mut non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])); 702 | /// let num = 42; 703 | /// let idx = non_empty.binary_search(&num).unwrap_or_else(|x| x); 704 | /// non_empty.insert(idx, num); 705 | /// assert_eq!(non_empty, NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]))); 706 | /// ``` 707 | pub fn binary_search(&self, x: &T) -> Result 708 | where 709 | T: Ord, 710 | { 711 | self.binary_search_by(|p| p.cmp(x)) 712 | } 713 | 714 | /// Binary searches this sorted non-empty with a comparator function. 715 | /// 716 | /// The comparator function should implement an order consistent with the sort order of the underlying slice, 717 | /// returning an order code that indicates whether its argument is Less, Equal or Greater the desired target. 718 | /// 719 | /// If the value is found then Result::Ok is returned, containing the index of the matching element. 720 | /// If there are multiple matches, then any one of the matches could be returned. 721 | /// If the value is not found then Result::Err is returned, containing the index where a matching element could be 722 | /// inserted while maintaining sorted order. 723 | /// 724 | /// # Examples 725 | /// 726 | /// Looks up a series of four elements. The first is found, with a uniquely determined 727 | /// position; the second and third are not found; the fourth could match any position in `[1,4]`. 728 | /// 729 | /// ``` 730 | /// use nonempty::NonEmpty; 731 | /// 732 | /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])); 733 | /// let seek = 0; 734 | /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(0)); 735 | /// let seek = 13; 736 | /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); 737 | /// let seek = 4; 738 | /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); 739 | /// let seek = 100; 740 | /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); 741 | /// let seek = 1; 742 | /// let r = non_empty.binary_search_by(|probe| probe.cmp(&seek)); 743 | /// assert!(match r { Ok(1..=4) => true, _ => false, }); 744 | /// ``` 745 | pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result 746 | where 747 | F: FnMut(&'a T) -> Ordering, 748 | { 749 | match f(&self.head) { 750 | Ordering::Equal => Ok(0), 751 | Ordering::Greater => Err(0), 752 | Ordering::Less => self 753 | .tail 754 | .binary_search_by(f) 755 | .map(|index| index + 1) 756 | .map_err(|index| index + 1), 757 | } 758 | } 759 | 760 | /// Binary searches this sorted non-empty vector with a key extraction function. 761 | /// 762 | /// Assumes that the vector is sorted by the key. 763 | /// 764 | /// If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, 765 | /// then any one of the matches could be returned. If the value is not found then Result::Err is returned, 766 | /// containing the index where a matching element could be inserted while maintaining sorted order. 767 | /// 768 | /// # Examples 769 | /// 770 | /// Looks up a series of four elements in a non-empty vector of pairs sorted by their second elements. 771 | /// The first is found, with a uniquely determined position; the second and third are not found; 772 | /// the fourth could match any position in [1, 4]. 773 | /// 774 | /// ``` 775 | /// use nonempty::NonEmpty; 776 | /// 777 | /// let non_empty = NonEmpty::from(( 778 | /// (0, 0), 779 | /// vec![(2, 1), (4, 1), (5, 1), (3, 1), 780 | /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), 781 | /// (1, 21), (2, 34), (4, 55)] 782 | /// )); 783 | /// 784 | /// assert_eq!(non_empty.binary_search_by_key(&0, |&(a,b)| b), Ok(0)); 785 | /// assert_eq!(non_empty.binary_search_by_key(&13, |&(a,b)| b), Ok(9)); 786 | /// assert_eq!(non_empty.binary_search_by_key(&4, |&(a,b)| b), Err(7)); 787 | /// assert_eq!(non_empty.binary_search_by_key(&100, |&(a,b)| b), Err(13)); 788 | /// let r = non_empty.binary_search_by_key(&1, |&(a,b)| b); 789 | /// assert!(match r { Ok(1..=4) => true, _ => false, }); 790 | /// ``` 791 | pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result 792 | where 793 | B: Ord, 794 | F: FnMut(&'a T) -> B, 795 | { 796 | self.binary_search_by(|k| f(k).cmp(b)) 797 | } 798 | 799 | /// Returns the maximum element in the non-empty vector. 800 | /// 801 | /// This will return the first item in the vector if the tail is empty. 802 | /// 803 | /// # Examples 804 | /// 805 | /// ``` 806 | /// use nonempty::NonEmpty; 807 | /// 808 | /// let non_empty = NonEmpty::new(42); 809 | /// assert_eq!(non_empty.maximum(), &42); 810 | /// 811 | /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5])); 812 | /// assert_eq!(non_empty.maximum(), &76); 813 | /// ``` 814 | pub fn maximum(&self) -> &T 815 | where 816 | T: Ord, 817 | { 818 | self.maximum_by(|i, j| i.cmp(j)) 819 | } 820 | 821 | /// Returns the minimum element in the non-empty vector. 822 | /// 823 | /// This will return the first item in the vector if the tail is empty. 824 | /// 825 | /// # Examples 826 | /// 827 | /// ``` 828 | /// use nonempty::NonEmpty; 829 | /// 830 | /// let non_empty = NonEmpty::new(42); 831 | /// assert_eq!(non_empty.minimum(), &42); 832 | /// 833 | /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5])); 834 | /// assert_eq!(non_empty.minimum(), &-34); 835 | /// ``` 836 | pub fn minimum(&self) -> &T 837 | where 838 | T: Ord, 839 | { 840 | self.minimum_by(|i, j| i.cmp(j)) 841 | } 842 | 843 | /// Returns the element that gives the maximum value with respect to the specified comparison function. 844 | /// 845 | /// This will return the first item in the vector if the tail is empty. 846 | /// 847 | /// # Examples 848 | /// 849 | /// ``` 850 | /// use nonempty::NonEmpty; 851 | /// 852 | /// let non_empty = NonEmpty::new((0, 42)); 853 | /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42)); 854 | /// 855 | /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)])); 856 | /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(4, 42)); 857 | /// ``` 858 | pub fn maximum_by(&self, mut compare: F) -> &T 859 | where 860 | F: FnMut(&T, &T) -> Ordering, 861 | { 862 | let mut max = &self.head; 863 | for i in self.tail.iter() { 864 | max = match compare(max, i) { 865 | Ordering::Equal => max, 866 | Ordering::Less => i, 867 | Ordering::Greater => max, 868 | }; 869 | } 870 | max 871 | } 872 | 873 | /// Returns the element that gives the minimum value with respect to the specified comparison function. 874 | /// 875 | /// This will return the first item in the vector if the tail is empty. 876 | /// 877 | /// ``` 878 | /// use nonempty::NonEmpty; 879 | /// 880 | /// let non_empty = NonEmpty::new((0, 42)); 881 | /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42)); 882 | /// 883 | /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)])); 884 | /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 76)); 885 | /// ``` 886 | pub fn minimum_by(&self, mut compare: F) -> &T 887 | where 888 | F: FnMut(&T, &T) -> Ordering, 889 | { 890 | self.maximum_by(|a, b| compare(a, b).reverse()) 891 | } 892 | 893 | /// Returns the element that gives the maximum value with respect to the specified function. 894 | /// 895 | /// This will return the first item in the vector if the tail is empty. 896 | /// 897 | /// # Examples 898 | /// 899 | /// ``` 900 | /// use nonempty::NonEmpty; 901 | /// 902 | /// let non_empty = NonEmpty::new((0, 42)); 903 | /// assert_eq!(non_empty.maximum_by_key(|(k, _)| *k), &(0, 42)); 904 | /// 905 | /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)])); 906 | /// assert_eq!(non_empty.maximum_by_key(|(k, _)| *k), &(4, 42)); 907 | /// assert_eq!(non_empty.maximum_by_key(|(k, _)| -k), &(0, 76)); 908 | /// ``` 909 | pub fn maximum_by_key(&self, mut f: F) -> &T 910 | where 911 | U: Ord, 912 | F: FnMut(&T) -> U, 913 | { 914 | self.maximum_by(|i, j| f(i).cmp(&f(j))) 915 | } 916 | 917 | /// Returns the element that gives the minimum value with respect to the specified function. 918 | /// 919 | /// This will return the first item in the vector if the tail is empty. 920 | /// 921 | /// # Examples 922 | /// 923 | /// ``` 924 | /// use nonempty::NonEmpty; 925 | /// 926 | /// let non_empty = NonEmpty::new((0, 42)); 927 | /// assert_eq!(non_empty.minimum_by_key(|(k, _)| *k), &(0, 42)); 928 | /// 929 | /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)])); 930 | /// assert_eq!(non_empty.minimum_by_key(|(k, _)| *k), &(0, 76)); 931 | /// assert_eq!(non_empty.minimum_by_key(|(k, _)| -k), &(4, 42)); 932 | /// ``` 933 | pub fn minimum_by_key(&self, mut f: F) -> &T 934 | where 935 | U: Ord, 936 | F: FnMut(&T) -> U, 937 | { 938 | self.minimum_by(|i, j| f(i).cmp(&f(j))) 939 | } 940 | 941 | /// Sorts the nonempty. 942 | /// 943 | /// The implementation uses [`slice::sort`](slice::sort) for the tail and then checks where the 944 | /// head belongs. If the head is already the smallest element, this should be as fast as sorting a 945 | /// slice. However, if the head needs to be inserted, then it incurs extra cost for removing 946 | /// the new head from the tail and adding the old head at the correct index. 947 | /// 948 | /// # Examples 949 | /// 950 | /// ``` 951 | /// use nonempty::nonempty; 952 | /// 953 | /// let mut non_empty = nonempty![-5, 4, 1, -3, 2]; 954 | /// 955 | /// non_empty.sort(); 956 | /// assert!(non_empty == nonempty![-5, -3, 1, 2, 4]); 957 | /// ``` 958 | pub fn sort(&mut self) 959 | where 960 | T: Ord, 961 | { 962 | self.tail.sort(); 963 | let index = match self.tail.binary_search(&self.head) { 964 | Ok(index) => index, 965 | Err(index) => index, 966 | }; 967 | 968 | if index != 0 { 969 | let new_head = self.tail.remove(0); 970 | let head = mem::replace(&mut self.head, new_head); 971 | self.tail.insert(index - 1, head); 972 | } 973 | } 974 | } 975 | 976 | impl Default for NonEmpty { 977 | fn default() -> Self { 978 | Self::new(T::default()) 979 | } 980 | } 981 | 982 | impl From> for Vec { 983 | /// Turns a non-empty list into a Vec. 984 | fn from(nonempty: NonEmpty) -> Vec { 985 | iter::once(nonempty.head).chain(nonempty.tail).collect() 986 | } 987 | } 988 | 989 | impl From> for (T, Vec) { 990 | /// Turns a non-empty list into a Vec. 991 | fn from(nonempty: NonEmpty) -> (T, Vec) { 992 | (nonempty.head, nonempty.tail) 993 | } 994 | } 995 | 996 | impl From<(T, Vec)> for NonEmpty { 997 | /// Turns a pair of an element and a Vec into 998 | /// a NonEmpty. 999 | fn from((head, tail): (T, Vec)) -> Self { 1000 | NonEmpty { head, tail } 1001 | } 1002 | } 1003 | 1004 | impl IntoIterator for NonEmpty { 1005 | type Item = T; 1006 | type IntoIter = iter::Chain, vec::IntoIter>; 1007 | 1008 | fn into_iter(self) -> Self::IntoIter { 1009 | iter::once(self.head).chain(self.tail) 1010 | } 1011 | } 1012 | 1013 | impl<'a, T> IntoIterator for &'a NonEmpty { 1014 | type Item = &'a T; 1015 | type IntoIter = iter::Chain, core::slice::Iter<'a, T>>; 1016 | 1017 | fn into_iter(self) -> Self::IntoIter { 1018 | iter::once(&self.head).chain(self.tail.iter()) 1019 | } 1020 | } 1021 | 1022 | impl core::ops::Index for NonEmpty { 1023 | type Output = T; 1024 | 1025 | /// ``` 1026 | /// use nonempty::NonEmpty; 1027 | /// 1028 | /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5])); 1029 | /// 1030 | /// assert_eq!(non_empty[0], 1); 1031 | /// assert_eq!(non_empty[1], 2); 1032 | /// assert_eq!(non_empty[3], 4); 1033 | /// ``` 1034 | fn index(&self, index: usize) -> &T { 1035 | if index > 0 { 1036 | &self.tail[index - 1] 1037 | } else { 1038 | &self.head 1039 | } 1040 | } 1041 | } 1042 | 1043 | impl core::ops::IndexMut for NonEmpty { 1044 | fn index_mut(&mut self, index: usize) -> &mut T { 1045 | if index > 0 { 1046 | &mut self.tail[index - 1] 1047 | } else { 1048 | &mut self.head 1049 | } 1050 | } 1051 | } 1052 | 1053 | impl Extend for NonEmpty { 1054 | fn extend>(&mut self, iter: T) { 1055 | self.tail.extend(iter) 1056 | } 1057 | } 1058 | 1059 | #[cfg(feature = "serialize")] 1060 | pub mod serialize { 1061 | use core::{convert::TryFrom, fmt}; 1062 | 1063 | use alloc::vec::Vec; 1064 | 1065 | use super::NonEmpty; 1066 | 1067 | #[derive(Debug)] 1068 | pub enum Error { 1069 | Empty, 1070 | } 1071 | 1072 | impl fmt::Display for Error { 1073 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1074 | match self { 1075 | Self::Empty => f.write_str( 1076 | "the vector provided was empty, NonEmpty needs at least one element", 1077 | ), 1078 | } 1079 | } 1080 | } 1081 | 1082 | impl TryFrom> for NonEmpty { 1083 | type Error = Error; 1084 | 1085 | fn try_from(vec: Vec) -> Result { 1086 | NonEmpty::from_vec(vec).ok_or(Error::Empty) 1087 | } 1088 | } 1089 | } 1090 | 1091 | #[cfg(test)] 1092 | mod tests { 1093 | use alloc::{string::String, vec::Vec}; 1094 | 1095 | use crate::NonEmpty; 1096 | 1097 | #[test] 1098 | fn test_from_conversion() { 1099 | let result = NonEmpty::from((1, vec![2, 3, 4, 5])); 1100 | let expected = NonEmpty { 1101 | head: 1, 1102 | tail: vec![2, 3, 4, 5], 1103 | }; 1104 | assert_eq!(result, expected); 1105 | } 1106 | 1107 | #[test] 1108 | fn test_into_iter() { 1109 | let nonempty = NonEmpty::from((0, vec![1, 2, 3])); 1110 | for (i, n) in nonempty.into_iter().enumerate() { 1111 | assert_eq!(i as i32, n); 1112 | } 1113 | } 1114 | 1115 | #[test] 1116 | fn test_iter_syntax() { 1117 | let nonempty = NonEmpty::from((0, vec![1, 2, 3])); 1118 | for n in &nonempty { 1119 | let _ = *n; // Prove that we're dealing with references. 1120 | } 1121 | for _ in nonempty {} 1122 | } 1123 | 1124 | #[test] 1125 | fn test_iter_both_directions() { 1126 | let mut nonempty = NonEmpty::from((0, vec![1, 2, 3])); 1127 | assert_eq!(nonempty.iter().cloned().collect::>(), [0, 1, 2, 3]); 1128 | assert_eq!( 1129 | nonempty.iter().rev().cloned().collect::>(), 1130 | [3, 2, 1, 0] 1131 | ); 1132 | assert_eq!( 1133 | nonempty.iter_mut().rev().collect::>(), 1134 | [&mut 3, &mut 2, &mut 1, &mut 0] 1135 | ); 1136 | } 1137 | 1138 | #[test] 1139 | fn test_iter_both_directions_at_once() { 1140 | let nonempty = NonEmpty::from((0, vec![1, 2, 3])); 1141 | let mut i = nonempty.iter(); 1142 | assert_eq!(i.next(), Some(&0)); 1143 | assert_eq!(i.next_back(), Some(&3)); 1144 | assert_eq!(i.next(), Some(&1)); 1145 | assert_eq!(i.next_back(), Some(&2)); 1146 | assert_eq!(i.next(), None); 1147 | assert_eq!(i.next_back(), None); 1148 | } 1149 | 1150 | #[test] 1151 | fn test_mutate_head() { 1152 | let mut non_empty = NonEmpty::new(42); 1153 | non_empty.head += 1; 1154 | assert_eq!(non_empty.head, 43); 1155 | 1156 | let mut non_empty = NonEmpty::from((1, vec![4, 2, 3])); 1157 | non_empty.head *= 42; 1158 | assert_eq!(non_empty.head, 42); 1159 | } 1160 | 1161 | #[test] 1162 | fn test_to_nonempty() { 1163 | use core::iter::{empty, once}; 1164 | 1165 | assert_eq!(NonEmpty::<()>::collect(empty()), None); 1166 | assert_eq!(NonEmpty::<()>::collect(once(())), Some(NonEmpty::new(()))); 1167 | assert_eq!( 1168 | NonEmpty::::collect(once(1).chain(once(2))), 1169 | Some(nonempty!(1, 2)) 1170 | ); 1171 | } 1172 | 1173 | #[test] 1174 | fn test_try_map() { 1175 | assert_eq!( 1176 | nonempty!(1, 2, 3, 4).try_map(Ok::<_, String>), 1177 | Ok(nonempty!(1, 2, 3, 4)) 1178 | ); 1179 | assert_eq!( 1180 | nonempty!(1, 2, 3, 4).try_map(|i| if i % 2 == 0 { Ok(i) } else { Err("not even") }), 1181 | Err("not even") 1182 | ); 1183 | } 1184 | 1185 | #[test] 1186 | fn test_nontrivial_minimum_by_key() { 1187 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 1188 | struct Position { 1189 | x: i32, 1190 | y: i32, 1191 | } 1192 | impl Position { 1193 | pub fn distance_squared(&self, other: Position) -> u32 { 1194 | let dx = self.x - other.x; 1195 | let dy = self.y - other.y; 1196 | (dx * dx + dy * dy) as u32 1197 | } 1198 | } 1199 | let positions = nonempty![ 1200 | Position { x: 1, y: 1 }, 1201 | Position { x: 0, y: 0 }, 1202 | Position { x: 3, y: 4 } 1203 | ]; 1204 | let target = Position { x: 1, y: 2 }; 1205 | let closest = positions.minimum_by_key(|position| position.distance_squared(target)); 1206 | assert_eq!(closest, &Position { x: 1, y: 1 }); 1207 | } 1208 | 1209 | #[test] 1210 | fn test_sort() { 1211 | let mut numbers = nonempty![1]; 1212 | numbers.sort(); 1213 | assert_eq!(numbers, nonempty![1]); 1214 | 1215 | let mut numbers = nonempty![2, 1, 3]; 1216 | numbers.sort(); 1217 | assert_eq!(numbers, nonempty![1, 2, 3]); 1218 | 1219 | let mut numbers = nonempty![1, 3, 2]; 1220 | numbers.sort(); 1221 | assert_eq!(numbers, nonempty![1, 2, 3]); 1222 | 1223 | let mut numbers = nonempty![3, 2, 1]; 1224 | numbers.sort(); 1225 | assert_eq!(numbers, nonempty![1, 2, 3]); 1226 | } 1227 | 1228 | #[cfg(feature = "serialize")] 1229 | mod serialize { 1230 | use crate::NonEmpty; 1231 | use alloc::boxed::Box; 1232 | use serde::{Deserialize, Serialize}; 1233 | 1234 | #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)] 1235 | pub struct SimpleSerializable(pub i32); 1236 | 1237 | #[test] 1238 | fn test_simple_round_trip() -> Result<(), Box> { 1239 | // Given 1240 | let mut non_empty = NonEmpty::new(SimpleSerializable(42)); 1241 | non_empty.push(SimpleSerializable(777)); 1242 | 1243 | // When 1244 | let res = serde_json::from_str::<'_, NonEmpty>( 1245 | &serde_json::to_string(&non_empty)?, 1246 | )?; 1247 | 1248 | // Then 1249 | assert_eq!(res, non_empty); 1250 | 1251 | Ok(()) 1252 | } 1253 | 1254 | #[test] 1255 | fn test_serialization() -> Result<(), Box> { 1256 | let ne = nonempty![1, 2, 3, 4, 5]; 1257 | let ve = vec![1, 2, 3, 4, 5]; 1258 | 1259 | assert_eq!(serde_json::to_string(&ne)?, serde_json::to_string(&ve)?); 1260 | 1261 | Ok(()) 1262 | } 1263 | } 1264 | 1265 | #[cfg(feature = "bincode")] 1266 | mod bincode { 1267 | use crate::NonEmpty; 1268 | use alloc::boxed::Box; 1269 | 1270 | #[derive(Clone, Debug, Eq, PartialEq, bincode::Encode, bincode::Decode)] 1271 | pub struct SimpleSerializable(pub i32); 1272 | 1273 | #[test] 1274 | fn test_simple_round_trip() -> Result<(), Box> { 1275 | // Given 1276 | let mut non_empty = NonEmpty::new(SimpleSerializable(42)); 1277 | non_empty.push(SimpleSerializable(777)); 1278 | 1279 | // When 1280 | let config = bincode::config::standard(); 1281 | let (res, _) = bincode::decode_from_slice::, _>( 1282 | &bincode::encode_to_vec(non_empty.clone(), config)?, 1283 | config, 1284 | )?; 1285 | 1286 | // Then 1287 | assert_eq!(res, non_empty); 1288 | 1289 | Ok(()) 1290 | } 1291 | } 1292 | 1293 | #[cfg(feature = "arbitrary")] 1294 | mod arbitrary { 1295 | use crate::NonEmpty; 1296 | use arbitrary::{Arbitrary, Unstructured}; 1297 | 1298 | #[test] 1299 | fn test_arbitrary_empty_tail() -> arbitrary::Result<()> { 1300 | let mut u = Unstructured::new(&[1, 2, 3, 4]); 1301 | let ne = NonEmpty::::arbitrary(&mut u)?; 1302 | assert!(!ne.is_empty()); 1303 | assert_eq!( 1304 | ne, 1305 | NonEmpty { 1306 | head: 67305985, 1307 | tail: vec![], 1308 | } 1309 | ); 1310 | Ok(()) 1311 | } 1312 | 1313 | #[test] 1314 | fn test_arbitrary_with_tail() -> arbitrary::Result<()> { 1315 | let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]); 1316 | let ne = NonEmpty::::arbitrary(&mut u)?; 1317 | assert!(!ne.is_empty()); 1318 | assert_eq!( 1319 | ne, 1320 | NonEmpty { 1321 | head: 67305985, 1322 | tail: vec![526086], 1323 | } 1324 | ); 1325 | Ok(()) 1326 | } 1327 | 1328 | #[test] 1329 | fn test_arbitrary_with_split() -> arbitrary::Result<()> { 1330 | let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]); 1331 | let ne = NonEmpty::::arbitrary(&mut u)?; 1332 | let (head, middle, last) = ne.split(); 1333 | let mut tail = middle.to_vec(); 1334 | tail.extend(last); 1335 | assert_eq!(ne, NonEmpty { head: *head, tail }); 1336 | Ok(()) 1337 | } 1338 | } 1339 | } 1340 | --------------------------------------------------------------------------------