|
| 1 | +package check |
| 2 | + |
| 3 | +import "testing" |
| 4 | + |
| 5 | +// runeSpanToBytes underpins every anchored alert; an off-by-one here |
| 6 | +// mislocates findings rather than failing loudly. |
| 7 | +func TestRuneSpanToBytes(t *testing.T) { |
| 8 | + cases := []struct { |
| 9 | + name string |
| 10 | + s string |
| 11 | + from, to int |
| 12 | + want string |
| 13 | + ok bool |
| 14 | + }{ |
| 15 | + {"ascii start", "hello world", 0, 5, "hello", true}, |
| 16 | + {"ascii middle", "hello world", 6, 11, "world", true}, |
| 17 | + {"ascii to end", "hello", 0, 5, "hello", true}, |
| 18 | + {"empty span", "hello", 2, 2, "", true}, |
| 19 | + {"multibyte before", "héllo wörld", 6, 11, "wörld", true}, |
| 20 | + {"multibyte inside", "héllo", 0, 5, "héllo", true}, |
| 21 | + {"emoji", "a 🎉 b", 2, 3, "🎉", true}, |
| 22 | + {"cjk", "漢字テスト", 0, 2, "漢字", true}, |
| 23 | + {"whole string", "naïve", 0, 5, "naïve", true}, |
| 24 | + {"negative", "abc", -1, 2, "", false}, |
| 25 | + {"reversed", "abc", 2, 1, "", false}, |
| 26 | + } |
| 27 | + |
| 28 | + for _, c := range cases { |
| 29 | + t.Run(c.name, func(t *testing.T) { |
| 30 | + lo, hi, ok := runeSpanToBytes(c.s, c.from, c.to) |
| 31 | + if ok != c.ok { |
| 32 | + t.Fatalf("ok = %v, want %v", ok, c.ok) |
| 33 | + } |
| 34 | + if !ok { |
| 35 | + return |
| 36 | + } |
| 37 | + if got := c.s[lo:hi]; got != c.want { |
| 38 | + t.Errorf("s[%d:%d] = %q, want %q", lo, hi, got, c.want) |
| 39 | + } |
| 40 | + }) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// The conversion must agree with the rune slicing it replaces, for every span |
| 45 | +// of a multi-byte string. |
| 46 | +func TestRuneSpanToBytesMatchesRuneSlicing(t *testing.T) { |
| 47 | + for _, s := range []string{ |
| 48 | + "hello world", |
| 49 | + "héllo wörld", |
| 50 | + "漢字テストです", |
| 51 | + "a 🎉 b 😀 c", |
| 52 | + "naïve café résumé", |
| 53 | + "", |
| 54 | + } { |
| 55 | + runes := []rune(s) |
| 56 | + for from := 0; from <= len(runes); from++ { |
| 57 | + for to := from; to <= len(runes); to++ { |
| 58 | + lo, hi, ok := runeSpanToBytes(s, from, to) |
| 59 | + if !ok { |
| 60 | + t.Fatalf("%q [%d:%d]: not ok", s, from, to) |
| 61 | + } |
| 62 | + want := string(runes[from:to]) |
| 63 | + if got := s[lo:hi]; got != want { |
| 64 | + t.Errorf("%q [%d:%d] = %q, want %q", s, from, to, got, want) |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments