diff --git a/Cargo.toml b/Cargo.toml index 13917b0..70f1932 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,17 +36,19 @@ version = "1.0" [dev-dependencies] matches = { version = "0.1" } bencher = "0.1.4" +borsh = { version = "1.5.5", default-features = false, features = ["derive"] } [[bench]] name = "extend" harness = false +required-features = ["std"] [[bench]] name = "arraystring" harness = false [features] -default = ["std"] +default = [] std = [] [profile.bench] diff --git a/benches/arraystring.rs b/benches/arraystring.rs index 5b986fa..fabb8cd 100644 --- a/benches/arraystring.rs +++ b/benches/arraystring.rs @@ -1,6 +1,6 @@ - extern crate arrayvec; -#[macro_use] extern crate bencher; +#[macro_use] +extern crate bencher; use arrayvec::ArrayString; @@ -10,8 +10,7 @@ fn try_push_c(b: &mut Bencher) { let mut v = ArrayString::<512>::new(); b.iter(|| { v.clear(); - while v.try_push('c').is_ok() { - } + while v.try_push('c').is_ok() {} v.len() }); b.bytes = v.capacity() as u64; @@ -21,8 +20,7 @@ fn try_push_alpha(b: &mut Bencher) { let mut v = ArrayString::<512>::new(); b.iter(|| { v.clear(); - while v.try_push('α').is_ok() { - } + while v.try_push('α').is_ok() {} v.len() }); b.bytes = v.capacity() as u64; @@ -85,6 +83,13 @@ fn push_string(b: &mut Bencher) { b.bytes = v.capacity() as u64; } -benchmark_group!(benches, try_push_c, try_push_alpha, try_push_string, push_c, - push_alpha, push_string); +benchmark_group!( + benches, + try_push_c, + try_push_alpha, + try_push_string, + push_c, + push_alpha, + push_string +); benchmark_main!(benches); diff --git a/benches/extend.rs b/benches/extend.rs index ba33a93..7aad2c7 100644 --- a/benches/extend.rs +++ b/benches/extend.rs @@ -1,13 +1,13 @@ - extern crate arrayvec; -#[macro_use] extern crate bencher; +#[macro_use] +extern crate bencher; use std::io::Write; use arrayvec::ArrayVec; -use bencher::Bencher; use bencher::black_box; +use bencher::Bencher; fn extend_with_constant(b: &mut Bencher) { let mut v = ArrayVec::::new(); @@ -67,12 +67,13 @@ fn extend_from_slice(b: &mut Bencher) { b.bytes = v.capacity() as u64; } -benchmark_group!(benches, - extend_with_constant, - extend_with_range, - extend_with_slice, - extend_with_write, - extend_from_slice +benchmark_group!( + benches, + extend_with_constant, + extend_with_range, + extend_with_slice, + extend_with_write, + extend_from_slice ); benchmark_main!(benches); diff --git a/src/array_string.rs b/src/array_string.rs index 227e01d..db323a1 100644 --- a/src/array_string.rs +++ b/src/array_string.rs @@ -1,26 +1,31 @@ -use std::borrow::{Borrow, BorrowMut}; -use std::cmp; -use std::convert::TryFrom; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::mem::MaybeUninit; -use std::ops::{Deref, DerefMut}; -#[cfg(feature="std")] +use core::borrow::{Borrow, BorrowMut}; +use core::cmp; +use core::convert::TryFrom; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::ptr; +use core::slice; +use core::str; +use core::str::FromStr; +use core::str::Utf8Error; + +#[cfg(feature = "std")] use std::path::Path; -use std::ptr; -use std::slice; -use std::str; -use std::str::FromStr; -use std::str::Utf8Error; -use crate::CapacityError; -use crate::LenUint; use crate::char::encode_utf8; use crate::utils::MakeMaybeUninit; +use crate::CapacityError; +use crate::LenUint; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; -#[cfg(feature="serde")] -use serde::{Serialize, Deserialize, Serializer, Deserializer}; +extern crate alloc; +#[cfg(all(not(feature = "std"), feature = "borsh"))] +use alloc::{format, string::ToString}; /// A string with a fixed capacity. /// @@ -40,16 +45,14 @@ pub struct ArrayString { xs: [MaybeUninit; CAP], } -impl Default for ArrayString -{ +impl Default for ArrayString { /// Return an empty `ArrayString` fn default() -> ArrayString { ArrayString::new() } } -impl ArrayString -{ +impl ArrayString { /// Create a new empty `ArrayString`. /// /// Capacity is inferred from the type parameter. @@ -65,7 +68,10 @@ impl ArrayString pub fn new() -> ArrayString { assert_capacity_limit!(CAP); unsafe { - ArrayString { xs: MaybeUninit::uninit().assume_init(), len: 0 } + ArrayString { + xs: MaybeUninit::uninit().assume_init(), + len: 0, + } } } @@ -80,16 +86,23 @@ impl ArrayString /// ``` pub const fn new_const() -> ArrayString { assert_capacity_limit_const!(CAP); - ArrayString { xs: MakeMaybeUninit::ARRAY, len: 0 } + ArrayString { + xs: MakeMaybeUninit::ARRAY, + len: 0, + } } /// Return the length of the string. #[inline] - pub const fn len(&self) -> usize { self.len as usize } + pub const fn len(&self) -> usize { + self.len as usize + } /// Returns whether the string is empty. #[inline] - pub const fn is_empty(&self) -> bool { self.len() == 0 } + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } /// Create a new `ArrayString` from a `str`. /// @@ -149,7 +162,7 @@ impl ArrayString unsafe { ArrayString { xs: MaybeUninit::zeroed().assume_init(), - len: CAP as _ + len: CAP as _, } } } @@ -163,7 +176,9 @@ impl ArrayString /// assert_eq!(string.capacity(), 3); /// ``` #[inline(always)] - pub const fn capacity(&self) -> usize { CAP } + pub const fn capacity(&self) -> usize { + CAP + } /// Return if the `ArrayString` is completely filled. /// @@ -175,7 +190,9 @@ impl ArrayString /// string.push_str("A"); /// assert!(string.is_full()); /// ``` - pub const fn is_full(&self) -> bool { self.len() == self.capacity() } + pub const fn is_full(&self) -> bool { + self.len() == self.capacity() + } /// Returns the capacity left in the `ArrayString`. /// @@ -301,7 +318,7 @@ impl ArrayString /// /// ``` /// use arrayvec::ArrayString; - /// + /// /// let mut s = ArrayString::<3>::from("foo").unwrap(); /// /// assert_eq!(s.pop(), Some('o')); @@ -341,7 +358,7 @@ impl ArrayString pub fn truncate(&mut self, new_len: usize) { if new_len <= self.len() { assert!(self.is_char_boundary(new_len)); - unsafe { + unsafe { // In libstd truncate is called on the underlying vector, // which in turns drops each element. // As we know we don't have to worry about Drop, @@ -361,7 +378,7 @@ impl ArrayString /// /// ``` /// use arrayvec::ArrayString; - /// + /// /// let mut s = ArrayString::<3>::from("foo").unwrap(); /// /// assert_eq!(s.remove(0), 'f'); @@ -378,10 +395,7 @@ impl ArrayString let len = self.len(); let ptr = self.as_mut_ptr(); unsafe { - ptr::copy( - ptr.add(next), - ptr.add(idx), - len - next); + ptr::copy(ptr.add(next), ptr.add(idx), len - next); self.set_len(len - (next - idx)); } ch @@ -428,8 +442,7 @@ impl ArrayString } } -impl Deref for ArrayString -{ +impl Deref for ArrayString { type Target = str; #[inline] fn deref(&self) -> &str { @@ -440,8 +453,7 @@ impl Deref for ArrayString } } -impl DerefMut for ArrayString -{ +impl DerefMut for ArrayString { #[inline] fn deref_mut(&mut self) -> &mut str { unsafe { @@ -452,72 +464,71 @@ impl DerefMut for ArrayString } } -impl PartialEq for ArrayString -{ +impl PartialEq for ArrayString { fn eq(&self, rhs: &Self) -> bool { **self == **rhs } } -impl PartialEq for ArrayString -{ +impl PartialEq for ArrayString { fn eq(&self, rhs: &str) -> bool { &**self == rhs } } -impl PartialEq> for str -{ +impl PartialEq> for str { fn eq(&self, rhs: &ArrayString) -> bool { self == &**rhs } } -impl Eq for ArrayString -{ } +impl Eq for ArrayString {} -impl Hash for ArrayString -{ +impl Hash for ArrayString { fn hash(&self, h: &mut H) { (**self).hash(h) } } -impl Borrow for ArrayString -{ - fn borrow(&self) -> &str { self } +impl Borrow for ArrayString { + fn borrow(&self) -> &str { + self + } } -impl BorrowMut for ArrayString -{ - fn borrow_mut(&mut self) -> &mut str { self } +impl BorrowMut for ArrayString { + fn borrow_mut(&mut self) -> &mut str { + self + } } -impl AsRef for ArrayString -{ - fn as_ref(&self) -> &str { self } +impl AsRef for ArrayString { + fn as_ref(&self) -> &str { + self + } } -impl fmt::Debug for ArrayString -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } +impl fmt::Debug for ArrayString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (**self).fmt(f) + } } -#[cfg(feature="std")] +#[cfg(feature = "std")] impl AsRef for ArrayString { fn as_ref(&self) -> &Path { self.as_str().as_ref() } } -impl fmt::Display for ArrayString -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } +impl fmt::Display for ArrayString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (**self).fmt(f) + } } /// `Write` appends written data to the end of the string. -impl fmt::Write for ArrayString -{ +impl fmt::Write for ArrayString { fn write_char(&mut self, c: char) -> fmt::Result { self.try_push(c).map_err(|_| fmt::Error) } @@ -527,8 +538,7 @@ impl fmt::Write for ArrayString } } -impl Clone for ArrayString -{ +impl Clone for ArrayString { fn clone(&self) -> ArrayString { *self } @@ -539,48 +549,67 @@ impl Clone for ArrayString } } -impl PartialOrd for ArrayString -{ +impl PartialOrd for ArrayString { fn partial_cmp(&self, rhs: &Self) -> Option { (**self).partial_cmp(&**rhs) } - fn lt(&self, rhs: &Self) -> bool { **self < **rhs } - fn le(&self, rhs: &Self) -> bool { **self <= **rhs } - fn gt(&self, rhs: &Self) -> bool { **self > **rhs } - fn ge(&self, rhs: &Self) -> bool { **self >= **rhs } + fn lt(&self, rhs: &Self) -> bool { + **self < **rhs + } + fn le(&self, rhs: &Self) -> bool { + **self <= **rhs + } + fn gt(&self, rhs: &Self) -> bool { + **self > **rhs + } + fn ge(&self, rhs: &Self) -> bool { + **self >= **rhs + } } -impl PartialOrd for ArrayString -{ +impl PartialOrd for ArrayString { fn partial_cmp(&self, rhs: &str) -> Option { (**self).partial_cmp(rhs) } - fn lt(&self, rhs: &str) -> bool { &**self < rhs } - fn le(&self, rhs: &str) -> bool { &**self <= rhs } - fn gt(&self, rhs: &str) -> bool { &**self > rhs } - fn ge(&self, rhs: &str) -> bool { &**self >= rhs } + fn lt(&self, rhs: &str) -> bool { + &**self < rhs + } + fn le(&self, rhs: &str) -> bool { + &**self <= rhs + } + fn gt(&self, rhs: &str) -> bool { + &**self > rhs + } + fn ge(&self, rhs: &str) -> bool { + &**self >= rhs + } } -impl PartialOrd> for str -{ +impl PartialOrd> for str { fn partial_cmp(&self, rhs: &ArrayString) -> Option { self.partial_cmp(&**rhs) } - fn lt(&self, rhs: &ArrayString) -> bool { self < &**rhs } - fn le(&self, rhs: &ArrayString) -> bool { self <= &**rhs } - fn gt(&self, rhs: &ArrayString) -> bool { self > &**rhs } - fn ge(&self, rhs: &ArrayString) -> bool { self >= &**rhs } + fn lt(&self, rhs: &ArrayString) -> bool { + self < &**rhs + } + fn le(&self, rhs: &ArrayString) -> bool { + self <= &**rhs + } + fn gt(&self, rhs: &ArrayString) -> bool { + self > &**rhs + } + fn ge(&self, rhs: &ArrayString) -> bool { + self >= &**rhs + } } -impl Ord for ArrayString -{ +impl Ord for ArrayString { fn cmp(&self, rhs: &Self) -> cmp::Ordering { (**self).cmp(&**rhs) } } -impl FromStr for ArrayString -{ +impl FromStr for ArrayString { type Err = CapacityError; fn from_str(s: &str) -> Result { @@ -588,23 +617,23 @@ impl FromStr for ArrayString } } -#[cfg(feature="serde")] +#[cfg(feature = "serde")] /// Requires crate feature `"serde"` -impl Serialize for ArrayString -{ +impl Serialize for ArrayString { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(&*self) } } -#[cfg(feature="serde")] +#[cfg(feature = "serde")] /// Requires crate feature `"serde"` -impl<'de, const CAP: usize> Deserialize<'de> for ArrayString -{ +impl<'de, const CAP: usize> Deserialize<'de> for ArrayString { fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { use serde::de::{self, Visitor}; use std::marker::PhantomData; @@ -619,15 +648,18 @@ impl<'de, const CAP: usize> Deserialize<'de> for ArrayString } fn visit_str(self, v: &str) -> Result - where E: de::Error, + where + E: de::Error, { ArrayString::from(v).map_err(|_| E::invalid_length(v.len(), &self)) } fn visit_bytes(self, v: &[u8]) -> Result - where E: de::Error, + where + E: de::Error, { - let s = str::from_utf8(v).map_err(|_| E::invalid_value(de::Unexpected::Bytes(v), &self))?; + let s = str::from_utf8(v) + .map_err(|_| E::invalid_value(de::Unexpected::Bytes(v), &self))?; ArrayString::from(s).map_err(|_| E::invalid_length(s.len(), &self)) } @@ -654,7 +686,7 @@ impl borsh::BorshDeserialize for ArrayString { return Err(borsh::io::Error::new( borsh::io::ErrorKind::InvalidData, format!("Expected a string no more than {} bytes long", CAP), - )) + )); } let mut buf = [0u8; CAP]; @@ -668,8 +700,7 @@ impl borsh::BorshDeserialize for ArrayString { } } -impl<'a, const CAP: usize> TryFrom<&'a str> for ArrayString -{ +impl<'a, const CAP: usize> TryFrom<&'a str> for ArrayString { type Error = CapacityError<&'a str>; fn try_from(f: &'a str) -> Result { @@ -679,8 +710,7 @@ impl<'a, const CAP: usize> TryFrom<&'a str> for ArrayString } } -impl<'a, const CAP: usize> TryFrom> for ArrayString -{ +impl<'a, const CAP: usize> TryFrom> for ArrayString { type Error = CapacityError; fn try_from(f: fmt::Arguments<'a>) -> Result { diff --git a/src/arrayvec.rs b/src/arrayvec.rs index e5ea52d..0311274 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -1,29 +1,33 @@ - -use std::cmp; -use std::iter; -use std::mem; -use std::ops::{Bound, Deref, DerefMut, RangeBounds}; -use std::ptr; -use std::slice; +use core::cmp; +use core::iter; +use core::mem; +use core::ops::{Bound, Deref, DerefMut, RangeBounds}; +use core::ptr; +use core::slice; // extra traits -use std::borrow::{Borrow, BorrowMut}; -use std::hash::{Hash, Hasher}; -use std::fmt; +use core::borrow::{Borrow, BorrowMut}; +use core::fmt; +use core::hash::{Hash, Hasher}; -#[cfg(feature="std")] +#[cfg(feature = "std")] use std::io; -use std::mem::ManuallyDrop; -use std::mem::MaybeUninit; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; -#[cfg(feature="serde")] -use serde::{Serialize, Deserialize, Serializer, Deserializer}; +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::LenUint; -use crate::errors::CapacityError; use crate::arrayvec_impl::ArrayVecImpl; +use crate::errors::CapacityError; use crate::utils::MakeMaybeUninit; +use crate::LenUint; + +extern crate alloc; + +#[cfg(all(not(feature = "std"), feature = "borsh"))] +use alloc::format; /// A vector with a fixed capacity. /// @@ -56,9 +60,15 @@ impl Drop for ArrayVec { macro_rules! panic_oob { ($method_name:expr, $index:expr, $len:expr) => { - panic!(concat!("ArrayVec::", $method_name, ": index {} is out of bounds in vector of length {}"), - $index, $len) - } + panic!( + concat!( + "ArrayVec::", + $method_name, + ": index {} is out of bounds in vector of length {}" + ), + $index, $len + ) + }; } impl ArrayVec { @@ -83,7 +93,10 @@ impl ArrayVec { pub fn new() -> ArrayVec { assert_capacity_limit!(CAP); unsafe { - ArrayVec { xs: MaybeUninit::uninit().assume_init(), len: 0 } + ArrayVec { + xs: MaybeUninit::uninit().assume_init(), + len: 0, + } } } @@ -98,7 +111,10 @@ impl ArrayVec { /// ``` pub const fn new_const() -> ArrayVec { assert_capacity_limit_const!(CAP); - ArrayVec { xs: MakeMaybeUninit::ARRAY, len: 0 } + ArrayVec { + xs: MakeMaybeUninit::ARRAY, + len: 0, + } } /// Return the number of elements in the `ArrayVec`. @@ -111,7 +127,9 @@ impl ArrayVec { /// assert_eq!(array.len(), 2); /// ``` #[inline(always)] - pub const fn len(&self) -> usize { self.len as usize } + pub const fn len(&self) -> usize { + self.len as usize + } /// Returns whether the `ArrayVec` is empty. /// @@ -123,7 +141,9 @@ impl ArrayVec { /// assert_eq!(array.is_empty(), true); /// ``` #[inline] - pub const fn is_empty(&self) -> bool { self.len() == 0 } + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } /// Return the capacity of the `ArrayVec`. /// @@ -134,7 +154,9 @@ impl ArrayVec { /// assert_eq!(array.capacity(), 3); /// ``` #[inline(always)] - pub const fn capacity(&self) -> usize { CAP } + pub const fn capacity(&self) -> usize { + CAP + } /// Return true if the `ArrayVec` is completely filled to its capacity, false otherwise. /// @@ -146,7 +168,9 @@ impl ArrayVec { /// array.push(1); /// assert!(array.is_full()); /// ``` - pub const fn is_full(&self) -> bool { self.len() == self.capacity() } + pub const fn is_full(&self) -> bool { + self.len() == self.capacity() + } /// Returns the capacity left in the `ArrayVec`. /// @@ -255,7 +279,6 @@ impl ArrayVec { ArrayVecImpl::clear(self) } - /// Get pointer to where element at `index` would be unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut T { self.as_mut_ptr().add(index) @@ -316,7 +339,8 @@ impl ArrayVec { let len = self.len(); // follows is just like Vec - unsafe { // infallible + unsafe { + // infallible // The spot to put the new value { let p: *mut _ = self.get_unchecked_ptr(index); @@ -371,14 +395,12 @@ impl ArrayVec { /// ``` pub fn swap_remove(&mut self, index: usize) -> T { self.swap_pop(index) - .unwrap_or_else(|| { - panic_oob!("swap_remove", index, self.len()) - }) + .unwrap_or_else(|| panic_oob!("swap_remove", index, self.len())) } /// Remove the element at `index` and swap the last element into its place. /// - /// This is a checked version of `.swap_remove`. + /// This is a checked version of `.swap_remove`. /// This operation is O(1). /// /// Return `Some(` *element* `)` if the index is in bounds, else `None`. @@ -419,9 +441,7 @@ impl ArrayVec { /// ``` pub fn remove(&mut self, index: usize) -> T { self.pop_at(index) - .unwrap_or_else(|| { - panic_oob!("remove", index, self.len()) - }) + .unwrap_or_else(|| panic_oob!("remove", index, self.len())) } /// Remove the element at `index` and shift down the following elements. @@ -462,7 +482,8 @@ impl ArrayVec { /// assert_eq!(&array[..], &[1, 3]); /// ``` pub fn retain(&mut self, mut f: F) - where F: FnMut(&mut T) -> bool + where + F: FnMut(&mut T) -> bool, { // Check the implementation of // https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain @@ -485,8 +506,10 @@ impl ArrayVec { unsafe { ptr::copy( self.v.as_ptr().add(self.processed_len), - self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), - self.original_len - self.processed_len + self.v + .as_mut_ptr() + .add(self.processed_len - self.deleted_cnt), + self.original_len - self.processed_len, ); } } @@ -496,12 +519,17 @@ impl ArrayVec { } } - let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; + let mut g = BackshiftOnDrop { + v: self, + processed_len: 0, + deleted_cnt: 0, + original_len, + }; #[inline(always)] fn process_one bool, T, const CAP: usize, const DELETED: bool>( f: &mut F, - g: &mut BackshiftOnDrop<'_, T, CAP> + g: &mut BackshiftOnDrop<'_, T, CAP>, ) -> bool { let cur = unsafe { g.v.as_mut_ptr().add(g.processed_len) }; if !f(unsafe { &mut *cur }) { @@ -602,7 +630,8 @@ impl ArrayVec { /// /// [`remaining_capacity`]: #method.remaining_capacity pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError> - where T: Copy, + where + T: Copy, { if self.remaining_capacity() < other.len() { return Err(CapacityError::new(())); @@ -638,7 +667,8 @@ impl ArrayVec { /// assert_eq!(&v2[..], &[1, 2]); /// ``` pub fn drain(&mut self, range: R) -> Drain - where R: RangeBounds + where + R: RangeBounds, { // Memory safety // @@ -664,8 +694,7 @@ impl ArrayVec { self.drain_range(start, end) } - fn drain_range(&mut self, start: usize, end: usize) -> Drain - { + fn drain_range(&mut self, start: usize, end: usize) -> Drain { let len = self.len(); // bounds check happens here (before length is changed!) @@ -717,7 +746,7 @@ impl ArrayVec { /// assert_eq!([0, 1, 2, 3], v.take().into_inner().unwrap()); /// assert!(v.is_empty()); /// ``` - pub fn take(&mut self) -> Self { + pub fn take(&mut self) -> Self { mem::replace(self, Self::new()) } @@ -746,7 +775,9 @@ impl ArrayVecImpl for ArrayVec { type Item = T; const CAPACITY: usize = CAP; - fn len(&self) -> usize { self.len() } + fn len(&self) -> usize { + self.len() + } unsafe fn set_len(&mut self, length: usize) { debug_assert!(length <= CAP); @@ -777,7 +808,6 @@ impl DerefMut for ArrayVec { } } - /// Create an `ArrayVec` from an array. /// /// ``` @@ -801,7 +831,6 @@ impl From<[T; CAP]> for ArrayVec { } } - /// Try to create an `ArrayVec` from a slice. This will return an error if the slice was too big to /// fit. /// @@ -814,7 +843,8 @@ impl From<[T; CAP]> for ArrayVec { /// assert_eq!(array.capacity(), 4); /// ``` impl std::convert::TryFrom<&[T]> for ArrayVec - where T: Clone, +where + T: Clone, { type Error = CapacityError; @@ -829,7 +859,6 @@ impl std::convert::TryFrom<&[T]> for ArrayVec } } - /// Iterate the `ArrayVec` with references to each element. /// /// ``` @@ -844,7 +873,9 @@ impl std::convert::TryFrom<&[T]> for ArrayVec impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a ArrayVec { type Item = &'a T; type IntoIter = slice::Iter<'a, T>; - fn into_iter(self) -> Self::IntoIter { self.iter() } + fn into_iter(self) -> Self::IntoIter { + self.iter() + } } /// Iterate the `ArrayVec` with mutable references to each element. @@ -861,7 +892,9 @@ impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a ArrayVec { impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a mut ArrayVec { type Item = &'a mut T; type IntoIter = slice::IterMut<'a, T>; - fn into_iter(self) -> Self::IntoIter { self.iter_mut() } + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } } /// Iterate the `ArrayVec` with each element by value. @@ -879,11 +912,10 @@ impl IntoIterator for ArrayVec { type Item = T; type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { - IntoIter { index: 0, v: self, } + IntoIter { index: 0, v: self } } } - #[cfg(feature = "zeroize")] /// "Best efforts" zeroing of the `ArrayVec`'s buffer when the `zeroize` feature is enabled. /// @@ -962,7 +994,7 @@ impl DoubleEndedIterator for IntoIter { } } -impl ExactSizeIterator for IntoIter { } +impl ExactSizeIterator for IntoIter {} impl Drop for IntoIter { fn drop(&mut self) { @@ -971,16 +1003,15 @@ impl Drop for IntoIter { let len = self.v.len(); unsafe { self.v.set_len(0); - let elements = slice::from_raw_parts_mut( - self.v.get_unchecked_ptr(index), - len - index); + let elements = slice::from_raw_parts_mut(self.v.get_unchecked_ptr(index), len - index); ptr::drop_in_place(elements); } } } impl Clone for IntoIter -where T: Clone, +where + T: Clone, { fn clone(&self) -> IntoIter { let mut v = ArrayVec::new(); @@ -994,9 +1025,7 @@ where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(&self.v[self.index..]) - .finish() + f.debug_list().entries(&self.v[self.index..]).finish() } } @@ -1018,11 +1047,9 @@ impl<'a, T: 'a, const CAP: usize> Iterator for Drain<'a, T, CAP> { type Item = T; fn next(&mut self) -> Option { - self.iter.next().map(|elt| - unsafe { - ptr::read(elt as *const _) - } - ) + self.iter + .next() + .map(|elt| unsafe { ptr::read(elt as *const _) }) } fn size_hint(&self) -> (usize, Option) { @@ -1030,14 +1057,11 @@ impl<'a, T: 'a, const CAP: usize> Iterator for Drain<'a, T, CAP> { } } -impl<'a, T: 'a, const CAP: usize> DoubleEndedIterator for Drain<'a, T, CAP> -{ +impl<'a, T: 'a, const CAP: usize> DoubleEndedIterator for Drain<'a, T, CAP> { fn next_back(&mut self) -> Option { - self.iter.next_back().map(|elt| - unsafe { - ptr::read(elt as *const _) - } - ) + self.iter + .next_back() + .map(|elt| unsafe { ptr::read(elt as *const _) }) } } @@ -1048,7 +1072,7 @@ impl<'a, T: 'a, const CAP: usize> Drop for Drain<'a, T, CAP> { // len is currently 0 so panicking while dropping will not cause a double drop. // exhaust self first - while let Some(_) = self.next() { } + while let Some(_) = self.next() {} if self.tail_len > 0 { unsafe { @@ -1065,7 +1089,8 @@ impl<'a, T: 'a, const CAP: usize> Drop for Drain<'a, T, CAP> { } struct ScopeExitGuard - where F: FnMut(&Data, &mut T) +where + F: FnMut(&Data, &mut T), { value: T, data: Data, @@ -1073,27 +1098,24 @@ struct ScopeExitGuard } impl Drop for ScopeExitGuard - where F: FnMut(&Data, &mut T) +where + F: FnMut(&Data, &mut T), { fn drop(&mut self) { (self.f)(&self.data, &mut self.value) } } - - /// Extend the `ArrayVec` with an iterator. -/// +/// /// ***Panics*** if extending the vector exceeds its capacity. impl Extend for ArrayVec { /// Extend the `ArrayVec` with an iterator. - /// + /// /// ***Panics*** if extending the vector exceeds its capacity. #[track_caller] - fn extend>(&mut self, iter: I) { - unsafe { - self.extend_from_iter::<_, true>(iter) - } + fn extend>(&mut self, iter: I) { + unsafe { self.extend_from_iter::<_, true>(iter) } } } @@ -1113,7 +1135,8 @@ impl ArrayVec { /// The caller must ensure the length of the input fits in the capacity. #[track_caller] pub(crate) unsafe fn extend_from_iter(&mut self, iterable: I) - where I: IntoIterator + where + I: IntoIterator, { let take = self.capacity() - self.len(); let len = self.len(); @@ -1128,12 +1151,14 @@ impl ArrayVec { data: len, f: move |&len, self_len| { **self_len = len as LenUint; - } + }, }; let mut iter = iterable.into_iter(); loop { if let Some(elt) = iter.next() { - if ptr == end_ptr && CHECK { extend_panic(); } + if ptr == end_ptr && CHECK { + extend_panic(); + } debug_assert_ne!(ptr, end_ptr); if mem::size_of::() != 0 { ptr.write(elt); @@ -1149,12 +1174,17 @@ impl ArrayVec { /// Extend the ArrayVec with clones of elements from the slice; /// the length of the slice must be <= the remaining capacity in the arrayvec. pub(crate) fn extend_from_slice(&mut self, slice: &[T]) - where T: Clone + where + T: Clone, { let take = self.capacity() - self.len(); debug_assert!(slice.len() <= take); unsafe { - let slice = if take < slice.len() { &slice[..take] } else { slice }; + let slice = if take < slice.len() { + &slice[..take] + } else { + slice + }; self.extend_from_iter::<_, false>(slice.iter().cloned()); } } @@ -1171,13 +1201,13 @@ unsafe fn raw_ptr_add(ptr: *mut T, offset: usize) -> *mut T { } /// Create an `ArrayVec` from an iterator. -/// +/// /// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity. impl iter::FromIterator for ArrayVec { /// Create an `ArrayVec` from an iterator. - /// + /// /// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity. - fn from_iter>(iter: I) -> Self { + fn from_iter>(iter: I) -> Self { let mut array = ArrayVec::new(); array.extend(iter); array @@ -1185,7 +1215,8 @@ impl iter::FromIterator for ArrayVec { } impl Clone for ArrayVec - where T: Clone +where + T: Clone, { fn clone(&self) -> Self { self.iter().cloned().collect() @@ -1207,7 +1238,8 @@ impl Clone for ArrayVec } impl Hash for ArrayVec - where T: Hash +where + T: Hash, { fn hash(&self, state: &mut H) { Hash::hash(&**self, state) @@ -1215,7 +1247,8 @@ impl Hash for ArrayVec } impl PartialEq for ArrayVec - where T: PartialEq +where + T: PartialEq, { fn eq(&self, other: &Self) -> bool { **self == **other @@ -1223,33 +1256,47 @@ impl PartialEq for ArrayVec } impl PartialEq<[T]> for ArrayVec - where T: PartialEq +where + T: PartialEq, { fn eq(&self, other: &[T]) -> bool { **self == *other } } -impl Eq for ArrayVec where T: Eq { } +impl Eq for ArrayVec where T: Eq {} impl Borrow<[T]> for ArrayVec { - fn borrow(&self) -> &[T] { self } + fn borrow(&self) -> &[T] { + self + } } impl BorrowMut<[T]> for ArrayVec { - fn borrow_mut(&mut self) -> &mut [T] { self } + fn borrow_mut(&mut self) -> &mut [T] { + self + } } impl AsRef<[T]> for ArrayVec { - fn as_ref(&self) -> &[T] { self } + fn as_ref(&self) -> &[T] { + self + } } impl AsMut<[T]> for ArrayVec { - fn as_mut(&mut self) -> &mut [T] { self } + fn as_mut(&mut self) -> &mut [T] { + self + } } -impl fmt::Debug for ArrayVec where T: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } +impl fmt::Debug for ArrayVec +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (**self).fmt(f) + } } impl Default for ArrayVec { @@ -1259,7 +1306,10 @@ impl Default for ArrayVec { } } -impl PartialOrd for ArrayVec where T: PartialOrd { +impl PartialOrd for ArrayVec +where + T: PartialOrd, +{ fn partial_cmp(&self, other: &Self) -> Option { (**self).partial_cmp(other) } @@ -1281,46 +1331,64 @@ impl PartialOrd for ArrayVec where T: PartialOrd { } } -impl Ord for ArrayVec where T: Ord { +impl Ord for ArrayVec +where + T: Ord, +{ fn cmp(&self, other: &Self) -> cmp::Ordering { (**self).cmp(other) } } -#[cfg(feature="std")] +impl ArrayVec { + /// `Write` appends written data to the end of the vector. + pub fn write(&mut self, data: &[u8]) -> usize { + let len = cmp::min(self.remaining_capacity(), data.len()); + let _result = self.try_extend_from_slice(&data[..len]); + debug_assert!(_result.is_ok()); + len + } +} + +#[cfg(feature = "std")] /// `Write` appends written data to the end of the vector. +/// Wraps the existing write function. /// /// Requires `features="std"`. impl io::Write for ArrayVec { fn write(&mut self, data: &[u8]) -> io::Result { - let len = cmp::min(self.remaining_capacity(), data.len()); - let _result = self.try_extend_from_slice(&data[..len]); - debug_assert!(_result.is_ok()); - Ok(len) + Ok(ArrayVec::write(self, data)) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) } - fn flush(&mut self) -> io::Result<()> { Ok(()) } } -#[cfg(feature="serde")] +#[cfg(feature = "serde")] /// Requires crate feature `"serde"` impl Serialize for ArrayVec { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.collect_seq(self) } } -#[cfg(feature="serde")] +#[cfg(feature = "serde")] /// Requires crate feature `"serde"` impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec { fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { - use serde::de::{Visitor, SeqAccess, Error}; + use serde::de::{Error, SeqAccess, Visitor}; use std::marker::PhantomData; - struct ArrayVecVisitor<'de, T: Deserialize<'de>, const CAP: usize>(PhantomData<(&'de (), [T; CAP])>); + struct ArrayVecVisitor<'de, T: Deserialize<'de>, const CAP: usize>( + PhantomData<(&'de (), [T; CAP])>, + ); impl<'de, T: Deserialize<'de>, const CAP: usize> Visitor<'de> for ArrayVecVisitor<'de, T, CAP> { type Value = ArrayVec; @@ -1330,7 +1398,8 @@ impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec(self, mut seq: SA) -> Result - where SA: SeqAccess<'de>, + where + SA: SeqAccess<'de>, { let mut values = ArrayVec::::new(); @@ -1359,6 +1428,33 @@ where } } +#[cfg(all(feature = "borsh"))] +/// Requires crate feature `"borsh"` +impl borsh::io::Write for ArrayVec { + fn write(&mut self, data: &[u8]) -> borsh::io::Result { + Ok(ArrayVec::write(self, data)) + } + + fn write_all(&mut self, mut buf: &[u8]) -> borsh::io::Result<()> { + while !buf.is_empty() { + match self.write(buf) { + 0 => { + return Err(borsh::io::Error::new( + borsh::io::ErrorKind::WriteZero, + "failed to write whole buffer", + )); + } + n => buf = &buf[n..], + } + } + Ok(()) + } + + fn flush(&mut self) -> borsh::io::Result<()> { + Ok(()) + } +} + #[cfg(feature = "borsh")] /// Requires crate feature `"borsh"` impl borsh::BorshDeserialize for ArrayVec diff --git a/src/arrayvec_impl.rs b/src/arrayvec_impl.rs index c5ebe7b..9e85bbc 100644 --- a/src/arrayvec_impl.rs +++ b/src/arrayvec_impl.rs @@ -1,5 +1,5 @@ -use std::ptr; -use std::slice; +use core::ptr; +use core::slice; use crate::CapacityError; @@ -16,17 +16,13 @@ pub(crate) trait ArrayVecImpl { /// Return a slice containing all elements of the vector. fn as_slice(&self) -> &[Self::Item] { let len = self.len(); - unsafe { - slice::from_raw_parts(self.as_ptr(), len) - } + unsafe { slice::from_raw_parts(self.as_ptr(), len) } } /// Return a mutable slice containing all elements of the vector. fn as_mut_slice(&mut self) -> &mut [Self::Item] { let len = self.len(); - unsafe { - std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) - } + unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } /// Return a raw pointer to the vector's buffer. @@ -84,4 +80,3 @@ pub(crate) trait ArrayVecImpl { } } } - diff --git a/src/char.rs b/src/char.rs index 939b6b4..77df311 100644 --- a/src/char.rs +++ b/src/char.rs @@ -11,13 +11,13 @@ // Original authors: alexchrichton, bluss // UTF-8 ranges and tags for encoding characters -const TAG_CONT: u8 = 0b1000_0000; -const TAG_TWO_B: u8 = 0b1100_0000; +const TAG_CONT: u8 = 0b1000_0000; +const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; -const TAG_FOUR_B: u8 = 0b1111_0000; -const MAX_ONE_B: u32 = 0x80; -const MAX_TWO_B: u32 = 0x800; -const MAX_THREE_B: u32 = 0x10000; +const TAG_FOUR_B: u8 = 0b1111_0000; +const MAX_ONE_B: u32 = 0x80; +const MAX_TWO_B: u32 = 0x800; +const MAX_THREE_B: u32 = 0x10000; /// Placeholder pub struct EncodeUtf8Error; @@ -29,8 +29,7 @@ pub struct EncodeUtf8Error; /// /// Safety: `ptr` must be writable for `len` bytes. #[inline] -pub unsafe fn encode_utf8(ch: char, ptr: *mut u8, len: usize) -> Result -{ +pub unsafe fn encode_utf8(ch: char, ptr: *mut u8, len: usize) -> Result { let code = ch as u32; if code < MAX_ONE_B && len >= 1 { ptr.add(0).write(code as u8); @@ -41,20 +40,19 @@ pub unsafe fn encode_utf8(ch: char, ptr: *mut u8, len: usize) -> Result= 3 { ptr.add(0).write((code >> 12 & 0x0F) as u8 | TAG_THREE_B); - ptr.add(1).write((code >> 6 & 0x3F) as u8 | TAG_CONT); + ptr.add(1).write((code >> 6 & 0x3F) as u8 | TAG_CONT); ptr.add(2).write((code & 0x3F) as u8 | TAG_CONT); return Ok(3); } else if len >= 4 { ptr.add(0).write((code >> 18 & 0x07) as u8 | TAG_FOUR_B); ptr.add(1).write((code >> 12 & 0x3F) as u8 | TAG_CONT); - ptr.add(2).write((code >> 6 & 0x3F) as u8 | TAG_CONT); + ptr.add(2).write((code >> 6 & 0x3F) as u8 | TAG_CONT); ptr.add(3).write((code & 0x3F) as u8 | TAG_CONT); return Ok(4); }; Err(EncodeUtf8Error) } - #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn test_encode_utf8() { @@ -62,7 +60,9 @@ fn test_encode_utf8() { let mut data = [0u8; 16]; for codepoint in 0..=(std::char::MAX as u32) { if let Some(ch) = std::char::from_u32(codepoint) { - for elt in &mut data { *elt = 0; } + for elt in &mut data { + *elt = 0; + } let ptr = data.as_mut_ptr(); let len = data.len(); unsafe { @@ -89,4 +89,3 @@ fn test_encode_utf8_oob() { } } } - diff --git a/src/errors.rs b/src/errors.rs index 7ca3ebc..19e479e 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,8 +1,8 @@ -use std::fmt; -#[cfg(feature="std")] +#[cfg(feature = "std")] use std::any::Any; -#[cfg(feature="std")] +#[cfg(feature = "std")] use std::error::Error; +use std::fmt; /// Error value indicating insufficient capacity #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] @@ -13,9 +13,7 @@ pub struct CapacityError { impl CapacityError { /// Create a new `CapacityError` from `element`. pub const fn new(element: T) -> CapacityError { - CapacityError { - element: element, - } + CapacityError { element: element } } /// Extract the overflowing element @@ -31,7 +29,7 @@ impl CapacityError { const CAPERROR: &'static str = "insufficient capacity"; -#[cfg(feature="std")] +#[cfg(feature = "std")] /// Requires `features="std"`. impl Error for CapacityError {} @@ -46,4 +44,3 @@ impl fmt::Debug for CapacityError { write!(f, "{}: {}", "CapacityError", CAPERROR) } } - diff --git a/src/lib.rs b/src/lib.rs index 5c4bcee..edea268 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -//! **arrayvec** provides the types [`ArrayVec`] and [`ArrayString`]: +//! **arrayvec** provides the types [`ArrayVec`] and [`ArrayString`]: //! array-backed vector and string types, which store their contents inline. //! //! The arrayvec package has the following cargo features: @@ -19,13 +19,13 @@ //! //! This version of arrayvec requires Rust 1.51 or later. //! -#![doc(html_root_url="https://docs.rs/arrayvec/0.7/")] -#![cfg_attr(not(feature="std"), no_std)] +#![doc(html_root_url = "https://docs.rs/arrayvec/0.7/")] +#![cfg_attr(not(feature = "std"), no_std)] -#[cfg(feature="serde")] +#[cfg(feature = "serde")] extern crate serde; -#[cfg(not(feature="std"))] +#[cfg(not(feature = "std"))] extern crate core as std; #[cfg(not(target_pointer_width = "16"))] @@ -44,7 +44,7 @@ macro_rules! assert_capacity_limit { panic!("ArrayVec: largest supported capacity is u16::MAX"); } } - } + }; } macro_rules! assert_capacity_limit_const { @@ -57,9 +57,9 @@ macro_rules! assert_capacity_limit_const { } } -mod arrayvec_impl; -mod arrayvec; mod array_string; +mod arrayvec; +mod arrayvec_impl; mod char; mod errors; mod utils; @@ -67,4 +67,4 @@ mod utils; pub use crate::array_string::ArrayString; pub use crate::errors::CapacityError; -pub use crate::arrayvec::{ArrayVec, IntoIter, Drain}; +pub use crate::arrayvec::{ArrayVec, Drain, IntoIter}; diff --git a/src/utils.rs b/src/utils.rs index b8e5ddb..a2b058f 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,5 +1,5 @@ -use std::marker::PhantomData; -use std::mem::MaybeUninit; +use core::marker::PhantomData; +use core::mem::MaybeUninit; pub(crate) struct MakeMaybeUninit(PhantomData T>); @@ -8,4 +8,3 @@ impl MakeMaybeUninit { pub(crate) const ARRAY: [MaybeUninit; N] = [Self::VALUE; N]; } - diff --git a/tests/borsh.rs b/tests/borsh.rs index f05abcf..f954ac6 100644 --- a/tests/borsh.rs +++ b/tests/borsh.rs @@ -9,7 +9,9 @@ fn assert_ser(v: &T, expected_bytes: &[u8]) { assert_eq!(actual_bytes, expected_bytes); } -fn assert_roundtrip(v: &T) { +fn assert_roundtrip( + v: &T, +) { let mut bytes = Vec::new(); v.serialize(&mut bytes).unwrap(); let v_de = T::try_from_slice(&bytes).unwrap(); @@ -17,8 +19,8 @@ fn assert_roundtrip::new(); + a.serialize(&mut vec).unwrap(); + let mut test = Vec::new(); + a.serialize(&mut test).unwrap(); + assert_eq!(vec.as_slice(), test.as_slice()); + } + + #[test] + fn test_borsh_more_than() { + use borsh::{io::ErrorKind, BorshDeserialize, BorshSerialize}; + #[derive(BorshSerialize, BorshDeserialize)] + struct Something { + a: String, + } + let mut b = ArrayVec::::new(); + let err = Something { + a: "Hello, world!".to_owned(), + } + .serialize(&mut b) + .unwrap_err(); + assert_eq!(ErrorKind::WriteZero, err.kind()); + } } mod array_string { + use super::{assert_roundtrip, assert_ser}; use arrayvec::ArrayString; - use super::{assert_ser, assert_roundtrip}; #[test] fn test_empty() { diff --git a/tests/serde.rs b/tests/serde.rs index f02c693..58630f5 100644 --- a/tests/serde.rs +++ b/tests/serde.rs @@ -5,19 +5,15 @@ extern crate serde_test; mod array_vec { use arrayvec::ArrayVec; - use serde_test::{Token, assert_tokens, assert_de_tokens_error}; + use serde_test::{assert_de_tokens_error, assert_tokens, Token}; #[test] fn test_ser_de_empty() { let vec = ArrayVec::::new(); - assert_tokens(&vec, &[ - Token::Seq { len: Some(0) }, - Token::SeqEnd, - ]); + assert_tokens(&vec, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); } - #[test] fn test_ser_de() { let mut vec = ArrayVec::::new(); @@ -25,55 +21,57 @@ mod array_vec { vec.push(55); vec.push(123); - assert_tokens(&vec, &[ - Token::Seq { len: Some(3) }, - Token::U32(20), - Token::U32(55), - Token::U32(123), - Token::SeqEnd, - ]); + assert_tokens( + &vec, + &[ + Token::Seq { len: Some(3) }, + Token::U32(20), + Token::U32(55), + Token::U32(123), + Token::SeqEnd, + ], + ); } #[test] fn test_de_too_large() { - assert_de_tokens_error::>(&[ - Token::Seq { len: Some(3) }, - Token::U32(13), - Token::U32(42), - Token::U32(68), - ], "invalid length 3, expected an array with no more than 2 items"); + assert_de_tokens_error::>( + &[ + Token::Seq { len: Some(3) }, + Token::U32(13), + Token::U32(42), + Token::U32(68), + ], + "invalid length 3, expected an array with no more than 2 items", + ); } } mod array_string { use arrayvec::ArrayString; - use serde_test::{Token, assert_tokens, assert_de_tokens_error}; + use serde_test::{assert_de_tokens_error, assert_tokens, Token}; #[test] fn test_ser_de_empty() { let string = ArrayString::<0>::new(); - assert_tokens(&string, &[ - Token::Str(""), - ]); + assert_tokens(&string, &[Token::Str("")]); } - #[test] fn test_ser_de() { let string = ArrayString::<9>::from("1234 abcd") .expect("expected exact specified capacity to be enough"); - assert_tokens(&string, &[ - Token::Str("1234 abcd"), - ]); + assert_tokens(&string, &[Token::Str("1234 abcd")]); } #[test] fn test_de_too_large() { - assert_de_tokens_error::>(&[ - Token::Str("afd") - ], "invalid length 3, expected a string no more than 2 bytes long"); + assert_de_tokens_error::>( + &[Token::Str("afd")], + "invalid length 3, expected a string no more than 2 bytes long", + ); } } diff --git a/tests/tests.rs b/tests/tests.rs index ff779ba..5cad53f 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -1,19 +1,20 @@ extern crate arrayvec; -#[macro_use] extern crate matches; +#[macro_use] +extern crate matches; -use arrayvec::ArrayVec; use arrayvec::ArrayString; -use std::mem; +use arrayvec::ArrayVec; use arrayvec::CapacityError; +use std::mem; +#[cfg(feature = "std")] use std::collections::HashMap; - #[test] fn test_simple() { use std::ops::Add; - let mut vec: ArrayVec, 3> = ArrayVec::new(); + let mut vec: ArrayVec, 3> = ArrayVec::new(); vec.push(vec![1, 2, 3, 4]); vec.push(vec![10]); @@ -29,7 +30,7 @@ fn test_simple() { #[test] fn test_capacity_left() { - let mut vec: ArrayVec = ArrayVec::new(); + let mut vec: ArrayVec = ArrayVec::new(); assert_eq!(vec.remaining_capacity(), 4); vec.push(1); assert_eq!(vec.remaining_capacity(), 3); @@ -43,7 +44,7 @@ fn test_capacity_left() { #[test] fn test_extend_from_slice() { - let mut vec: ArrayVec = ArrayVec::new(); + let mut vec: ArrayVec = ArrayVec::new(); vec.try_extend_from_slice(&[1, 2, 3]).unwrap(); assert_eq!(vec.len(), 3); @@ -54,13 +55,13 @@ fn test_extend_from_slice() { #[test] fn test_extend_from_slice_error() { - let mut vec: ArrayVec = ArrayVec::new(); + let mut vec: ArrayVec = ArrayVec::new(); vec.try_extend_from_slice(&[1, 2, 3]).unwrap(); let res = vec.try_extend_from_slice(&[0; 8]); assert_matches!(res, Err(_)); - let mut vec: ArrayVec = ArrayVec::new(); + let mut vec: ArrayVec = ArrayVec::new(); let res = vec.try_extend_from_slice(&[0; 1]); assert_matches!(res, Err(_)); } @@ -70,14 +71,14 @@ fn test_try_from_slice_error() { use arrayvec::ArrayVec; use std::convert::TryInto as _; - let res: Result, _> = (&[1, 2, 3] as &[_]).try_into(); + let res: Result, _> = (&[1, 2, 3] as &[_]).try_into(); assert_matches!(res, Err(_)); } #[test] fn test_u16_index() { const N: usize = 4096; - let mut vec: ArrayVec<_, N> = ArrayVec::new(); + let mut vec: ArrayVec<_, N> = ArrayVec::new(); for _ in 0..N { assert!(vec.try_push(1u8).is_ok()); } @@ -113,7 +114,7 @@ fn test_drop() { } { - let mut array = ArrayVec::::new(); + let mut array = ArrayVec::::new(); array.push(Bump(flag)); array.push(Bump(flag)); } @@ -123,7 +124,7 @@ fn test_drop() { flag.set(0); { - let mut array = ArrayVec::<_, 3>::new(); + let mut array = ArrayVec::<_, 3>::new(); array.push(vec![Bump(flag)]); array.push(vec![Bump(flag), Bump(flag)]); array.push(vec![]); @@ -142,7 +143,7 @@ fn test_drop() { // test into_inner flag.set(0); { - let mut array = ArrayVec::<_, 3>::new(); + let mut array = ArrayVec::<_, 3>::new(); array.push(Bump(flag)); array.push(Bump(flag)); array.push(Bump(flag)); @@ -156,7 +157,7 @@ fn test_drop() { // test take flag.set(0); { - let mut array1 = ArrayVec::<_, 3>::new(); + let mut array1 = ArrayVec::<_, 3>::new(); array1.push(Bump(flag)); array1.push(Bump(flag)); array1.push(Bump(flag)); @@ -171,7 +172,7 @@ fn test_drop() { // test cloning into_iter flag.set(0); { - let mut array = ArrayVec::<_, 3>::new(); + let mut array = ArrayVec::<_, 3>::new(); array.push(Bump(flag)); array.push(Bump(flag)); array.push(Bump(flag)); @@ -225,7 +226,7 @@ fn test_drop_panics() { flag.set(0); { - let mut array = ArrayVec::::new(); + let mut array = ArrayVec::::new(); array.push(Bump(flag)); array.push(Bump(flag)); array.push(Bump(flag)); @@ -238,10 +239,9 @@ fn test_drop_panics() { // Check that all the elements drop, even if the first drop panics. assert_eq!(flag.get(), 3); - flag.set(0); { - let mut array = ArrayVec::::new(); + let mut array = ArrayVec::::new(); array.push(Bump(flag)); array.push(Bump(flag)); array.push(Bump(flag)); @@ -258,22 +258,20 @@ fn test_drop_panics() { // Check that all the tail elements drop, even if the first drop panics. assert_eq!(flag.get(), tail_len as i32); } - - } #[test] fn test_extend() { let mut range = 0..10; - let mut array: ArrayVec<_, 5> = range.by_ref().take(5).collect(); + let mut array: ArrayVec<_, 5> = range.by_ref().take(5).collect(); assert_eq!(&array[..], &[0, 1, 2, 3, 4]); assert_eq!(range.next(), Some(5)); array.extend(range.by_ref().take(0)); assert_eq!(range.next(), Some(6)); - let mut array: ArrayVec<_, 10> = (0..3).collect(); + let mut array: ArrayVec<_, 10> = (0..3).collect(); assert_eq!(&array[..], &[0, 1, 2]); array.extend(3..5); assert_eq!(&array[..], &[0, 1, 2, 3, 4]); @@ -284,7 +282,7 @@ fn test_extend() { fn test_extend_capacity_panic_1() { let mut range = 0..10; - let _: ArrayVec<_, 5> = range.by_ref().collect(); + let _: ArrayVec<_, 5> = range.by_ref().collect(); } #[should_panic] @@ -292,7 +290,7 @@ fn test_extend_capacity_panic_1() { fn test_extend_capacity_panic_2() { let mut range = 0..10; - let mut array: ArrayVec<_, 5> = range.by_ref().take(5).collect(); + let mut array: ArrayVec<_, 5> = range.by_ref().take(5).collect(); assert_eq!(&array[..], &[0, 1, 2, 3, 4]); assert_eq!(range.next(), Some(5)); array.extend(range.by_ref().take(1)); @@ -300,7 +298,7 @@ fn test_extend_capacity_panic_2() { #[test] fn test_is_send_sync() { - let data = ArrayVec::, 5>::new(); + let data = ArrayVec::, 5>::new(); &data as &dyn Send; &data as &dyn Sync; } @@ -308,24 +306,24 @@ fn test_is_send_sync() { #[test] fn test_compact_size() { // 4 bytes + padding + length - type ByteArray = ArrayVec; + type ByteArray = ArrayVec; println!("{}", mem::size_of::()); assert!(mem::size_of::() <= 2 * mem::size_of::()); // just length - type EmptyArray = ArrayVec; + type EmptyArray = ArrayVec; println!("{}", mem::size_of::()); assert!(mem::size_of::() <= mem::size_of::()); // 3 elements + padding + length - type QuadArray = ArrayVec; + type QuadArray = ArrayVec; println!("{}", mem::size_of::()); assert!(mem::size_of::() <= 4 * 4 + mem::size_of::()); } #[test] fn test_still_works_with_option_arrayvec() { - type RefArray = ArrayVec<&'static i32, 2>; + type RefArray = ArrayVec<&'static i32, 2>; let array = Some(RefArray::new()); assert!(array.is_some()); println!("{:?}", array); @@ -341,7 +339,7 @@ fn test_drain() { v.extend(0..8); v.drain(1..4); assert_eq!(&v[..], &[0, 4, 5, 6, 7]); - let u: ArrayVec<_, 3> = v.drain(1..4).rev().collect(); + let u: ArrayVec<_, 3> = v.drain(1..4).rev().collect(); assert_eq!(&u[..], &[6, 5, 4]); assert_eq!(&v[..], &[0, 7]); v.drain(..); @@ -357,7 +355,7 @@ fn test_drain_range_inclusive() { v.extend(0..8); v.drain(1..=4); assert_eq!(&v[..], &[0, 5, 6, 7]); - let u: ArrayVec<_, 3> = v.drain(1..=2).rev().collect(); + let u: ArrayVec<_, 3> = v.drain(1..=2).rev().collect(); assert_eq!(&u[..], &[6, 5]); assert_eq!(&v[..], &[0, 7]); v.drain(..); @@ -407,7 +405,7 @@ fn test_drop_panic() { } } - let mut array = ArrayVec::::new(); + let mut array = ArrayVec::::new(); array.push(DropPanic); } @@ -422,7 +420,7 @@ fn test_drop_panic_into_iter() { } } - let mut array = ArrayVec::::new(); + let mut array = ArrayVec::::new(); array.push(DropPanic); array.into_iter(); } @@ -432,7 +430,7 @@ fn test_insert() { let mut v = ArrayVec::from([]); assert_matches!(v.try_push(1), Err(_)); - let mut v = ArrayVec::<_, 3>::new(); + let mut v = ArrayVec::<_, 3>::new(); v.insert(0, 0); v.insert(1, 1); //let ret1 = v.try_insert(3, 3); @@ -461,7 +459,7 @@ fn test_into_inner_1() { #[test] fn test_into_inner_2() { - let mut v = ArrayVec::::new(); + let mut v = ArrayVec::::new(); v.push("a".into()); v.push("b".into()); v.push("c".into()); @@ -471,44 +469,44 @@ fn test_into_inner_2() { #[test] fn test_into_inner_3() { - let mut v = ArrayVec::::new(); + let mut v = ArrayVec::::new(); v.extend(1..=4); assert_eq!(v.into_inner().unwrap(), [1, 2, 3, 4]); } #[test] fn test_take() { - let mut v1 = ArrayVec::::new(); + let mut v1 = ArrayVec::::new(); v1.extend(1..=4); let v2 = v1.take(); assert!(v1.into_inner().is_err()); assert_eq!(v2.into_inner().unwrap(), [1, 2, 3, 4]); } -#[cfg(feature="std")] +#[cfg(feature = "std")] #[test] fn test_write() { use std::io::Write; - let mut v = ArrayVec::<_, 8>::new(); + let mut v = ArrayVec::<_, 8>::new(); write!(&mut v, "\x01\x02\x03").unwrap(); assert_eq!(&v[..], &[1, 2, 3]); - let r = v.write(&[9; 16]).unwrap(); + let r = v.write(&[9; 16]); assert_eq!(r, 5); assert_eq!(&v[..], &[1, 2, 3, 9, 9, 9, 9, 9]); } #[test] fn array_clone_from() { - let mut v = ArrayVec::<_, 4>::new(); + let mut v = ArrayVec::<_, 4>::new(); v.push(vec![1, 2]); v.push(vec![3, 4, 5]); v.push(vec![6]); let reference = v.to_vec(); - let mut u = ArrayVec::<_, 4>::new(); + let mut u = ArrayVec::<_, 4>::new(); u.clone_from(&v); assert_eq!(&u, &reference[..]); - let mut t = ArrayVec::<_, 4>::new(); + let mut t = ArrayVec::<_, 4>::new(); t.push(vec![97]); t.push(vec![]); t.push(vec![5, 6, 2]); @@ -520,7 +518,7 @@ fn array_clone_from() { assert_eq!(&t, &reference[..]); } -#[cfg(feature="std")] +#[cfg(feature = "std")] #[test] fn test_string() { use std::error::Error; @@ -557,7 +555,7 @@ fn test_string() { #[test] fn test_string_from() { let text = "hello world"; - // Test `from` constructor + // Test `from` constructor let u = ArrayString::<11>::from(text).unwrap(); assert_eq!(&u, text); assert_eq!(u.len(), text.len()); @@ -604,10 +602,9 @@ fn test_string_push() { assert!(s.try_push('x').is_err()); } - #[test] fn test_insert_at_length() { - let mut v = ArrayVec::<_, 8>::new(); + let mut v = ArrayVec::<_, 8>::new(); let result1 = v.try_insert(0, "a"); let result2 = v.try_insert(1, "b"); assert!(result1.is_ok() && result2.is_ok()); @@ -617,7 +614,7 @@ fn test_insert_at_length() { #[should_panic] #[test] fn test_insert_out_of_bounds() { - let mut v = ArrayVec::<_, 8>::new(); + let mut v = ArrayVec::<_, 8>::new(); let _ = v.try_insert(1, "test"); } @@ -650,7 +647,7 @@ fn test_drop_in_insert() { flag.set(0); { - let mut array = ArrayVec::<_, 2>::new(); + let mut array = ArrayVec::<_, 2>::new(); array.push(Bump(flag)); array.insert(0, Bump(flag)); assert_eq!(flag.get(), 0); @@ -665,7 +662,7 @@ fn test_drop_in_insert() { #[test] fn test_pop_at() { - let mut v = ArrayVec::::new(); + let mut v = ArrayVec::::new(); let s = String::from; v.push(s("a")); v.push(s("b")); @@ -691,7 +688,7 @@ fn test_default() { use std::net; let s: ArrayString<4> = Default::default(); // Something without `Default` implementation. - let v: ArrayVec = Default::default(); + let v: ArrayVec = Default::default(); assert_eq!(s.len(), 0); assert_eq!(v.len(), 0); } @@ -702,14 +699,14 @@ fn test_extend_zst() { #[derive(Copy, Clone, PartialEq, Debug)] struct Z; // Zero sized type - let mut array: ArrayVec<_, 5> = range.by_ref().take(5).map(|_| Z).collect(); + let mut array: ArrayVec<_, 5> = range.by_ref().take(5).map(|_| Z).collect(); assert_eq!(&array[..], &[Z; 5]); assert_eq!(range.next(), Some(5)); array.extend(range.by_ref().take(0).map(|_| Z)); assert_eq!(range.next(), Some(6)); - let mut array: ArrayVec<_, 10> = (0..3).map(|_| Z).collect(); + let mut array: ArrayVec<_, 10> = (0..3).map(|_| Z).collect(); assert_eq!(&array[..], &[Z; 3]); array.extend((3..5).map(|_| Z)); assert_eq!(&array[..], &[Z; 5]); @@ -726,23 +723,23 @@ fn test_try_from_argument() { #[test] fn allow_max_capacity_arrayvec_type() { // this type is allowed to be used (but can't be constructed) - let _v: ArrayVec<(), {usize::MAX}>; + let _v: ArrayVec<(), { usize::MAX }>; } -#[should_panic(expected="largest supported capacity")] +#[should_panic(expected = "largest supported capacity")] #[cfg(not(target_pointer_width = "16"))] #[test] fn deny_max_capacity_arrayvec_value() { // this type is allowed to be used (but can't be constructed) - let _v: ArrayVec<(), {usize::MAX}> = ArrayVec::new(); + let _v: ArrayVec<(), { usize::MAX }> = ArrayVec::new(); } -#[should_panic(expected="index out of bounds")] +#[should_panic(expected = "index out of bounds")] #[cfg(not(target_pointer_width = "16"))] #[test] fn deny_max_capacity_arrayvec_value_const() { // this type is allowed to be used (but can't be constructed) - let _v: ArrayVec<(), {usize::MAX}> = ArrayVec::new_const(); + let _v: ArrayVec<(), { usize::MAX }> = ArrayVec::new_const(); } #[test] @@ -767,7 +764,6 @@ fn test_arraystring_const_constructible() { assert_eq!(var, *"hello"); } - #[test] fn test_arraystring_zero_filled_has_some_sanity_checks() { let string = ArrayString::<4>::zero_filled();