Debian Codegraph @

src/tests.rs

raw ◀ ▶
1 Debian patch touch this file
•1 #![cfg(feature = "std")]
2 use alloc::borrow::Cow;
3 use alloc::boxed::Box;
4 use alloc::string::{String, ToString};
5 use alloc::vec::Vec;
6 use core::str::FromStr;
7 use core::{num, slice};
8
9 use proptest::collection::SizeRange;
10 use proptest::prelude::*;
11 use test_case::test_case;
12 use test_strategy::proptest;
13
14 use crate::{format_compact, CompactString, ToCompactString};
15
16 #[cfg(target_pointer_width = "64")]
17 const MAX_SIZE: usize = 24;
18 #[cfg(target_pointer_width = "32")]
19 const MAX_SIZE: usize = 12;
20
21 const SIXTEEN_MB: usize = 16 * 1024 * 1024;
22
23 /// generates random unicode strings, upto 80 chars long
24 pub(crate) fn rand_unicode() -> impl Strategy<Value = String> {
25 proptest::collection::vec(proptest::char::any(), 0..80).prop_map(|v| v.into_iter().collect())
26 }
27
28 /// generates a random collection of bytes, upto 80 bytes long
29 pub(crate) fn rand_bytes() -> impl Strategy<Value = Vec<u8>> {
30 proptest::collection::vec(any::<u8>(), 0..80)
31 }
32
33 /// Generates byte sequences that interleave valid (often multibyte) UTF-8 runs with arbitrary byte
34 /// fragments. Uniformly random bytes are almost never long valid non-ASCII runs, so this is what
35 /// exercises `from_utf8_lossy` bulk-copying a valid multibyte run that sits between two errors.
36 pub(crate) fn rand_utf8_with_errors() -> impl Strategy<Value = Vec<u8>> {
37 let segment = prop_oneof![
38 rand_unicode().prop_map(String::into_bytes),
39 proptest::collection::vec(any::<u8>(), 0..8),
40 ];
41 proptest::collection::vec(segment, 0..20).prop_map(|segments| segments.concat())
42 }
43
44 /// generates a random collection of `u16`s, upto 80 elements long
45 pub(crate) fn rand_u16s() -> impl Strategy<Value = Vec<u16>> {
46 proptest::collection::vec(any::<u16>(), 0..80)
47 }
48
49 /// [`proptest::strategy::Strategy`] that generates [`String`]s with up to `len` bytes
50 pub(crate) fn rand_unicode_with_range(
51 range: impl Into<SizeRange>,
52 ) -> impl Strategy<Value = String> {
53 proptest::collection::vec(proptest::char::any(), range).prop_map(|v| v.into_iter().collect())
54 }
55
56 /// generates groups upto 40 strings long of random unicode strings, upto 80 chars long
57 fn rand_unicode_collection() -> impl Strategy<Value = Vec<String>> {
58 proptest::collection::vec(rand_unicode(), 0..40)
59 }
60
61 /// Asserts a [`CompactString`] is allocated properly
62 fn assert_allocated_properly(compact: &CompactString) {
63 if compact.len() <= MAX_SIZE {
64 assert!(!compact.is_heap_allocated())
65 } else {
66 assert!(compact.is_heap_allocated())
67 }
68 }
69
70 #[proptest]
71 #[cfg_attr(miri, ignore)]
72 fn proptest_strings_roundtrip(#[strategy(rand_unicode())] word: String) {
73 let compact = CompactString::new(&word);
74 prop_assert_eq!(&word, &compact);
75 }
76
77 #[proptest]
78 #[cfg_attr(miri, ignore)]
79 fn proptest_strings_allocated_properly(#[strategy(rand_unicode())] word: String) {
80 let compact = CompactString::new(word);
81 assert_allocated_properly(&compact);
82 }
83
84 #[test]
85 fn test_new_owned_string_reuses_heap_allocation() {
86 let value = "a".repeat(MAX_SIZE + 1);
87 let ptr = value.as_ptr();
88 let capacity = value.capacity();
89 let compact = CompactString::new(value);
90 assert_eq!(compact.as_ptr(), ptr);
91 assert_eq!(compact.capacity(), capacity);
92 }
93
94 #[proptest]
95 #[cfg_attr(miri, ignore)]
96 fn proptest_char_iterator_roundtrips(#[strategy(rand_unicode())] word: String) {
97 let compact: CompactString = word.clone().chars().collect();
98 prop_assert_eq!(&word, &compact)
99 }
100
101 #[proptest]
102 #[cfg_attr(miri, ignore)]
103 fn proptest_string_iterator_roundtrips(
104 #[strategy(rand_unicode_collection())] collection: Vec<String>,
105 ) {
106 let compact: CompactString = collection.clone().into_iter().collect();
107 let word: String = collection.into_iter().collect();
108 prop_assert_eq!(&word, &compact);
109 }
110
111 #[proptest]
112 #[cfg_attr(miri, ignore)]
113 fn proptest_from_bytes_roundtrips(#[strategy(rand_unicode())] word: String) {
114 let bytes = word.into_bytes();
115 let compact = CompactString::from_utf8(&bytes).unwrap();
116 let word = String::from_utf8(bytes).unwrap();
117
118 prop_assert_eq!(compact, word);
119 }
120
121 #[proptest]
122 #[cfg_attr(miri, ignore)]
123 fn proptest_from_bytes_only_valid_utf8(#[strategy(rand_bytes())] bytes: Vec<u8>) {
124 let compact_result = CompactString::from_utf8(&bytes);
125 let word_result = String::from_utf8(bytes);
126
127 match (compact_result, word_result) {
128 (Ok(c), Ok(s)) => prop_assert_eq!(c, s),
129 (Err(c_err), Err(s_err)) => prop_assert_eq!(c_err, s_err.utf8_error()),
130 _ => panic!("CompactString and core::str read UTF-8 differently?"),
131 }
132 }
133
134 #[proptest]
135 #[cfg_attr(miri, ignore)]
136 fn proptest_from_lossy_cow_roundtrips(#[strategy(rand_bytes())] bytes: Vec<u8>) {
137 let cow = String::from_utf8_lossy(&bytes[..]);
138 let compact = CompactString::from(cow.clone());
139 prop_assert_eq!(cow, compact);
140 }
141
142 #[test]
143 fn test_as_mut_bytes_only_exposes_initialized_data() {
144 for mut compact in [
145 CompactString::new("inline"),
146 CompactString::with_capacity(100),
147 ] {
148 let len = compact.len();
149
150 // SAFETY: We do not modify the buffer, so the string remains valid UTF-8.
151 let bytes = unsafe { compact.as_mut_bytes() };
152
153 assert_eq!(bytes.len(), len);
154 for byte in bytes {
155 // Reading each byte under Miri verifies that `as_mut_bytes` only exposes initialized
156 // string data through a `[u8]` reference.
157 core::hint::black_box(*byte);
158 }
159 }
160 }
161
162 #[test]
163 fn test_spare_capacity_mut() {
164 let mut inline = CompactString::new("");
165 let spare = unsafe { inline.spare_capacity_mut() };
166 assert_eq!(spare.len(), MAX_SIZE);
167 for slot in spare {
168 slot.write(b'a');
169 }
170 // SAFETY: Every byte is initialized to ASCII, including the inline tag byte, so the full
171 // buffer is valid UTF-8.
172 unsafe { inline.set_len(MAX_SIZE) };
173 assert_eq!(inline, "a".repeat(MAX_SIZE));
174
175 let mut heap = CompactString::with_capacity(100);
176 let suffix = b"hello";
177 let spare = unsafe { heap.spare_capacity_mut() };
178 for (slot, byte) in spare.iter_mut().zip(suffix) {
179 slot.write(*byte);
180 }
181 // SAFETY: The first `suffix.len()` bytes were initialized to valid UTF-8 above.
182 unsafe { heap.set_len(suffix.len()) };
183 assert_eq!(heap, "hello");
184 }
185
186 #[proptest]
187 #[cfg_attr(miri, ignore)]
188 fn proptest_reserve_and_write_bytes(#[strategy(rand_unicode())] word: String) {
189 let mut compact = CompactString::default();
190 prop_assert!(compact.is_empty());
191
192 // reserve enough space to write our bytes
193 compact.reserve(word.len());
194
195 // SAFETY: We only initialize a prefix of the spare capacity, and don't overwrite the inline
196 // tag unless `word` fills the entire inline buffer with valid UTF-8.
197 let spare = unsafe { compact.spare_capacity_mut() };
198 for (slot, byte) in spare.iter_mut().zip(word.bytes()) {
199 slot.write(byte);
200 }
201
202 // SAFETY: We know this is the length of our string, since `compact` started with 0 bytes
203 // and we just wrote `word.len()` bytes
204 unsafe { compact.set_len(word.len()) }
205
206 prop_assert_eq!(&word, &compact);
207 }
208
209 #[proptest]
210 #[cfg_attr(miri, ignore)]
211 fn proptest_reserve_and_write_bytes_allocated_properly(#[strategy(rand_unicode())] word: String) {
212 let mut compact = CompactString::default();
213 prop_assert!(compact.is_empty());
214
215 // reserve enough space to write our bytes
216 compact.reserve(word.len());
217
218 // SAFETY: We only initialize a prefix of the spare capacity, and don't overwrite the inline
219 // tag unless `word` fills the entire inline buffer with valid UTF-8.
220 let spare = unsafe { compact.spare_capacity_mut() };
221 for (slot, byte) in spare.iter_mut().zip(word.bytes()) {
222 slot.write(byte);
223 }
224
225 // SAFETY: We know this is the length of our string, since `compact` started with 0 bytes
226 // and we just wrote `word.len()` bytes
227 unsafe { compact.set_len(word.len()) }
228
229 prop_assert_eq!(compact.len(), word.len());
230
231 // The string should be heap allocated if `word` was > MAX_SIZE
232 //
233 // NOTE: The reserve and write API's don't currently support the Packed representation
234 prop_assert_eq!(compact.is_heap_allocated(), word.len() > MAX_SIZE);
235 }
236
237 #[proptest]
238 #[cfg_attr(miri, ignore)]
239 fn proptest_arbitrary_compact_string_converts_to_string(#[strategy(rand_unicode())] word: String) {
240 let compact = CompactString::new(&word);
241 let result = String::from(compact);
242
243 prop_assert_eq!(result.len(), word.len());
244 prop_assert_eq!(result, word);
245 }
246
247 #[proptest]
248 #[cfg_attr(miri, ignore)]
249 fn proptest_extend_chars_allocated_properly(
250 #[strategy(rand_unicode())] start: String,
251 #[strategy(rand_unicode())] extend: String,
252 ) {
253 let mut compact = CompactString::new(&start);
254 compact.extend(extend.chars());
255
256 let mut control = start.clone();
257 #[allow(clippy::string_extend_chars)]
258 control.extend(extend.chars());
259
260 prop_assert_eq!(&compact, &control);
261 assert_allocated_properly(&compact);
262 }
263
264 #[proptest]
265 #[cfg_attr(miri, ignore)]
266 fn proptest_truncate(#[strategy(rand_unicode())] mut control: String, val: u8) {
267 let initial_len = control.len();
268 let mut compact = CompactString::new(&control);
269
270 // turn the arbitrary number `val` into character indices
271 let new_len = control
272 .char_indices()
273 .cycle()
274 .nth(val as usize)
275 .unwrap_or_default()
276 .0;
277
278 // then truncate both strings string
279 control.truncate(new_len);
280 compact.truncate(new_len);
281
282 // assert they're equal
283 prop_assert_eq!(&control, &compact);
284 prop_assert_eq!(control.len(), compact.len());
285
286 // If we started as heap allocated, we should stay heap allocated. This prevents us from
287 // needing to deallocate the buffer on the heap
288 if initial_len > MAX_SIZE {
289 prop_assert!(compact.is_heap_allocated());
290 } else {
291 prop_assert!(!compact.is_heap_allocated());
292 }
293 }
294
295 #[proptest]
296 #[cfg_attr(miri, ignore)]
297 fn proptest_from_utf16_roundtrips(#[strategy(rand_unicode())] control: String) {
298 let utf16_buf: Vec<u16> = control.encode_utf16().collect();
299 let compact = CompactString::from_utf16(utf16_buf).unwrap();
300
301 assert_eq!(compact, control);
302 }
303
304 #[proptest]
305 #[cfg_attr(miri, ignore)]
306 fn proptest_from_utf16_random(#[strategy(rand_u16s())] buf: Vec<u16>) {
307 let compact = CompactString::from_utf16(&buf);
308 let std_str = String::from_utf16(&buf);
309
310 match (compact, std_str) {
311 (Ok(c), Ok(s)) => assert_eq!(c, s),
312 (Err(_), Err(_)) => (),
313 (c_res, s_res) => panic!(
314 "CompactString and String decode UTF-16 differently? {:?} {:?}",
315 c_res, s_res
316 ),
317 }
318 }
319
320 #[proptest]
321 #[cfg_attr(miri, ignore)]
322 fn proptest_from_utf16_lossy_roundtrips(#[strategy(rand_unicode())] control: String) {
323 let utf16_buf: Vec<u16> = control.encode_utf16().collect();
324 let compact = CompactString::from_utf16_lossy(utf16_buf);
325
326 assert_eq!(compact, control);
327 }
328
329 #[proptest]
330 #[cfg_attr(miri, ignore)]
331 fn proptest_from_utf16_lossy_random(#[strategy(rand_u16s())] buf: Vec<u16>) {
332 let control = String::from_utf16_lossy(&buf);
333 let compact = CompactString::from_utf16_lossy(&buf);
334 assert_eq!(compact, control);
335 }
336
337 #[proptest]
338 #[cfg_attr(miri, ignore)]
339 fn proptest_remove(#[strategy(rand_unicode_with_range(1..80))] mut control: String, val: u8) {
340 let initial_len = control.len();
341 let mut compact = CompactString::new(&control);
342
343 let idx = control
344 .char_indices()
345 .cycle()
346 .nth(val as usize)
347 .unwrap_or_default()
348 .0;
349
350 let control_char = control.remove(idx);
351 let compact_char = compact.remove(idx);
352
353 prop_assert_eq!(control_char, compact_char);
354 prop_assert_eq!(control_char, compact_char);
355 prop_assert_eq!(control.len(), compact.len());
356
357 // If we started as heap allocated, we should stay heap allocated. This prevents us from
358 // needing to deallocate the buffer on the heap
359 if initial_len > MAX_SIZE {
360 prop_assert!(compact.is_heap_allocated());
361 } else {
362 prop_assert!(!compact.is_heap_allocated());
363 }
364 }
365
366 #[proptest]
367 #[cfg_attr(miri, ignore)]
368 fn proptest_from_utf8_unchecked(#[strategy(rand_unicode())] std_str: String) {
369 let bytes = std_str.as_bytes();
370 let compact = unsafe { CompactString::from_utf8_unchecked(bytes) };
371
372 // we should be able to read the underlying bytes
373 assert_eq!(compact.as_bytes(), std_str.as_bytes());
374 assert_eq!(compact.as_bytes(), bytes);
375
376 // make sure the length is correct
377 assert_eq!(compact.len(), bytes.len());
378
379 // check if we were valid UTF-8, if so, assert the data written into the CompactString is
380 // correct
381 let data_is_valid = core::str::from_utf8(bytes);
382 let compact_is_valid = core::str::from_utf8(compact.as_bytes());
383 let std_str_is_valid = core::str::from_utf8(std_str.as_bytes());
384
385 match (data_is_valid, compact_is_valid, std_str_is_valid) {
386 (Ok(d), Ok(c), Ok(s)) => {
387 // if we get &str's back, make sure they're all equal
388 assert_eq!(d, c);
389 assert_eq!(c, s);
390 }
391 (Err(d), Err(c), Err(s)) => {
392 // if we get errors back, the errors should be the same
393 assert_eq!(d, c);
394 assert_eq!(c, s);
395 }
396 _ => panic!("data, CompactString, and String disagreed?"),
397 }
398 }
399
400 #[proptest]
401 #[cfg_attr(miri, ignore)]
402 fn proptest_to_ascii_uppercase(#[strategy(rand_unicode())] control: String) {
403 let compact = CompactString::new(&control);
404
405 let control = control.to_ascii_uppercase();
406 let compact = compact.to_ascii_uppercase();
407
408 prop_assert_eq!(control, compact);
409 }
410
411 #[proptest]
412 #[cfg_attr(miri, ignore)]
413 fn proptest_to_ascii_lowercase(#[strategy(rand_unicode())] control: String) {
414 let compact = CompactString::new(&control);
415
416 let control = control.to_ascii_lowercase();
417 let compact = compact.to_ascii_lowercase();
418
419 prop_assert_eq!(control, compact);
420 }
421
422 #[proptest]
423 #[cfg_attr(miri, ignore)]
424 fn proptest_to_uppercase(#[strategy(rand_unicode())] control: String) {
425 let compact = CompactString::new(&control);
426
427 let control = control.to_uppercase();
428 let compact = compact.to_uppercase();
429
430 prop_assert_eq!(control, compact);
431 }
432
433 #[proptest]
434 #[cfg_attr(miri, ignore)]
435 fn proptest_to_lowercase(#[strategy(rand_unicode())] control: String) {
436 let compact = CompactString::new(&control);
437
438 let control = control.to_lowercase();
439 let compact = compact.to_lowercase();
440
441 prop_assert_eq!(control, compact);
442 }
443
444 #[test]
445 fn test_const_creation() {
446 const EMPTY: CompactString = CompactString::const_new("");
447 const SHORT: CompactString = CompactString::const_new("rust");
448
449 const EMPTY_STATIC_STR: CompactString = CompactString::const_new("");
450 const SHORT_STATIC_STR: CompactString = CompactString::const_new("rust");
451
452 #[cfg(target_pointer_width = "64")]
453 const PACKED: CompactString = CompactString::const_new("i am 24 characters long!");
454 #[cfg(target_pointer_width = "32")]
455 const PACKED: CompactString = CompactString::const_new("i am 12 char");
456
457 const PACKED_STATIC_STR0: CompactString = CompactString::const_new("i am 24 characters long!");
458 const PACKED_STATIC_STR1: CompactString = CompactString::const_new("i am 12 char");
459
460 assert_eq!(EMPTY, CompactString::new(""));
461 assert_eq!(SHORT, CompactString::new("rust"));
462
463 assert_eq!(EMPTY_STATIC_STR, CompactString::new(""));
464 assert_eq!(SHORT_STATIC_STR, CompactString::new("rust"));
465
466 #[cfg(target_pointer_width = "64")]
467 assert_eq!(PACKED, CompactString::new("i am 24 characters long!"));
468 #[cfg(target_pointer_width = "32")]
469 assert_eq!(PACKED, CompactString::new("i am 12 char"));
470
471 assert_eq!(
472 PACKED_STATIC_STR0,
473 CompactString::new("i am 24 characters long!")
474 );
475 assert_eq!(PACKED_STATIC_STR1, CompactString::new("i am 12 char"));
476 }
477
478 #[test]
479 fn test_short_ascii() {
480 // always inlined on all archs
481 let strs = vec!["nyc", "statue", "liberty", "img_1234.png"];
482
483 for s in strs {
484 let compact = CompactString::new(s);
485 assert_eq!(compact, s);
486 assert_eq!(s, compact);
487 assert!(!compact.is_heap_allocated());
488 }
489 }
490
491 #[test]
492 fn test_short_unicode() {
493 let strs = vec![
494 ("🦀", false),
495 ("🌧☀️", false),
496 // str is 12 bytes long, and leading character is non-ASCII
497 ("咬𓅈ꁈ:_", false),
498 ];
499
500 for (s, is_heap) in strs {
501 let compact = CompactString::new(s);
502 assert_eq!(compact, s);
503 assert_eq!(s, compact);
504 assert_eq!(compact.is_heap_allocated(), is_heap);
505 }
506 }
507
508 #[test]
509 fn test_medium_ascii() {
510 let strs = vec![
511 "rustconf 2021",
512 "new york city",
513 "nyc pizza is good",
514 "test the 24 char limit!!",
515 ];
516
517 for s in strs {
518 let compact = CompactString::new(s);
519 assert_eq!(compact, s);
520 assert_eq!(s, compact);
521
522 #[cfg(target_pointer_width = "64")]
523 let is_heap = false;
524 #[cfg(target_pointer_width = "32")]
525 let is_heap = true;
526 assert_eq!(compact.is_heap_allocated(), is_heap);
527 }
528 }
529
530 #[test]
531 fn test_medium_unicode() {
532 let strs = vec![
533 ("☕️👀😁🎉", false),
534 // str is 24 bytes long, and leading character is non-ASCII
535 ("🦀😀😃😄😁🦀", false),
536 ];
537
538 #[allow(unused_variables)]
539 for (s, is_heap) in strs {
540 let compact = CompactString::new(s);
541 assert_eq!(compact, s);
542 assert_eq!(s, compact);
543
544 #[cfg(target_pointer_width = "32")]
545 let is_heap = true;
546
547 assert_eq!(compact.is_heap_allocated(), is_heap);
548 }
549 }
550
551 #[test]
552 fn test_from_str_trait() {
553 let s = "hello_world";
554
555 // Until the never type `!` is stabilized, we have to unwrap here
556 let c = CompactString::from_str(s).unwrap();
557
558 assert_eq!(s, c);
559 }
560
561 #[test]
562 #[cfg_attr(target_pointer_width = "32", ignore)]
563 fn test_from_char_iter() {
564 let s = "\u{0} 0 \u{0}a𐀀𐀀 𐀀a𐀀";
565 let compact: CompactString = s.chars().collect();
566
567 assert!(!compact.is_heap_allocated());
568 assert_eq!(s, compact);
569 }
570
571 #[test]
572 #[cfg_attr(target_pointer_width = "32", ignore)]
573 fn test_extend_packed_from_empty() {
574 let s = " 0\u{80}A\u{0}𐀀 𐀀¡a𐀀0";
575
576 let mut compact = CompactString::new(s);
577 assert!(!compact.is_heap_allocated());
578
579 // extend from an empty iterator
580 compact.extend("".chars());
581
582 // we should still be heap allocated
583 assert!(!compact.is_heap_allocated());
584 }
585
586 #[test_case(CompactString::from(""); "inline")]
587 #[test_case(CompactString::const_new(""); "static_str")]
588 fn test_pop_empty(mut compact: CompactString) {
589 let num_pops = 256;
590 (0..num_pops).for_each(|_| {
591 let ch = compact.pop();
592 assert!(ch.is_none());
593 });
594 assert!(compact.is_empty());
595 assert_eq!(compact, "");
596 }
597
598 #[test]
599 fn test_extend_from_empty_strs() {
600 let strs = vec![
601 "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
602 "", "",
603 ];
604 let compact: CompactString = strs.clone().into_iter().collect();
605
606 assert_eq!(compact, "");
607 assert!(compact.is_empty());
608 assert!(!compact.is_heap_allocated());
609 }
610
611 #[test]
612 fn test_compact_str_is_send_and_sync() {
613 fn is_send_and_sync<T: Send + Sync>() {}
614 is_send_and_sync::<CompactString>();
615 }
616
617 #[test_case(CompactString::default(); "inline")]
618 #[test_case(CompactString::const_new(""); "static_str")]
619 fn test_fmt_write(mut compact: CompactString) {
620 use core::fmt::Write;
621
622 write!(compact, "test").unwrap();
623 assert_eq!(compact, "test");
624
625 writeln!(compact, "{}", 1234).unwrap();
626 assert_eq!(compact, "test1234\n");
627
628 #[allow(clippy::write_literal)]
629 write!(compact, "{:>8} {} {:<8}", "some", "more", "words").unwrap();
630 assert_eq!(compact, "test1234\n some more words ");
631 }
632
633 #[allow(clippy::unnecessary_to_owned, clippy::op_ref)]
634 #[test]
635 fn test_plus_operator() {
636 // + &CompactString
637 assert_eq!(CompactString::from("a") + &CompactString::from("b"), "ab");
638 // + &str
639 assert_eq!(CompactString::from("a") + "b", "ab");
640 // + &String
641 assert_eq!(CompactString::from("a") + &String::from("b"), "ab");
642 // + &Box<str>
643 let box_str = String::from("b").into_boxed_str();
644 assert_eq!(CompactString::from("a") + &box_str, "ab");
645 // + &Cow<'a, str>
646 let cow = Cow::from("b");
647 assert_eq!(CompactString::from("a") + &cow, "ab");
648
649 // Implementing `Add<T> for String` can break adding &String or other types to String, so we
650 // explicitly don't do this. See https://github.com/rust-lang/rust/issues/77143 for more details.
651 // Below we assert adding types to String still compiles
652
653 // String + &CompactString
654 assert_eq!(String::from("a") + &CompactString::from("b"), "ab");
655 // String + &String
656 assert_eq!(String::from("a") + &("b".to_string()), "ab");
657 // String + &str
658 assert_eq!(String::from("a") + "b", "ab");
659 }
660
661 #[allow(clippy::unnecessary_to_owned, clippy::op_ref)]
662 #[test]
663 fn test_plus_operator_static_str() {
664 // + &CompactString
665 assert_eq!(
666 CompactString::const_new("a") + &CompactString::const_new("b"),
667 "ab"
668 );
669 // + &str
670 assert_eq!(CompactString::const_new("a") + "b", "ab");
671 // + &String
672 assert_eq!(CompactString::const_new("a") + &String::from("b"), "ab");
673 // + &Box<str>
674 let box_str = String::from("b").into_boxed_str();
675 assert_eq!(CompactString::const_new("a") + &box_str, "ab");
676 // + &Cow<'a, str>
677 let cow = Cow::from("b");
678 assert_eq!(CompactString::const_new("a") + &cow, "ab");
679
680 // Implementing `Add<T> for String` can break adding &String or other types to String, so we
681 // explicitly don't do this. See https://github.com/rust-lang/rust/issues/77143 for more details.
682 // Below we assert adding types to String still compiles
683
684 // String + &CompactString
685 assert_eq!(String::from("a") + &CompactString::const_new("b"), "ab");
686 // String + &String
687 assert_eq!(String::from("a") + &("b".to_string()), "ab");
688 // String + &str
689 assert_eq!(String::from("a") + "b", "ab");
690 }
691
692 #[test]
693 fn test_plus_equals_operator() {
694 let mut m = CompactString::from("a");
695 m += "b";
696 assert_eq!(m, "ab");
697 }
698
699 #[test]
700 fn test_plus_equals_operator_static_str() {
701 let mut m = CompactString::const_new("a");
702 m += "b";
703 assert_eq!(m, "ab");
704 }
705
706 // Allow these lints because we're explicitly testing impls for owned types and
707 // reference types.
708 #[allow(clippy::cmp_owned)]
709 #[allow(clippy::op_ref)]
710 #[test]
711 fn test_eq_operator() {
712 let x = CompactString::const_new("foo");
713 let y = x.clone();
714
715 macro_rules! test_impl {
716 ($a:expr, $b:expr) => {
717 let _ = $a == $b;
718 let _ = &$a == $b;
719 let _ = &$a == &$b;
720
721 let _ = $b == $a;
722 let _ = &$b == $a;
723 let _ = &$b == &$a;
724 };
725 }
726
727 test_impl!("a", x);
728 test_impl!(String::from("a"), x);
729 test_impl!(Cow::Borrowed("a"), x);
730 test_impl!(y, x);
731 }
732
733 #[test]
734 fn test_u8_to_compact_string() {
735 let vals = [u8::MIN, 1, 42, u8::MAX - 2, u8::MAX - 1, u8::MAX];
736
737 for x in &vals {
738 let c = x.to_compact_string();
739 let s = x.to_string();
740
741 assert_eq!(c, s);
742 assert!(!c.is_heap_allocated());
743 }
744 }
745
746 #[test]
747 fn test_i8_to_compact_string() {
748 let vals = [
749 i8::MIN,
750 i8::MIN + 1,
751 i8::MIN + 2,
752 -1,
753 0,
754 1,
755 42,
756 i8::MAX - 2,
757 i8::MAX - 1,
758 i8::MAX,
759 ];
760
761 for x in &vals {
762 let c = x.to_compact_string();
763 let s = x.to_string();
764
765 assert_eq!(c, s);
766 assert!(!c.is_heap_allocated());
767 }
768 }
769
770 #[test]
771 fn test_u16_to_compact_string() {
772 let vals = [u16::MIN, 1, 42, 999, u16::MAX - 2, u16::MAX - 1, u16::MAX];
773
774 for x in &vals {
775 let c = x.to_compact_string();
776 let s = x.to_string();
777
778 assert_eq!(c, s);
779 assert!(!c.is_heap_allocated());
780 }
781 }
782
783 #[test]
784 fn test_i16_to_compact_string() {
785 let vals = [
786 i16::MIN,
787 i16::MIN + 1,
788 i16::MIN + 2,
789 -42,
790 -1,
791 0,
792 1,
793 42,
794 999,
795 i16::MAX - 2,
796 i16::MAX - 1,
797 i16::MAX,
798 ];
799
800 for x in &vals {
801 let c = x.to_compact_string();
802 let s = x.to_string();
803
804 assert_eq!(c, s);
805 assert!(!c.is_heap_allocated());
806 }
807 }
808
809 #[test]
810 fn test_u32_to_compact_string() {
811 let vals = [
812 u32::MIN,
813 1,
814 42,
815 999,
816 123456789,
817 u32::MAX - 2,
818 u32::MAX - 1,
819 u32::MAX,
820 ];
821
822 for x in &vals {
823 let c = x.to_compact_string();
824 let s = x.to_string();
825
826 assert_eq!(c, s);
827 assert!(!c.is_heap_allocated());
828 }
829 }
830
831 #[test]
832 fn test_i32_to_compact_string() {
833 let vals = [
834 i32::MIN,
835 i32::MIN + 2,
836 i32::MIN + 1,
837 -12345678,
838 -42,
839 -1,
840 0,
841 1,
842 999,
843 123456789,
844 i32::MAX - 2,
845 i32::MAX - 1,
846 i32::MAX,
847 ];
848
849 for x in &vals {
850 let c = x.to_compact_string();
851 let s = x.to_string();
852
853 assert_eq!(c, s);
854 assert!(!c.is_heap_allocated());
855 }
856 }
857
858 #[test]
859 fn test_u64_to_compact_string() {
860 let vals = [
861 u64::MIN,
862 1,
863 999,
864 123456789,
865 98765432123456,
866 u64::MAX - 2,
867 u64::MAX - 1,
868 u64::MAX,
869 ];
870
871 for x in &vals {
872 let c = x.to_compact_string();
873 let s = x.to_string();
874
875 assert_eq!(c, s);
876
877 // u64 can be up-to 20 characters long, which can't be inlined on 32-bit arches
878 #[cfg(target_pointer_width = "64")]
879 assert!(!c.is_heap_allocated());
880 }
881 }
882
883 #[test]
884 fn test_i64_to_compact_string() {
885 let vals = [
886 i64::MIN,
887 i64::MIN + 1,
888 i64::MIN + 2,
889 -22222222,
890 -42,
891 0,
892 1,
893 999,
894 123456789,
895 i64::MAX - 2,
896 i64::MAX - 1,
897 i64::MAX,
898 ];
899
900 for x in &vals {
901 let c = x.to_compact_string();
902 let s = x.to_string();
903
904 assert_eq!(c, s);
905
906 // i64 can be up-to 20 characters long, which can't be inlined on 32-bit arches
907 #[cfg(target_pointer_width = "64")]
908 assert!(!c.is_heap_allocated());
909 }
910 }
911
912 #[test]
913 fn test_u128_to_compact_string() {
914 let vals = [
915 u128::MIN,
916 1,
917 999,
918 123456789,
919 u128::MAX - 2,
920 u128::MAX - 1,
921 u128::MAX,
922 ];
923
924 for x in &vals {
925 let c = x.to_compact_string();
926 let s = x.to_string();
927
928 assert_eq!(c, s);
929 }
930 }
931
932 #[test]
933 fn test_i128_to_compact_string() {
934 let vals = [
935 i128::MIN,
936 i128::MIN + 1,
937 i128::MIN + 2,
938 -22222222,
939 -42,
940 0,
941 1,
942 999,
943 123456789,
944 i128::MAX - 2,
945 i128::MAX - 1,
946 i128::MAX,
947 ];
948
949 for x in &vals {
950 let c = x.to_compact_string();
951 let s = x.to_string();
952
953 assert_eq!(c, s);
954 }
955 }
956
957 #[test]
958 fn test_bool_to_compact_string() {
959 let c = true.to_compact_string();
960 let s = true.to_string();
961
962 assert_eq!("true", c);
963 assert_eq!(c, s);
964 assert!(!c.is_heap_allocated());
965
966 let c = false.to_compact_string();
967 let s = false.to_string();
968
969 assert_eq!("false", c);
970 assert_eq!(c, s);
971 assert!(!c.is_heap_allocated());
972 }
973
974 macro_rules! assert_int_MAX_to_compact_string {
975 ($int: ty) => {
976 assert_eq!(&*<$int>::MAX.to_string(), &*<$int>::MAX.to_compact_string());
977 };
978 }
979
980 #[test]
981 fn test_to_compact_string() {
982 // Test specialisation for bool, char and String
983 assert_eq!(&*true.to_string(), "true".to_compact_string());
984 assert_eq!(&*false.to_string(), "false".to_compact_string());
985
986 assert_eq!("1", '1'.to_compact_string());
987 assert_eq!("2333", "2333".to_string().to_compact_string());
988 assert_eq!("2333", "2333".to_compact_string().to_compact_string());
989
990 // Test specialisation for int and nonzero_int using itoa
991 assert_eq!("234", 234.to_compact_string());
992 assert_eq!(
993 "234",
994 num::NonZeroU64::new(234).unwrap().to_compact_string()
995 );
996
997 assert_int_MAX_to_compact_string!(u8);
998 assert_int_MAX_to_compact_string!(i8);
999
1000 assert_int_MAX_to_compact_string!(u16);
1001 assert_int_MAX_to_compact_string!(i16);
1002
1003 assert_int_MAX_to_compact_string!(u32);
1004 assert_int_MAX_to_compact_string!(i32);
1005
1006 assert_int_MAX_to_compact_string!(u64);
1007 assert_int_MAX_to_compact_string!(i64);
1008
1009 assert_int_MAX_to_compact_string!(usize);
1010 assert_int_MAX_to_compact_string!(isize);
1011
1012 // Test specialisation for f32 and f64 using zmij
1013 // TODO: Fix bug in powerpc64, which is a little endian system
1014 #[cfg(not(all(target_arch = "powerpc64", target_pointer_width = "64")))]
1015 {
1016 assert_eq!(
1017 (&*3.2_f32.to_string(), &*288888.290028_f64.to_string()),
1018 (
1019 &*3.2_f32.to_compact_string(),
1020 &*288888.290028_f64.to_compact_string()
1021 )
1022 );
1023
1024 assert_eq!("inf", f32::INFINITY.to_compact_string());
1025 assert_eq!("-inf", f32::NEG_INFINITY.to_compact_string());
1026
1027 assert_eq!("inf", f64::INFINITY.to_compact_string());
1028 assert_eq!("-inf", f64::NEG_INFINITY.to_compact_string());
1029
1030 assert_eq!("NaN", f32::NAN.to_compact_string());
1031 assert_eq!("NaN", f64::NAN.to_compact_string());
1032 }
1033
1034 // Test generic Display implementation
1035 assert_eq!("234", "234".to_compact_string());
1036 assert_eq!("12345", format_compact!("{}", "12345"));
1037 assert_eq!("112345", format_compact!("1{}", "12345"));
1038 assert_eq!("1123452", format_compact!("1{}{}", "12345", 2));
1039 assert_eq!("11234522", format_compact!("1{}{}{}", "12345", 2, '2'));
1040 assert_eq!(
1041 "112345221000",
1042 format_compact!("1{}{}{}{}", "12345", 2, '2', 1000)
1043 );
1044
1045 // Test string longer than repr::MAX_SIZE
1046 assert_eq!(
1047 "01234567890123456789999999",
1048 format_compact!("0{}67890123456789{}", "12345", 999999)
1049 );
1050 }
1051
1052 #[test]
1053 fn test_into_string_large_string_with_excess_capacity() {
1054 let mut string = String::with_capacity(128);
1055 string.push_str("abcdefghijklmnopqrstuvwxyz");
1056 let str_addr = string.as_ptr();
1057 let str_len = string.len();
1058 let str_cap = string.capacity();
1059
1060 let compact = CompactString::from(string);
1061 let new_string = String::from(compact);
1062 let new_str_addr = new_string.as_ptr();
1063 let new_str_len = new_string.len();
1064 let new_str_cap = new_string.capacity();
1065
1066 assert_eq!(str_addr, new_str_addr);
1067 assert_eq!(str_len, new_str_len);
1068 assert_eq!(str_cap, new_str_cap);
1069 }
1070
1071 #[test]
1072 fn test_into_string_where_32_bit_capacity_is_on_heap() {
1073 let buf = vec![b'a'; SIXTEEN_MB - 1];
1074 // SAFETY: `buf` is filled with ASCII `a`s.
1075 // This primarily speeds up miri, as we don't need to check every byte
1076 // in the input buffer
1077 let string = unsafe { String::from_utf8_unchecked(buf) };
1078
1079 let str_addr = string.as_ptr();
1080 let str_len = string.len();
1081 let str_cap = string.capacity();
1082
1083 let compact = CompactString::from(string);
1084 let new_string = String::from(compact);
1085 let new_str_addr = new_string.as_ptr();
1086 let new_str_len = new_string.len();
1087 let new_str_cap = new_string.capacity();
1088
1089 assert_eq!(str_len, new_str_len);
1090
1091 if cfg!(target_pointer_width = "64") {
1092 assert_eq!(str_addr, new_str_addr);
1093 assert_eq!(str_cap, new_str_cap);
1094 } else {
1095 assert_eq!(&new_string.as_bytes()[0..10], b"aaaaaaaaaa");
1096 assert_eq!(str_len, new_str_cap);
1097 }
1098 }
1099
1100 #[test]
1101 fn test_into_string_small_string_with_excess_capacity() {
1102 let mut string = String::with_capacity(128);
1103 string.push_str("abcdef");
1104 let str_len = string.len();
1105
1106 let compact = CompactString::from(string);
1107 // we should inline this string, which would truncate capacity
1108 //
1109 // note: String truncates capacity on Clone, so truncating here seems reasonable
1110 assert!(!compact.is_heap_allocated());
1111 assert_eq!(compact.len(), str_len);
1112 assert_eq!(compact.capacity(), MAX_SIZE);
1113 }
1114
1115 #[test]
1116 fn test_from_string_buffer_small_string_with_excess_capacity() {
1117 let mut string = String::with_capacity(128);
1118 string.push_str("abcedfg");
1119
1120 let str_ptr = string.as_ptr();
1121 let str_len = string.len();
1122 let str_cap = string.capacity();
1123
1124 // using from_string_buffer should always re-use the underlying buffer
1125 let compact = CompactString::from_string_buffer(string);
1126 assert!(compact.is_heap_allocated());
1127
1128 let cpt_ptr = compact.as_ptr();
1129 let cpt_len = compact.len();
1130 let cpt_cap = compact.capacity();
1131
1132 assert_eq!(str_ptr, cpt_ptr);
1133 assert_eq!(str_len, cpt_len);
1134 assert_eq!(str_cap, cpt_cap);
1135 }
1136
1137 #[test]
1138 fn test_into_string_small_string_with_no_excess_capacity() {
1139 let string = String::from("abcdef");
1140 let str_len = string.len();
1141
1142 let compact = CompactString::from(string);
1143
1144 // we should eagerly inline the string
1145 assert!(!compact.is_heap_allocated());
1146 assert_eq!(compact.len(), str_len);
1147 assert_eq!(compact.capacity(), MAX_SIZE);
1148 }
1149
1150 #[test]
1151 fn test_from_string_buffer_small_string_with_no_excess_capacity() {
1152 let string = String::from("abcdefg");
1153
1154 let str_ptr = string.as_ptr();
1155 let str_len = string.len();
1156 let str_cap = string.capacity();
1157
1158 // using from_string_buffer should always re-use the underlying buffer
1159 let compact = CompactString::from_string_buffer(string);
1160 assert!(compact.is_heap_allocated());
1161
1162 let cpt_ptr = compact.as_ptr();
1163 let cpt_len = compact.len();
1164 let cpt_cap = compact.capacity();
1165
1166 assert_eq!(str_ptr, cpt_ptr);
1167 assert_eq!(str_len, cpt_len);
1168 assert_eq!(str_cap, cpt_cap);
1169 }
1170
1171 #[test]
1172 fn test_roundtrip_from_string_empty_string() {
1173 let string = String::new();
1174
1175 let str_ptr = string.as_ptr();
1176 let str_len = string.len();
1177 let str_cap = string.capacity();
1178
1179 let compact = CompactString::from(string);
1180 // we should always inline empty strings
1181 assert!(!compact.is_heap_allocated());
1182
1183 let new_string = String::from(compact);
1184
1185 let new_str_ptr = new_string.as_ptr();
1186 let new_str_len = new_string.len();
1187 let new_str_cap = new_string.capacity();
1188
1189 assert_eq!(str_ptr, new_str_ptr);
1190 assert_eq!(str_len, new_str_len);
1191 assert_eq!(str_cap, new_str_cap);
1192 }
1193
1194 #[test]
1195 fn test_roundtrip_from_string_buffer_empty_string() {
1196 let string = String::new();
1197
1198 let str_ptr = string.as_ptr();
1199 let str_len = string.len();
1200 let str_cap = string.capacity();
1201
1202 let compact = CompactString::from_string_buffer(string);
1203 // we should always inline empty strings
1204 assert!(!compact.is_heap_allocated());
1205
1206 let new_string = String::from(compact);
1207
1208 let new_str_ptr = new_string.as_ptr();
1209 let new_str_len = new_string.len();
1210 let new_str_cap = new_string.capacity();
1211
1212 assert_eq!(str_ptr, new_str_ptr);
1213 assert_eq!(str_len, new_str_len);
1214 assert_eq!(str_cap, new_str_cap);
1215 }
1216
1217 #[test]
1218 fn test_into_string_small_str() {
1219 let data = "abcdef";
1220 let str_addr = data.as_ptr();
1221 let str_len = data.len();
1222
1223 let compact = CompactString::from(data);
1224 let new_string = String::from(compact);
1225 let new_str_addr = new_string.as_ptr();
1226 let new_str_len = new_string.len();
1227 let new_str_cap = new_string.capacity();
1228
1229 assert_ne!(str_addr, new_str_addr);
1230 assert_eq!(str_len, new_str_len);
1231 assert_eq!(str_len, new_str_cap);
1232 }
1233
1234 #[test]
1235 fn test_into_string_small_static_str() {
1236 let data = "abcdef";
1237 let str_addr = data.as_ptr();
1238 let str_len = data.len();
1239
1240 let compact = CompactString::const_new(data);
1241 let new_string = String::from(compact);
1242 let new_str_addr = new_string.as_ptr();
1243 let new_str_len = new_string.len();
1244 let new_str_cap = new_string.capacity();
1245
1246 assert_ne!(str_addr, new_str_addr);
1247 assert_eq!(str_len, new_str_len);
1248 assert_eq!(str_len, new_str_cap);
1249 }
1250
1251 #[test]
1252 fn test_into_string_long_str() {
1253 let data = "this is a long string that will be on the heap";
1254 let str_addr = data.as_ptr();
1255 let str_len = data.len();
1256
1257 let compact = CompactString::from(data);
1258 let new_string = String::from(compact);
1259 let new_str_addr = new_string.as_ptr();
1260 let new_str_len = new_string.len();
1261 let new_str_cap = new_string.capacity();
1262
1263 assert_ne!(str_addr, new_str_addr);
1264 assert_eq!(str_len, new_str_len);
1265 assert_eq!(str_len, new_str_cap);
1266 }
1267
1268 #[test]
1269 fn test_into_string_long_static_str() {
1270 let data = "this is a long string that will be on the heap";
1271 let str_addr = data.as_ptr();
1272 let str_len = data.len();
1273
1274 let compact = CompactString::const_new(data);
1275 let new_string = String::from(compact);
1276 let new_str_addr = new_string.as_ptr();
1277 let new_str_len = new_string.len();
1278 let new_str_cap = new_string.capacity();
1279
1280 assert_ne!(str_addr, new_str_addr);
1281 assert_eq!(str_len, new_str_len);
1282 assert_eq!(str_len, new_str_cap);
1283 }
1284
1285 #[test]
1286 fn test_into_string_empty_str() {
1287 let data = "";
1288 let str_len = data.len();
1289
1290 let compact = CompactString::from(data);
1291 let new_string = String::from(compact);
1292 let new_str_addr = new_string.as_ptr();
1293 let new_str_len = new_string.len();
1294 let new_str_cap = new_string.capacity();
1295
1296 let empty_string = String::new();
1297
1298 assert_eq!(empty_string.as_ptr(), new_str_addr);
1299 assert_eq!(str_len, new_str_len);
1300 assert_eq!(str_len, new_str_cap);
1301 }
1302
1303 #[test]
1304 fn test_into_string_empty_static_str() {
1305 let data = "";
1306 let str_len = data.len();
1307
1308 let compact = CompactString::const_new(data);
1309 let new_string = String::from(compact);
1310 let new_str_addr = new_string.as_ptr();
1311 let new_str_len = new_string.len();
1312 let new_str_cap = new_string.capacity();
1313
1314 let empty_string = String::new();
1315
1316 assert_eq!(empty_string.as_ptr(), new_str_addr);
1317 assert_eq!(str_len, new_str_len);
1318 assert_eq!(str_len, new_str_cap);
1319 }
1320
1321 #[test]
1322 fn test_truncate_noops_if_new_len_greater_than_current() {
1323 let mut short = CompactString::from("short");
1324 let short_cap = short.capacity();
1325 short.truncate(100);
1326
1327 assert_eq!(short.len(), 5);
1328 assert_eq!(short.capacity(), short_cap);
1329
1330 let mut long = CompactString::from("i am a long string that will be allocated on the heap");
1331 let long_cap = long.capacity();
1332 long.truncate(500);
1333
1334 assert_eq!(long.len(), 53);
1335 assert_eq!(long.capacity(), long_cap);
1336 }
1337
1338 #[test]
1339 fn test_truncate_noops_if_new_len_greater_than_current_static_str() {
1340 let mut short = CompactString::const_new("short");
1341 short.truncate(100);
1342
1343 assert_eq!(short.len(), 5);
1344 assert_eq!(short.capacity(), MAX_SIZE);
1345
1346 let mut long =
1347 CompactString::const_new("i am a long string that will be allocated on the heap");
1348 long.truncate(500);
1349
1350 assert_eq!(long.len(), 53);
1351 assert_eq!(long.capacity(), 53);
1352 }
1353
1354 #[test]
1355 #[should_panic(expected = "new_len must lie on char boundary")]
1356 fn test_truncate_panics_on_non_char_boundary() {
1357 let mut emojis = CompactString::from("😀😀😀😀");
1358 assert!('😀'.len_utf8() > 1);
1359 emojis.truncate(1);
1360 }
1361
1362 #[test_case(CompactString::from; "inline")]
1363 #[test_case(CompactString::const_new; "static_str")]
1364 fn test_insert(to_compact: fn(&'static str) -> CompactString) {
1365 // insert into empty string
1366 let mut one_byte = to_compact("");
1367 one_byte.insert(0, '.');
1368 assert_eq!(one_byte, ".");
1369
1370 let mut two_bytes = to_compact("");
1371 two_bytes.insert(0, 'Ü');
1372 assert_eq!(two_bytes, "Ü");
1373
1374 let mut three_bytes = to_compact("");
1375 three_bytes.insert(0, '€');
1376 assert_eq!(three_bytes, "€");
1377
1378 let mut four_bytes = to_compact("");
1379 four_bytes.insert(0, '😀');
1380 assert_eq!(four_bytes, "😀");
1381
1382 // insert at the front of string
1383 let mut one_byte = to_compact("😀");
1384 one_byte.insert(0, '.');
1385 assert_eq!(one_byte, ".😀");
1386
1387 let mut two_bytes = to_compact("😀");
1388 two_bytes.insert(0, 'Ü');
1389 assert_eq!(two_bytes, "Ü😀");
1390
1391 let mut three_bytes = to_compact("😀");
1392 three_bytes.insert(0, '€');
1393 assert_eq!(three_bytes, "€😀");
1394
1395 let mut four_bytes = to_compact("😀");
1396 four_bytes.insert(0, '😀');
1397 assert_eq!(four_bytes, "😀😀");
1398
1399 // insert at the end of string
1400 let mut one_byte = to_compact("😀");
1401 one_byte.insert(4, '.');
1402 assert_eq!(one_byte, "😀.");
1403
1404 let mut two_bytes = to_compact("😀");
1405 two_bytes.insert(4, 'Ü');
1406 assert_eq!(two_bytes, "😀Ü");
1407
1408 let mut three_bytes = to_compact("😀");
1409 three_bytes.insert(4, '€');
1410 assert_eq!(three_bytes, "😀€");
1411
1412 let mut four_bytes = to_compact("😀");
1413 four_bytes.insert(4, '😀');
1414 assert_eq!(four_bytes, "😀😀");
1415
1416 // insert in the middle of string
1417 let mut one_byte = to_compact("😀😀");
1418 one_byte.insert(4, '.');
1419 assert_eq!(one_byte, "😀.😀");
1420
1421 let mut two_bytes = to_compact("😀😀");
1422 two_bytes.insert(4, 'Ü');
1423 assert_eq!(two_bytes, "😀Ü😀");
1424
1425 let mut three_bytes = to_compact("😀😀");
1426 three_bytes.insert(4, '€');
1427 assert_eq!(three_bytes, "😀€😀");
1428
1429 let mut four_bytes = to_compact("😀😀");
1430 four_bytes.insert(4, '😀');
1431 assert_eq!(four_bytes, "😀😀😀");
1432
1433 // edge case: new length is 24 bytes
1434 let mut s = to_compact("\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}");
1435 s.insert(21, '\u{ffff}');
1436 assert_eq!(
1437 s,
1438 "\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}\u{ffff}",
1439 );
1440 }
1441
1442 #[test]
1443 #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]
1444 fn test_retain() {
1445 let mut s = CompactString::from("α_β_γ");
1446
1447 s.retain(|_| true);
1448 assert_eq!(s, "α_β_γ");
1449
1450 s.retain(|c| c != '_');
1451 assert_eq!(s, "αβγ");
1452
1453 s.retain(|c| c != 'β');
1454 assert_eq!(s, "αγ");
1455
1456 s.retain(|c| c == 'α');
1457 assert_eq!(s, "α");
1458
1459 s.retain(|_| false);
1460 assert_eq!(s, "");
1461
1462 // Moving a multi-byte character by one byte temporarily leaves the full old-length
1463 // buffer invalid UTF-8. `retain` must only interpret the untouched source suffix.
1464 let mut s = CompactString::from("0è0");
1465 s.retain(|c| c != '0');
1466 assert_eq!(s, "è");
1467
1468 let input = "0èabcdefghijklmnopqrstuvwxyz";
1469 let expected = "èabcdefghijklmnopqrstuvwxyz";
1470
1471 let mut heap = CompactString::from(input);
1472 assert!(heap.is_heap_allocated());
1473 heap.retain(|c| c != '0');
1474 assert_eq!(heap, expected);
1475
1476 let mut static_str = CompactString::const_new(input);
1477 assert_eq!(static_str.as_static_str(), Some(input));
1478 static_str.retain(|c| c != '0');
1479 assert_eq!(static_str, expected);
1480
1481 let mut s = CompactString::from("0è0");
1482 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1483 let mut count = 0;
1484 s.retain(|_| {
1485 count += 1;
1486 match count {
1487 1 => false,
1488 2 => true,
1489 _ => panic!(),
1490 }
1491 });
1492 }));
1493 assert!(std::str::from_utf8(s.as_bytes()).is_ok());
1494 }
1495
1496 #[test]
1497 fn test_remove() {
1498 let mut control = String::from("🦄🦀hello🎶world🇺🇸");
1499 let mut compact = CompactString::from(&control);
1500
1501 assert_eq!(control.remove(0), compact.remove(0));
1502 assert_eq!(control, compact);
1503 assert_eq!(compact, "🦀hello🎶world🇺🇸");
1504
1505 let music_idx = control
1506 .char_indices()
1507 .find(|(_idx, c)| *c == '🎶')
1508 .map(|(idx, _c)| idx)
1509 .unwrap();
1510 assert_eq!(control.remove(music_idx), compact.remove(music_idx));
1511 assert_eq!(control, compact);
1512 assert_eq!(compact, "🦀helloworld🇺🇸");
1513 }
1514
1515 #[test]
1516 #[should_panic(expected = "cannot remove a char from the end of a string")]
1517 fn test_remove_empty_string() {
1518 let mut compact = CompactString::new("");
1519 compact.remove(0);
1520 }
1521
1522 #[test]
1523 #[should_panic(expected = "cannot remove a char from the end of a string")]
1524 fn test_remove_empty_string_static() {
1525 let mut compact = CompactString::const_new("");
1526 compact.remove(0);
1527 }
1528
1529 #[test]
1530 #[should_panic(expected = "cannot remove a char from the end of a string")]
1531 fn test_remove_str_len() {
1532 let mut compact = CompactString::new("hello world");
1533 compact.remove(compact.len());
1534 }
1535
1536 #[test]
1537 fn test_with_capacity_16711422() {
1538 // Fuzzing with AFL on a 32-bit ARM arch found this bug!
1539 //
1540 // We have our own heap implementation called BoxString, which optionally stores the capacity
1541 // on the heap, which is really only relevant for 32-bit architectures. The discriminant it used
1542 // to determine if capacity was on the heap, was when the last `usize` number of bytes were all
1543 // equal to our internal HEAP_MASK, which at the time was `255`. At the time this worked and was
1544 // correct.
1545 //
1546 // When we released support to make the size of CompactString == Option<CompactString>, we
1547 // changed the HEAP_MASK to `254`, which unintentionally made our discriminant for determining
1548 // if our capacity was on the heap, all `254`s, yet our "max inline capacity value" was still
1549 // based on the discriminant being all `255`s.
1550 //
1551 // When creating a BoxString with capacity 16711422, we'd correctly decide we could store the
1552 // capacity inline, but this would create a capacity with an underlying value of
1553 // [254, 254, 254, HEAP_MASK]. Once the HEAP_MASK changed to 254, this capacity was now the same
1554 // as the discriminant to determine if the capacity was on the heap, so we'd incorrectly
1555 // identify the capacity as being on the heap, when it was really inline.
1556
1557 assert_eq!(16711422_u32.to_le_bytes(), [254, 254, 254, 0]);
1558
1559 let compact = CompactString::with_capacity(16711422);
1560 let std_str = String::with_capacity(16711422);
1561
1562 assert!(compact.is_heap_allocated());
1563 assert_eq!(compact.capacity(), std_str.capacity());
1564 assert_eq!(compact, "");
1565 assert_eq!(compact, std_str);
1566 }
1567
1568 #[test]
1569 fn test_from_utf16() {
1570 let control = String::from("🦄 hello world! 🎮 ");
1571 let utf16_buf: Vec<u16> = control.encode_utf16().collect();
1572 let compact = CompactString::from_utf16(utf16_buf).unwrap();
1573
1574 assert_eq!(compact, control);
1575
1576 cfg_if::cfg_if! {
1577 if #[cfg(target_pointer_width = "64")] {
1578 assert!(!compact.is_heap_allocated());
1579 } else if #[cfg(target_pointer_width = "32")] {
1580 assert!(compact.is_heap_allocated());
1581 } else {
1582 compile_error!("unsupported pointer width!");
1583 }
1584 }
1585 }
1586
1587 #[test]
1588 fn test_reserve_shrink_roundtrip() {
1589 const TEXT: &str = "Hello.";
1590
1591 let mut s = CompactString::new(TEXT);
1592 assert!(!s.is_heap_allocated());
1593 assert_eq!(s.capacity(), MAX_SIZE);
1594 assert_eq!(s, TEXT);
1595
1596 s.reserve(128);
1597 assert!(s.is_heap_allocated());
1598 assert!(s.capacity() >= 128 + TEXT.len());
1599 assert_eq!(s, TEXT);
1600
1601 s.shrink_to(64);
1602 assert!(s.is_heap_allocated());
1603 assert!(s.capacity() >= 64);
1604 assert_eq!(s, TEXT);
1605
1606 s.shrink_to_fit();
1607 assert!(!s.is_heap_allocated());
1608 assert_eq!(s.capacity(), MAX_SIZE);
1609 assert_eq!(s, TEXT);
1610
1611 s.reserve(SIXTEEN_MB);
1612 assert!(s.is_heap_allocated());
1613 assert!(s.capacity() >= SIXTEEN_MB + TEXT.len());
1614 assert_eq!(s, TEXT);
1615
1616 s.shrink_to(64);
1617 assert!(s.is_heap_allocated());
1618 assert!(s.capacity() >= 64);
1619 assert_eq!(s, TEXT);
1620
1621 s.reserve(SIXTEEN_MB);
1622 assert!(s.is_heap_allocated());
1623 assert!(s.capacity() >= SIXTEEN_MB + TEXT.len());
1624 assert_eq!(s, TEXT);
1625
1626 s.shrink_to_fit();
1627 assert!(!s.is_heap_allocated());
1628 assert_eq!(s.capacity(), MAX_SIZE);
1629 assert_eq!(s, TEXT);
1630 }
1631
1632 #[test]
1633 fn test_reserve_shrink_roundtrip_static() {
1634 // longer than 24 bytes, so the string does not get inlined
1635 const TEXT: &str = "Hello, world! How are you today?";
1636
1637 let mut s = CompactString::const_new(TEXT);
1638 assert!(!s.is_heap_allocated());
1639 assert_eq!(s.capacity(), TEXT.len());
1640 assert_eq!(s, TEXT);
1641
1642 s.reserve(128);
1643 assert!(s.is_heap_allocated());
1644 assert!(s.capacity() >= 128 + TEXT.len());
1645 assert_eq!(s, TEXT);
1646
1647 s.shrink_to(64);
1648 assert!(s.is_heap_allocated());
1649 assert!(s.capacity() >= 64);
1650 assert_eq!(s, TEXT);
1651
1652 s.shrink_to_fit();
1653 assert!(s.is_heap_allocated());
1654 assert_eq!(s.capacity(), s.len());
1655 assert_eq!(s, TEXT);
1656
1657 s.reserve(SIXTEEN_MB);
1658 assert!(s.is_heap_allocated());
1659 assert!(s.capacity() >= SIXTEEN_MB + TEXT.len());
1660 assert_eq!(s, TEXT);
1661
1662 s.shrink_to(64);
1663 assert!(s.is_heap_allocated());
1664 assert!(s.capacity() >= 64);
1665 assert_eq!(s, TEXT);
1666
1667 s.reserve(SIXTEEN_MB);
1668 assert!(s.is_heap_allocated());
1669 assert!(s.capacity() >= SIXTEEN_MB + TEXT.len());
1670 assert_eq!(s, TEXT);
1671
1672 s.shrink_to_fit();
1673 assert!(s.is_heap_allocated());
1674 assert_eq!(s.capacity(), s.len());
1675 assert_eq!(s, TEXT);
1676 }
1677
1678 #[test]
1679 fn test_reserve_shrink_roundtrip_static_inline() {
1680 // shorter than 12 bytes, so the string gets inlined
1681 const TEXT: &str = "Hello.";
1682
1683 let mut s = CompactString::const_new(TEXT);
1684 assert!(!s.is_heap_allocated());
1685 assert_eq!(s.capacity(), MAX_SIZE);
1686 assert_eq!(s, TEXT);
1687
1688 s.reserve(128);
1689 assert!(s.is_heap_allocated());
1690 assert!(s.capacity() >= 128 + TEXT.len());
1691 assert_eq!(s, TEXT);
1692
1693 s.shrink_to(64);
1694 assert!(s.is_heap_allocated());
1695 assert!(s.capacity() >= 64);
1696 assert_eq!(s, TEXT);
1697
1698 s.shrink_to_fit();
1699 assert!(!s.is_heap_allocated());
1700 assert_eq!(s.capacity(), MAX_SIZE);
1701 assert_eq!(s, TEXT);
1702
1703 s.reserve(SIXTEEN_MB);
1704 assert!(s.is_heap_allocated());
1705 assert!(s.capacity() >= SIXTEEN_MB + TEXT.len());
1706 assert_eq!(s, TEXT);
1707
1708 s.shrink_to(64);
1709 assert!(s.is_heap_allocated());
1710 assert!(s.capacity() >= 64);
1711 assert_eq!(s, TEXT);
1712
1713 s.reserve(SIXTEEN_MB);
1714 assert!(s.is_heap_allocated());
1715 assert!(s.capacity() >= SIXTEEN_MB + TEXT.len());
1716 assert_eq!(s, TEXT);
1717
1718 s.shrink_to_fit();
1719 assert!(!s.is_heap_allocated());
1720 assert_eq!(s.capacity(), MAX_SIZE);
1721 assert_eq!(s, TEXT);
1722 }
1723
1724 #[test]
1725 fn test_from_utf8_unchecked_sanity() {
1726 let text = "hello 🌎, you are nice";
1727 let compact = unsafe { CompactString::from_utf8_unchecked(text) };
1728
1729 assert_eq!(compact, text);
1730 }
1731
1732 #[test]
1733 fn test_from_utf8_unchecked_long() {
1734 let bytes = [255; 2048];
1735 let compact = unsafe { CompactString::from_utf8_unchecked(bytes) };
1736
1737 assert_eq!(compact.len(), 2048);
1738 assert_eq!(compact.as_bytes(), bytes);
1739 }
1740
1741 #[test]
1742 fn test_from_utf8_unchecked_short() {
1743 let bytes = [255; 10];
1744 let compact = unsafe { CompactString::from_utf8_unchecked(bytes) };
1745
1746 assert_eq!(compact.len(), 10);
1747 assert_eq!(compact.as_bytes(), bytes);
1748 }
1749
1750 #[test]
1751 fn test_from_utf8_unchecked_empty() {
1752 let bytes = [255; 0];
1753 let compact = unsafe { CompactString::from_utf8_unchecked(bytes) };
1754
1755 assert_eq!(compact.len(), 0);
1756 assert_eq!(compact.as_bytes(), bytes);
1757 }
1758
1759 #[proptest]
1760 #[cfg_attr(miri, ignore)]
1761 fn proptest_from_utf8_lossy(#[strategy(rand_bytes())] bytes: Vec<u8>) {
1762 let compact = CompactString::from_utf8_lossy(&bytes);
1763 let control = String::from_utf8_lossy(&bytes);
1764
1765 assert_eq!(compact, control);
1766 assert_eq!(compact.len(), control.len());
1767 }
1768
1769 // Like `proptest_from_utf8_lossy`, but the inputs interleave valid multibyte runs with invalid
1770 // fragments, which stresses the bulk-copy of valid runs between errors that random bytes miss.
1771 #[proptest]
1772 #[cfg_attr(miri, ignore)]
1773 fn proptest_from_utf8_lossy_interleaved(#[strategy(rand_utf8_with_errors())] bytes: Vec<u8>) {
1774 let compact = CompactString::from_utf8_lossy(&bytes);
1775 let control = String::from_utf8_lossy(&bytes);
1776
1777 assert_eq!(compact, control);
1778 assert_eq!(compact.len(), control.len());
1779 }
1780
1781 #[proptest]
1782 #[cfg_attr(miri, ignore)]
1783 fn proptest_from_utf16(#[strategy(rand_u16s())] buf: Vec<u16>) {
1784 type FromUtf16Func = fn(&[u8]) -> Result<CompactString, crate::Utf16Error>;
1785 type FromU16Endian = fn(u16) -> u16;
1786 type FromU16EndianBytes = fn([u8; 2]) -> u16;
1787
1788 const FUNCS: &[(FromUtf16Func, FromU16Endian, FromU16EndianBytes)] = &[
1789 (
1790 |v| CompactString::from_utf16le(v),
1791 u16::from_le,
1792 u16::from_le_bytes,
1793 ),
1794 (
1795 |v| CompactString::from_utf16be(v),
1796 u16::from_be,
1797 u16::from_be_bytes,
1798 ),
1799 ];
1800
1801 for (new_compact_string, from_int, from_bytes) in FUNCS {
1802 let buf = &*buf;
1803 let bytes: &[u8] = unsafe { slice::from_raw_parts(buf.as_ptr().cast(), buf.len() * 2) };
1804
1805 let compact = new_compact_string(bytes);
1806 let control = String::from_utf16(&buf.iter().copied().map(from_int).collect::<Vec<u16>>());
1807 assert_eq!(compact.is_ok(), control.is_ok());
1808
1809 if let (Ok(compact), Ok(control)) = (compact, control) {
1810 assert_eq!(compact.len(), control.len());
1811 assert_eq!(compact, control);
1812 }
1813
1814 if bytes.len() >= 2 {
1815 // Test if `CompactString::from_utf16x()` works with misaligned slices.
1816
1817 let bytes: &[u8] = &bytes[1..bytes.len() - 1];
1818 let buf: Vec<u16> = bytes
1819 .chunks_exact(2)
1820 .map(|v| from_bytes([v[0], v[1]]))
1821 .collect();
1822
1823 let compact = new_compact_string(bytes);
1824 let control = String::from_utf16(&buf);
1825 assert_eq!(compact.is_ok(), control.is_ok());
1826
1827 if let (Ok(compact), Ok(control)) = (compact, control) {
1828 assert_eq!(compact.len(), control.len());
1829 assert_eq!(compact, control);
1830 }
1831 }
1832 }
1833 }
1834
1835 #[proptest]
1836 #[cfg_attr(miri, ignore)]
1837 fn proptest_repeat(n: u16, s: String) {
1838 let compact = CompactString::new(&s).repeat(n as usize);
1839 let control = s.repeat(n as usize);
1840
1841 assert_eq!(compact, control);
1842 }
1843
1844 #[test]
1845 fn test_from_utf16x() {
1846 let dancing_men = b"\x3d\xd8\x6f\xdc\x0d\x20\x42\x26\x0f\xfe";
1847 assert_eq!(CompactString::from_utf16le(dancing_men).unwrap(), "👯‍♂️");
1848
1849 let dancing_men = b"0\x3d\xd8\x6f\xdc\x0d\x20\x42\x26\x0f\xfe";
1850 assert!(CompactString::from_utf16le(dancing_men).is_err());
1851 assert_eq!(
1852 CompactString::from_utf16le(&dancing_men[1..]).unwrap(),
1853 "👯‍♂️",
1854 );
1855
1856 let dancing_women = b"\xd8\x3d\xdc\x6f\x20\x0d\x26\x40\xfe\x0f";
1857 assert_eq!(CompactString::from_utf16be(dancing_women).unwrap(), "👯‍♀️");
1858
1859 let dancing_women = b"0\xd8\x3d\xdc\x6f\x20\x0d\x26\x40\xfe\x0f";
1860 assert!(CompactString::from_utf16be(dancing_women).is_err());
1861 assert_eq!(
1862 CompactString::from_utf16be(&dancing_women[1..]).unwrap(),
1863 "👯‍♀️",
1864 );
1865 }
1866
1867 #[test]
1868 fn test_from_utf16x_lossy() {
1869 let dancing_men = b"\x3d\xd8\x6f\xfc\x0d\x20\x42\x26\x0f\xfe";
1870 assert_eq!(
1871 CompactString::from_utf16le_lossy(dancing_men),
1872 "�\u{fc6f}\u{200d}♂️",
1873 );
1874
1875 let dancing_men = b"0\x3d\xd8\x6f\xfc\x0d\x20\x42\x26\x0f\xfe";
1876 assert_eq!(
1877 CompactString::from_utf16le_lossy(&dancing_men[1..]),
1878 "�\u{fc6f}\u{200d}♂️",
1879 );
1880
1881 let dancing_women = b"\xd8\x3d\xdc\x6f\x20\x0d\x26\x40\xde\x0f";
1882 assert_eq!(
1883 CompactString::from_utf16be_lossy(dancing_women),
1884 "👯\u{200d}♀�",
1885 );
1886
1887 let dancing_women = b"0\xd8\x3d\xdc\x6f\x20\x0d\x26\x40\xde\x0f";
1888 assert_eq!(
1889 CompactString::from_utf16be_lossy(&dancing_women[1..]),
1890 "👯\u{200d}♀�",
1891 );
1892 }
1893
1894 #[test]
1895 fn test_collect() {
1896 const VALUES: &[&str] = &["foo", "bar", "baz"];
1897
1898 assert_eq!(
1899 VALUES
1900 .iter()
1901 .copied()
1902 .map(Cow::Borrowed)
1903 .collect::<CompactString>(),
1904 "foobarbaz",
1905 );
1906 assert_eq!(
1907 VALUES
1908 .iter()
1909 .copied()
1910 .map(|s| Cow::Owned(s.into()))
1911 .collect::<CompactString>(),
1912 "foobarbaz",
1913 );
1914 assert_eq!(
1915 VALUES
1916 .iter()
1917 .copied()
1918 .map(Box::<str>::from)
1919 .collect::<CompactString>(),
1920 "foobarbaz",
1921 );
1922 assert_eq!(
1923 VALUES
1924 .iter()
1925 .copied()
1926 .map(CompactString::from)
1927 .collect::<String>(),
1928 "foobarbaz",
1929 );
1930 assert_eq!(
1931 VALUES
1932 .iter()
1933 .copied()
1934 .map(CompactString::from)
1935 .collect::<Cow<'_, str>>(),
1936 "foobarbaz",
1937 );
1938 assert_eq!(
1939 VALUES
1940 .iter()
1941 .copied()
1942 .flat_map(|s| s.chars())
1943 .collect::<Cow<'_, str>>(),
1944 "foobarbaz",
1945 );
1946 }
1947
1948 #[test]
1949 fn test_into_cow() {
1950 let og = "aaa";
1951 let compact = CompactString::new(og);
1952 let cow: alloc::borrow::Cow<'_, str> = compact.into();
1953
1954 assert_eq!(og, cow);
1955 }
1956
1957 #[test]
1958 fn test_into_arc() {
1959 let short = "short";
1960 let long = "i am a long string that will be allocated on the heap";
1961 let arc = alloc::sync::Arc::<str>::from(CompactString::new(short));
1962 assert_eq!(short, &*arc);
1963 let arc = alloc::sync::Arc::<str>::from(CompactString::new(long));
1964 assert_eq!(long, &*arc);
1965 }
1966
1967 #[test]
1968 fn test_into_rc() {
1969 let short = "short";
1970 let long = "i am a long string that will be allocated on the heap";
1971 let rc = alloc::rc::Rc::<str>::from(CompactString::new(short));
1972 assert_eq!(short, &*rc);
1973 let rc = alloc::rc::Rc::<str>::from(CompactString::new(long));
1974 assert_eq!(long, &*rc);
1975 }
1976
1977 #[test]
1978 fn test_into_error() {
1979 let short = "short";
1980 let long = "i am a long string that will be allocated on the heap";
1981 let short_error_ss =
1982 Box::<dyn std::error::Error + Send + Sync>::from(CompactString::new(short));
1983 assert_eq!(short, format!("{short_error_ss}"));
1984 assert_eq!(format!("{short:?}"), format!("{short_error_ss:?}"));
1985 let long_error_ss = Box::<dyn std::error::Error + Send + Sync>::from(CompactString::new(long));
1986 assert_eq!(long, format!("{long_error_ss}"));
1987 assert_eq!(format!("{long:?}"), format!("{long_error_ss:?}"));
1988
1989 let short_error = Box::<dyn std::error::Error>::from(CompactString::new(short));
1990 assert_eq!(short, format!("{short_error}"));
1991 assert_eq!(format!("{short:?}"), format!("{short_error:?}"));
1992 let long_error = Box::<dyn std::error::Error>::from(CompactString::new(long));
1993 assert_eq!(long, format!("{long_error}"));
1994 assert_eq!(format!("{long:?}"), format!("{long_error:?}"));
1995 }
1996
1997 #[test]
1998 fn test_into_box_str() {
1999 let short = "short";
2000 let long = "i am a long string that will be allocated on the heap";
2001 let s = Box::<str>::from(CompactString::new(short));
2002 assert_eq!(short, &*s);
2003 let l = Box::<str>::from(CompactString::new(long));
2004 assert_eq!(long, &*l);
2005 }
2006
2007 #[test]
2008 fn test_into_os_string() {
2009 let short = "short";
2010 let long = "i am a long string that will be allocated on the heap";
2011 let s = std::ffi::OsString::from(CompactString::new(short));
2012 assert_eq!(s.as_os_str().to_str().unwrap(), short);
2013 let l = std::ffi::OsString::from(CompactString::new(long));
2014 assert_eq!(l.as_os_str().to_str().unwrap(), long);
2015 }
2016
2017 #[test]
2018 fn test_into_path_buf() {
2019 let short = "short";
2020 let long = "i am a long string that will be allocated on the heap";
2021 let s = std::path::PathBuf::from(CompactString::new(short));
2022 assert_eq!(s.as_os_str().to_str().unwrap(), short);
2023 let l = std::path::PathBuf::from(CompactString::new(long));
2024 assert_eq!(l.as_os_str().to_str().unwrap(), long);
2025 }
2026
2027 #[test]
2028 fn test_as_ref_path() {
2029 let short = "short";
2030 let long = "i am a long string that will be allocated on the heap";
2031 let s = CompactString::new(short);
2032 assert_eq!(
2033 AsRef::<std::path::Path>::as_ref(&s).to_str().unwrap(),
2034 short
2035 );
2036 let l = CompactString::new(long);
2037 assert_eq!(AsRef::<std::path::Path>::as_ref(&l).to_str().unwrap(), long);
2038 }
2039
2040 #[test]
2041 fn test_into_vec_u8() {
2042 let short = "short";
2043 let long = "i am a long string that will be allocated on the heap";
2044 let s = Vec::<u8>::from(CompactString::new(short));
2045 assert_eq!(&s, short.as_bytes());
2046 let l = Vec::<u8>::from(CompactString::new(long));
2047 assert_eq!(&l, long.as_bytes());
2048 }
2049
2050 #[test]
2051 fn test_from_string_buffer_inlines_on_push() {
2052 let mut compact = CompactString::from_string_buffer("hello".to_string());
2053 assert!(compact.is_heap_allocated());
2054
2055 compact.push_str(" world");
2056 // when growing the CompactString we should inline it
2057 assert!(!compact.is_heap_allocated());
2058 }
2059
2060 #[test]
2061 fn test_from_string_buffer_inlines_on_clone() {
2062 let a = CompactString::from_string_buffer("hello".to_string());
2063 assert!(a.is_heap_allocated());
2064
2065 let b = a.clone();
2066 // when cloning the CompactString we should inline it
2067 assert!(!b.is_heap_allocated());
2068 }
2069
2070 // With debug assertions enabled the invocation will panic if you try to allocate more memory than
2071 // the system even has.
2072 #[cfg(not(debug_assertions))]
2073 #[cfg(target_pointer_width = "64")]
2074 #[test]
2075 #[should_panic = "Cannot allocate memory to hold CompactString"]
2076 fn test_alloc_excessively_long_string() {
2077 // 2**56 - 2 bytes, the maximum number `Capacity` can hold
2078 std::hint::black_box(CompactString::with_capacity((1 << 56) - 2));
2079 }
2080
2081 // This feature was enabled by <https://github.com/rust-lang/rust/pull/94075> which was first
2082 // released in Rust 1.65.
2083 #[test]
2084 fn multiple_niches_test() {
2085 #[allow(unused)]
2086 enum Value {
2087 String(CompactString),
2088 Bool(bool),
2089 Signed(isize),
2090 Unsigned(usize),
2091 Null,
2092 }
2093 assert_eq!(
2094 core::mem::size_of::<Value>(),
2095 core::mem::size_of::<String>()
2096 );
2097 }
2098
2099 #[test]
2100 fn test_is_empty() {
2101 const ZEROS: &[&str] = &[
2102 "\0", // 1
2103 "\0\0\0\0\0\0\0\0\0\0\0\0", // 12
2104 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", // 24
2105 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", // 25
2106 ];
2107
2108 assert!(CompactString::new("").is_empty());
2109 assert!(CompactString::const_new("").is_empty());
2110
2111 for (len, s) in ZEROS.iter().copied().enumerate() {
2112 let mut a = CompactString::new(s);
2113 let mut b = CompactString::new(s);
2114
2115 for _ in (1..=len).rev() {
2116 a.truncate(len);
2117 b.truncate(len);
2118 assert!(!a.is_empty());
2119 assert!(!b.is_empty());
2120 }
2121 }
2122 }
2123
2124 #[test]
2125 fn test_shrink_to_within_min_heap_gap() {
2126 // N.B. shrinking a heap allocated string to a capacity just above the inline limit
2127 // must report a capacity matching the actual allocation layout.
2128 let mut s = CompactString::with_capacity(100);
2129 assert!(s.is_heap_allocated());
2130
2131 let target = crate::repr::MAX_SIZE + 1;
2132 s.shrink_to(target);
2133 assert!(s.is_heap_allocated());
2134
2135 // Capacity is clamped up to MIN_HEAP_SIZE by the allocator, the stored value must reflect that.
2136 assert!(s.capacity() >= target);
2137 drop(s);
2138 }
2139
2140 #[test]
2141 #[should_panic(expected = "capacity overflow")]
2142 fn test_repeat_capacity_overflow() {
2143 let s = CompactString::new("abc");
2144 let _ = s.repeat(usize::MAX);
2145 }
2146
2147 #[test]
2148 fn test_inline_max_len_maximal_last_byte() {
2149 // Tightest case for `from_inline_ok`: a `MAX_SIZE`-length inline string. At `len == MAX_SIZE`
2150 // the length byte is overwritten by real UTF-8 data, so the discriminant *is* the final data
2151 // byte. `U+07FF` encodes as `DF BF`, giving a trailing byte of `0xBF` (191) — the largest a
2152 // valid UTF-8 trailing byte can be, i.e. the closest the invariant ever gets to `HEAP_MASK`.
2153 let s = "a".repeat(MAX_SIZE - 2) + "\u{07FF}";
2154 assert_eq!(s.len(), MAX_SIZE);
2155
2156 // via `&str` -> `Repr::new` inline arm -> `from_inline_ok`
2157 let a = CompactString::new(s.as_str());
2158 assert!(!a.is_heap_allocated());
2159 assert_eq!(a, s);
2160
2161 // via `String` -> `Repr::from_string(_, true)` inline arm -> `from_inline_ok`
2162 let b = CompactString::from(s.clone());
2163 assert!(!b.is_heap_allocated());
2164 assert_eq!(b, s);
2165 }
2166
2167 #[test]
2168 fn test_inline_all_lengths_reach_from_inline_ok() {
2169 // Walk every inline length through both call sites of `from_inline_ok`.
2170 for len in 0..=MAX_SIZE {
2171 let s = "a".repeat(len);
2172
2173 let a = CompactString::new(s.as_str()); // Repr::new
2174 assert!(!a.is_heap_allocated(), "len {} via &str went to heap", len);
2175 assert_eq!(a, s);
2176
2177 let b = CompactString::from(s.clone()); // Repr::from_string(_, true)
2178 assert!(
2179 !b.is_heap_allocated(),
2180 "len {} via String went to heap",
2181 len
2182 );
2183 assert_eq!(b, s);
2184 }
2185 }
2186
2187 // Tests for `drain`, and specifically the drop-without-consuming path (see issue #435).
2188 // `Drain` is intentionally not `#[must_use]`: dropping it, even without iterating, still
2189 // removes the drained range, so `drain(range)` is a valid way to just delete a range.
2190
2191 #[test]
2192 fn test_drain_without_consuming_removes_range_inline() {
2193 // Keep this short enough to stay inline on 32-bit targets too (MAX_SIZE is 12 there, 24 here).
2194 let mut s = CompactString::new("Hi world!");
2195 assert!(!s.is_heap_allocated());
2196 // Use `drain` purely to delete a range, without touching the returned iterator.
2197 s.drain(2..8);
2198 assert_eq!(s, "Hi!");
2199 }
2200
2201 #[test]
2202 fn test_drain_without_consuming_removes_range_heap() {
2203 let mut s = CompactString::new("this is a fairly long heap-allocated string value");
2204 assert!(s.is_heap_allocated());
2205 s.drain(10..22); // remove "fairly long "
2206 assert_eq!(s, "this is a heap-allocated string value");
2207 assert!(s.is_heap_allocated());
2208 }
2209
2210 #[test]
2211 fn test_drain_partial_consume_removes_full_range() {
2212 let mut s = CompactString::new("Hello, world!");
2213 let mut d = s.drain(5..12); // ", world"
2214 assert_eq!(d.next(), Some(','));
2215 // Only one char was consumed, but dropping must still remove the WHOLE drained range.
2216 drop(d);
2217 assert_eq!(s, "Hello!");
2218 }
2219
2220 #[test]
2221 fn test_drain_yields_removed_chars() {
2222 let mut s = CompactString::new("Hello, world!");
2223 let drained: String = s.drain(5..12).collect();
2224 assert_eq!(drained, ", world");
2225 assert_eq!(s, "Hello!");
2226 }
2227
2228 #[test]
2229 fn test_drain_empty_range_is_noop() {
2230 let mut s = CompactString::new("Hello");
2231 s.drain(2..2);
2232 assert_eq!(s, "Hello");
2233 }
2234
2235 #[test]
2236 fn test_drain_full_range_clears() {
2237 let mut s = CompactString::new("this is a fairly long heap-allocated string value");
2238 assert!(s.is_heap_allocated());
2239 s.drain(..);
2240 assert_eq!(s, "");
2241 assert!(s.is_empty());
2242 }
2243
2244 #[test]
2245 fn test_drain_multibyte_boundary() {
2246 let mut s = CompactString::new("αβγδε"); // each char is 2 bytes
2247 s.drain(2..6); // remove "βγ"
2248 assert_eq!(s, "αδε");
2249 }
2250
2251 /// `CompactString::drain` must behave exactly like `String::drain`, both when the iterator
2252 /// is fully consumed and when it is dropped without consuming.
2253 #[proptest]
2254 #[cfg_attr(miri, ignore)]
2255 fn proptest_drain_matches_std(#[strategy(rand_unicode())] control: String, lo: usize, hi: usize) {
2256 // Snap two arbitrary indices to char boundaries so the range is always valid.
2257 let bounds: Vec<usize> = control
2258 .char_indices()
2259 .map(|(i, _)| i)
2260 .chain(core::iter::once(control.len()))
2261 .collect();
2262 let i = lo % bounds.len();
2263 let j = hi % bounds.len();
2264 let (start, end) = (bounds[i.min(j)], bounds[i.max(j)]);
2265
2266 // (1) Fully consuming the iterator yields the same chars and leaves the same remainder.
2267 let mut compact = CompactString::new(&control);
2268 let mut std_string = control.clone();
2269 let drained_compact: String = compact.drain(start..end).collect();
2270 let drained_std: String = std_string.drain(start..end).collect();
2271 prop_assert_eq!(&drained_compact, &drained_std);
2272 prop_assert_eq!(compact.as_str(), std_string.as_str());
2273
2274 // (2) Dropping the iterator without consuming removes exactly the same range.
2275 let mut compact = CompactString::new(&control);
2276 let mut std_string = control.clone();
2277 compact.drain(start..end);
2278 std_string.drain(start..end);
2279 prop_assert_eq!(compact.as_str(), std_string.as_str());
2280 }