use crate::{bytearray::ByteArray, tinyvec::ArrayVec};
use core::{
convert::{TryFrom, TryInto},
fmt,
hash::{Hash, Hasher},
iter::{DoubleEndedIterator, FromIterator, FusedIterator},
ops::{
self, Add, AddAssign, Bound, Deref, DerefMut, Index, IndexMut,
RangeBounds,
},
ptr,
str::{self, Chars, FromStr, Utf8Error},
};
#[cfg(feature = "alloc")]
use alloc::{borrow::Cow, string::String};
#[derive(Copy, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct ArrayString<A: ByteArray> {
vec: ArrayVec<A>,
}
impl<A: ByteArray> Default for ArrayString<A> {
fn default() -> Self {
ArrayString {
vec: ArrayVec::from_array_len(A::DEFAULT, 0),
}
}
}
impl<A: ByteArray> ArrayString<A> {
#[inline]
pub fn new() -> ArrayString<A> {
Self::default()
}
pub fn from<S>(s: S) -> Self
where
S: fmt::Debug,
Self: TryFrom<S, Error = CapacityOverflowError<S>>,
{
s.try_into().expect("Failed to convert into ArrayString")
}
#[inline]
pub fn from_utf8(
vec: ArrayVec<A>,
) -> Result<ArrayString<A>, FromUtf8Error<A>> {
match str::from_utf8(&vec) {
Ok(..) => Ok(ArrayString { vec }),
Err(error) => Err(FromUtf8Error { vec, error }),
}
}
#[inline]
pub unsafe fn from_utf8_unchecked(vec: ArrayVec<A>) -> ArrayString<A> {
ArrayString { vec }
}
#[inline]
pub fn into_bytes(self) -> ArrayVec<A> {
self.vec
}
#[inline]
pub fn as_str(&self) -> &str {
&*self
}
#[inline]
pub fn as_mut_str(&mut self) -> &mut str {
&mut *self
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&*self.vec
}
#[inline]
pub unsafe fn as_mut_vec(&mut self) -> &mut ArrayVec<A> {
&mut self.vec
}
#[inline]
pub fn capacity(&self) -> usize {
self.vec.capacity()
}
#[inline]
pub fn len(&self) -> usize {
self.vec.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn push_str(&mut self, string: &str) {
self.vec.extend_from_slice(string.as_bytes())
}
#[inline]
pub fn try_push_str<'other>(
&mut self,
string: &'other str,
) -> Result<(), CapacityOverflowError<&'other str>> {
if self.len() + string.len() > self.capacity() {
Err(CapacityOverflowError {
overflow_amount: self.len() + string.len() - self.capacity(),
inner: string,
})
} else {
self.vec.extend_from_slice(string.as_bytes());
Ok(())
}
}
#[inline]
pub fn push(&mut self, ch: char) {
match ch.len_utf8() {
1 => self.vec.push(ch as u8),
_ => self
.vec
.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
}
}
#[inline]
pub fn try_push(
&mut self,
ch: char,
) -> Result<(), CapacityOverflowError<char>> {
if self.len() + ch.len_utf8() > self.capacity() {
Err(CapacityOverflowError {
overflow_amount: self.len() + ch.len_utf8() - self.capacity(),
inner: ch,
})
} else {
match ch.len_utf8() {
1 => self.vec.push(ch as u8),
_ => self
.vec
.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
}
Ok(())
}
}
#[inline]
pub fn truncate(&mut self, new_len: usize) {
if new_len <= self.len() {
assert!(self.is_char_boundary(new_len));
self.vec.truncate(new_len)
}
}
#[inline]
pub fn pop(&mut self) -> Option<char> {
let ch = self.chars().rev().next()?;
let newlen = self.len() - ch.len_utf8();
self.vec.set_len(newlen);
Some(ch)
}
#[inline]
pub fn remove(&mut self, idx: usize) -> char {
let ch = match self[idx..].chars().next() {
Some(ch) => ch,
None => panic!("cannot remove a char from the end of a string"),
};
let next = idx + ch.len_utf8();
let len = self.len();
unsafe {
ptr::copy(
self.vec.as_ptr().add(next),
self.vec.as_mut_ptr().add(idx),
len - next,
);
self.vec.set_len(len - (next - idx));
}
ch
}
#[inline]
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(char) -> bool,
{
let len = self.len();
let mut del_bytes = 0;
let mut idx = 0;
while idx < len {
let ch =
unsafe { self.get_unchecked(idx..len).chars().next().unwrap() };
let ch_len = ch.len_utf8();
if !f(ch) {
del_bytes += ch_len;
} else if del_bytes > 0 {
unsafe {
ptr::copy(
self.vec.as_ptr().add(idx),
self.vec.as_mut_ptr().add(idx - del_bytes),
ch_len,
);
}
}
idx += ch_len;
}
if del_bytes > 0 {
self.vec.set_len(len - del_bytes);
}
}
#[inline]
pub fn insert(&mut self, idx: usize, ch: char) {
assert!(self.is_char_boundary(idx));
let mut bits = [0; 4];
let bits = ch.encode_utf8(&mut bits).as_bytes();
assert!(
self.len() + bits.len() <= self.capacity(),
"ArrayString::insert: capacity overflow"
);
unsafe {
self.insert_bytes(idx, bits);
}
}
#[inline]
pub fn try_insert(
&mut self,
idx: usize,
ch: char,
) -> Result<(), CapacityOverflowError<char>> {
assert!(self.is_char_boundary(idx));
let mut bits = [0; 4];
let bits = ch.encode_utf8(&mut bits).as_bytes();
if self.len() + bits.len() > self.capacity() {
Err(CapacityOverflowError {
overflow_amount: self.len() + bits.len() - self.capacity(),
inner: ch,
})
} else {
unsafe {
self.insert_bytes(idx, bits);
}
Ok(())
}
}
#[inline]
pub fn insert_str(&mut self, idx: usize, string: &str) {
assert!(self.is_char_boundary(idx));
assert!(
self.len() + string.len() <= self.capacity(),
"ArrayString::insert_str: capacity overflow"
);
unsafe {
self.insert_bytes(idx, string.as_bytes());
}
}
#[inline]
pub fn try_insert_str<'other>(
&mut self,
idx: usize,
string: &'other str,
) -> Result<(), CapacityOverflowError<&'other str>> {
assert!(self.is_char_boundary(idx));
if self.len() + string.len() > self.capacity() {
Err(CapacityOverflowError {
overflow_amount: self.len() + string.len() - self.capacity(),
inner: string,
})
} else {
unsafe {
self.insert_bytes(idx, string.as_bytes());
}
Ok(())
}
}
unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
let len = self.len();
let amt = bytes.len();
ptr::copy(
self.vec.as_ptr().add(idx),
self.vec.as_mut_ptr().add(idx + amt),
len - idx,
);
ptr::copy(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
self.vec.set_len(len + amt);
}
#[inline]
pub fn clear(&mut self) {
self.vec.clear()
}
pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
where
R: RangeBounds<usize>,
{
use Bound::*;
let len = self.len();
let start = match range.start_bound() {
Included(&n) => n,
Excluded(&n) => n + 1,
Unbounded => 0,
};
let end = match range.end_bound() {
Included(&n) => n + 1,
Excluded(&n) => n,
Unbounded => len,
};
let self_ptr = self as *mut _;
let chars_iter = self[start..end].chars();
Drain {
start,
end,
iter: chars_iter,
string: self_ptr,
}
}
pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
where
R: RangeBounds<usize>,
{
match range.start_bound() {
Bound::Included(&n) => assert!(self.is_char_boundary(n)),
Bound::Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
Bound::Unbounded => {}
};
match range.end_bound() {
Bound::Included(&n) => assert!(self.is_char_boundary(n + 1)),
Bound::Excluded(&n) => assert!(self.is_char_boundary(n)),
Bound::Unbounded => {}
};
unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes());
}
#[inline]
#[must_use = "use `.truncate()` if you don't need the other half"]
pub fn split_off(&mut self, at: usize) -> ArrayString<A> {
assert!(self.is_char_boundary(at));
let mut other = ArrayVec::from(A::DEFAULT);
let moves = &mut self.vec[at..];
let split_len = moves.len();
let targets = &mut other[..split_len];
moves.swap_with_slice(targets);
other.set_len(split_len);
self.vec.set_len(at);
unsafe { ArrayString::from_utf8_unchecked(other) }
}
}
impl ArrayString<[u8; 4]> {
pub fn from_char_infallible(c: char) -> Self {
let mut arr = [0u8; 4];
let len = c.encode_utf8(&mut arr).len();
unsafe { Self::from_utf8_unchecked(ArrayVec::from_array_len(arr, len)) }
}
}
impl<A: ByteArray> Deref for ArrayString<A> {
type Target = str;
fn deref(&self) -> &str {
unsafe { str::from_utf8_unchecked(&*self.vec) }
}
}
impl<A: ByteArray> DerefMut for ArrayString<A> {
fn deref_mut(&mut self) -> &mut str {
unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
}
}
impl<A: ByteArray> fmt::Display for ArrayString<A> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<A: ByteArray> fmt::Debug for ArrayString<A> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<A: ByteArray> Hash for ArrayString<A> {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
(**self).hash(hasher)
}
}
impl<A: ByteArray + Clone> Clone for ArrayString<A> {
fn clone(&self) -> Self {
ArrayString {
vec: self.vec.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.vec.clone_from(&source.vec);
}
}
impl<A: ByteArray, A2: ByteArray> FromIterator<ArrayString<A2>>
for ArrayString<A>
{
fn from_iter<I: IntoIterator<Item = ArrayString<A2>>>(iter: I) -> Self {
let mut buf = Self::new();
buf.extend(iter);
buf
}
}
macro_rules! impl_from_iterator {
($(#[$meta:meta])* $ty:ty) => {
$(#[$meta])*
#[allow(unused_lifetimes)]
impl<'a, A: ByteArray> FromIterator<$ty>
for ArrayString<A>
{
fn from_iter<I: IntoIterator<Item = $ty>>(iter: I) -> Self {
let mut buf = Self::new();
buf.extend(iter);
buf
}
}
};
}
impl_from_iterator!(
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")] Cow<'a, str>);
impl_from_iterator!(
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
String
);
impl_from_iterator!(&'a str);
impl_from_iterator!(&'a char);
impl_from_iterator!(char);
impl<A: ByteArray> Extend<char> for ArrayString<A> {
fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
let iterator = iter.into_iter();
iterator.for_each(move |c| self.push(c));
}
}
impl<'a, A: ByteArray> Extend<&'a char> for ArrayString<A> {
fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(|&c| c));
}
}
impl<'a, A: ByteArray> Extend<&'a str> for ArrayString<A> {
fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(s));
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
impl<A: ByteArray> Extend<String> for ArrayString<A> {
fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(&s));
}
}
impl<A: ByteArray, A2: ByteArray> Extend<ArrayString<A2>> for ArrayString<A> {
fn extend<I: IntoIterator<Item = ArrayString<A2>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(&s));
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
impl<'a, A: ByteArray> Extend<Cow<'a, str>> for ArrayString<A> {
fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(&s));
}
}
macro_rules! impl_eq {
($(#[$meta:meta])* $lhs:ty, $rhs: ty) => {
$(#[$meta])*
#[allow(unused_lifetimes)]
impl<'a, 'b, A: ByteArray> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
#[inline]
fn ne(&self, other: &$rhs) -> bool {
PartialEq::ne(&self[..], &other[..])
}
}
$(#[$meta])*
#[allow(unused_lifetimes)]
impl<'a, 'b, A: ByteArray> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
#[inline]
fn ne(&self, other: &$lhs) -> bool {
PartialEq::ne(&self[..], &other[..])
}
}
};
}
impl_eq! { ArrayString<A>, str }
impl_eq! { ArrayString<A>, &'a str }
impl_eq! {
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
ArrayString<A>, Cow<'a, str>
}
impl_eq! {
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
ArrayString<A>, String
}
impl<A1, A2> PartialEq<ArrayString<A1>> for ArrayString<A2>
where
A1: ByteArray,
A2: ByteArray,
{
#[inline]
fn eq(&self, other: &ArrayString<A1>) -> bool {
PartialEq::eq(&self[..], &other[..])
}
#[inline]
fn ne(&self, other: &ArrayString<A1>) -> bool {
PartialEq::ne(&self[..], &other[..])
}
}
impl<A: ByteArray> Add<&str> for ArrayString<A> {
type Output = ArrayString<A>;
#[inline]
fn add(mut self, other: &str) -> Self {
self.push_str(other);
self
}
}
impl<A: ByteArray> AddAssign<&str> for ArrayString<A> {
#[inline]
fn add_assign(&mut self, other: &str) {
self.push_str(other);
}
}
impl<A: ByteArray> ops::Index<ops::Range<usize>> for ArrayString<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::Range<usize>) -> &str {
&self[..][index]
}
}
impl<A: ByteArray> ops::Index<ops::RangeTo<usize>> for ArrayString<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeTo<usize>) -> &str {
&self[..][index]
}
}
impl<A: ByteArray> ops::Index<ops::RangeFrom<usize>> for ArrayString<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &str {
&self[..][index]
}
}
impl<A: ByteArray> ops::Index<ops::RangeFull> for ArrayString<A> {
type Output = str;
#[inline]
fn index(&self, _index: ops::RangeFull) -> &str {
unsafe { str::from_utf8_unchecked(&self.vec) }
}
}
impl<A: ByteArray> ops::Index<ops::RangeInclusive<usize>> for ArrayString<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
Index::index(&**self, index)
}
}
impl<A: ByteArray> ops::Index<ops::RangeToInclusive<usize>> for ArrayString<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
Index::index(&**self, index)
}
}
impl<A: ByteArray> ops::IndexMut<ops::Range<usize>> for ArrayString<A> {
#[inline]
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
&mut self[..][index]
}
}
impl<A: ByteArray> ops::IndexMut<ops::RangeTo<usize>> for ArrayString<A> {
#[inline]
fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
&mut self[..][index]
}
}
impl<A: ByteArray> ops::IndexMut<ops::RangeFrom<usize>> for ArrayString<A> {
#[inline]
fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
&mut self[..][index]
}
}
impl<A: ByteArray> ops::IndexMut<ops::RangeFull> for ArrayString<A> {
#[inline]
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
}
}
impl<A: ByteArray> ops::IndexMut<ops::RangeInclusive<usize>>
for ArrayString<A>
{
#[inline]
fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
IndexMut::index_mut(&mut **self, index)
}
}
impl<A: ByteArray> ops::IndexMut<ops::RangeToInclusive<usize>>
for ArrayString<A>
{
#[inline]
fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
IndexMut::index_mut(&mut **self, index)
}
}
impl<A: ByteArray> AsRef<str> for ArrayString<A> {
#[inline]
fn as_ref(&self) -> &str {
&*self
}
}
impl<A: ByteArray> AsMut<str> for ArrayString<A> {
#[inline]
fn as_mut(&mut self) -> &mut str {
&mut *self
}
}
impl<A: ByteArray> AsRef<[u8]> for ArrayString<A> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CapacityOverflowError<S> {
overflow_amount: usize,
inner: S,
}
impl<S> CapacityOverflowError<S> {
pub fn overflow_amount(&self) -> usize {
self.overflow_amount
}
pub fn into_inner(self) -> S {
self.inner
}
}
impl<S: fmt::Display> fmt::Display for CapacityOverflowError<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
r#"Failed to convert "{}" to an ArrayString: capacity overflowed by {} bytes"#,
self.inner, self.overflow_amount
)
}
}
impl<'a, A: ByteArray> TryFrom<&'a str> for ArrayString<A> {
type Error = CapacityOverflowError<&'a str>;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
let mut arr = A::DEFAULT;
let slice = arr.as_slice_mut();
if s.len() <= slice.len() {
slice[..s.len()].copy_from_slice(s.as_bytes());
unsafe {
Ok(Self::from_utf8_unchecked(ArrayVec::from_array_len(
arr,
s.len(),
)))
}
} else {
Err(CapacityOverflowError {
overflow_amount: s.len() - slice.len(),
inner: s,
})
}
}
}
impl<'a, A: ByteArray> TryFrom<&'a mut str> for ArrayString<A> {
type Error = CapacityOverflowError<&'a mut str>;
fn try_from(s: &'a mut str) -> Result<Self, Self::Error> {
match Self::try_from(&*s) {
Ok(s) => Ok(s),
Err(e) => Err(CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: s,
}),
}
}
}
impl<'c, A: ByteArray> TryFrom<&'c char> for ArrayString<A> {
type Error = CapacityOverflowError<&'c char>;
fn try_from(c: &'c char) -> Result<Self, Self::Error> {
let mut buf = [0u8; 4];
let s = c.encode_utf8(&mut buf);
Self::try_from(&*s).map_err(|e| CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: c,
})
}
}
impl<A: ByteArray> TryFrom<char> for ArrayString<A> {
type Error = CapacityOverflowError<char>;
fn try_from(c: char) -> Result<Self, Self::Error> {
let mut buf = [0u8; 4];
let s = c.encode_utf8(&mut buf);
Self::try_from(&*s).map_err(|e| CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: c,
})
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
impl<'a, A: ByteArray> TryFrom<&'a String> for ArrayString<A> {
type Error = CapacityOverflowError<&'a String>;
fn try_from(s: &'a String) -> Result<Self, Self::Error> {
Self::try_from(s.as_str()).map_err(|e| CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: s,
})
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
impl<A: ByteArray> TryFrom<String> for ArrayString<A> {
type Error = CapacityOverflowError<String>;
fn try_from(s: String) -> Result<Self, Self::Error> {
match Self::try_from(&*s) {
Ok(s) => Ok(s),
Err(e) => Err(CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: s,
}),
}
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "alloc")))]
#[cfg(feature = "alloc")]
impl<'a, A: ByteArray> TryFrom<Cow<'a, str>> for ArrayString<A> {
type Error = CapacityOverflowError<Cow<'a, str>>;
fn try_from(s: Cow<'a, str>) -> Result<Self, Self::Error> {
match Self::try_from(&*s) {
Ok(s) => Ok(s),
Err(e) => Err(CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: s,
}),
}
}
}
impl<A: ByteArray> FromStr for ArrayString<A> {
type Err = CapacityOverflowError<()>;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s).map_err(|e| CapacityOverflowError {
overflow_amount: e.overflow_amount,
inner: (),
})
}
}
impl<A: ByteArray> fmt::Write for ArrayString<A> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.try_push_str(s).map_err(|_| fmt::Error::default())
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.try_push(c).map_err(|_| fmt::Error::default())
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "serde")))]
#[cfg(feature = "serde")]
impl<A: ByteArray> serde::Serialize for ArrayString<A> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "serde")))]
#[cfg(feature = "serde")]
impl<'de, A: ByteArray> serde::Deserialize<'de> for ArrayString<A> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use core::marker::PhantomData;
struct ArrayStringVisitor<A>(PhantomData<fn() -> A>);
impl<'de, A: ByteArray> serde::de::Visitor<'de> for ArrayStringVisitor<A> {
type Value = ArrayString<A>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a string up to length {}", A::CAPACITY)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
ArrayString::try_from(v)
.map_err(|_| E::invalid_length(v.len(), &self))
}
}
deserializer.deserialize_str(ArrayStringVisitor(PhantomData))
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FromUtf8Error<A: ByteArray> {
pub(crate) vec: ArrayVec<A>,
pub(crate) error: Utf8Error,
}
impl<A: ByteArray> FromUtf8Error<A> {
pub fn as_bytes(&self) -> &[u8] {
&self.vec[..]
}
pub fn into_bytes(self) -> ArrayVec<A> {
self.vec
}
pub fn utf8_error(&self) -> Utf8Error {
self.error
}
}
impl<A: ByteArray> fmt::Debug for FromUtf8Error<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FromUtf8Error")
.field("vec", &self.vec)
.field("error", &self.error)
.finish()
}
}
impl<A: ByteArray> fmt::Display for FromUtf8Error<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
#[cfg_attr(docs_rs, doc(cfg(target_feature = "std")))]
#[cfg(feature = "std")]
impl<A: ByteArray> std::error::Error for FromUtf8Error<A> {}
pub struct Drain<'a, A: ByteArray> {
string: *mut ArrayString<A>,
start: usize,
end: usize,
iter: Chars<'a>,
}
impl<A: ByteArray> fmt::Debug for Drain<'_, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Drain { .. }")
}
}
unsafe impl<A: ByteArray> Send for Drain<'_, A> {}
unsafe impl<A: ByteArray> Sync for Drain<'_, A> {}
impl<A: ByteArray> Drop for Drain<'_, A> {
fn drop(&mut self) {
unsafe {
let self_vec = (*self.string).as_mut_vec();
if self.start <= self.end && self.end <= self_vec.len() {
self_vec.drain(self.start..self.end);
}
}
}
}
impl<A: ByteArray> Iterator for Drain<'_, A> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[inline]
fn last(mut self) -> Option<char> {
self.next_back()
}
}
impl<A: ByteArray> DoubleEndedIterator for Drain<'_, A> {
#[inline]
fn next_back(&mut self) -> Option<char> {
self.iter.next_back()
}
}
impl<A: ByteArray> FusedIterator for Drain<'_, A> {}