Debian Codegraph @

src/tests.rs

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