Debian Codegraph @

src/repr/mod.rs

raw
1 use alloc::borrow::Cow;
2 use alloc::boxed::Box;
3 use core::str::Utf8Error;
4 use core::{mem, ptr};
5
6 #[cfg(feature = "bytes")]
7 mod bytes;
8 #[cfg(feature = "smallvec")]
9 mod smallvec;
10
11 mod capacity;
12 mod heap;
13 mod inline;
14 mod iter;
15 mod last_utf8_char;
16 mod num;
17 #[allow(unexpected_cfgs)]
18 #[cfg(kani)]
19 mod proofs;
20 mod static_str;
21 mod traits;
22
23 use alloc::string::String;
24
25 use capacity::Capacity;
26 use heap::HeapBuffer;
27 use inline::InlineBuffer;
28 use last_utf8_char::LastByte;
29 use static_str::StaticStr;
30 pub(crate) use traits::IntoRepr;
31
32 use crate::{ReserveError, UnwrapWithMsg};
33
34 /// The max size of a string we can fit inline
35 pub(crate) const MAX_SIZE: usize = core::mem::size_of::<String>();
36 /// Used as a discriminant to identify different variants
37 pub(crate) const HEAP_MASK: u8 = LastByte::Heap as u8;
38 /// Used for `StaticStr` variant
39 pub(crate) const STATIC_STR_MASK: u8 = LastByte::Static as u8;
40 /// When our string is stored inline, we represent the length of the string in the last byte, offset
41 /// by `LENGTH_MASK`
42 pub(crate) const LENGTH_MASK: u8 = 0b11000000;
43
44 const EMPTY: Repr = Repr::const_new("");
45
46 #[repr(C)]
47 pub(crate) struct Repr(
48 /// We have a pointer in the representation to properly carry provenance.
49 *const (),
50 /// Then we need two `usize`s (aka WORDs) of data, for the first we just define a `usize`...
51 usize,
52 /// ...but the second we breakup into multiple pieces...
53 #[cfg(target_pointer_width = "64")]
54 u32,
55 u16,
56 u8,
57 /// ...so that the last byte can be a [`LastByte`], which allows the compiler to see a niche
58 /// value.
59 LastByte,
60 );
61 static_assertions::assert_eq_size!([u8; MAX_SIZE], Repr);
62
63 unsafe impl Send for Repr {}
64 unsafe impl Sync for Repr {}
65
66 impl Repr {
67 #[inline]
68 pub(crate) fn new(text: &str) -> Result<Self, ReserveError> {
69 let len = text.len();
70
71 if len == 0 {
72 Ok(EMPTY)
73 } else if len <= MAX_SIZE {
74 // SAFETY: We checked that the length of text is less than or equal to MAX_SIZE
75 let inline = unsafe { InlineBuffer::new(text) };
76 Repr::from_inline_ok(inline)
77 } else {
78 HeapBuffer::new(text).map(Repr::from_heap)
79 }
80 }
81
82 /// Infallible variant of [`Repr::new`] that panics on allocation failure.
83 ///
84 /// Keeping the inline arm out of the `Result` machinery lets the compiler drop the dead unwrap
85 /// check from the hot inline path.
86 #[inline]
87 #[track_caller]
88 pub(crate) fn new_panic(text: &str) -> Self {
89 let len = text.len();
90
91 // Note(parker): `len == 0` is intentionally not special-cased.
92 //
93 // I've gone back and forth on this a few times, but the slight performance win
94 // for empty strings is not worth the instruction bloat. `copy_small(_, _, 0)` in
95 // `InlineBuffer::new` ends up being a no-op as well.
96
97 if len <= MAX_SIZE {
98 // SAFETY: We checked that the length of text is less than or equal to MAX_SIZE
99 let inline = unsafe { InlineBuffer::new(text) };
100 Repr::from_inline(inline)
101 } else {
102 // N.B. `alloc_copy_panic` is `#[inline(always)]`, so the `HeapBuffer` it
103 // returns is assembled right here at the callsite. The only value crossing
104 // the call boundary is the two-word `(ptr, capacity)`.
105 //
106 // Previously returning a full 24-byte `HeapBuffer` across that boundary
107 // instead routed it through a stack temporary that LLVM scatter-copied into
108 // the return slot on x86 which caused a store-forwarding stall.
109 let heap = HeapBuffer::alloc_copy_panic(text);
110 Repr::from_heap(heap)
111 }
112 }
113
114 #[inline]
115 pub(crate) const fn const_new(text: &'static str) -> Self {
116 if text.len() <= MAX_SIZE {
117 let inline = InlineBuffer::new_const(text);
118 Repr::from_inline(inline)
119 } else {
120 let repr = StaticStr::new(text);
121 Repr::from_static(repr)
122 }
123 }
124
125 /// Create a [`Repr`] with the provided `capacity`
126 #[inline]
127 pub(crate) fn with_capacity(capacity: usize) -> Result<Self, ReserveError> {
128 if capacity <= MAX_SIZE {
129 Ok(EMPTY)
130 } else {
131 HeapBuffer::with_capacity(capacity).map(Repr::from_heap)
132 }
133 }
134
135 /// Create a [`Repr`] from a slice of bytes that is UTF-8
136 #[inline]
137 pub(crate) fn from_utf8<B: AsRef<[u8]>>(buf: B) -> Result<Self, Utf8Error> {
138 // Get a &str from the Vec, failing if it's not valid UTF-8
139 let s = core::str::from_utf8(buf.as_ref())?;
140 // Construct a Repr from the &str
141 Ok(Self::new(s).unwrap_with_msg())
142 }
143
144 /// Create a [`Repr`] from a slice of bytes that is UTF-8, without validating that it is indeed
145 /// UTF-8
146 ///
147 /// # Safety
148 ///
149 /// * The caller must guarantee that `buf` is valid UTF-8.
150 #[inline]
151 pub(crate) unsafe fn from_utf8_unchecked<B: AsRef<[u8]>>(buf: B) -> Result<Self, ReserveError> {
152 let bytes = buf.as_ref();
153 let bytes_len = bytes.len();
154
155 // Create a Repr with enough capacity for the entire buffer
156 let mut repr = Repr::with_capacity(bytes_len)?;
157
158 // Write the bytes into the uninitialized buffer without first creating a reference to
159 // that memory.
160 //
161 // SAFETY:
162 // * `repr` was created with capacity for at least `bytes_len` bytes.
163 // * `bytes` is valid for reads of `bytes_len` bytes.
164 // * The newly allocated buffer does not overlap `bytes`.
165 unsafe {
166 repr.as_mut_ptr()
167 .copy_from_nonoverlapping(bytes.as_ptr(), bytes_len)
168 };
169
170 // Set the length of the Repr
171 // SAFETY: We just wrote the entire `buf` into the Repr
172 repr.set_len(bytes_len);
173
174 Ok(repr)
175 }
176
177 /// Create a [`Repr`] from a [`String`], in `O(1)` time. We'll attempt to inline the string
178 /// if `should_inline` is `true`
179 ///
180 /// Note: If the provided [`String`] is >16 MB and we're on a 32-bit arch, we'll copy the
181 /// `String`.
182 #[inline]
183 pub(crate) fn from_string(s: String, should_inline: bool) -> Result<Self, ReserveError> {
184 let og_cap = s.capacity();
185 let cap = Capacity::new(og_cap);
186
187 if cap.is_heap() {
188 // We only hit this case if the provided String is > 16MB and we're on a 32-bit arch.
189 //
190 // `alloc_copy` is the cold out-of-line core, keeping this arm off the hot path without
191 // a helper that would return the 24-byte `Repr` through a stack temporary.
192 let len = s.len();
193 let (ptr, cap) = HeapBuffer::alloc_copy(s.as_str())?;
194 Ok(Repr::from_heap(HeapBuffer { ptr, len, cap }))
195 } else if og_cap == 0 {
196 Ok(EMPTY)
197 } else if should_inline && s.len() <= MAX_SIZE {
198 // SAFETY: Checked to make sure the string would fit inline
199 let inline = unsafe { InlineBuffer::new(s.as_str()) };
200 Repr::from_inline_ok(inline)
201 } else {
202 let mut s = mem::ManuallyDrop::new(s.into_bytes());
203 let len = s.len();
204 let raw_ptr = s.as_mut_ptr();
205
206 let ptr = ptr::NonNull::new(raw_ptr).expect("string with capacity has null ptr?");
207 let heap = HeapBuffer { ptr, len, cap };
208
209 Ok(Repr::from_heap(heap))
210 }
211 }
212
213 /// Converts a [`Repr`] into a [`String`], in `O(1)` time, if possible
214 #[inline]
215 pub(crate) fn into_string(self) -> String {
216 #[cold]
217 fn into_string_heap(this: HeapBuffer) -> String {
218 // SAFETY: We know pointer is valid for `length` bytes
219 let slice = unsafe { core::slice::from_raw_parts(this.ptr.as_ptr(), this.len) };
220 // SAFETY: A `Repr` contains valid UTF-8
221 let s = unsafe { core::str::from_utf8_unchecked(slice) };
222
223 String::from(s)
224 }
225
226 if self.is_heap_allocated() {
227 // SAFETY: we just checked that the discriminant indicates we're a HeapBuffer
228 let heap_buffer = unsafe { self.into_heap() };
229
230 if heap_buffer.cap.is_heap() {
231 // We don't expect capacity to be on the heap often, so we mark it as cold
232 into_string_heap(heap_buffer)
233 } else {
234 // Wrap the BoxString in a ManuallyDrop so the underlying buffer doesn't get freed
235 let this = mem::ManuallyDrop::new(heap_buffer);
236
237 // SAFETY: We checked above to make sure capacity is valid
238 let cap = unsafe { this.cap.as_usize() };
239
240 // SAFETY:
241 // * The memory in `ptr` was previously allocated by the same allocator the standard
242 // library uses, with a required alignment of exactly 1.
243 // * `length` is less than or equal to capacity, due to internal invaraints.
244 // * `capacity` is correctly maintained internally.
245 // * `BoxString` only ever contains valid UTF-8.
246 unsafe { String::from_raw_parts(this.ptr.as_ptr(), this.len, cap) }
247 }
248 } else {
249 String::from(self.as_str())
250 }
251 }
252
253 /// Reserves at least `additional` bytes. If there is already enough capacity to store
254 /// `additional` bytes this is a no-op
255 #[inline]
256 pub(crate) fn reserve(&mut self, additional: usize) -> Result<(), ReserveError> {
257 let len = self.len();
258 let needed_capacity = len.checked_add(additional).ok_or(ReserveError(()))?;
259
260 if !self.is_static_str() && needed_capacity <= self.capacity() {
261 // we already have enough space, no-op
262 // If self.is_static_str() is true, then we would have to convert
263 // it to other variants since static_str variant cannot be modified.
264 Ok(())
265 } else if needed_capacity <= MAX_SIZE {
266 // It's possible to have a `Repr` that is heap allocated with a capacity less than
267 // MAX_SIZE, if that `Repr` was created From a String or Box<str>
268 //
269 // SAFETY: Our needed_capacity is >= our length, which is <= than MAX_SIZE
270 let inline = unsafe { InlineBuffer::new(self.as_str()) };
271 *self = Repr::from_inline(inline);
272 Ok(())
273 } else if !self.is_heap_allocated() {
274 // We're not heap allocated, but need to be, create a HeapBuffer
275 let heap = HeapBuffer::with_additional(self.as_str(), additional)?;
276 *self = Repr::from_heap(heap);
277 Ok(())
278 } else {
279 // We're already heap allocated, but we need more capacity
280 //
281 // SAFETY: We checked above to see if we're heap allocated
282 let heap_buffer = unsafe { self.as_mut_heap() };
283
284 // To reduce allocations, we amortize our growth
285 let amortized_capacity = heap::amortized_growth(len, additional);
286 // Attempt to grow our capacity, allocating a new HeapBuffer on failure
287 if heap_buffer.realloc(amortized_capacity).is_err() {
288 // Create a new HeapBuffer
289 let heap = HeapBuffer::with_additional(self.as_str(), additional)?;
290 *self = Repr::from_heap(heap);
291 }
292
293 Ok(())
294 }
295 }
296
297 pub(crate) fn shrink_to(&mut self, min_capacity: usize) {
298 // Note: We can't shrink the inline variant since it's buffer is a fixed size
299 // or the static str variant since it is just a pointer, so we only
300 // take action here if our string is heap allocated
301 if !self.is_heap_allocated() {
302 return;
303 }
304
305 // SAFETY: We just checked the discriminant to make sure we're heap allocated
306 let heap = unsafe { self.as_mut_heap() };
307
308 let old_capacity = heap.capacity();
309 let new_capacity = heap.len.max(min_capacity);
310
311 if new_capacity <= MAX_SIZE {
312 // Inline string if possible.
313
314 let mut inline = InlineBuffer::empty();
315 // SAFETY: Our src is on the heap, so it does not overlap with our new inline
316 // buffer, and the src is a `Repr` so we can assume it's valid UTF-8
317 unsafe {
318 inline
319 .0
320 .as_mut_ptr()
321 .copy_from_nonoverlapping(heap.ptr.as_ptr(), heap.len)
322 };
323 // SAFETY: The src we wrote from was a `Repr` which we can assume is valid UTF-8
324 unsafe { inline.set_len(heap.len) }
325 *self = Repr::from_inline(inline);
326 return;
327 }
328
329 // Return if the string cannot be strunk.
330 if new_capacity >= old_capacity {
331 return;
332 }
333
334 // Try to shrink in-place.
335 if heap.realloc(new_capacity).is_ok() {
336 return;
337 }
338
339 // Otherwise try to allocate a new, smaller chunk.
340 // We can ignore the error. The string keeps its old capacity, but that's okay.
341 if let Ok(mut new_this) = Repr::with_capacity(new_capacity) {
342 new_this.push_str(self.as_str());
343 *self = new_this;
344 }
345 }
346
347 #[inline]
348 pub(crate) fn push_str(&mut self, s: &str) {
349 // If `s` is empty, then there's no reason to reserve or push anything
350 // at all.
351 if s.is_empty() {
352 return;
353 }
354
355 let len = self.len();
356 let str_len = s.len();
357
358 // Only call the (out-of-line) grow path when we actually need to; the common append
359 // already has room. A `&'static str` always has to be converted first.
360 if self.is_static_str() || len + str_len > self.capacity() {
361 self.reserve(str_len).unwrap_with_msg();
362 }
363
364 // Copy the string into the spare capacity without first creating a reference to the
365 // uninitialized memory.
366 //
367 // SAFETY:
368 // * `reserve` guarantees at least `len + str_len` bytes of capacity.
369 // * `s` is valid for reads of `str_len` bytes.
370 // * The mutable borrow of `self` guarantees the source and destination do not overlap.
371 unsafe {
372 self.as_mut_ptr()
373 .add(len)
374 .copy_from_nonoverlapping(s.as_ptr(), str_len)
375 };
376
377 // Increment the length of our string
378 //
379 // SAFETY: We appended `s` which is valid UTF-8, and if our size became greater than
380 // MAX_SIZE, our call to reserve would make us heap allocated
381 unsafe { self.set_len(len + str_len) };
382 }
383
384 #[inline]
385 pub(crate) fn pop(&mut self) -> Option<char> {
386 let ch = self.as_str().chars().next_back()?;
387
388 // SAFETY: We know this is is a valid length which falls on a char boundary
389 unsafe { self.set_len(self.len() - ch.len_utf8()) };
390
391 Some(ch)
392 }
393
394 /// Returns the string content, and only the string content, as a slice of bytes.
395 #[inline]
396 pub(crate) fn as_slice(&self) -> &[u8] {
397 // initially has the value of the stack pointer, conditionally becomes the heap pointer
398 let mut pointer = self as *const Self as *const u8;
399 let heap_pointer = self.0 as *const u8;
400 if self.last_byte() >= HEAP_MASK {
401 pointer = heap_pointer;
402 }
403
404 // initially has the value of the stack length, conditionally becomes the heap length
405 let mut length = core::cmp::min(
406 self.last_byte().wrapping_sub(LENGTH_MASK) as usize,
407 MAX_SIZE,
408 );
409 let heap_length = self.1;
410 if self.last_byte() >= HEAP_MASK {
411 length = heap_length;
412 }
413
414 // SAFETY: We know the data is valid, aligned, and part of the same contiguous allocated
415 // chunk. It's also valid for the lifetime of self
416 unsafe { core::slice::from_raw_parts(pointer, length) }
417 }
418
419 #[inline]
420 pub(crate) fn as_str(&self) -> &str {
421 // SAFETY: A `Repr` contains valid UTF-8
422 unsafe { core::str::from_utf8_unchecked(self.as_slice()) }
423 }
424
425 /// Returns the length of the string that we're storing
426 #[inline]
427 pub(crate) fn len(&self) -> usize {
428 // This ugly looking code results in two conditional moves and only one comparison, without
429 // branching. The outcome of a comparison is a tristate `{lt, eq, gt}`, but the compiler
430 // won't use this optimization if you match on `len_inline.cmp(&MAX_SIZE)`, so we have to
431 // do it manually.
432
433 // Force the compiler to read the variable, so it won't put the reading in a branch.
434 let len_heap = ensure_read(self.1);
435
436 let last_byte = self.last_byte();
437
438 // Extending the variable early results in fewer instructions, because loading and
439 // extending can be done in one instruction.
440 let mut len = (last_byte as usize)
441 .wrapping_sub(LENGTH_MASK as usize)
442 .min(MAX_SIZE);
443
444 // our discriminant is stored in the last byte and denotes stack vs heap
445 //
446 // Note: We should never add an `else` statement here, keeping the conditional simple allows
447 // the compiler to optimize this to a conditional-move instead of a branch
448 if last_byte >= HEAP_MASK {
449 len = len_heap;
450 }
451
452 len
453 }
454
455 /// Returns `true` if the length is 0, `false` otherwise
456 #[inline]
457 pub(crate) fn is_empty(&self) -> bool {
458 let len_heap = ensure_read(self.1);
459 let last_byte = self.last_byte() as usize;
460 let mut len = last_byte.wrapping_sub(LastByte::L0 as u8 as usize);
461 if last_byte >= LastByte::Heap as u8 as usize {
462 len = len_heap;
463 }
464 len == 0
465 }
466
467 /// Returns the overall capacity of the underlying buffer
468 #[inline]
469 pub(crate) fn capacity(&self) -> usize {
470 #[cold]
471 fn heap_capacity(this: &Repr) -> usize {
472 // SAFETY: We just checked the discriminant to make sure we're heap allocated
473 let heap_buffer = unsafe { this.as_heap() };
474 heap_buffer.capacity()
475 }
476
477 if let Some(s) = self.as_static_str() {
478 s.len()
479 } else if self.is_heap_allocated() {
480 heap_capacity(self)
481 } else {
482 MAX_SIZE
483 }
484 }
485
486 #[inline(always)]
487 pub(crate) fn is_heap_allocated(&self) -> bool {
488 let last_byte = self.last_byte();
489 last_byte == HEAP_MASK
490 }
491
492 #[inline(always)]
493 const fn is_static_str(&self) -> bool {
494 let last_byte = self.last_byte();
495 last_byte == STATIC_STR_MASK
496 }
497
498 #[inline]
499 pub(crate) const fn as_static_str(&self) -> Option<&'static str> {
500 if self.is_static_str() {
501 // SAFETY: A `Repr` is transmuted from `StaticStr`
502 let s: &StaticStr = unsafe { &*(self as *const Self as *const StaticStr) };
503 Some(s.get_text())
504 } else {
505 None
506 }
507 }
508
509 #[inline]
510 fn as_static_variant_mut(&mut self) -> Option<&mut StaticStr> {
511 if self.is_static_str() {
512 // SAFETY: A `Repr` is transmuted from `StaticStr`
513 let s: &mut StaticStr = unsafe { &mut *(self as *mut Self as *mut StaticStr) };
514 Some(s)
515 } else {
516 None
517 }
518 }
519
520 /// Returns a mutable raw pointer to the start of the underlying buffer.
521 ///
522 /// The pointer is valid for writes up to [`Repr::capacity`], but only the first [`Repr::len`]
523 /// bytes are guaranteed to be initialized.
524 #[inline]
525 pub(crate) fn as_mut_ptr(&mut self) -> *mut u8 {
526 #[cold]
527 fn inline_static_str(this: &mut Repr) {
528 if let Some(s) = this.as_static_str() {
529 *this = Repr::new(s).unwrap_with_msg();
530 }
531 }
532
533 if self.is_static_str() {
534 inline_static_str(self);
535 }
536
537 if self.is_heap_allocated() {
538 // SAFETY: We just checked the discriminant to make sure we're heap allocated.
539 unsafe { self.as_mut_heap().ptr.as_ptr() }
540 } else {
541 self as *mut Self as *mut u8
542 }
543 }
544
545 /// Sets the length of the string that our underlying buffer contains
546 ///
547 /// # Safety
548 /// * `len` bytes in the buffer must be valid UTF-8
549 /// * If the underlying buffer is stored inline, `len` must be <= MAX_SIZE
550 #[inline]
551 pub(crate) unsafe fn set_len(&mut self, len: usize) {
552 if let Some(s) = self.as_static_variant_mut() {
553 s.set_len(len);
554 } else if self.is_heap_allocated() {
555 // SAFETY: We just checked the discriminant to make sure we're heap allocated
556 let heap_buffer = self.as_mut_heap();
557 // SAFETY: The caller guarantees that `len` bytes is valid UTF-8
558 heap_buffer.set_len(len);
559 } else {
560 // SAFETY: We just checked the discriminant to make sure we're an InlineBuffer
561 let inline_buffer = self.as_mut_inline();
562 // SAFETY: The caller guarantees that len <= MAX_SIZE, and `len` bytes is valid UTF-8
563 inline_buffer.set_len(len);
564 }
565 }
566
567 /// Zero out the memory backing this [`Repr`].
568 #[cfg(feature = "zeroize")]
569 pub(crate) fn zeroize(&mut self) {
570 // We can't zero out static memory so we just replace ourselves with
571 // the EMPTY variant.
572 if self.is_static_str() {
573 *self = EMPTY;
574 return;
575 }
576
577 /// Performs a volatile `memset` operation which fills a slice with a value.
578 ///
579 /// # SAFETY:
580 ///
581 /// * The memory pointed to by `dst` must be valid for `count` contiguous bytes.
582 /// * `count` must not be larger than an isize
583 /// * `dst` + `count` must not wrap around the address space.
584 ///
585 /// Derived from: <https://github.com/RustCrypto/utils/blob/c68a5204b2e66b0f60832d845e048fca96a81211/zeroize/src/lib.rs#L766-L791>.
586 ///
587 /// TODO(parkmycar): use `volatile_set_memory` when stabilized
588 #[inline(always)]
589 unsafe fn volatile_zero(dst: *mut u8, count: usize) {
590 for i in 0..count {
591 let dst = dst.add(i);
592 ptr::write_volatile(dst, 0);
593 }
594 }
595
596 /// Uses fences to prevent the compiler from re-ordering memory accesses.
597 #[inline(always)]
598 fn atomic_fence() {
599 use core::sync::atomic;
600 atomic::compiler_fence(atomic::Ordering::SeqCst);
601 }
602
603 // The last byte stores our discriminant and stack length.
604 let last_byte = self.last_byte();
605
606 let (ptr, cap) = if last_byte == HEAP_MASK {
607 // SAFETY: We just checked the discriminant to make sure we're heap allocated.
608 let heap_buffer = unsafe { self.as_mut_heap() };
609 // SAFTEY: Setting the length to 0 is always safe because the empty string is
610 // valid UTF-8.
611 unsafe { heap_buffer.set_len(0) };
612
613 let ptr = heap_buffer.ptr.as_ptr();
614 let cap = heap_buffer.capacity();
615 (ptr, cap)
616 } else {
617 // SAFETY: We just checked the discriminant above to see if we're heap allocated.
618 let inline_buffer = unsafe { self.as_mut_inline() };
619 // SAFTEY: Setting the length to 0 is always safe because the empty string is
620 // valid UTF-8.
621 unsafe { inline_buffer.set_len(0) };
622
623 let ptr = self as *mut Self as *mut u8;
624 let cap = MAX_SIZE - 1;
625 (ptr, cap)
626 };
627
628 // SAFTEY: We know our pointer is valid for `cap` bytes because the capacity came
629 // from an already existing CompactString. Also we don't allow allocations larger
630 // then an isize.
631 unsafe { volatile_zero(ptr, cap) };
632 atomic_fence()
633 }
634
635 /// Returns the last byte that's on the stack.
636 ///
637 /// The last byte stores the discriminant that indicates whether the string is on the stack or
638 /// on the heap. When the string is on the stack the last byte also stores the length
639 #[inline(always)]
640 const fn last_byte(&self) -> u8 {
641 cfg_if::cfg_if! {
642 if #[cfg(target_pointer_width = "64")] {
643 let last_byte = self.5;
644 } else if #[cfg(target_pointer_width = "32")] {
645 let last_byte = self.4;
646 } else {
647 compile_error!("Unsupported target_pointer_width");
648 }
649 };
650 last_byte as u8
651 }
652
653 /// Reinterprets an [`InlineBuffer`] into a [`Repr`]
654 ///
655 /// Note: This is safe because [`InlineBuffer`] and [`Repr`] are the same size. We used to
656 /// define [`Repr`] as a `union` which implicitly transmuted between the two types, but that
657 /// prevented us from defining a "niche" value to make `Option<CompactString>` the same size as
658 /// just `CompactString`
659 #[inline(always)]
660 const fn from_inline(inline: InlineBuffer) -> Self {
661 // SAFETY: An `InlineBuffer` and `Repr` have the same size
662 unsafe { core::mem::transmute(inline) }
663 }
664
665 /// `Ok(from_inline(inline))`, plus a hint to the compiler that the result is in fact `Ok`.
666 #[inline(always)]
667 fn from_inline_ok(inline: InlineBuffer) -> Result<Self, ReserveError> {
668 let repr = Self::from_inline(inline);
669 // SAFETY: `InlineBuffer` always produces a valid inline last byte (`< HEAP_MASK`). The
670 // compiler cannot see this through the transmute; without the hint it cannot fold the
671 // niche-encoded `Err` arm at the call site. Kept here (not in `from_inline`) so callers
672 // that don't wrap in `Result` avoid materializing the load of the last byte.
673 unsafe { assume(repr.last_byte() < HEAP_MASK) };
674 Ok(repr)
675 }
676
677 /// Reinterprets a [`HeapBuffer`] into a [`Repr`]
678 ///
679 /// Note: This is safe because [`HeapBuffer`] and [`Repr`] are the same size. We used to define
680 /// [`Repr`] as a `union` which implicitly transmuted between the two types, but that prevented
681 /// us from defining a "niche" value to make `Option<CompactString>` the same size as just
682 /// `CompactString`
683 #[inline(always)]
684 const fn from_heap(heap: HeapBuffer) -> Self {
685 // SAFETY: A `HeapBuffer` and `Repr` have the same size
686 unsafe { core::mem::transmute(heap) }
687 }
688
689 /// Reinterprets a [`StaticStr`] into a [`Repr`]
690 ///
691 /// Note: This is safe because [`StaticStr`] and [`Repr`] are the same size. We used to define
692 /// [`Repr`] as a `union` which implicitly transmuted between the two types, but that prevented
693 /// us from defining a "niche" value to make `Option<CompactString>` the same size as just
694 /// `CompactString`
695 #[inline(always)]
696 const fn from_static(heap: StaticStr) -> Self {
697 // SAFETY: A `StaticStr` and `Repr` have the same size
698 unsafe { core::mem::transmute(heap) }
699 }
700
701 /// Reinterprets a [`Repr`] as a [`HeapBuffer`]
702 ///
703 /// # SAFETY
704 /// * The caller must guarantee that the provided [`Repr`] is actually a [`HeapBuffer`] by
705 /// checking the discriminant.
706 ///
707 /// Note: We used to define [`Repr`] as a `union` which implicitly transmuted between the two
708 /// types, but that prevented us from defining a "niche" value to make `Option<CompactString>`
709 /// the same size as just `CompactString`
710 #[inline(always)]
711 const unsafe fn into_heap(self) -> HeapBuffer {
712 core::mem::transmute(self)
713 }
714
715 /// Reinterprets a `&mut Repr` as a `&mut HeapBuffer`
716 ///
717 /// # SAFETY
718 /// * The caller must guarantee that the provided [`Repr`] is actually a [`HeapBuffer`] by
719 /// checking the discriminant.
720 ///
721 /// Note: We used to define [`Repr`] as a `union` which implicitly transmuted between the two
722 /// types, but that prevented us from defining a "niche" value to make `Option<CompactString>`
723 /// the same size as just `CompactString`
724 #[inline(always)]
725 unsafe fn as_mut_heap(&mut self) -> &mut HeapBuffer {
726 // SAFETY: A `HeapBuffer` and `Repr` have the same size
727 &mut *(self as *mut _ as *mut HeapBuffer)
728 }
729
730 /// Reinterprets a `&Repr` as a `&HeapBuffer`
731 ///
732 /// # SAFETY
733 /// * The caller must guarantee that the provided [`Repr`] is actually a [`HeapBuffer`] by
734 /// checking the discriminant.
735 ///
736 /// Note: We used to define [`Repr`] as a `union` which implicitly transmuted between the two
737 /// types, but that prevented us from defining a "niche" value to make `Option<CompactString>`
738 /// the same size as just `CompactString`
739 #[inline(always)]
740 unsafe fn as_heap(&self) -> &HeapBuffer {
741 // SAFETY: A `HeapBuffer` and `Repr` have the same size
742 &*(self as *const _ as *const HeapBuffer)
743 }
744
745 /// Reinterprets a [`Repr`] as an [`InlineBuffer`]
746 ///
747 /// # SAFETY
748 /// * The caller must guarantee that the provided [`Repr`] is actually an [`InlineBuffer`] by
749 /// checking the discriminant.
750 ///
751 /// Note: We used to define [`Repr`] as a `union` which implicitly transmuted between the two
752 /// types, but that prevented us from defining a "niche" value to make `Option<CompactString>`
753 /// the same size as just `CompactString`
754 #[inline(always)]
755 #[cfg(feature = "smallvec")]
756 const unsafe fn into_inline(self) -> InlineBuffer {
757 core::mem::transmute(self)
758 }
759
760 /// Reinterprets a `&mut Repr` as an `&mut InlineBuffer`
761 ///
762 /// # SAFETY
763 /// * The caller must guarantee that the provided [`Repr`] is actually an [`InlineBuffer`] by
764 /// checking the discriminant.
765 ///
766 /// Note: We used to define [`Repr`] as a `union` which implicitly transmuted between the two
767 /// types, but that prevented us from defining a "niche" value to make `Option<CompactString>`
768 /// the same size as just `CompactString`
769 #[inline(always)]
770 unsafe fn as_mut_inline(&mut self) -> &mut InlineBuffer {
771 // SAFETY: An `InlineBuffer` and `Repr` have the same size
772 &mut *(self as *mut _ as *mut InlineBuffer)
773 }
774 }
775
776 impl Clone for Repr {
777 #[inline]
778 fn clone(&self) -> Self {
779 // There are only two cases we need to care about: If the string is allocated on the heap
780 // or not. If it is, then the data must be cloned properly, otherwise we can simply copy
781 // the `Repr`.
782 //
783 // `new_panic`'s heap arm is the cold out-of-line `alloc_copy` returning `(ptr, cap)` in
784 // registers; an out-of-line helper returning the 24-byte `Repr` here would route the hot
785 // copy arm below through a scatter-copied stack temporary on x86 (store-forwarding stall).
786 if self.is_heap_allocated() {
787 Repr::new_panic(self.as_str())
788 } else {
789 // SAFETY: We just checked that `self` can be copied because it is an inline string or
790 // a reference to a `&'static str`.
791 unsafe { core::ptr::read(self) }
792 }
793 }
794
795 #[inline]
796 fn clone_from(&mut self, source: &Self) {
797 #[inline(never)]
798 fn clone_from_heap(this: &mut Repr, source: &Repr) {
799 unsafe { this.set_len(0) };
800 this.push_str(source.as_str());
801 }
802
803 // There are only two cases we need to care about: If the string is allocated on the heap
804 // or not. If it is, then the data must be cloned proberly, otherwise we can simply copy
805 // the `Repr`.
806 if source.is_heap_allocated() {
807 clone_from_heap(self, source)
808 } else {
809 // SAFETY: We just checked that `source` can be copied because it is an inline string or
810 // a reference to a `&'static str`.
811 *self = unsafe { core::ptr::read(source) }
812 }
813 }
814 }
815
816 impl Drop for Repr {
817 #[inline]
818 fn drop(&mut self) {
819 // By "outlining" the actual Drop code and only calling it if we're a heap variant, it
820 // allows dropping an inline variant to be as cheap as possible.
821 if self.is_heap_allocated() {
822 // SAFETY: We just checked the discriminant to make sure we're heap allocated
823 let heap = unsafe { self.as_heap() };
824 // Pass the heap fields by value so the address of `*self` never escapes, otherwise
825 // dropping a by-value `CompactString` must materialize the full 24 bytes on the
826 // caller's stack just to hand `&mut Repr` to the outlined function.
827 outlined_drop(heap.ptr, heap.cap)
828 }
829
830 #[cold]
831 fn outlined_drop(ptr: ptr::NonNull<u8>, cap: Capacity) {
832 heap::deallocate_ptr(ptr, cap);
833 }
834 }
835 }
836
837 impl Extend<char> for Repr {
838 #[inline]
839 fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
840 let mut iter = iter.into_iter();
841
842 let (lower_bound, _) = iter.size_hint();
843 if lower_bound > 0 {
844 // Ignore the error and hope that the lower_bound is incorrect.
845 let _: Result<(), ReserveError> = self.reserve(lower_bound);
846 }
847
848 // Append into the spare capacity directly, tracking the length locally so we avoid the
849 // per-char `len`/`set_len` discriminant work of pushing one char at a time. If a char
850 // doesn't fit, grow via `push_str` and re-resolve the buffer.
851 'refetch: loop {
852 // Pull a char before resolving the buffer so an empty iterator does no work.
853 let mut next = iter.next();
854 if next.is_none() {
855 return;
856 }
857
858 let cap = self.capacity();
859 let mut cur = self.len();
860 // Also converts a `&'static str` into an owned inline buffer.
861 let ptr = self.as_mut_ptr();
862 let mut buf = [0u8; 4];
863
864 while let Some(c) = next {
865 let encoded = c.encode_utf8(&mut buf);
866 let n = encoded.len();
867
868 if cur + n > cap {
869 // SAFETY: `cur` bytes of valid UTF-8 have been written into the buffer.
870 unsafe { self.set_len(cur) };
871 self.push_str(encoded);
872 continue 'refetch;
873 }
874
875 // SAFETY: `cur + n <= cap` leaves room for `n` bytes; `ptr` stays valid until the
876 // next `continue 'refetch`, which re-derives it; `encoded` cannot overlap `ptr`.
877 unsafe {
878 ptr.add(cur).copy_from_nonoverlapping(encoded.as_ptr(), n);
879 }
880 cur += n;
881
882 next = iter.next();
883 }
884
885 // SAFETY: `cur` bytes of valid UTF-8 have been written into the buffer.
886 unsafe { self.set_len(cur) };
887 return;
888 }
889 }
890 }
891
892 impl<'a> Extend<&'a char> for Repr {
893 fn extend<T: IntoIterator<Item = &'a char>>(&mut self, iter: T) {
894 self.extend(iter.into_iter().copied());
895 }
896 }
897
898 impl<'a> Extend<&'a str> for Repr {
899 fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
900 iter.into_iter().for_each(|s| self.push_str(s));
901 }
902 }
903
904 impl Extend<Box<str>> for Repr {
905 fn extend<T: IntoIterator<Item = Box<str>>>(&mut self, iter: T) {
906 iter.into_iter().for_each(move |s| self.push_str(&s));
907 }
908 }
909
910 impl<'a> Extend<Cow<'a, str>> for Repr {
911 fn extend<T: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: T) {
912 iter.into_iter().for_each(move |s| self.push_str(&s));
913 }
914 }
915
916 impl Extend<String> for Repr {
917 fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
918 iter.into_iter().for_each(move |s| self.push_str(&s));
919 }
920 }
921
922 /// Returns the supplied value, and ensures that the value is eagerly loaded into a register.
923 #[inline(always)]
924 fn ensure_read(value: usize) -> usize {
925 // SAFETY: This assembly instruction is a noop that only affects the instruction ordering.
926 //
927 // TODO(parkmycar): Re-add loongarch and riscv once we have CI coverage for them.
928 #[allow(unexpected_cfgs)]
929 #[cfg(all(
930 not(any(kani, miri)),
931 any(
932 target_arch = "x86",
933 target_arch = "x86_64",
934 target_arch = "arm",
935 target_arch = "aarch64",
936 )
937 ))]
938 unsafe {
939 core::arch::asm!(
940 "/* {value} */",
941 value = in(reg) value,
942 options(nomem, nostack),
943 );
944 };
945
946 value
947 }
948
949 /// Polyfill for [`core::hint::assert_unchecked`] (stabilized in Rust 1.81; our MSRV is 1.71). The
950 /// two are equivalent — `assert_unchecked` is defined as this — so the release codegen is identical.
951 ///
952 /// In debug builds we also `debug_assert!` the condition, so a violated invariant panics loudly
953 /// instead of being silent UB. This compiles out of release builds, leaving only the hint.
954 ///
955 /// TODO(MSRV 1.81): drop this and call `core::hint::assert_unchecked` directly.
956 ///
957 /// # Safety
958 /// `cond` must always hold; the compiler is free to assume it.
959 #[inline(always)]
960 const unsafe fn assume(cond: bool) {
961 debug_assert!(cond);
962 if !cond {
963 // SAFETY: guaranteed by the caller.
964 core::hint::unreachable_unchecked();
965 }
966 }
967
968 /// Copies `len` bytes (`len <= MAX_SIZE`) from `src` to `dst`, for the inline-string path.
969 ///
970 /// A `ptr::copy_nonoverlapping` with a *runtime* length lowers to an out-of-line `memcpy` call
971 /// (the backend only inlines the copy when the length is a compile-time constant), which is
972 /// wasteful for the tiny copies used when inlining a string. Since an inline string is at most
973 /// `MAX_SIZE` bytes we instead use a ladder of *constant*-length overlapping copies, each of which
974 /// the compiler lowers to a couple of load/store instructions — and which const-fold away entirely
975 /// when `len` is known (e.g. `CompactString::const_new` / string literals).
976 ///
977 /// # Safety
978 /// * `len <= MAX_SIZE`.
979 /// * `src` is valid for reads of `len` bytes; `dst` is valid for writes of `len` bytes.
980 /// * `src` and `dst` do not overlap.
981 #[cfg(not(all(target_pointer_width = "64", target_endian = "little")))]
982 #[inline(always)]
983 pub(crate) unsafe fn copy_small(src: *const u8, dst: *mut u8, len: usize) {
984 debug_assert!(len <= MAX_SIZE);
985
986 // Each branch only touches bytes within `[0, len)` — the tail copy starts at `len - N` only
987 // once we know `len >= N` — so the overlapping copies never read or write out of range.
988 if len >= 16 {
989 ptr::copy_nonoverlapping(src, dst, 16);
990 ptr::copy_nonoverlapping(src.add(len - 16), dst.add(len - 16), 16);
991 } else if len >= 8 {
992 ptr::copy_nonoverlapping(src, dst, 8);
993 ptr::copy_nonoverlapping(src.add(len - 8), dst.add(len - 8), 8);
994 } else if len >= 4 {
995 ptr::copy_nonoverlapping(src, dst, 4);
996 ptr::copy_nonoverlapping(src.add(len - 4), dst.add(len - 4), 4);
997 } else if len >= 2 {
998 ptr::copy_nonoverlapping(src, dst, 2);
999 ptr::copy_nonoverlapping(src.add(len - 2), dst.add(len - 2), 2);
1000 } else if len == 1 {
1001 *dst = *src;
1002 }
1003 }
1004
1005 /// Copies `len` bytes from `src` to `dst`, for the heap-string path.
1006 ///
1007 /// The common case for a freshly heap-allocated `CompactString` is a length just over
1008 /// the inline threshold. For those the medium bands `[16,64]` are copied inline with two
1009 /// overlapping fixed-size load/stores, skipping the `memcpy` call boundary like
1010 /// [`copy_small`].
1011 ///
1012 /// Copies `> 64` bytes delegate to `memcpy`, which has per-CPU-tuned large-copy paths
1013 /// that any optimization we do won't beat.
1014 /// Copies `< 16` bytes are rare on this path so they simply delegate to `memcpy` as well
1015 /// which keeps this correct for *any* length.
1016 ///
1017 /// # Safety
1018 ///
1019 /// * `src` is valid for reads of `len` bytes; `dst` is valid for writes of `len` bytes.
1020 /// * `src` and `dst` do not overlap.
1021 ///
1022 #[inline]
1023 pub(crate) unsafe fn copy_medium(src: *const u8, dst: *mut u8, len: usize) {
1024 if len > 64 {
1025 ptr::copy_nonoverlapping(src, dst, len);
1026 } else if len >= 32 {
1027 ptr::copy_nonoverlapping(src, dst, 32);
1028 ptr::copy_nonoverlapping(src.add(len - 32), dst.add(len - 32), 32);
1029 } else if len >= 16 {
1030 ptr::copy_nonoverlapping(src, dst, 16);
1031 ptr::copy_nonoverlapping(src.add(len - 16), dst.add(len - 16), 16);
1032 } else {
1033 ptr::copy_nonoverlapping(src, dst, len);
1034 }
1035 }
1036
1037 #[cfg(test)]
1038 mod tests {
1039 use alloc::string::{String, ToString};
1040 use alloc::vec::Vec;
1041
1042 use quickcheck_macros::quickcheck;
1043 use test_case::test_case;
1044
1045 use super::{Repr, MAX_SIZE};
1046 use crate::ReserveError;
1047
1048 const EIGHTEEN_MB: usize = 18 * 1024 * 1024;
1049 const EIGHTEEN_MB_STR: &str = unsafe { core::str::from_utf8_unchecked(&[42; EIGHTEEN_MB]) };
1050
1051 #[test_case("hello world!"; "inline")]
1052 #[test_case("this is a long string that should be stored on the heap"; "heap")]
1053 fn test_create(s: &'static str) {
1054 let repr = Repr::new(s).unwrap();
1055 assert_eq!(repr.as_str(), s);
1056 assert_eq!(repr.len(), s.len());
1057
1058 // test StaticStr variant
1059 let repr = Repr::const_new(s);
1060 assert_eq!(repr.as_str(), s);
1061 assert_eq!(repr.len(), s.len());
1062 }
1063
1064 #[quickcheck]
1065 #[cfg_attr(miri, ignore)]
1066 fn quickcheck_create(s: String) {
1067 let repr = Repr::new(&s).unwrap();
1068 assert_eq!(repr.as_str(), s);
1069 assert_eq!(repr.len(), s.len());
1070 }
1071
1072 #[test_case(0; "empty")]
1073 #[test_case(10; "short")]
1074 #[test_case(64; "long")]
1075 #[test_case(EIGHTEEN_MB; "huge")]
1076 fn test_with_capacity(cap: usize) {
1077 let r = Repr::with_capacity(cap).unwrap();
1078 assert!(r.capacity() >= MAX_SIZE);
1079 assert_eq!(r.len(), 0);
1080 }
1081
1082 #[test_case(""; "empty")]
1083 #[test_case("abc"; "short")]
1084 #[test_case("hello world! I am a longer string 🦀"; "long")]
1085 fn test_from_utf8_valid(s: &'static str) {
1086 let bytes = s.as_bytes();
1087 let r = Repr::from_utf8(bytes).expect("valid UTF-8");
1088
1089 assert_eq!(r.as_str(), s);
1090 assert_eq!(r.len(), s.len());
1091 }
1092
1093 #[quickcheck]
1094 #[cfg_attr(miri, ignore)]
1095 fn quickcheck_from_utf8(buf: Vec<u8>) {
1096 match (core::str::from_utf8(&buf), Repr::from_utf8(&buf)) {
1097 (Ok(s), Ok(r)) => {
1098 assert_eq!(r.as_str(), s);
1099 assert_eq!(r.len(), s.len());
1100 }
1101 (Err(e), Err(r)) => assert_eq!(e, r),
1102 _ => panic!("core::str and Repr differ on what is valid UTF-8!"),
1103 }
1104 }
1105
1106 #[test_case(String::new(), true; "empty should inline")]
1107 #[test_case(String::new(), false; "empty not inline")]
1108 #[test_case(String::with_capacity(10), true ; "empty with small capacity inline")]
1109 #[test_case(String::with_capacity(10), false ; "empty with small capacity not inline")]
1110 #[test_case(String::with_capacity(128), true ; "empty with large capacity inline")]
1111 #[test_case(String::with_capacity(128), false ; "empty with large capacity not inline")]
1112 #[test_case(String::from("nyc 🗽"), true; "short should inline")]
1113 #[test_case(String::from("nyc 🗽"), false ; "short not inline")]
1114 #[test_case(String::from("this is a really long string, which is intended"), true; "long")]
1115 #[test_case(String::from("this is a really long string, which is intended"), false; "long not inline")]
1116 #[test_case(EIGHTEEN_MB_STR.to_string(), true ; "huge should inline")]
1117 #[test_case(EIGHTEEN_MB_STR.to_string(), false ; "huge not inline")]
1118 fn test_from_string(s: String, try_to_inline: bool) {
1119 // note: when cloning a String it truncates capacity, which is why we measure these values
1120 // before cloning the string
1121 let s_len = s.len();
1122 let s_cap = s.capacity();
1123 let s_str = s.clone();
1124
1125 let r = Repr::from_string(s, try_to_inline).unwrap();
1126
1127 assert_eq!(r.len(), s_len);
1128 assert_eq!(r.as_str(), s_str.as_str());
1129
1130 if s_cap == 0 || (try_to_inline && s_len <= MAX_SIZE) {
1131 // we should inline the string, if we were asked to, and the length of the string would
1132 // fit inline, meaning we would truncate capacity
1133 assert!(!r.is_heap_allocated());
1134 } else {
1135 assert!(r.is_heap_allocated());
1136 }
1137 }
1138
1139 #[quickcheck]
1140 #[cfg_attr(miri, ignore)]
1141 fn quickcheck_from_string(s: String, try_to_inline: bool) {
1142 let r = Repr::from_string(s.clone(), try_to_inline).unwrap();
1143
1144 assert_eq!(r.len(), s.len());
1145 assert_eq!(r.as_str(), s.as_str());
1146
1147 if s.capacity() == 0 {
1148 // we should always inline the string, if the length of the source string is 0
1149 assert!(!r.is_heap_allocated());
1150 } else if s.capacity() <= MAX_SIZE {
1151 // we should inline the string, if we were asked to
1152 assert_eq!(!r.is_heap_allocated(), try_to_inline);
1153 } else {
1154 assert!(r.is_heap_allocated());
1155 }
1156 }
1157
1158 #[test_case(""; "empty")]
1159 #[test_case("nyc 🗽"; "short")]
1160 #[test_case("this is a really long string, which is intended"; "long")]
1161 fn test_into_string(control: &'static str) {
1162 let r = Repr::new(control).unwrap();
1163 let s = r.into_string();
1164
1165 assert_eq!(control.len(), s.len());
1166 assert_eq!(control, s.as_str());
1167
1168 // test StaticStr variant
1169 let r = Repr::const_new(control);
1170 let s = r.into_string();
1171
1172 assert_eq!(control.len(), s.len());
1173 assert_eq!(control, s.as_str());
1174 }
1175
1176 #[quickcheck]
1177 #[cfg_attr(miri, ignore)]
1178 fn quickcheck_into_string(control: String) {
1179 let r = Repr::new(&control).unwrap();
1180 let s = r.into_string();
1181
1182 assert_eq!(control.len(), s.len());
1183 assert_eq!(control, s.as_str());
1184 }
1185
1186 #[test_case("", "a", false; "empty")]
1187 #[test_case("", "🗽", false; "empty_emoji")]
1188 #[test_case("abc", "🗽🙂🦀🌈👏🐶", true; "inline_to_heap")]
1189 #[test_case("i am a long string that will be on the heap", "extra", true; "heap_to_heap")]
1190 fn test_push_str(control: &'static str, append: &'static str, is_heap: bool) {
1191 let mut r = Repr::new(control).unwrap();
1192 let mut c = String::from(control);
1193
1194 r.push_str(append);
1195 c.push_str(append);
1196
1197 assert_eq!(r.as_str(), c.as_str());
1198 assert_eq!(r.len(), c.len());
1199
1200 assert_eq!(r.is_heap_allocated(), is_heap);
1201
1202 // test StaticStr variant
1203 let mut r = Repr::const_new(control);
1204 let mut c = String::from(control);
1205
1206 r.push_str(append);
1207 c.push_str(append);
1208
1209 assert_eq!(r.as_str(), c.as_str());
1210 assert_eq!(r.len(), c.len());
1211
1212 assert_eq!(r.is_heap_allocated(), is_heap);
1213 }
1214
1215 #[quickcheck]
1216 #[cfg_attr(miri, ignore)]
1217 fn quickcheck_push_str(control: String, append: String) {
1218 let mut r = Repr::new(&control).unwrap();
1219 let mut c = control;
1220
1221 r.push_str(&append);
1222 c.push_str(&append);
1223
1224 assert_eq!(r.as_str(), c.as_str());
1225 assert_eq!(r.len(), c.len());
1226 }
1227
1228 #[test_case(&[42; 0], &[42; EIGHTEEN_MB]; "empty_to_heap_capacity")]
1229 #[test_case(&[42; 8], &[42; EIGHTEEN_MB]; "inline_to_heap_capacity")]
1230 #[test_case(&[42; 128], &[42; EIGHTEEN_MB]; "heap_inline_to_heap_capacity")]
1231 #[test_case(&[42; EIGHTEEN_MB], &[42; 64]; "heap_capacity_to_heap_capacity")]
1232 fn test_push_str_from_buf(buf: &[u8], append: &[u8]) {
1233 // The goal of this test is to exercise the scenario when our capacity is stored on the heap
1234
1235 let control = unsafe { core::str::from_utf8_unchecked(buf) };
1236 let append = unsafe { core::str::from_utf8_unchecked(append) };
1237
1238 let mut r = Repr::new(control).unwrap();
1239 let mut c = String::from(control);
1240
1241 r.push_str(append);
1242 c.push_str(append);
1243
1244 assert_eq!(r.as_str(), c.as_str());
1245 assert_eq!(r.len(), c.len());
1246
1247 assert!(r.is_heap_allocated());
1248 }
1249
1250 #[test_case("", 0, false; "empty_zero")]
1251 #[test_case("", 10, false; "empty_small")]
1252 #[test_case("", 64, true; "empty_large")]
1253 #[test_case("abc", 0, false; "short_zero")]
1254 #[test_case("abc", 8, false; "short_small")]
1255 #[test_case("abc", 64, true; "short_large")]
1256 #[test_case("I am a long string that will be on the heap", 0, true; "large_zero")]
1257 #[test_case("I am a long string that will be on the heap", 10, true; "large_small")]
1258 #[test_case("I am a long string that will be on the heap", EIGHTEEN_MB, true; "large_huge")]
1259 fn test_reserve(initial: &'static str, additional: usize, is_heap: bool) {
1260 let mut r = Repr::new(initial).unwrap();
1261 r.reserve(additional).unwrap();
1262
1263 assert!(r.capacity() >= initial.len() + additional);
1264 assert_eq!(r.is_heap_allocated(), is_heap);
1265
1266 // Test static_str variant
1267 let mut r = Repr::const_new(initial);
1268 r.reserve(additional).unwrap();
1269
1270 assert!(r.capacity() >= initial.len() + additional);
1271 assert_eq!(r.is_heap_allocated(), is_heap);
1272 }
1273
1274 #[test]
1275 fn test_reserve_overflow() {
1276 let mut r = Repr::new("abc").unwrap();
1277 let err = r.reserve(usize::MAX).unwrap_err();
1278 assert_eq!(err, ReserveError(()));
1279 }
1280
1281 #[test_case(""; "empty")]
1282 #[test_case("abc"; "short")]
1283 #[test_case("i am a longer string that will be on the heap"; "long")]
1284 #[test_case(EIGHTEEN_MB_STR; "huge")]
1285 fn test_clone(initial: &'static str) {
1286 let r_a = Repr::new(initial).unwrap();
1287 let r_b = r_a.clone();
1288
1289 assert_eq!(r_a.as_str(), initial);
1290 assert_eq!(r_a.len(), initial.len());
1291
1292 assert_eq!(r_a.as_str(), r_b.as_str());
1293 assert_eq!(r_a.len(), r_b.len());
1294 assert_eq!(r_a.capacity(), r_b.capacity());
1295 assert_eq!(r_a.is_heap_allocated(), r_b.is_heap_allocated());
1296
1297 // test StaticStr variant
1298 let r_a = Repr::const_new(initial);
1299 let r_b = r_a.clone();
1300
1301 assert_eq!(r_a.as_str(), initial);
1302 assert_eq!(r_a.len(), initial.len());
1303
1304 assert_eq!(r_a.as_str(), r_b.as_str());
1305 assert_eq!(r_a.len(), r_b.len());
1306 assert_eq!(r_a.capacity(), r_b.capacity());
1307 assert_eq!(r_a.is_heap_allocated(), r_b.is_heap_allocated());
1308 }
1309
1310 #[test_case(Repr::const_new(""), Repr::const_new(""); "empty clone from static")]
1311 #[test_case(Repr::const_new("abc"), Repr::const_new("efg"); "short clone from static")]
1312 #[test_case(Repr::new("i am a longer string that will be on the heap").unwrap(), Repr::const_new(EIGHTEEN_MB_STR); "long clone from static")]
1313 #[test_case(Repr::const_new(""), Repr::const_new(""); "empty clone from inline")]
1314 #[test_case(Repr::const_new("abc"), Repr::const_new("efg"); "short clone from inline")]
1315 #[test_case(Repr::new("i am a longer string that will be on the heap").unwrap(), Repr::const_new("small"); "long clone from inline")]
1316 #[test_case(Repr::const_new(""), Repr::new(EIGHTEEN_MB_STR).unwrap(); "empty clone from heap")]
1317 #[test_case(Repr::const_new("abc"), Repr::new(EIGHTEEN_MB_STR).unwrap(); "short clone from heap")]
1318 #[test_case(Repr::new("i am a longer string that will be on the heap").unwrap(), Repr::new(EIGHTEEN_MB_STR).unwrap(); "long clone from heap")]
1319 fn test_clone_from(mut initial: Repr, source: Repr) {
1320 initial.clone_from(&source);
1321 assert_eq!(initial.as_str(), source.as_str());
1322 assert_eq!(initial.is_heap_allocated(), source.is_heap_allocated());
1323 }
1324
1325 #[quickcheck]
1326 #[cfg_attr(miri, ignore)]
1327 fn quickcheck_clone(initial: String) {
1328 let r_a = Repr::new(&initial).unwrap();
1329 let r_b = r_a.clone();
1330
1331 assert_eq!(r_a.as_str(), initial);
1332 assert_eq!(r_a.len(), initial.len());
1333
1334 assert_eq!(r_a.as_str(), r_b.as_str());
1335 assert_eq!(r_a.len(), r_b.len());
1336 assert_eq!(r_a.capacity(), r_b.capacity());
1337 assert_eq!(r_a.is_heap_allocated(), r_b.is_heap_allocated());
1338 }
1339 }