use std::{
borrow::{Borrow, Cow},
fmt::{self, Display, Formatter},
iter::{FromIterator, FusedIterator},
marker::PhantomData,
ops::{Deref, Index, Range},
ptr,
str::{from_utf8, Chars, FromStr, Utf8Error},
string::FromUtf16Error,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[allow(unused_imports)]
use core_extensions::{SelfOps, SliceExt, StringExt};
use crate::std_types::{RStr, RVec};
mod iters;
#[cfg(test)]
mod tests;
pub use self::iters::{Drain, IntoIter};
#[derive(Clone)]
#[repr(C)]
#[derive(StableAbi)]
pub struct RString {
inner: RVec<u8>,
}
impl RString {
pub const fn new() -> Self {
Self::NEW
}
const NEW: Self = Self { inner: RVec::new() };
pub fn with_capacity(cap: usize) -> Self {
String::with_capacity(cap).into()
}
#[inline]
#[allow(clippy::needless_lifetimes)]
pub fn slice<'a, I>(&'a self, i: I) -> RStr<'a>
where
str: Index<I, Output = str>,
{
(&self[i]).into()
}
conditionally_const! {
feature = "rust_1_64"
;
#[inline]
pub fn as_str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(self.inner.as_slice()) }
}
}
#[inline]
pub const fn as_rstr(&self) -> RStr<'_> {
unsafe { RStr::from_raw_parts(self.as_ptr(), self.len()) }
}
#[inline]
pub const fn len(&self) -> usize {
self.inner.len()
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub const fn as_ptr(&self) -> *const u8 {
self.inner.as_ptr()
}
#[inline]
pub const fn capacity(&self) -> usize {
self.inner.capacity()
}
#[inline]
pub const unsafe fn from_utf8_unchecked(vec: RVec<u8>) -> Self {
RString { inner: vec }
}
pub fn from_utf8<V>(vec: V) -> Result<Self, FromUtf8Error>
where
V: Into<RVec<u8>>,
{
let vec = vec.into();
match from_utf8(&vec) {
Ok(..) => Ok(RString { inner: vec }),
Err(e) => Err(FromUtf8Error {
bytes: vec,
error: e,
}),
}
}
pub fn from_utf16(s: &[u16]) -> Result<Self, FromUtf16Error> {
String::from_utf16(s).map(From::from)
}
#[allow(clippy::missing_const_for_fn)]
pub fn into_bytes(self) -> RVec<u8> {
self.inner
}
pub fn into_string(self) -> String {
unsafe { String::from_utf8_unchecked(self.inner.into_vec()) }
}
#[allow(clippy::inherent_to_string_shadow_display)]
pub fn to_string(&self) -> String {
self.as_str().to_string()
}
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional);
}
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit()
}
pub fn reserve_exact(&mut self, additional: usize) {
self.inner.reserve_exact(additional);
}
pub fn push(&mut self, ch: char) {
match ch.len_utf8() {
1 => self.inner.push(ch as u8),
_ => self.push_str(ch.encode_utf8(&mut [0; 4])),
}
}
pub fn push_str(&mut self, str: &str) {
self.inner.extend_from_copy_slice(str.as_bytes());
}
pub fn pop(&mut self) -> Option<char> {
let ch = self.chars().rev().next()?;
let newlen = self.len() - ch.len_utf8();
unsafe {
self.inner.set_len(newlen);
}
Some(ch)
}
pub fn remove(&mut self, idx: usize) -> char {
let ch = match self[idx..].chars().next() {
Some(ch) => ch,
None => panic!("cannot remove a char beyond the end of a string"),
};
let next = idx + ch.len_utf8();
let len = self.len();
unsafe {
let ptr = self.inner.as_mut_ptr();
ptr::copy(ptr.add(next), ptr.add(idx), len - next);
self.inner.set_len(len - (next - idx));
}
ch
}
pub fn insert(&mut self, idx: usize, ch: char) {
let mut bits = [0; 4];
let str_ = ch.encode_utf8(&mut bits);
self.insert_str(idx, str_);
}
pub fn insert_str(&mut self, idx: usize, string: &str) {
assert!(self.is_char_boundary(idx));
unsafe {
self.insert_bytes(idx, string.as_bytes());
}
}
unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
let len = self.len();
let amt = bytes.len();
self.inner.reserve(amt);
let ptr = self.inner.as_mut_ptr();
unsafe {
ptr::copy(ptr.add(idx), ptr.add(idx + amt), len - idx);
ptr::copy(bytes.as_ptr(), self.inner.as_mut_ptr().add(idx), amt);
self.inner.set_len(len + amt);
}
}
#[inline]
pub fn retain<F>(&mut self, mut pred: F)
where
F: FnMut(char) -> bool,
{
let len = self.len();
let mut del_bytes = 0;
let mut idx = 0;
unsafe {
self.inner.set_len(0);
}
let start = self.inner.as_mut_ptr();
while idx < len {
let curr = unsafe { start.add(idx) };
let ch = unsafe {
RStr::from_raw_parts(curr, len - idx)
.chars()
.next()
.unwrap()
};
let ch_len = ch.len_utf8();
if !pred(ch) {
del_bytes += ch_len;
} else if del_bytes > 0 {
unsafe {
ptr::copy(curr, curr.sub(del_bytes), ch_len);
}
}
idx += ch_len;
}
unsafe {
self.inner.set_len(len - del_bytes);
}
}
pub fn clear(&mut self) {
self.inner.clear();
}
}
impl Default for RString {
fn default() -> Self {
String::new().into()
}
}
deref_coerced_impl_cmp_traits! {
RString;
coerce_to = str,
[
String,
str,
&str,
RStr<'_>,
std::borrow::Cow<'_, str>,
crate::std_types::RCowStr<'_>,
]
}
impl_into_rust_repr! {
impl Into<String> for RString {
fn(this){
this.into_string()
}
}
}
impl<'a> From<RString> for Cow<'a, str> {
fn from(this: RString) -> Cow<'a, str> {
this.into_string().piped(Cow::Owned)
}
}
impl From<&str> for RString {
fn from(this: &str) -> Self {
this.to_owned().into()
}
}
impl_from_rust_repr! {
impl From<String> for RString {
fn(this){
RString {
inner: this.into_bytes().into(),
}
}
}
}
impl<'a> From<Cow<'a, str>> for RString {
fn from(this: Cow<'a, str>) -> Self {
this.into_owned().into()
}
}
impl FromStr for RString {
type Err = <String as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<String>().map(RString::from)
}
}
impl Borrow<str> for RString {
fn borrow(&self) -> &str {
self
}
}
impl AsRef<str> for RString {
fn as_ref(&self) -> &str {
self
}
}
impl AsRef<[u8]> for RString {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl Deref for RString {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl Display for RString {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Display::fmt(self.as_str(), f)
}
}
impl fmt::Write for RString {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_str(s);
Ok(())
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.push(c);
Ok(())
}
}
shared_impls! {
mod = string_impls
new_type = RString[][],
original_type = str,
}
impl<'de> Deserialize<'de> for RString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).map(From::from)
}
}
impl Serialize for RString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_str().serialize(serializer)
}
}
impl RString {
pub fn drain<I>(&mut self, range: I) -> Drain<'_>
where
str: Index<I, Output = str>,
{
let string = self as *mut _;
let slic_ = &(*self)[range];
let start = self.offset_of_slice(slic_);
let end = start + slic_.len();
Drain {
string,
removed: start..end,
iter: slic_.chars(),
variance: PhantomData,
}
}
}
impl IntoIterator for RString {
type Item = char;
type IntoIter = IntoIter;
fn into_iter(self) -> IntoIter {
unsafe {
let text: &'static str = &*(&*self as *const str);
IntoIter {
iter: text.chars(),
_buf: self,
}
}
}
}
impl FromIterator<char> for RString {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = char>,
{
iter.piped(String::from_iter).piped(Self::from)
}
}
impl<'a> FromIterator<&'a char> for RString {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = &'a char>,
{
iter.piped(String::from_iter).piped(Self::from)
}
}
#[derive(Debug)]
pub struct FromUtf8Error {
bytes: RVec<u8>,
error: Utf8Error,
}
#[allow(clippy::missing_const_for_fn)]
impl FromUtf8Error {
pub fn into_bytes(self) -> RVec<u8> {
self.bytes
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn error(&self) -> Utf8Error {
self.error
}
}
impl fmt::Display for FromUtf8Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
impl std::error::Error for FromUtf8Error {}