use alloc::sync::Arc;
use core::mem::MaybeUninit;
use super::repr::{InnerString, INLINE_CAPACITY};
use super::CheetahString;
use crate::inline::InlineStr;
pub(super) struct Writer<'a> {
target: Target<'a>,
filled: usize,
}
enum Target<'a> {
Inline(&'a mut [u8]),
Shared(&'a mut [MaybeUninit<u8>]),
}
impl Writer<'_> {
#[inline]
pub(super) fn push_str(&mut self, piece: &str) {
let end = self.filled + piece.len();
match &mut self.target {
Target::Inline(bytes) => bytes[self.filled..end].copy_from_slice(piece.as_bytes()),
Target::Shared(slots) => {
slots[self.filled..end].write_copy_of_slice(piece.as_bytes());
}
}
self.filled = end;
}
#[inline]
pub(super) fn push_str_swapping_ascii(&mut self, piece: &str, from: u8, to: u8) {
assert!(
from.is_ascii() && to.is_ascii(),
"only ASCII bytes can be swapped"
);
let end = self.filled + piece.len();
let swap = |byte: u8| if byte == from { to } else { byte };
match &mut self.target {
Target::Inline(bytes) => {
for (slot, &byte) in bytes[self.filled..end].iter_mut().zip(piece.as_bytes()) {
*slot = swap(byte);
}
}
Target::Shared(slots) => {
for (slot, &byte) in slots[self.filled..end].iter_mut().zip(piece.as_bytes()) {
slot.write(swap(byte));
}
}
}
self.filled = end;
}
#[inline]
fn filled(&self) -> usize {
self.filled
}
}
#[inline]
pub(super) fn assemble(len: usize, fill: impl FnOnce(&mut Writer<'_>)) -> CheetahString {
if len <= INLINE_CAPACITY {
assemble_inline(len, fill)
} else {
assemble_shared(len, fill)
}
}
#[inline]
fn assemble_inline(len: usize, fill: impl FnOnce(&mut Writer<'_>)) -> CheetahString {
let mut buffer = [0u8; INLINE_CAPACITY];
let mut writer = Writer {
target: Target::Inline(&mut buffer[..len]),
filled: 0,
};
fill(&mut writer);
assert_eq!(writer.filled(), len, "assembled pieces must fill the value");
let inline = unsafe { InlineStr::from_assembled(buffer, len) };
CheetahString {
inner: InnerString::Inline(inline),
}
}
#[inline(never)]
fn assemble_shared(len: usize, fill: impl FnOnce(&mut Writer<'_>)) -> CheetahString {
let mut slots = Arc::<[u8]>::new_uninit_slice(len);
let target = Arc::get_mut(&mut slots).expect("a new Arc is uniquely owned");
let mut writer = Writer {
target: Target::Shared(target),
filled: 0,
};
fill(&mut writer);
assert_eq!(writer.filled(), len, "assembled pieces must fill the value");
let bytes: Arc<[u8]> = unsafe { slots.assume_init() };
let shared: Arc<str> = unsafe { Arc::from_raw(Arc::into_raw(bytes) as *const str) };
CheetahString {
inner: InnerString::Shared(shared),
}
}
#[cfg(test)]
mod tests {
use super::assemble;
use crate::cheetah_string::repr::InnerString;
use alloc::string::String;
fn assembled(parts: &[&str]) -> crate::CheetahString {
let len = parts.iter().map(|part| part.len()).sum();
assemble(len, |writer| {
for part in parts {
writer.push_str(part);
}
})
}
#[test]
fn short_results_are_inline_and_long_results_are_shared() {
for parts in [
&[][..],
&["", ""][..],
&["inline", "-", "value"][..],
&["exactly-twenty-three-b", "!"][..],
&["twenty-four-bytes-value", "!"][..],
&[
"\u{1f980}",
"\u{e9}t\u{e9}",
" shared value well past the inline limit",
][..],
] {
let value = assembled(parts);
let expected: String = parts.concat();
assert_eq!(value.as_str(), expected);
match &value.inner {
InnerString::Inline(_) => assert!(expected.len() <= 23),
InnerString::Shared(_) => assert!(expected.len() > 23),
InnerString::Static(_) => panic!("assembled values are never static"),
}
let cloned = value.clone();
assert_eq!(cloned, value);
}
}
#[test]
#[should_panic(expected = "assembled pieces must fill the value")]
fn short_fill_is_rejected_before_the_value_is_read() {
let _ = assemble(40, |writer| writer.push_str("too short"));
}
#[test]
#[should_panic]
fn overlong_fill_is_rejected() {
let _ = assemble(3, |writer| writer.push_str("too long"));
}
fn swapped(
head: &str,
middle: &str,
from: u8,
to: u8,
tail: &str,
) -> (crate::CheetahString, String) {
let value = assemble(head.len() + middle.len() + tail.len(), |writer| {
writer.push_str(head);
writer.push_str_swapping_ascii(middle, from, to);
writer.push_str(tail);
});
let replacement = String::from(char::from(to));
let expected = [
head,
middle.replace(char::from(from), &replacement).as_str(),
tail,
]
.concat();
(value, expected)
}
#[test]
fn ascii_swap_mixes_with_whole_pieces_in_both_storages() {
let cases: [(&str, &str, u8, u8, &str); 5] = [
("", "a-b-c", b'-', b'_', ""),
("\u{e9}", "x-\u{1f980}-y", b'-', b'.', "!"),
("k", "a-b", b'-', b'\0', "z"),
(
"\u{1f980} head ",
"order-consumer-group-\u{e9}t\u{e9}-0001",
b'-',
b'_',
" tail",
),
("", "no match in this piece of shared text", b'#', b'_', ""),
];
for (head, middle, from, to, tail) in cases {
let (value, expected) = swapped(head, middle, from, to, tail);
assert_eq!(value.as_str(), expected);
assert_eq!(value, crate::CheetahString::from(expected.as_str()));
match &value.inner {
InnerString::Inline(_) => assert!(expected.len() <= 23),
InnerString::Shared(_) => assert!(expected.len() > 23),
InnerString::Static(_) => panic!("assembled values are never static"),
}
}
}
#[test]
#[should_panic(expected = "only ASCII bytes can be swapped")]
fn ascii_swap_rejects_a_non_ascii_pattern_byte() {
let _ = assemble(3, |writer| {
writer.push_str_swapping_ascii("abc", 0xc3, b'_')
});
}
#[test]
#[should_panic(expected = "only ASCII bytes can be swapped")]
fn ascii_swap_rejects_a_non_ascii_replacement_byte() {
let _ = assemble(3, |writer| {
writer.push_str_swapping_ascii("a-c", b'-', 0xa9)
});
}
#[test]
#[should_panic(expected = "assembled pieces must fill the value")]
fn ascii_swap_short_fill_is_rejected() {
let _ = assemble(40, |writer| {
writer.push_str_swapping_ascii("a-b", b'-', b'_')
});
}
#[test]
#[should_panic]
fn ascii_swap_overlong_fill_is_rejected() {
let _ = assemble(2, |writer| {
writer.push_str_swapping_ascii("a-b", b'-', b'_')
});
}
}