diff options
| author | Jeroen van Rijn <Kelimion@users.noreply.github.com> | 2022-06-16 12:34:13 +0200 |
|---|---|---|
| committer | Jeroen van Rijn <Kelimion@users.noreply.github.com> | 2022-06-16 12:34:13 +0200 |
| commit | 9f413862e985a984773df6b6f63641f9497948be (patch) | |
| tree | 578b00213ae32ef70547024e704a8ee2f12b2b13 /core/strings | |
| parent | b8802d7df769b257fcac0bc1c976e67fd1339b05 (diff) | |
Add `strings.prefix_length` & `slice.prefix_length`
Diffstat (limited to 'core/strings')
| -rw-r--r-- | core/strings/strings.odin | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/core/strings/strings.odin b/core/strings/strings.odin index 2429b451d..678cc94cd 100644 --- a/core/strings/strings.odin +++ b/core/strings/strings.odin @@ -216,6 +216,29 @@ equal_fold :: proc(u, v: string) -> bool { } /* + return the prefix length common between strings `a` and `b`. + + strings.prefix_length("testing", "test") -> 4 + strings.prefix_length("testing", "te") -> 2 + strings.prefix_length("telephone", "te") -> 2 + strings.prefix_length("testing", "est") -> 0 +*/ +prefix_length :: proc(a, b: string) -> (n: int) { + _len := min(len(a), len(b)) + idx := 0 + + #no_bounds_check for idx < _len && a[idx] == b[idx] { + idx += 1 + + if a[idx] & 128 != 128 { + // new codepoint or end of multi-byte codepoint, update match length + n = idx + } + } + return +} + +/* return true when the string `prefix` is contained at the start of the string `s` strings.has_prefix("testing", "test") -> true |