Skip to content

Commit c243a10

Browse files
bors[bot]Dr-Emann
andauthored
21: Add a new test for a bad size hint r=bjorn3 a=Dr-Emann 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. Co-authored-by: Zachary Dremann <dremann@gmail.com>
2 parents 20b435d + 11468b9 commit c243a10

File tree

1 file changed

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

1 file changed

+36
-0
lines changed

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,4 +215,40 @@ fn test_from_char_iterator() {
215215
assert_eq!(s.as_str(), *raw);
216216
assert_eq!(s.is_heap_allocated(), *is_heap);
217217
}
218+
// String which has too many characters to even consider inlining: Chars::size_hint uses
219+
// (`len` + 3) / 4. With `len` = 89, this results in 23, so `from_iter` will immediately
220+
// heap allocate
221+
let raw: String = std::iter::repeat('a').take(22 * 4 + 1).collect();
222+
let s: SmolStr = raw.chars().collect();
223+
assert_eq!(s.as_str(), raw);
224+
assert!(s.is_heap_allocated());
225+
}
226+
227+
#[test]
228+
fn test_bad_size_hint_char_iter() {
229+
struct BadSizeHint<I>(I);
230+
231+
impl<T, I: Iterator<Item = T>> Iterator for BadSizeHint<I> {
232+
type Item = T;
233+
234+
fn next(&mut self) -> Option<Self::Item> {
235+
self.0.next()
236+
}
237+
238+
fn size_hint(&self) -> (usize, Option<usize>) {
239+
(1024, None)
240+
}
241+
}
242+
243+
let data = "testing";
244+
let collected: SmolStr = BadSizeHint(data.chars()).collect();
245+
let new = SmolStr::new(data);
246+
247+
// Because of the bad size hint, `collected` will be heap allocated, but `new` will be inline
248+
249+
// If we try to use the type of the string (inline/heap) to quickly test for equality, we need to ensure
250+
// `collected` is inline allocated instead
251+
assert!(collected.is_heap_allocated());
252+
assert!(!new.is_heap_allocated());
253+
assert_eq!(new, collected);
218254
}

0 commit comments

Comments
 (0)