]> git.lizzy.rs Git - rust.git/commitdiff
generalize str.contains() tests to a range of haystack sizes
authorThe 8472 <git@infinite-source.de>
Sun, 30 Oct 2022 20:50:08 +0000 (21:50 +0100)
committerThe 8472 <git@infinite-source.de>
Tue, 15 Nov 2022 17:30:07 +0000 (18:30 +0100)
The Big-O is cubic, but this is only called with ~70 chars so it's still fast enough

library/alloc/tests/str.rs

index e30329aa1cb6c78e46c8952eae1f839763ec8df4..9689196ef21ac78d537ebb9926a249bd3fd331f6 100644 (file)
@@ -1590,11 +1590,27 @@ fn test_bool_from_str() {
     assert_eq!("not even a boolean".parse::<bool>().ok(), None);
 }
 
-fn check_contains_all_substrings(s: &str) {
-    assert!(s.contains(""));
-    for i in 0..s.len() {
-        for j in i + 1..=s.len() {
-            assert!(s.contains(&s[i..j]));
+fn check_contains_all_substrings(haystack: &str) {
+    let mut modified_needle = String::new();
+
+    for i in 0..haystack.len() {
+        // check different haystack lengths since we special-case short haystacks.
+        let haystack = &haystack[0..i];
+        assert!(haystack.contains(""));
+        for j in 0..haystack.len() {
+            for k in j + 1..=haystack.len() {
+                let needle = &haystack[j..k];
+                assert!(haystack.contains(needle));
+                modified_needle.clear();
+                modified_needle.push_str(needle);
+                modified_needle.replace_range(0..1, "\0");
+                assert!(!haystack.contains(&modified_needle));
+
+                modified_needle.clear();
+                modified_needle.push_str(needle);
+                modified_needle.replace_range(needle.len() - 1..needle.len(), "\0");
+                assert!(!haystack.contains(&modified_needle));
+            }
         }
     }
 }