From 4aadde313e2aca87995c9344d20e5a8c5c9e1e7a Mon Sep 17 00:00:00 2001 From: Silvan Jegen Date: Thu, 10 Sep 2015 19:14:37 +0200 Subject: Use a queue and read from channel (WIP) --- gwic.go | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file 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() } -- cgit v1.2.1-18-gbd029