Skip to content

Instantly share code, notes, and snippets.

@robfig
Created April 11, 2015 16:20
Show Gist options
  • Save robfig/cd703205edcd64e46589 to your computer and use it in GitHub Desktop.
Save robfig/cd703205edcd64e46589 to your computer and use it in GitHub Desktop.
gobench Find Words
// Package bench is a package which contains
// programs of Go Benchmark Competition.
package bench
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"strconv"
)
func Find(path, s string) (string, error) {
if s == "" {
return "", errors.New("empty string to search for")
}
var f, err = os.Open(path)
if err != nil {
return "", fmt.Errorf("failed to open file: %v", err)
}
var (
lens = len(s)
sb = []byte(s)
answer = make([]byte, 0, 1<<16)
lineno int64
first = true
scanner = bufio.NewScanner(f)
)
for scanner.Scan() {
lineno++
var line = scanner.Bytes()
if lens > len(line) {
continue
}
for i := range line[:len(line)-lens] {
if bytes.HasPrefix(line[i:], sb) {
if !first {
answer = append(answer, ',')
}
answer = strconv.AppendInt(answer, lineno, 10)
answer = append(answer, ':')
answer = strconv.AppendInt(answer, int64(i), 10)
first = false
}
}
}
return string(answer), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment