Skip to content

Commit 267c02f

Browse files
committed
Add a new test for bad size hint
Changes in PR rust-analyzer/smol_str#20 allow for an incorrect size hint to create a non-canonical SmolStr. Add a new test which will fail if we ever rely on SmolStrs to be canonical when comparing for equality.
1 parent 20b435d commit 267c02f

File tree

1 file changed

+31
-0
lines changed
  • src/tools/rust-analyzer/lib/smol_str/tests

1 file changed

+31
-0
lines changed

src/tools/rust-analyzer/lib/smol_str/tests/test.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,41 @@ fn test_from_char_iterator() {
209209
("사회과학원 어학연구소", true),
210210
// String containing diverse characters
211211
("表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀", true),
212+
// String which has too many characters to even consider inlining
213+
("☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺", true),
212214
];
213215
for (raw, is_heap) in &examples {
214216
let s: SmolStr = raw.chars().collect();
215217
assert_eq!(s.as_str(), *raw);
216218
assert_eq!(s.is_heap_allocated(), *is_heap);
217219
}
218220
}
221+
222+
#[test]
223+
fn test_bad_size_hint_char_iter() {
224+
struct BadSizeHint<I>(I);
225+
226+
impl<T, I: Iterator<Item = T>> Iterator for BadSizeHint<I> {
227+
type Item = T;
228+
229+
fn next(&mut self) -> Option<Self::Item> {
230+
self.0.next()
231+
}
232+
233+
fn size_hint(&self) -> (usize, Option<usize>) {
234+
(1024, None)
235+
}
236+
}
237+
238+
let data = "testing";
239+
let collected: SmolStr = BadSizeHint(data.chars()).collect();
240+
let new = SmolStr::new(data);
241+
242+
// Because of the bad size hint, `collected` will be heap allocated, but `new` will be inline
243+
244+
// If we try to use the type of the string (inline/heap) to quickly test for equality, we need to ensure
245+
// `collected` is inline allocated instead
246+
assert!(collected.is_heap_allocated());
247+
assert!(!new.is_heap_allocated());
248+
assert_eq!(new, collected);
249+
}

0 commit comments

Comments
 (0)