| @@ -0,0 +1,90 @@ |
| 1 | +// Substring search over an 8 MiB corpus: string.find and string.contains |
| 2 | +// with needles of 1, 4, 16 and 64 bytes, absent (a miss is the common |
| 3 | +// case of a search) or present once at the very end (issue #380). |
| 4 | + |
| 5 | +import std/bytes as raw |
| 6 | +import std/io |
| 7 | +import std/list |
| 8 | +import std/prng |
| 9 | +import std/string |
| 10 | +import std/u64 |
| 11 | + |
| 12 | +/// 32 symbols, no 'q': needles of 'q's never occur in the corpus. |
| 13 | +fn alphabet :: -> Bytes |
| 14 | +{ |
| 15 | + raw.from_string "abcdefgh ijklmnop rstuvwxyz " |
| 16 | +} |
| 17 | + |
| 18 | +/// A chunk of `n` pseudo-random symbols. |
| 19 | +fn chunk :: abc: Bytes g: prng.Prng n: Int b: raw.Builder -> (String, prng.Prng) |
| 20 | +{ |
| 21 | + if n == 0 |
| 22 | + { |
| 23 | + (raw.build_string b, g) |
| 24 | + } |
| 25 | + else |
| 26 | + { |
| 27 | + let (x, next) = prng.next g |
| 28 | + let at = u64.to_int (u64.and x (u64.from_int 31)) |
| 29 | + chunk abc next (n - 1) (raw.append_byte b (raw.read_u8 abc at)) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +fn chunks :: |
| 34 | + abc: Bytes |
| 35 | + g: prng.Prng |
| 36 | + n: Int |
| 37 | + acc: List<String> |
| 38 | + -> (List<String>, prng.Prng) |
| 39 | +{ |
| 40 | + if n == 0 |
| 41 | + { |
| 42 | + (list.reverse acc, g) |
| 43 | + } |
| 44 | + else |
| 45 | + { |
| 46 | + let (c, next) = chunk abc g 4096 (raw.builder_with_capacity 4096) |
| 47 | + chunks abc next (n - 1) [c, ..acc] |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/// 8 MiB of pseudo-random text. |
| 52 | +fn corpus :: -> String |
| 53 | +{ |
| 54 | + let abc = alphabet () |
| 55 | + let (base, _) = chunks abc (prng.seeded 380) 256 [] |
| 56 | + let mib = string.concat base |
| 57 | + string.concat [mib, mib, mib, mib, mib, mib, mib, mib] |
| 58 | +} |
| 59 | + |
| 60 | +/// `times` finds and contains of `needle` in `corpus`, summed. |
| 61 | +fn scan :: corpus: String needle: String times: Int acc: Int -> Int |
| 62 | +{ |
| 63 | + if times == 0 |
| 64 | + { |
| 65 | + acc |
| 66 | + } |
| 67 | + else |
| 68 | + { |
| 69 | + let at = match string.find corpus needle { Some(i) -> i, None -> 0 } |
| 70 | + let has = if string.contains corpus needle { 1 } else { 0 } |
| 71 | + scan corpus needle (times - 1) (acc + at + has) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +pub fn main :: -> () / <io> |
| 76 | +{ |
| 77 | + let marker = string.repeat "q" 63 <> "z" |
| 78 | + let corpus = corpus () <> marker |
| 79 | + let needles = |
| 80 | + [ "Q" |
| 81 | + , string.repeat "Q" 4 |
| 82 | + , string.repeat "Q" 16 |
| 83 | + , string.repeat "Q" 64 |
| 84 | + , string.repeat "q" 15 <> "z" |
| 85 | + , marker |
| 86 | + ] |
| 87 | + let total = list.fold needles 0 fn sum n { sum + scan corpus n 25 0 } |
| 88 | + io.println (show total) |
| 89 | +} |
| 90 | +//> 419431650 |