Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ version = "1.2.0"
optional = true
default-features = false

[dependencies.diesel]
version = "2.3.4"
optional = true
default-features = false

[dependencies.serde]
version = "1.0"
optional = true
Expand Down
108 changes: 84 additions & 24 deletions src/array_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,7 @@ impl<const CAP: usize> ArrayString<CAP>
/// assert_eq!(s.pop(), None);
/// ```
pub fn pop(&mut self) -> Option<char> {
let ch = match self.chars().rev().next() {
Some(ch) => ch,
None => return None,
};
let ch = self.chars().next_back()?;
let new_len = self.len() - ch.len_utf8();
unsafe {
self.set_len(new_len);
Expand Down Expand Up @@ -396,6 +393,7 @@ impl<const CAP: usize> ArrayString<CAP>

/// Set the strings’s length.
///
/// # Safety
/// This function is `unsafe` because it changes the notion of the
/// number of “valid” bytes in the string. Use with care.
///
Expand All @@ -408,21 +406,25 @@ impl<const CAP: usize> ArrayString<CAP>
}

/// Return a string slice of the whole `ArrayString`.
#[inline]
pub fn as_str(&self) -> &str {
self
}

/// Return a mutable string slice of the whole `ArrayString`.
#[inline]
pub fn as_mut_str(&mut self) -> &mut str {
self
}

/// Return a raw pointer to the string's buffer.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.xs.as_ptr() as *const u8
}

/// Return a raw mutable pointer to the string's buffer.
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut u8 {
self.xs.as_mut_ptr() as *mut u8
}
Expand Down Expand Up @@ -473,6 +475,20 @@ impl<const CAP: usize> PartialEq<ArrayString<CAP>> for str
}
}

impl<const CAP: usize> PartialEq<&str> for ArrayString<CAP>
{
fn eq(&self, rhs: &&str) -> bool {
self == *rhs
}
}

impl<const CAP: usize> PartialEq<ArrayString<CAP>> for &str
{
fn eq(&self, rhs: &ArrayString<CAP>) -> bool {
*self == rhs
}
}

impl<const CAP: usize> Eq for ArrayString<CAP>
{ }

Expand Down Expand Up @@ -527,6 +543,7 @@ impl<const CAP: usize> fmt::Write for ArrayString<CAP>
}
}

#[expect(clippy::non_canonical_clone_impl)]
impl<const CAP: usize> Clone for ArrayString<CAP>
{
fn clone(&self) -> ArrayString<CAP> {
Expand All @@ -542,40 +559,42 @@ impl<const CAP: usize> Clone for ArrayString<CAP>
impl<const CAP: usize> PartialOrd for ArrayString<CAP>
{
fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
(**self).partial_cmp(&**rhs)
Some(self.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 }
}

impl<const CAP: usize> PartialOrd<str> for ArrayString<CAP>
{
fn partial_cmp(&self, rhs: &str) -> Option<cmp::Ordering> {
(**self).partial_cmp(rhs)
self.as_str().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 }
}

impl<const CAP: usize> PartialOrd<ArrayString<CAP>> for str
{
fn partial_cmp(&self, rhs: &ArrayString<CAP>) -> Option<cmp::Ordering> {
self.partial_cmp(&**rhs)
self.partial_cmp(rhs.as_str())
}
}

impl<const CAP: usize> PartialOrd<&str> for ArrayString<CAP>
{
fn partial_cmp(&self, rhs: &&str) -> Option<cmp::Ordering> {
self.as_str().partial_cmp(*rhs)
}
}

impl<const CAP: usize> PartialOrd<ArrayString<CAP>> for &str
{
fn partial_cmp(&self, rhs: &ArrayString<CAP>) -> Option<cmp::Ordering> {
(*self).partial_cmp(rhs.as_str())
}
fn lt(&self, rhs: &ArrayString<CAP>) -> bool { self < &**rhs }
fn le(&self, rhs: &ArrayString<CAP>) -> bool { self <= &**rhs }
fn gt(&self, rhs: &ArrayString<CAP>) -> bool { self > &**rhs }
fn ge(&self, rhs: &ArrayString<CAP>) -> bool { self >= &**rhs }
}

impl<const CAP: usize> Ord for ArrayString<CAP>
{
fn cmp(&self, rhs: &Self) -> cmp::Ordering {
(**self).cmp(&**rhs)
self.as_str().cmp(rhs.as_str())
}
}

Expand All @@ -595,7 +614,7 @@ impl<const CAP: usize> Serialize for ArrayString<CAP>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&*self)
serializer.serialize_str(self)
}
}

