-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmatch.go
117 lines (99 loc) · 1.71 KB
/
match.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// ported from http://cellperformance-snippets.googlecode.com/files/match.c
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"os"
)
var (
hex = flag.Bool("h", false, "output hex")
)
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() != 2 {
usage()
}
source := open(flag.Arg(0))
defer source.Close()
uniq := open(flag.Arg(1))
defer uniq.Close()
for {
index := uint64(0)
found := false
line, err := source.Line()
if err != nil {
break
}
for {
xline, err := uniq.Line()
if err != nil {
break
}
if line == xline {
if *hex {
fmt.Printf("%#08x\n", index)
} else {
fmt.Printf("%d\n", index)
}
found = true
break
}
index++
}
if !found {
fmt.Println("NO MATCH")
}
uniq.Reset()
}
}
func open(name string) *Reader {
f, err := os.Open(name)
ck(err)
return &Reader{File: f, Reader: bufio.NewReader(f)}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: match [-h] <source_file> <uniq_file>")
flag.PrintDefaults()
os.Exit(2)
}
func ck(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "match:", err)
os.Exit(1)
}
}
type Reader struct {
*os.File
*bufio.Reader
err error
}
func (r *Reader) Reset() {
r.File.Seek(0, io.SeekStart)
r.Reader.Reset(r.File)
}
func (r *Reader) Line() (string, error) {
if r.err != nil {
return "", r.err
}
var buf bytes.Buffer
for {
ch, _, err := r.ReadRune()
if err != nil {
str := buf.String()
if str == "" {
return str, err
}
r.err = err
return str, nil
}
buf.WriteRune(ch)
if ch == '\n' {
break
}
}
return buf.String(), nil
}