summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSilvan Jegen <s.jegen@gmail.com>2015-09-10 19:14:37 +0200
committerSilvan Jegen <s.jegen@gmail.com>2015-10-27 21:40:56 +0100
commit4aadde313e2aca87995c9344d20e5a8c5c9e1e7a (patch)
treeaf9c351d4c67b8372288d1a984cb1127db453bfd
parent8d703bbf3b9abf1042cee87a1612b3c23c5a2c50 (diff)
Use a queue and read from channel (WIP)
-rw-r--r--gwic.go79
1 files changed, 62 insertions, 17 deletions
diff --git a/gwic.go b/gwic.go
index 3c6522a..db35fca 100644
--- a/gwic.go
+++ b/gwic.go
@@ -4,13 +4,26 @@ import (
"bufio"
"flag"
"fmt"
- "io/ioutil"
"os"
"regexp"
"strings"
"text/tabwriter"
)
+type queue struct {
+ q []string
+ l int
+ 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]+"\"")
@@ -30,32 +43,64 @@ func printWithContext(all []string, ind, ctxlen int) {
fmt.Fprintf(tw, "%s\n", strings.Join(slice, "\t"))
}
-var tw *tabwriter.Writer
+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 = 10
func main() {
flag.Parse()
- kw := flag.Arg(0)
+ 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]")
- reader := bufio.NewReader(os.Stdin)
- all, err := ioutil.ReadAll(reader)
- if err != nil {
- fmt.Printf("Could not read everything because there was an error: %q. Exiting\n", err)
- os.Exit(1)
- }
+ q := queue{maxl: MAX, q: make([]string, MAX), l: MAX}
+ sc := make(chan string, 1000)
- splitreg := regexp.MustCompile("[ \t\n]")
- splline := splitreg.Split(string(all), -1)
- for i, w := range splline {
- index := strings.Index(w, kw)
- if index < 0 {
- continue
+ 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'))
}
- printWithContext(splline, i, 5)
- }
+ fmt.Printf("Got an error: %q.\n", err)
+ c <- w
+ close(c)
+ }(sc)
+
+ printqueue(&q, sc, 5)
+ //printWithContext(splline, i, 5)
tw.Flush()
}