Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Package bench is a package which contains
- // programs of Go Benchmark Competition.
- package bench
- import (
- "bytes"
- "errors"
- "fmt"
- "os"
- )
- var ErrNoWord = errors.New("Must pass word in")
- type Match struct {
- line int
- col int
- len int
- }
- func printMatches(matches []Match) string {
- var buf bytes.Buffer
- for _, m := range matches {
- buf.WriteString(fmt.Sprintf("%d:%d,", m.line, m.col))
- }
- s := buf.String()
- return s[:len(s)-1]
- }
- // Find reads the text file on the `path`,
- // finds the `s` words on the file and
- // returns the row numbers and indices
- // in the form of `r:c,r:c,...r:c`,
- // at which the `s` word exists.
- func Find(path, s string) (string, error) {
- if s == "" {
- return "", ErrNoWord
- }
- f, err := os.Open(path)
- if err != nil {
- return "", err
- }
- defer f.Close()
- bs := []byte(s)
- var buf [4096]byte
- matches := make([]Match, 0, 16)
- maybe := make([]Match, 0, 8)
- newmaybe := make([]Match, 0, 8)
- col := 0
- line := 1
- for n, err := f.Read(buf[:]); n > 0; {
- for i := 0; i < n; i++ {
- if buf[i] == '\n' {
- col = 0
- line++
- maybe = maybe[:0]
- continue
- }
- newmaybe := newmaybe[:0]
- for _, m := range maybe {
- if m.len == len(bs) {
- matches = append(matches, m)
- continue
- }
- if bs[m.len] == buf[i] {
- m.len++
- newmaybe = append(newmaybe, m)
- }
- }
- if bs[0] == buf[i] {
- newmaybe = append(newmaybe, Match{line, col, 1})
- }
- maybe = newmaybe
- col++
- }
- if n < len(buf) || err != nil {
- break
- }
- }
- for _, m := range maybe {
- if m.len == len(bs) {
- matches = append(matches, m)
- }
- }
- if len(matches) == 0 {
- return "", nil
- }
- return printMatches(matches), nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement