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
|
package main
import (
"bufio"
"flag"
"fmt"
"os"
"regexp"
"strings"
"text/tabwriter"
)
type queue struct {
q []string
maxl int
}
func (q *queue) insert(s string) {
if len(q.q) <= q.maxl {
q.q = append(q.q, s)
return
}
q.q = append(q.q[1:len(q.q)], s)
}
func printWithContext(all []string, ind, ctxlen int) {
var slice []string
slice = append(slice, "\""+all[ind]+"\"")
if len(all[:ind]) < ctxlen {
slice = append(all[:ind], slice...)
} else {
slice = append(all[ind-ctxlen:ind], slice...)
}
if len(all[ind:]) < ctxlen {
slice = append(slice, all[ind+1:]...)
} else {
slice = append(slice, all[ind+1:ind+ctxlen]...)
}
fmt.Fprintf(tw, "%s\n", strings.Join(slice, "\t"))
}
func printqueue(q *queue, c chan string, left int) {
if left == 0 {
fmt.Fprintf(tw, "%s\n", strings.Join(q.q, "\t"))
fmt.Fprintf(os.Stdout, "called writer with %v\n", q.q)
return
}
for w := range c {
index := strings.Index(w, kw)
if index < 0 {
q.insert(w)
continue
}
fmt.Fprintf(os.Stdout, "%q totally matched %q\n", w, kw)
fmt.Fprintf(os.Stdout, "queue was %v\n", q.q)
q.insert(fmt.Sprintf("%q", w))
left--
printqueue(q, c, left)
left = 5
}
}
var (
tw *tabwriter.Writer
kw string
)
const MAX int = 11
func main() {
flag.Parse()
kw = flag.Arg(0)
if len(kw) == 0 {
fmt.Printf("Need string to search for. Exiting...\n")
os.Exit(1)
}
tw = tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
splitreg := regexp.MustCompile("[ \t\n]")
q := queue{maxl: MAX, q: make([]string, MAX)}
sc := make(chan string, 1000)
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString(byte('\n'))
go func(c chan string) {
var w string
for err == nil {
splline := splitreg.Split(line, -1)
for _, w = range splline {
c <- w
}
line, err = reader.ReadString(byte('\n'))
}
fmt.Printf("Got an error: %q.\n", err)
c <- w
close(c)
}(sc)
printqueue(&q, sc, 5)
//printWithContext(splline, i, 5)
tw.Flush()
}
|