search_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package strings_test
  5. import (
  6. "reflect"
  7. . "strings"
  8. "testing"
  9. )
  10. func TestFinderNext(t *testing.T) {
  11. testCases := []struct {
  12. pat, text string
  13. index int
  14. }{
  15. {"", "", 0},
  16. {"", "abc", 0},
  17. {"abc", "", -1},
  18. {"abc", "abc", 0},
  19. {"d", "abcdefg", 3},
  20. {"nan", "banana", 2},
  21. {"pan", "anpanman", 2},
  22. {"nnaaman", "anpanmanam", -1},
  23. {"abcd", "abc", -1},
  24. {"abcd", "bcd", -1},
  25. {"bcd", "abcd", 1},
  26. {"abc", "acca", -1},
  27. {"aa", "aaa", 0},
  28. {"baa", "aaaaa", -1},
  29. {"at that", "which finally halts. at that point", 22},
  30. }
  31. for _, tc := range testCases {
  32. got := StringFind(tc.pat, tc.text)
  33. want := tc.index
  34. if got != want {
  35. t.Errorf("stringFind(%q, %q) got %d, want %d\n", tc.pat, tc.text, got, want)
  36. }
  37. }
  38. }
  39. func TestFinderCreation(t *testing.T) {
  40. testCases := []struct {
  41. pattern string
  42. bad [256]int
  43. suf []int
  44. }{
  45. {
  46. "abc",
  47. [256]int{'a': 2, 'b': 1, 'c': 3},
  48. []int{5, 4, 1},
  49. },
  50. {
  51. "mississi",
  52. [256]int{'i': 3, 'm': 7, 's': 1},
  53. []int{15, 14, 13, 7, 11, 10, 7, 1},
  54. },
  55. // From https://www.cs.utexas.edu/~moore/publications/fstrpos.pdf
  56. {
  57. "abcxxxabc",
  58. [256]int{'a': 2, 'b': 1, 'c': 6, 'x': 3},
  59. []int{14, 13, 12, 11, 10, 9, 11, 10, 1},
  60. },
  61. {
  62. "abyxcdeyx",
  63. [256]int{'a': 8, 'b': 7, 'c': 4, 'd': 3, 'e': 2, 'y': 1, 'x': 5},
  64. []int{17, 16, 15, 14, 13, 12, 7, 10, 1},
  65. },
  66. }
  67. for _, tc := range testCases {
  68. bad, good := DumpTables(tc.pattern)
  69. for i, got := range bad {
  70. want := tc.bad[i]
  71. if want == 0 {
  72. want = len(tc.pattern)
  73. }
  74. if got != want {
  75. t.Errorf("boyerMoore(%q) bad['%c']: got %d want %d", tc.pattern, i, got, want)
  76. }
  77. }
  78. if !reflect.DeepEqual(good, tc.suf) {
  79. t.Errorf("boyerMoore(%q) got %v want %v", tc.pattern, good, tc.suf)
  80. }
  81. }
  82. }