Last active
August 29, 2015 14:18
-
-
Save tobgu/4cd1ed1c3d9c421fb5d7 to your computer and use it in GitHub Desktop.
gobench competition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package bench is a package which contains | |
// programs of Go Benchmark Competition. | |
package bench | |
import ( | |
"errors" | |
"bufio" | |
"os" | |
"fmt" | |
"bytes" | |
"strconv" | |
) | |
func Find(path, s string) (string, error) { | |
bS := []byte(s) | |
if len(bS) == 0 { | |
return "", errors.New("String cannot be empty"); | |
} | |
file, err := os.Open(path) | |
if err != nil { | |
return "", err | |
} | |
scanner := bufio.NewScanner(file) | |
i := 1 | |
buffer := make([]byte, 0, 16384) | |
hasHit := false | |
for scanner.Scan() { | |
line := scanner.Bytes() | |
offset := 0; | |
for { | |
index := bytes.Index(line[offset:], bS) | |
if index >= 0 { | |
offset += index | |
if hasHit { | |
buffer = append(buffer, 44) | |
} else { | |
hasHit = true | |
} | |
buffer = strconv.AppendInt(buffer, int64(i), 10) | |
buffer = append(buffer, 58) | |
buffer = strconv.AppendInt(buffer, int64(offset), 10) | |
offset++ | |
} else { | |
break; | |
} | |
} | |
i += 1 | |
} | |
if err := scanner.Err(); err != nil { | |
fmt.Fprintln(os.Stderr, "Error reading file", err) | |
} | |
return string(buffer), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment