use crate::{
alloc::{AllocRef, Global},
boxed::Box,
capacity_overflow,
collections::TryReserveError::{self, AllocError, CapacityOverflow},
iter::TryExtend,
str::from_boxed_utf8_unchecked,
vec::Vec,
};
use core::{
char::{decode_utf16, REPLACEMENT_CHARACTER},
fmt,
hash,
iter::{FromIterator, FusedIterator},
ops::{
self,
Add,
AddAssign,
Bound::{Excluded, Included, Unbounded},
Index,
IndexMut,
RangeBounds,
},
ptr,
str::{self, lossy, Chars, FromStr, Utf8Error},
};
#[cfg(feature = "std")]
use std::borrow::Cow;
use crate::{alloc::handle_alloc_error, clone::CloneIn};
pub use liballoc::string::{ParseError, ToString};
#[derive(PartialOrd, Eq, Ord)]
pub struct String<A: AllocRef = Global> {
vec: Vec<u8, A>,
}
#[derive(Debug)]
pub struct FromUtf8Error<A: AllocRef = Global> {
bytes: Vec<u8, A>,
error: Utf8Error,
}
#[derive(Debug)]
pub struct FromUtf16Error(());
impl String {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { vec: Vec::new() }
}
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self::with_capacity_in(capacity, Global)
}
pub fn from_utf16(v: &[u16]) -> Result<Self, FromUtf16Error> {
Self::from_utf16_in(v, Global)
}
#[inline]
#[must_use]
pub fn from_utf16_lossy(v: &[u16]) -> Self {
decode_utf16(v.iter().cloned())
.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
.collect()
}
#[inline]
pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> Self {
Self::from_raw_parts_in(buf, length, capacity, Global)
}
}
impl<A: AllocRef> String<A> {
#[inline]
pub fn new_in(a: A) -> Self {
Self {
vec: Vec::new_in(a),
}
}
#[inline]
pub fn with_capacity_in(capacity: usize, a: A) -> Self
where
A: AllocRef,
{
Self {
vec: Vec::with_capacity_in(capacity, a),
}
}
#[inline]
pub fn try_with_capacity_in(capacity: usize, a: A) -> Result<Self, TryReserveError>
where
A: AllocRef,
{
Ok(Self {
vec: Vec::try_with_capacity_in(capacity, a)?,
})
}
#[inline]
pub fn from_str_in(s: &str, a: A) -> Self {
let mut v = Self::with_capacity_in(s.len(), a);
v.push_str(s);
v
}
#[inline]
pub fn try_from_str_in(s: &str, a: A) -> Result<Self, TryReserveError> {
let mut v = Self::try_with_capacity_in(s.len(), a)?;
v.try_push_str(s)?;
Ok(v)
}
#[inline]
pub fn from_utf8(vec: Vec<u8, A>) -> Result<Self, FromUtf8Error<A>> {
match str::from_utf8(&vec) {
Ok(..) => Ok(Self { vec }),
Err(e) => Err(FromUtf8Error {
bytes: vec,
error: e,
}),
}
}
pub fn from_utf8_lossy_in(v: &[u8], a: A) -> Self {
match Self::try_from_utf8_lossy_in(v, a) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(string) => string,
}
}
pub fn try_from_utf8_lossy_in(v: &[u8], a: A) -> Result<Self, TryReserveError> {
const REPLACEMENT: &str = "\u{FFFD}";
let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
let lossy::Utf8LossyChunk { valid, broken } = chunk;
if valid.len() == v.len() {
debug_assert!(broken.is_empty());
return Self::try_from_str_in(valid, a);
}
(valid, broken)
} else {
return Ok(Self::new_in(a));
};
let mut res = Self::try_with_capacity_in(v.len(), a)?;
res.try_push_str(first_valid)?;
if !first_broken.is_empty() {
res.try_push_str(REPLACEMENT)?;
}
for lossy::Utf8LossyChunk { valid, broken } in iter {
res.try_push_str(valid)?;
if !broken.is_empty() {
res.try_push_str(REPLACEMENT)?;
}
}
Ok(res)
}
pub fn from_utf16_in(v: &[u16], a: A) -> Result<Self, FromUtf16Error> {
let mut ret = Self::with_capacity_in(v.len(), a);
for c in decode_utf16(v.iter().cloned()) {
if let Ok(c) = c {
ret.push(c);
} else {
return Err(FromUtf16Error(()));
}
}
Ok(ret)
}
pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
self.vec.into_raw_parts()
}
#[inline]
pub unsafe fn from_raw_parts_in(
buf: *mut u8,
length: usize,
capacity: usize,
alloc: A,
) -> Self {
Self {
vec: Vec::from_raw_parts_in(buf, length, capacity, alloc),
}
}
#[inline]
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8, A>) -> Self {
Self { vec: bytes }
}
#[inline]
pub fn into_bytes(self) -> Vec<u8, A> {
self.vec
}
#[inline]
pub fn as_str(&self) -> &str {
self
}
#[inline]
pub fn as_mut_str(&mut self) -> &mut str {
self
}
#[inline]
pub fn push_str(&mut self, string: &str) {
self.vec.extend_from_slice(string.as_bytes())
}
#[inline]
pub fn try_push_str(&mut self, string: &str) -> Result<(), TryReserveError> {
self.vec.try_extend_from_slice(string.as_bytes())
}
#[inline]
pub fn capacity(&self) -> usize {
self.vec.capacity()
}
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.vec.reserve(additional)
}
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.vec.reserve_exact(additional)
}
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.vec.try_reserve(additional)
}
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.vec.try_reserve_exact(additional)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.vec.shrink_to_fit()
}
#[inline]
pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError> {
self.vec.try_shrink_to_fit()
}
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.vec.shrink_to(min_capacity)
}
#[inline]
pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), TryReserveError> {
self.vec.try_shrink_to(min_capacity)
}
#[inline]
pub fn push(&mut self, ch: char) {
match self.try_push(ch) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { }
}
}
#[inline]
pub fn try_push(&mut self, ch: char) -> Result<(), TryReserveError> {
match ch.len_utf8() {
1 => self.vec.try_push(ch as u8),
_ => self
.vec
.try_extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
}
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.vec
}
#[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();
unsafe {
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 {
unsafe {
self.vec.set_len(len - del_bytes);
}
}
}
#[inline]
pub fn insert(&mut self, idx: usize, ch: char) {
match self.try_insert(idx, ch) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { }
}
}
#[inline]
pub fn try_insert(&mut self, idx: usize, ch: char) -> Result<(), TryReserveError> {
assert!(self.is_char_boundary(idx));
let mut bits = [0; 4];
let bits = ch.encode_utf8(&mut bits).as_bytes();
unsafe { self.try_insert_bytes(idx, bits) }
}
unsafe fn try_insert_bytes(&mut self, idx: usize, bytes: &[u8]) -> Result<(), TryReserveError> {
let len = self.len();
let amt = bytes.len();
self.vec.try_reserve(amt)?;
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);
Ok(())
}
#[inline]
pub fn insert_str(&mut self, idx: usize, string: &str) {
match self.try_insert_str(idx, string) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { }
}
}
#[inline]
pub fn try_insert_str(&mut self, idx: usize, string: &str) -> Result<(), TryReserveError> {
assert!(self.is_char_boundary(idx));
unsafe { self.try_insert_bytes(idx, string.as_bytes()) }
}
#[inline]
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, A> {
&mut self.vec
}
#[inline]
pub fn len(&self) -> usize {
self.vec.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn split_off(&mut self, at: usize) -> Self
where
A: AllocRef + Clone,
{
match self.try_split_off(at) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(split) => split,
}
}
#[inline]
pub fn try_split_off(&mut self, at: usize) -> Result<Self, TryReserveError>
where
A: AllocRef + Clone,
{
assert!(self.is_char_boundary(at));
let other = self.vec.try_split_off(at)?;
unsafe { Ok(Self::from_utf8_unchecked(other)) }
}
#[inline]
pub fn clear(&mut self) {
self.vec.clear()
}
pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
where
R: RangeBounds<usize>,
{
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: *mut Self = self;
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() {
Included(&n) => assert!(self.is_char_boundary(n)),
Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
Unbounded => {}
};
match range.end_bound() {
Included(&n) => assert!(self.is_char_boundary(n + 1)),
Excluded(&n) => assert!(self.is_char_boundary(n)),
Unbounded => {}
};
unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes());
}
#[inline]
pub fn into_boxed_str(self) -> Box<str, A> {
let slice = self.vec.into_boxed_slice();
unsafe { from_boxed_utf8_unchecked(slice) }
}
#[inline]
pub fn try_into_boxed_str(self) -> Result<Box<str, A>, TryReserveError> {
let slice = self.vec.try_into_boxed_slice()?;
unsafe { Ok(from_boxed_utf8_unchecked(slice)) }
}
}
impl<A: AllocRef> FromUtf8Error<A> {
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..]
}
pub fn into_bytes(self) -> Vec<u8, A> {
self.bytes
}
pub fn utf8_error(&self) -> Utf8Error {
self.error
}
}
impl<A: AllocRef> fmt::Display for FromUtf8Error<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
impl fmt::Display for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
}
}
impl<A> Clone for String<A>
where
A: AllocRef + Clone,
{
#[inline]
#[must_use = "Cloning is expected to be expensive"]
fn clone(&self) -> Self {
Self {
vec: self.vec.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.vec.clone_from(&source.vec);
}
}
#[allow(clippy::use_self)]
impl<A: AllocRef, B: AllocRef> CloneIn<B> for String<A> {
type Cloned = String<B>;
#[inline]
#[must_use = "Cloning is expected to be expensive"]
fn clone_in(&self, a: B) -> Self::Cloned {
String {
vec: self.vec.clone_in(a),
}
}
#[inline]
fn try_clone_in(&self, a: B) -> Result<Self::Cloned, TryReserveError> {
Ok(String {
vec: self.vec.try_clone_in(a)?,
})
}
}
impl FromIterator<char> for String {
fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
let mut buf = Self::new();
buf.extend(iter);
buf
}
}
impl<'a> FromIterator<&'a char> for String {
fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> Self {
let mut buf = Self::new();
buf.extend(iter);
buf
}
}
impl<'a> FromIterator<&'a str> for String {
fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
let mut buf = Self::new();
buf.extend(iter);
buf
}
}
impl FromIterator<String> for String {
fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
let mut iterator = iter.into_iter();
match iterator.next() {
None => Self::new(),
Some(mut buf) => {
buf.extend(iterator);
buf
}
}
}
}
#[cfg(feature = "std")]
impl<'a> FromIterator<Cow<'a, str>> for String {
fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> Self {
let mut iterator = iter.into_iter();
match iterator.next() {
None => Self::new(),
Some(cow) => {
let mut buf = Self::from(&cow[..]);
buf.extend(iterator);
buf
}
}
}
}
impl<A: AllocRef> Extend<char> for String<A> {
fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
let iterator = iter.into_iter();
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
iterator.for_each(move |c| self.push(c));
}
}
impl<A: AllocRef> TryExtend<char> for String<A> {
type Err = TryReserveError;
fn try_extend<I: IntoIterator<Item = char>>(&mut self, iter: I) -> Result<(), Self::Err> {
let mut iterator = iter.into_iter();
let (lower_bound, _) = iterator.size_hint();
self.try_reserve(lower_bound)?;
iterator.try_for_each(move |c| self.try_push(c))?;
Ok(())
}
}
impl<'a, A: AllocRef> Extend<&'a char> for String<A> {
fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}
impl<'a, A: AllocRef> TryExtend<&'a char> for String<A> {
type Err = TryReserveError;
fn try_extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) -> Result<(), Self::Err> {
self.try_extend(iter.into_iter().cloned())
}
}
impl<'a, A: AllocRef> Extend<&'a str> for String<A> {
fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(s));
}
}
impl<'a, A: AllocRef> TryExtend<&'a str> for String<A> {
type Err = TryReserveError;
fn try_extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) -> Result<(), Self::Err> {
iter.into_iter().try_for_each(move |s| self.try_push_str(s))
}
}
impl<A, B> Extend<String<B>> for String<A>
where
A: AllocRef,
B: AllocRef,
{
fn extend<I: IntoIterator<Item = String<B>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(&s));
}
}
impl<A: AllocRef, B: AllocRef> TryExtend<String<B>> for String<A> {
type Err = TryReserveError;
fn try_extend<I: IntoIterator<Item = String<B>>>(&mut self, iter: I) -> Result<(), Self::Err> {
iter.into_iter()
.try_for_each(move |s| self.try_push_str(&s))
}
}
#[cfg(feature = "std")]
impl<'a, A> Extend<Cow<'a, str>> for String<A>
where
A: AllocRef,
{
fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_str(&s));
}
}
#[cfg(feature = "std")]
impl<'a, A: AllocRef> TryExtend<Cow<'a, str>> for String<A> {
type Err = TryReserveError;
fn try_extend<I: IntoIterator<Item = Cow<'a, str>>>(
&mut self,
iter: I,
) -> Result<(), Self::Err> {
iter.into_iter()
.try_for_each(move |s| self.try_push_str(&s))
}
}
impl<A: AllocRef, B: AllocRef> PartialEq<String<B>> for String<A> {
#[inline]
fn eq(&self, other: &String<B>) -> bool {
PartialEq::eq(&self[..], &other[..])
}
}
macro_rules! impl_eq {
($lhs:ty, $rhs:ty) => {
#[allow(unused_lifetimes)]
impl<A: AllocRef> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
}
#[allow(unused_lifetimes)]
#[allow(clippy::use_self)]
impl<A: AllocRef> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
}
};
}
impl_eq! { String<A>, str }
impl_eq! { String<A>, &'_ str }
#[cfg(feature = "std")]
mod borrow {
use super::String;
use crate::alloc::AllocRef;
use std::borrow::Cow;
impl_eq! { Cow<'_, str>, String<A> }
impl_eq! { String<A>, std::string::String }
}
impl Default for String {
#[inline]
#[must_use]
fn default() -> Self {
Self::new()
}
}
impl<A: AllocRef> fmt::Display for String<A> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<A: AllocRef> fmt::Debug for String<A> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<A: AllocRef> hash::Hash for String<A> {
#[inline]
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
(**self).hash(hasher)
}
}
impl<A> Add<&str> for String<A>
where
A: AllocRef,
{
type Output = Self;
#[inline]
fn add(mut self, other: &str) -> Self {
self.push_str(other);
self
}
}
impl<A> AddAssign<&str> for String<A>
where
A: AllocRef,
{
#[inline]
fn add_assign(&mut self, other: &str) {
self.push_str(other);
}
}
impl<A: AllocRef> Index<ops::Range<usize>> for String<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::Range<usize>) -> &str {
&self[..][index]
}
}
impl<A: AllocRef> Index<ops::RangeTo<usize>> for String<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeTo<usize>) -> &str {
&self[..][index]
}
}
impl<A: AllocRef> Index<ops::RangeFrom<usize>> for String<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &str {
&self[..][index]
}
}
impl<A: AllocRef> Index<ops::RangeFull> for String<A> {
type Output = str;
#[inline]
fn index(&self, _index: ops::RangeFull) -> &str {
unsafe { str::from_utf8_unchecked(&self.vec) }
}
}
impl<A: AllocRef> Index<ops::RangeInclusive<usize>> for String<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
Index::index(&**self, index)
}
}
impl<A: AllocRef> Index<ops::RangeToInclusive<usize>> for String<A> {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
Index::index(&**self, index)
}
}
impl<A: AllocRef> IndexMut<ops::Range<usize>> for String<A> {
#[inline]
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
&mut self[..][index]
}
}
impl<A: AllocRef> IndexMut<ops::RangeTo<usize>> for String<A> {
#[inline]
fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
&mut self[..][index]
}
}
impl<A: AllocRef> IndexMut<ops::RangeFrom<usize>> for String<A> {
#[inline]
fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
&mut self[..][index]
}
}
impl<A: AllocRef> IndexMut<ops::RangeFull> for String<A> {
#[inline]
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
}
}
impl<A: AllocRef> IndexMut<ops::RangeInclusive<usize>> for String<A> {
#[inline]
fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
IndexMut::index_mut(&mut **self, index)
}
}
impl<A: AllocRef> IndexMut<ops::RangeToInclusive<usize>> for String<A> {
#[inline]
fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
IndexMut::index_mut(&mut **self, index)
}
}
impl<A: AllocRef> ops::Deref for String<A> {
type Target = str;
#[inline]
fn deref(&self) -> &str {
unsafe { str::from_utf8_unchecked(&self.vec) }
}
}
impl<A: AllocRef> ops::DerefMut for String<A> {
#[inline]
fn deref_mut(&mut self) -> &mut str {
unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
}
}
impl FromStr for String {
type Err = core::convert::Infallible;
#[inline]
fn from_str(s: &str) -> Result<Self, ParseError> {
Ok(Self::from(s))
}
}
impl<A: AllocRef> AsRef<str> for String<A> {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
impl<A: AllocRef> AsRef<[u8]> for String<A> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl From<&str> for String {
#[inline]
#[must_use]
fn from(s: &str) -> Self {
let mut v = Self::new();
v.push_str(s);
v
}
}
impl From<&String> for String {
#[inline]
#[must_use]
fn from(s: &Self) -> Self {
s.clone()
}
}
#[cfg(not(test))]
impl From<Box<str>> for String {
#[must_use]
fn from(s: Box<str>) -> Self {
Self::from(&s[..])
}
}
impl<A> From<String<A>> for Box<str, A>
where
A: AllocRef,
{
fn from(s: String<A>) -> Self {
s.into_boxed_str()
}
}
#[cfg(feature = "std")]
impl<'a> From<Cow<'a, str>> for String {
#[must_use]
fn from(s: Cow<'a, str>) -> Self {
Self::from(&s[..])
}
}
#[cfg(feature = "std")]
impl<'a, A: AllocRef> From<&'a String<A>> for Cow<'a, str> {
#[inline]
fn from(s: &'a String<A>) -> Cow<'a, str> {
Cow::Borrowed(s.as_str())
}
}
impl<A: AllocRef> From<String<A>> for Vec<u8, A> {
fn from(string: String<A>) -> Self {
string.into_bytes()
}
}
impl<A: AllocRef> fmt::Write for String<A> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.try_push_str(s).map_err(|_| fmt::Error)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.try_push(c).map_err(|_| fmt::Error)
}
}
pub struct Drain<'a, A: AllocRef> {
string: *mut String<A>,
start: usize,
end: usize,
iter: Chars<'a>,
}
impl<A: AllocRef> fmt::Debug for Drain<'_, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Drain { .. }")
}
}
unsafe impl<A: AllocRef> Sync for Drain<'_, A> {}
unsafe impl<A: AllocRef> Send for Drain<'_, A> {}
impl<A: AllocRef> 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: AllocRef> Iterator for Drain<'_, A> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
self.iter.next()
}
#[must_use]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[inline]
#[must_use]
fn last(mut self) -> Option<char> {
self.next_back()
}
}
impl<A: AllocRef> DoubleEndedIterator for Drain<'_, A> {
#[inline]
fn next_back(&mut self) -> Option<char> {
self.iter.next_back()
}
}
impl<A: AllocRef> FusedIterator for Drain<'_, A> {}