#![doc = include_str!("../README.md")]
#![no_std]
extern crate alloc;
mod impls;
mod shared;
use alloc::{
borrow::Cow,
boxed::Box,
string::{FromUtf8Error, String, ToString},
vec::Vec,
};
use shared::Shared;
use core::{
borrow::Borrow,
mem::{ManuallyDrop, take},
num::NonZeroUsize,
ops::Deref,
ptr::{self, NonNull},
slice,
};
#[cfg(feature = "nami")]
nami_core::impl_constant!(Str);
const WORD: usize = size_of::<usize>();
const INLINE_CAPACITY: usize = 2 * WORD - 1;
const INLINE_MARK: usize = 1 << (usize::BITS - 1);
const STATIC_MARK: usize = 1 << (usize::BITS - 2);
const LEN_MASK: usize = STATIC_MARK - 1;
const MAX_LEN: usize = LEN_MASK;
const INLINE_TAG: u8 = 0b1000_0000;
const INLINE_LEN_MASK: usize = 0b0111_1111;
#[derive(Clone, Copy)]
enum Repr {
Inline,
Static,
Shared,
}
#[repr(C)]
#[derive(Clone, Copy)]
union Payload {
ptr: NonNull<()>,
bytes: [u8; WORD],
}
#[repr(C)]
pub struct Str {
payload: Payload,
meta: NonZeroUsize,
}
impl Drop for Str {
#[inline]
fn drop(&mut self) {
let Some(shared) = self.as_shared() else {
return;
};
if shared.is_unique() {
let ptr = unsafe { self.payload.ptr }.cast::<Shared>().as_ptr();
drop(unsafe { Box::from_raw(ptr) });
} else {
unsafe {
shared.decrement_count();
}
}
}
}
impl Clone for Str {
#[inline]
fn clone(&self) -> Self {
if let Some(shared) = self.as_shared() {
unsafe {
shared.increment_count();
}
}
Self {
payload: self.payload,
meta: self.meta,
}
}
}
impl Deref for Str {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl Borrow<str> for Str {
fn borrow(&self) -> &str {
self.as_str()
}
}
impl AsRef<str> for Str {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for Str {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl Default for Str {
fn default() -> Self {
Self::new()
}
}
impl From<Cow<'static, str>> for Str {
fn from(value: Cow<'static, str>) -> Self {
match value {
Cow::Borrowed(s) => s.into(),
Cow::Owned(s) => s.into(),
}
}
}
#[cfg(feature = "std")]
mod std_on {
use alloc::{string::FromUtf8Error, vec::IntoIter};
use crate::Str;
extern crate std;
use core::{net::SocketAddr, ops::Deref};
use std::{
ffi::{OsStr, OsString},
io,
net::ToSocketAddrs,
path::Path,
};
impl AsRef<OsStr> for Str {
fn as_ref(&self) -> &OsStr {
self.deref().as_ref()
}
}
impl AsRef<Path> for Str {
fn as_ref(&self) -> &Path {
self.deref().as_ref()
}
}
impl TryFrom<OsString> for Str {
type Error = FromUtf8Error;
fn try_from(value: OsString) -> Result<Self, Self::Error> {
Self::from_utf8(value.into_encoded_bytes())
}
}
impl ToSocketAddrs for Str {
type Iter = IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
self.deref().to_socket_addrs()
}
}
}
impl Str {
#[must_use]
#[inline]
pub const fn from_static(s: &'static str) -> Self {
let len = s.len();
assert!(len <= MAX_LEN, "a `Str` cannot describe a string this long");
let ptr = unsafe { NonNull::new_unchecked(s.as_ptr().cast_mut().cast::<()>()) };
let meta = unsafe { NonZeroUsize::new_unchecked((STATIC_MARK | len).to_le()) };
Self {
payload: Payload { ptr },
meta,
}
}
#[inline]
fn from_inline(s: &str, suffix: &str) -> Self {
let len = s
.len()
.checked_add(suffix.len())
.expect("inline string length overflow");
assert!(len <= INLINE_CAPACITY, "the string does not fit inline");
let mut bytes = [0u8; 2 * WORD];
Self::copy_inline(s.as_bytes(), &mut bytes[..s.len()]);
Self::copy_inline(suffix.as_bytes(), &mut bytes[s.len()..len]);
#[expect(
clippy::cast_possible_truncation,
reason = "the assert above bounds `len` by `INLINE_CAPACITY`, at most 15"
)]
let tag = INLINE_TAG | len as u8;
bytes[2 * WORD - 1] = tag;
let mut head = [0u8; WORD];
let mut tail = [0u8; WORD];
head.copy_from_slice(&bytes[..WORD]);
tail.copy_from_slice(&bytes[WORD..]);
Self {
payload: Payload { bytes: head },
meta: unsafe { NonZeroUsize::new_unchecked(usize::from_ne_bytes(tail)) },
}
}
#[inline]
fn copy_inline(source: &[u8], destination: &mut [u8]) {
#[inline]
fn ends<const N: usize>(source: &[u8], destination: &mut [u8]) {
let end = source.len();
destination[..N].copy_from_slice(&source[..N]);
destination[end - N..end].copy_from_slice(&source[end - N..end]);
}
match source.len() {
0 => {}
1 => destination[0] = source[0],
2..=3 => ends::<2>(source, destination),
4..=7 => ends::<4>(source, destination),
_ => ends::<8>(source, destination),
}
}
#[expect(
clippy::inline_always,
reason = "keep the empty borrowed-string branch inside callers instead of an allocation-sized frame"
)]
#[inline(always)]
pub(crate) fn from_borrowed(s: &str) -> Self {
if s.is_empty() {
Self::new()
} else if s.len() <= INLINE_CAPACITY {
Self::from_inline(s, "")
} else {
Self::from_string(s.to_string())
}
}
#[inline(never)]
fn allocate_owned(string: String) -> NonNull<()> {
NonNull::from(Box::leak(Box::new(Shared::new(string)))).cast::<()>()
}
#[expect(
clippy::inline_always,
reason = "x86-64 cross-crate codegen otherwise outlines the empty owned-string fast path"
)]
#[inline(always)]
fn from_string(string: String) -> Self {
let len = string.len();
if len == 0 {
return Self::new();
}
assert!(len <= MAX_LEN, "a `Str` cannot describe a string this long");
Self {
payload: Payload {
ptr: Self::allocate_owned(string),
},
meta: unsafe { NonZeroUsize::new_unchecked(len.to_le()) },
}
}
const fn tag_word(&self) -> usize {
usize::from_le(self.meta.get())
}
const fn repr(&self) -> Repr {
let tag_word = self.tag_word();
if tag_word & (INLINE_MARK | STATIC_MARK) == 0 {
Repr::Shared
} else if tag_word & INLINE_MARK != 0 {
Repr::Inline
} else {
Repr::Static
}
}
const fn inline_len(&self) -> usize {
(self.tag_word() >> (usize::BITS - 8)) & INLINE_LEN_MASK
}
const fn is_shared(&self) -> bool {
self.tag_word() & (INLINE_MARK | STATIC_MARK) == 0
}
const fn as_shared(&self) -> Option<&Shared> {
if self.is_shared() {
Some(unsafe { self.payload.ptr.cast::<Shared>().as_ref() })
} else {
None
}
}
#[must_use]
#[inline]
pub const fn as_str(&self) -> &str {
let (ptr, len) = match self.repr() {
Repr::Inline => (ptr::from_ref(self).cast::<u8>(), self.inline_len()),
Repr::Static => (
unsafe { self.payload.ptr }
.as_ptr()
.cast_const()
.cast::<u8>(),
self.tag_word() & LEN_MASK,
),
Repr::Shared => {
return unsafe { self.as_shared_unchecked().as_str() };
}
};
unsafe { core::str::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) }
}
const unsafe fn as_shared_unchecked(&self) -> &Shared {
unsafe { self.payload.ptr.cast::<Shared>().as_ref() }
}
#[must_use]
pub const fn len(&self) -> usize {
if self.tag_word() & INLINE_MARK != 0 {
self.inline_len()
} else {
self.tag_word() & LEN_MASK
}
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
#[inline]
pub fn into_string(self) -> String {
let this = ManuallyDrop::new(self);
match this.as_shared() {
Some(shared) => unsafe {
if shared.is_unique() {
let shared = Box::from_raw(this.payload.ptr.cast::<Shared>().as_ptr());
shared.take()
} else {
shared.decrement_count();
shared.as_str().to_string()
}
},
None => this.as_str().to_string(),
}
}
}
impl Str {
#[must_use]
#[inline]
pub const fn new() -> Self {
Self::from_static("")
}
#[inline]
pub fn from_utf8(bytes: Vec<u8>) -> Result<Self, FromUtf8Error> {
String::from_utf8(bytes).map(Self::from)
}
#[must_use]
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> Self {
unsafe { Self::from(String::from_utf8_unchecked(bytes)) }
}
fn handle(&mut self, f: impl FnOnce(&mut String)) {
let mut string = take(self).into_string();
f(&mut string);
*self = Self::from(string);
}
fn extend_parts<S: AsRef<str>>(&mut self, iter: impl IntoIterator<Item = S>) {
fn extend_string<S: AsRef<str>>(string: &mut String, iter: impl Iterator<Item = S>) {
for part in iter {
string.push_str(part.as_ref());
}
}
let mut iter = iter.into_iter().peekable();
if iter.peek().is_none() {
return;
}
if self.is_shared() || self.len() > INLINE_CAPACITY {
self.handle(|string| extend_string(string, iter));
return;
}
let mut bytes = [0u8; INLINE_CAPACITY];
let mut len = self.len();
bytes[..len].copy_from_slice(self.as_bytes());
while let Some(part) = iter.next() {
let part = part.as_ref();
if part.len() <= INLINE_CAPACITY - len {
let end = len + part.len();
Self::copy_inline(part.as_bytes(), &mut bytes[len..end]);
len = end;
} else {
let total = len.checked_add(part.len()).expect("string length overflow");
let prefix =
core::str::from_utf8(&bytes[..len]).expect("concatenated UTF-8 strings");
let mut string = String::with_capacity(total);
string.push_str(prefix);
string.push_str(part);
extend_string(&mut string, iter);
*self = Self::from(string);
return;
}
}
*self = Self::from_borrowed(
core::str::from_utf8(&bytes[..len]).expect("concatenated UTF-8 strings"),
);
}
pub fn append(&mut self, s: impl AsRef<str>) {
let s = s.as_ref();
if s.is_empty() {
return;
}
if !self.is_shared()
&& self
.len()
.checked_add(s.len())
.is_some_and(|len| len <= INLINE_CAPACITY)
{
*self = Self::from_inline(self.as_str(), s);
} else {
self.handle(|string| string.push_str(s));
}
}
}
impl From<&'static str> for Str {
#[inline]
fn from(value: &'static str) -> Self {
Self::from_static(value)
}
}
impl From<String> for Str {
#[inline]
fn from(value: String) -> Self {
Self::from_string(value)
}
}
impl From<Str> for String {
fn from(value: Str) -> Self {
value.into_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[derive(Default)]
struct Recorder(alloc::vec::Vec<u8>);
impl core::hash::Hasher for Recorder {
fn write(&mut self, bytes: &[u8]) {
self.0.extend_from_slice(bytes);
}
fn finish(&self) -> u64 {
self.0.iter().fold(0u64, |acc, &b| {
acc.wrapping_mul(31).wrapping_add(u64::from(b))
})
}
}
fn hash_of(value: &Str) -> u64 {
use core::hash::{Hash, Hasher};
let mut hasher = Recorder::default();
value.hash(&mut hasher);
hasher.finish()
}
fn every_representation(text: &'static str) -> [Str; 3] {
[
Str::from_static(text),
Str::from(String::from(text)),
Str::from_borrowed(text),
]
}
#[test]
fn a_str_is_two_words_wide() {
assert_eq!(size_of::<Str>(), 2 * size_of::<usize>());
assert_eq!(align_of::<Str>(), align_of::<usize>());
assert_eq!(size_of::<Option<Str>>(), size_of::<Str>());
}
#[test]
fn a_static_string_is_still_a_constant() {
const GREETING: Str = Str::from_static("hello");
assert_eq!(GREETING.as_str(), "hello");
assert_eq!(GREETING.len(), 5);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn sixteen_bytes_hold_fifteen() {
assert_eq!(size_of::<Str>(), 16);
assert_eq!(INLINE_CAPACITY, 15);
}
#[test]
fn empty_construction_uses_static_storage() {
for value in [
Str::new(),
Str::from_borrowed(""),
Str::from(String::new()),
Str::from(String::with_capacity(64)),
Str::from_utf8(Vec::with_capacity(64)).unwrap(),
] {
assert!(matches!(value.repr(), Repr::Static));
assert!(value.is_empty());
assert_eq!(value.as_str(), "");
}
}
#[test]
fn borrowed_strings_use_static_empty_or_inline_storage() {
for len in 0..=INLINE_CAPACITY {
let text: String = "abcdefghijklmno".chars().take(len).collect();
let inline = Str::from_borrowed(&text);
if len == 0 {
assert!(matches!(inline.repr(), Repr::Static));
} else {
assert!(matches!(inline.repr(), Repr::Inline), "{len} bytes");
}
assert_eq!(inline.as_str(), text, "{len} bytes");
assert_eq!(inline.len(), len, "{len} bytes");
assert_eq!(inline.is_empty(), len == 0, "{len} bytes");
}
}
#[test]
fn one_byte_past_the_capacity_is_shared() {
let text = "abcdefghijklmnopqrstuvwxyz"
.chars()
.take(INLINE_CAPACITY + 1)
.collect::<String>();
let shared = Str::from(text.clone());
assert!(matches!(shared.repr(), Repr::Shared));
assert_eq!(shared.as_str(), text);
assert_eq!(shared.len(), INLINE_CAPACITY + 1);
assert_eq!(shared.clone().as_str().as_ptr(), shared.as_str().as_ptr());
}
#[test]
fn a_static_string_stays_borrowed_whatever_its_length() {
let short = Str::from_static("short");
let long = Str::from_static("a string that is well past the inline capacity");
assert!(matches!(short.repr(), Repr::Static));
assert!(matches!(long.repr(), Repr::Static));
assert_eq!(short.as_str().as_ptr(), "short".as_ptr());
}
#[test]
fn the_representation_does_not_change_what_a_str_is() {
for text in [
"",
"x",
"fifteen bytes!!",
"sixteen bytes!!!",
"a much longer string",
] {
let [borrowed, owned, copied] = every_representation(text);
assert_eq!(borrowed, owned);
assert_eq!(owned, copied);
assert_eq!(borrowed.as_str(), text);
assert_eq!(copied.as_str(), text);
assert_eq!(borrowed.len(), text.len());
assert_eq!(owned.len(), text.len());
assert_eq!(copied.len(), text.len());
assert_eq!(hash_of(&borrowed), hash_of(&owned));
assert_eq!(hash_of(&owned), hash_of(&copied));
assert_eq!(borrowed.cmp(&owned), core::cmp::Ordering::Equal);
assert_eq!(borrowed.clone().into_string(), text);
assert_eq!(owned.clone().into_string(), text);
assert_eq!(copied.clone().into_string(), text);
}
}
#[test]
fn an_inline_string_survives_being_moved() {
let mut moved = vec![Str::from_borrowed("inline!")];
for i in 0..64 {
let mut text = String::from("n");
text.push_str(&i.to_string());
moved.push(Str::from_borrowed(&text));
}
moved.rotate_left(7);
let boxed = moved.into_boxed_slice();
assert_eq!(boxed[boxed.len() - 7].as_str(), "inline!");
assert_eq!(boxed[boxed.len() - 6].as_str(), "n0");
}
#[test]
fn appending_crosses_the_boundary_in_both_directions() {
let mut s = Str::from_borrowed("inline");
assert!(matches!(s.repr(), Repr::Inline));
s.append(" and then some more bytes");
assert!(matches!(s.repr(), Repr::Shared));
assert_eq!(s.as_str(), "inline and then some more bytes");
let mut back = Str::from_borrowed(&s.as_str()[..6]);
assert!(matches!(back.repr(), Repr::Inline));
back.append("");
assert_eq!(back.as_str(), "inline");
}
#[test]
fn a_long_string_is_still_a_string() {
let text = "x".repeat(1 << 20);
let s = Str::from(text.clone());
assert_eq!(s.len(), text.len());
assert_eq!(s.as_str(), text);
}
#[test]
fn test_static_string_creation() {
let s = Str::from_static("hello");
assert_eq!(s.as_str(), "hello");
assert_eq!(s.len(), 5);
assert!(!s.is_empty());
}
#[test]
fn test_owned_string_creation() {
let s = Str::from(String::from("hello"));
assert_eq!(s.as_str(), "hello");
assert_eq!(s.len(), 5);
assert!(!s.is_empty());
}
#[test]
fn test_empty_string() {
let s = Str::new();
assert_eq!(s.as_str(), "");
assert_eq!(s.len(), 0);
assert!(s.is_empty());
}
#[test]
fn test_static_string_clone() {
let s1 = Str::from_static("hello");
let s2 = s1.clone();
assert_eq!(s1.as_str(), "hello");
assert_eq!(s2.as_str(), "hello");
}
#[test]
fn test_owned_string_clone() {
let s1 = Str::from(String::from("hello"));
let s2 = s1.clone();
assert_eq!(s1.as_str(), "hello");
assert_eq!(s2.as_str(), "hello");
}
#[test]
fn test_multiple_clones() {
let s1 = Str::from(String::from("test"));
let s2 = s1.clone();
let s3 = s1;
let s4 = s2.clone();
drop(s4);
drop(s3);
drop(s2);
}
#[test]
fn test_reference_counting_drop() {
let s1 = Str::from(String::from("hello"));
{
let _s2 = s1;
}
}
#[test]
fn test_into_string_unique() {
let s = Str::from(String::from("hello"));
let string = s.into_string();
assert_eq!(string, "hello");
}
#[test]
fn test_into_string_shared() {
let s1 = Str::from(String::from("hello"));
let _s2 = s1.clone();
let string = s1.into_string();
assert_eq!(string, "hello");
}
#[test]
fn test_into_string_static() {
let s = Str::from_static("hello");
let string = s.into_string();
assert_eq!(string, "hello");
}
#[test]
fn test_from_utf8_valid() {
let bytes = vec![104, 101, 108, 108, 111]; let s = Str::from_utf8(bytes).unwrap();
assert_eq!(s.as_str(), "hello");
}
#[test]
fn test_from_utf8_invalid() {
let bytes = vec![0xFF, 0xFF];
assert!(Str::from_utf8(bytes).is_err());
}
#[test]
fn test_from_utf8_unchecked() {
let bytes = vec![104, 101, 108, 108, 111]; let s = unsafe { Str::from_utf8_unchecked(bytes) };
assert_eq!(s.as_str(), "hello");
}
#[test]
fn test_append() {
let mut s = Str::from("hello");
s.append(" world");
assert_eq!(s.as_str(), "hello world");
}
#[test]
fn test_append_static_to_owned() {
let mut s = Str::from_static("hello");
s.append(" world");
assert_eq!(s.as_str(), "hello world");
}
#[test]
fn test_as_bytes() {
let s = Str::from("hello");
assert_eq!(s.as_bytes(), b"hello");
}
#[test]
fn test_deref() {
let s = Str::from("hello");
assert_eq!(&*s, "hello");
assert_eq!(s.chars().count(), 5);
}
#[test]
fn test_empty_string_from_string() {
let s = Str::from(String::new());
assert_eq!(s.as_str(), "");
assert!(s.is_empty());
}
#[test]
fn test_memory_safety_clone_drop_cycles() {
for text in ["test", "a heap string long enough to remain shared"] {
for _ in 0..100 {
let s1 = Str::from(String::from(text));
let s2 = s1.clone();
let s3 = s2.clone();
drop(s1);
drop(s3);
drop(s2);
}
}
}
#[test]
fn every_inline_length_survives_offset_input_and_moves() {
for len in 0..=INLINE_CAPACITY + 1 {
for offset in 0..WORD {
let text = "q".repeat(offset + len + 1).into_boxed_str();
let input = &text[offset..offset + len];
let value = Str::from_borrowed(input);
let mut values = vec![None, Some(value.clone()), Some(value)];
values.rotate_left(1);
let boxed = values.into_boxed_slice();
drop(text);
for value in boxed.iter().flatten() {
assert_eq!(value.as_str(), "q".repeat(len));
assert_eq!(value.len(), len);
assert_eq!(value.clone().into_string(), "q".repeat(len));
}
}
}
}
#[test]
fn utf8_boundaries_and_nuls_survive_ownership_transitions() {
for scalar in ["\0", "é", "界", "\u{1f642}"] {
for padding in 0..=INLINE_CAPACITY + 1 {
let text = "x".repeat(padding) + scalar;
for mut value in [
Str::from_utf8(text.as_bytes().to_vec()).unwrap(),
Str::from_borrowed(&text),
] {
let alias = value.clone();
value.append(scalar);
assert_eq!(alias.as_str(), text);
assert_eq!(alias.len(), text.len());
assert_eq!(value.as_str(), text.clone() + scalar);
drop(value);
assert_eq!(alias.into_string(), text);
}
}
}
for bytes in [
vec![0xc0, 0x80],
vec![0xed, 0xa0, 0x80],
vec![0xf4, 0x90, 0x80, 0x80],
vec![0xe2, 0x82],
] {
let mut input = vec![b'x'; INLINE_CAPACITY];
input.extend(bytes);
let error = Str::from_utf8(input.clone()).unwrap_err();
assert_eq!(error.into_bytes(), input);
}
}
#[test]
fn heap_aliases_survive_every_three_owner_release_order() {
let text = "shared".repeat(INLINE_CAPACITY + 1);
for order in [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
] {
for convert in 0..8 {
let value = Str::from(text.clone());
let pointer = value.as_str().as_ptr();
let mut owners = [Some(value.clone()), Some(value.clone()), Some(value)];
for (step, index) in order.into_iter().enumerate() {
let owner = owners[index].take().unwrap();
if convert & (1 << step) == 0 {
drop(owner);
} else {
let string = owner.into_string();
assert_eq!(string, text);
if step == 2 {
assert_eq!(string.as_ptr(), pointer);
} else {
assert_ne!(string.as_ptr(), pointer);
}
}
for survivor in owners.iter().flatten() {
assert_eq!(survivor.as_str(), text);
assert_eq!(survivor.as_str().as_ptr(), pointer);
}
}
}
}
}
#[test]
fn heap_mutation_detaches_and_preserves_reserved_capacity() {
let text = "a".repeat(INLINE_CAPACITY + 1);
let mut string = String::with_capacity(text.len() + 128);
string.push_str(&text);
let pointer = string.as_ptr();
let capacity = string.capacity();
let mut unique = Str::from(string);
unique.append("tail");
let string = unique.into_string();
assert_eq!(string.as_ptr(), pointer);
assert_eq!(string.capacity(), capacity);
let mut shared = Str::from(string);
let original = shared.clone();
shared += "suffix";
assert_eq!(original.as_str(), text.clone() + "tail");
assert_eq!(shared.as_str(), text + "tailsuffix");
drop(shared);
let string = original.into_string();
assert_eq!(string.as_ptr(), pointer);
}
#[test]
fn iterator_unwind_keeps_alias_and_receiver_valid() {
extern crate std;
for text in ["short", "a long shared string beyond inline"] {
for mut value in every_representation(text) {
let alias = value.clone();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
value.extend(["first", "second"].into_iter().inspect(|&part| {
assert_ne!(part, "second", "iterator panic");
}));
}));
assert!(result.is_err());
assert_eq!(alias.as_str(), text);
assert_eq!(value.len(), value.as_str().len());
value.append("after unwind");
assert!(value.as_str().ends_with("after unwind"));
drop(alias);
}
}
}
#[test]
fn empty_extend_preserves_shared_buffer_and_aliases() {
let mut value = Str::from(String::from("short"));
let alias = value.clone();
let pointer = value.as_str().as_ptr();
value.extend(core::iter::empty::<&str>());
value.extend(core::iter::empty::<String>());
value.extend(core::iter::empty::<Str>());
assert_eq!(value.as_str().as_ptr(), pointer);
assert_eq!(value, alias);
}
#[test]
fn owned_strings_preserve_buffers_at_every_inline_boundary() {
for len in 1..=INLINE_CAPACITY + 1 {
let mut string = String::with_capacity(INLINE_CAPACITY * 4);
string.push_str(&"x".repeat(len));
let pointer = string.as_ptr();
let capacity = string.capacity();
let mut value = Str::from(string);
assert!(matches!(value.repr(), Repr::Shared));
assert_eq!(value.as_str().as_ptr(), pointer);
let alias = value.clone();
let copied = alias.into_string();
assert_eq!(copied, "x".repeat(len));
assert_ne!(copied.as_ptr(), pointer);
value.append("y");
let string = value.into_string();
assert_eq!(string, "x".repeat(len) + "y");
assert_eq!(string.as_ptr(), pointer);
assert_eq!(string.capacity(), capacity);
}
}
#[test]
fn equal_addresses_do_not_make_different_lengths_equal() {
let text = "same allocation, different lengths";
let full = Str::from_static(text);
let prefix = Str::from_static(&text[..4]);
assert_eq!(full.as_str().as_ptr(), prefix.as_str().as_ptr());
assert_ne!(full, prefix);
assert_eq!(full, full.clone());
assert_eq!(Str::from_borrowed(""), Str::new());
}
#[test]
fn mutation_traits_match_string_across_representations() {
for text in [
"",
"x",
"é水",
"a long heap string past the inline boundary",
] {
for value in every_representation(text) {
let suffixes = ["", "a", "é", "an appended heap string"];
let expected = String::from(text) + &suffixes.concat();
let mut by_append = value.clone();
let mut by_assign = value.clone();
let mut by_extend = value.clone();
let mut by_owned = value.clone();
let mut by_str = value.clone();
for suffix in suffixes {
by_append.append(suffix);
by_assign += suffix;
}
by_extend.extend(suffixes);
by_owned.extend(suffixes.map(String::from));
by_str.extend(suffixes.map(Str::from_static));
for result in [by_append, by_assign, by_extend, by_owned, by_str] {
assert_eq!(result.as_str(), expected);
assert_eq!(result.len(), expected.len());
}
assert_eq!((&value + "tail").as_str(), String::from(text) + "tail");
assert_eq!(value.as_str(), text);
}
}
}
#[cfg(feature = "serde")]
#[test]
fn serde_owned_and_borrowed_inputs_keep_their_storage_contracts() {
use serde::{
Deserialize,
de::value::{Error, StrDeserializer, StringDeserializer},
};
for text in ["", "short", "a long heap string past the inline boundary"] {
let borrowed = Str::deserialize(StrDeserializer::<Error>::new(text)).unwrap();
let string = String::from(text);
let pointer = string.as_ptr();
let owned = Str::deserialize(StringDeserializer::<Error>::new(string)).unwrap();
assert_eq!(borrowed.as_str(), text);
assert_eq!(owned.as_str(), text);
if !text.is_empty() {
assert_eq!(owned.as_str().as_ptr(), pointer);
}
assert_eq!(owned, borrowed);
}
}
#[test]
fn test_memory_safety_interleaved_operations() {
let mut strings = vec![];
for i in 0..10 {
let mut content = String::from("string_");
content.push_str(&(i.to_string()));
let s = Str::from(content);
strings.push(s.clone());
strings.push(s);
}
for i in (0..strings.len()).step_by(3) {
if i < strings.len() {
strings.remove(i);
}
}
for s in &strings {
assert!(!s.as_str().is_empty());
}
}
#[test]
fn test_memory_safety_reference_counting() {
let original = Str::from(String::from("reference test"));
let mut clones = vec![];
for _ in 0..50 {
clones.push(original.clone());
}
assert_eq!(clones.len(), 50);
clones.truncate(25);
assert_eq!(clones.len(), 25);
clones.clear();
assert!(clones.is_empty());
}
#[test]
fn test_memory_safety_into_string_with_clones() {
let s1 = Str::from(String::from("unique test"));
let _s2 = s1.clone();
let _s3 = s1.clone();
let string = s1.into_string();
assert_eq!(string, "unique test");
}
#[test]
fn test_memory_safety_unique_into_string() {
let s = Str::from(String::from("unique"));
let string = s.into_string();
assert_eq!(string, "unique");
}
#[test]
fn test_memory_safety_static_vs_owned() {
let static_str = Str::from_static("static");
let owned_str = Str::from(String::from("owned"));
let mut static_clones = vec![];
let mut owned_clones = vec![];
for _ in 0..100 {
static_clones.push(static_str.clone());
owned_clones.push(owned_str.clone());
}
for clone in &static_clones {
assert_eq!(clone.as_str(), "static");
}
for clone in &owned_clones {
assert_eq!(clone.as_str(), "owned");
}
}
#[test]
fn test_memory_safety_mixed_operations() {
let mut s = Str::from_static("hello");
s.append(" world");
let _s2 = s.clone();
let string = s.into_string();
assert_eq!(string, "hello world");
}
#[test]
fn test_memory_safety_zero_length_edge_cases() {
let empty1 = Str::new();
let empty2 = Str::from("");
let empty3 = Str::from(String::new());
let empty4 = Str::from_utf8(vec![]).unwrap();
assert!(empty1.is_empty());
assert!(empty2.is_empty());
assert!(empty3.is_empty());
assert!(empty4.is_empty());
}
#[test]
fn test_memory_safety_large_strings() {
let large_content = "x".repeat(10000);
let s1 = Str::from(large_content.clone());
let s2 = s1.clone();
assert_eq!(s1.len(), 10000);
assert_eq!(s2.len(), 10000);
assert_eq!(s1.as_str(), large_content);
assert_eq!(s2.as_str(), large_content);
}
#[test]
fn test_memory_safety_concurrent_like_pattern() {
let base = Str::from(String::from("base"));
let mut handles = vec![];
for _ in 0..1000 {
handles.push(base.clone());
}
for chunk in handles.chunks_mut(100) {
for (i, handle) in chunk.iter().enumerate() {
assert_eq!(handle.as_str(), "base");
if i.is_multiple_of(2) {
}
}
}
let mut i = 0;
handles.retain(|_| {
i += 1;
i % 3 == 0
});
let _expected_count = handles.len() + 1;
for handle in &handles {
assert_eq!(handle.as_str(), "base");
}
}
#[test]
fn test_memory_safety_drop_order_stress() {
let s1 = Str::from(String::from("original"));
let s2 = s1.clone();
let s3 = s1.clone();
let s4 = s2.clone();
let s5 = s3.clone();
{
let temp1 = s1.clone();
let temp2 = s2.clone();
drop(temp2);
drop(temp1);
}
drop(s5);
drop(s2);
drop(s1);
drop(s4);
assert_eq!(s3.as_str(), "original");
}
#[test]
fn test_memory_safety_ptr_stability() {
let s1 = Str::from(String::from("a stable, heap-sized allocation"));
let ptr1 = s1.as_str().as_ptr();
let s2 = s1.clone();
let ptr2 = s2.as_str().as_ptr();
assert_eq!(ptr1, ptr2);
let s3 = s2.clone();
let ptr3 = s3.as_str().as_ptr();
assert_eq!(ptr1, ptr3);
assert_eq!(ptr2, ptr3);
drop(s1);
assert_eq!(s2.as_str().as_ptr(), ptr2);
assert_eq!(s3.as_str().as_ptr(), ptr3);
}
#[test]
fn test_memory_safety_alternating_clone_drop() {
let original = Str::from(String::from("alternating"));
let mut refs = vec![original];
for i in 0..100 {
if i % 4 == 0 || i % 4 == 1 {
let new_ref = refs[0].clone();
refs.push(new_ref);
} else if i % 4 == 2 && refs.len() > 1 {
refs.pop();
}
for r in &refs {
assert_eq!(r.as_str(), "alternating");
}
}
}
}