Expand Down Expand Up @@ -641,7 +660,7 @@ impl<'de, const CAP: usize> Deserialize<'de> for ArrayString<CAP>
/// Requires crate feature `"borsh"`
impl<const CAP: usize> borsh::BorshSerialize for ArrayString<CAP> {
fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
<str as borsh::BorshSerialize>::serialize(&*self, writer)
<str as borsh::BorshSerialize>::serialize(self, writer)
}
}

Expand All @@ -661,7 +680,7 @@ impl<const CAP: usize> borsh::BorshDeserialize for ArrayString<CAP> {
let buf = &mut buf[..len];
reader.read_exact(buf)?;

let s = str::from_utf8(&buf).map_err(|err| {
let s = str::from_utf8(buf).map_err(|err| {
borsh::io::Error::new(borsh::io::ErrorKind::InvalidData, err.to_string())
})?;
Ok(Self::from(s).unwrap())
Expand All @@ -686,7 +705,7 @@ impl<'a, const CAP: usize> TryFrom<fmt::Arguments<'a>> for ArrayString<CAP>
fn try_from(f: fmt::Arguments<'a>) -> Result<Self, Self::Error> {
use fmt::Write;
let mut v = Self::new();
v.write_fmt(f).map_err(|e| CapacityError::new(e))?;
v.write_fmt(f).map_err(CapacityError::new)?;
Ok(v)
}
}
Expand Down Expand Up @@ -714,3 +733,44 @@ impl<const CAP: usize> zeroize::Zeroize for ArrayString<CAP> {
self.xs.zeroize();
}
}

#[cfg(feature = "diesel")]
mod diesel {
use diesel::backend::Backend;
use diesel::deserialize;
use diesel::deserialize::FromSql;
use diesel::sql_types::Text;
use diesel::serialize;
use diesel::serialize::{Output, ToSql};

use super::ArrayString;

/// Requires crate feature `"diesel"`
impl<ST, DB, const CAP: usize> FromSql<ST, DB> for ArrayString<CAP>
where
DB: Backend,
*const str: FromSql<ST, DB>
{
#[inline]
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
use std::convert::TryInto as _;

let str_ptr = <*const str as FromSql<ST, DB>>::from_sql(bytes)?;
// Diesel guarantees the pointer impl will be non-null and pointing to valid UTF-8
let string = unsafe { &*str_ptr };
Ok(string.try_into()?)
}
}

/// Requires crate feature `"diesel"`
impl<ST, DB, const CAP: usize> ToSql<ST, DB> for ArrayString<CAP>
where
DB: Backend,
str: ToSql<Text, DB>
{
#[inline]
fn to_sql<'a>(&'a self, out: &mut Output<'a, '_, DB>) -> serialize::Result {
self.as_str().to_sql(out)
}
}
}
19 changes: 10 additions & 9 deletions src/arrayvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {

/// Push `element` to the end of the vector without checking the capacity.
///
/// # Safety
/// It is up to the caller to ensure the capacity of the vector is
/// sufficiently large.
///
Expand Down Expand Up @@ -572,6 +573,7 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {

/// Set the vector’s length without dropping or moving out elements
///
/// # Safety
/// This method is `unsafe` because it changes the notion of the
/// number of “valid” elements in the vector. Use with care.
///
Expand Down Expand Up @@ -637,7 +639,7 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
/// assert_eq!(&v1[..], &[3]);
/// assert_eq!(&v2[..], &[1, 2]);
/// ```
pub fn drain<R>(&mut self, range: R) -> Drain<T, CAP>
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, CAP>
where R: RangeBounds<usize>
{
// Memory safety
Expand All @@ -664,7 +666,7 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
self.drain_range(start, end)
}

fn drain_range(&mut self, start: usize, end: usize) -> Drain<T, CAP>
fn drain_range(&mut self, start: usize, end: usize) -> Drain<'_, T, CAP>
{
let len = self.len();

Expand Down Expand Up @@ -699,13 +701,12 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {

/// Return the inner fixed size array.
///
/// Safety:
/// # Safety
/// This operation is safe if and only if length equals capacity.
pub unsafe fn into_inner_unchecked(self) -> [T; CAP] {
debug_assert_eq!(self.len(), self.capacity());
let self_ = ManuallyDrop::new(self);
let array = ptr::read(self_.as_ptr() as *const [T; CAP]);
array
ptr::read(self_.as_ptr() as *const [T; CAP])
}

/// Returns the ArrayVec, replacing the original with a new empty ArrayVec.
Expand All @@ -718,7 +719,7 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
/// assert!(v.is_empty());
/// ```
pub fn take(&mut self) -> Self {
mem::replace(self, Self::new())
mem::take(self)
}

/// Return a slice containing all elements of the vector.
Expand Down Expand Up @@ -1048,7 +1049,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() { }
for _ in self.by_ref() {}

if self.tail_len > 0 {
unsafe {
Expand Down Expand Up @@ -1335,7 +1336,7 @@ impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec<T
let mut values = ArrayVec::<T, CAP>::new();

while let Some(value) = seq.next_element()? {
if let Err(_) = values.try_push(value) {
if values.try_push(value).is_err() {
return Err(SA::Error::invalid_length(CAP + 1, &self));
}
}
Expand Down Expand Up @@ -1370,7 +1371,7 @@ where
let len = <u32 as borsh::BorshDeserialize>::deserialize_reader(reader)?;
for _ in 0..len {
let elem = <T as borsh::BorshDeserialize>::deserialize_reader(reader)?;
if let Err(_) = values.try_push(elem) {
if values.try_push(elem).is_err() {
return Err(borsh::io::Error::new(
borsh::io::ErrorKind::InvalidData,
format!("Expected an array with no more than {} items", CAP),
Expand Down
6 changes: 3 additions & 3 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl<T> CapacityError<T> {
/// Create a new `CapacityError` from `element`.
pub const fn new(element: T) -> CapacityError<T> {
CapacityError {
element: element,
element,
}
}

Expand All @@ -29,7 +29,7 @@ impl<T> CapacityError<T> {
}
}

const CAPERROR: &'static str = "insufficient capacity";
const CAPERROR: &str = "insufficient capacity";

#[cfg(feature="std")]
/// Requires `features="std"`.
Expand All @@ -43,7 +43,7 @@ impl<T> fmt::Display for CapacityError<T> {

impl<T> fmt::Debug for CapacityError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", "CapacityError", CAPERROR)
write!(f, "CapacityError: {}", CAPERROR)
}
}

19 changes: 18 additions & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,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());
Expand Down Expand Up @@ -774,3 +774,20 @@ fn test_arraystring_zero_filled_has_some_sanity_checks() {
assert_eq!(string.as_str(), "\0\0\0\0");
assert_eq!(string.len(), 4);
}

#[test]
fn test_arraystring_ord() {
let a_arraystring: ArrayString<1> = ArrayString::from("a").unwrap();
let b_arraystring: ArrayString<1> = ArrayString::from("b").unwrap();

let a_str = "a";
let b_str = "b";

assert!(a_arraystring < b_arraystring);
assert!(b_arraystring > a_arraystring);
assert!(a_arraystring < b_str);
assert!(a_str < b_arraystring);
assert!(b_arraystring > a_str);
assert!(b_str > a_arraystring);
}

Loading