Advertisement
Guest User

Untitled

a guest
May 28th, 2015
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. // Package bench is a package which contains
  2. // programs of Go Benchmark Competition.
  3. package bench
  4.  
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "os"
  10. )
  11.  
  12. var ErrNoWord = errors.New("Must pass word in")
  13.  
  14. type Match struct {
  15. line int
  16. col int
  17. len int
  18. }
  19.  
  20. func printMatches(matches []Match) string {
  21. var buf bytes.Buffer
  22. for _, m := range matches {
  23. buf.WriteString(fmt.Sprintf("%d:%d,", m.line, m.col))
  24. }
  25. s := buf.String()
  26. return s[:len(s)-1]
  27. }
  28.  
  29. // Find reads the text file on the `path`,
  30. // finds the `s` words on the file and
  31. // returns the row numbers and indices
  32. // in the form of `r:c,r:c,...r:c`,
  33. // at which the `s` word exists.
  34. func Find(path, s string) (string, error) {
  35. if s == "" {
  36. return "", ErrNoWord
  37. }
  38. f, err := os.Open(path)
  39. if err != nil {
  40. return "", err
  41. }
  42. defer f.Close()
  43. bs := []byte(s)
  44. var buf [4096]byte
  45. matches := make([]Match, 0, 16)
  46. maybe := make([]Match, 0, 8)
  47. newmaybe := make([]Match, 0, 8)
  48. col := 0
  49. line := 1
  50. for n, err := f.Read(buf[:]); n > 0; {
  51. for i := 0; i < n; i++ {
  52. if buf[i] == '\n' {
  53. col = 0
  54. line++
  55. maybe = maybe[:0]
  56. continue
  57. }
  58. newmaybe := newmaybe[:0]
  59. for _, m := range maybe {
  60. if m.len == len(bs) {
  61. matches = append(matches, m)
  62. continue
  63. }
  64. if bs[m.len] == buf[i] {
  65. m.len++
  66. newmaybe = append(newmaybe, m)
  67. }
  68. }
  69. if bs[0] == buf[i] {
  70. newmaybe = append(newmaybe, Match{line, col, 1})
  71. }
  72. maybe = newmaybe
  73. col++
  74. }
  75. if n < len(buf) || err != nil {
  76. break
  77. }
  78. }
  79. for _, m := range maybe {
  80. if m.len == len(bs) {
  81. matches = append(matches, m)
  82. }
  83. }
  84. if len(matches) == 0 {
  85. return "", nil
  86. }
  87. return printMatches(matches), nil
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement