From 11641596fa34073e8c137dd4019793ebc2d31424 Mon Sep 17 00:00:00 2001
From: Aadhavan Srinivasan <aadhavan@twomorecents.org>
Date: Sun, 17 Nov 2024 21:49:11 -0500
Subject: [PATCH] Read multiple lines from stdin and apply regex to each one;
 Convert the array of matchIndex structs into a flat array of indices; speeds
 up process of checking if we have to print a character in color

---
 main.go | 50 ++++++++++++++++++++++++++++----------------------
 1 file changed, 28 insertions(+), 22 deletions(-)

diff --git a/main.go b/main.go
index d92d56f..816b8f1 100644
--- a/main.go
+++ b/main.go
@@ -383,33 +383,39 @@ func main() {
 	var re string
 	re = os.Args[1]
 	var test_str string
-	// Read test string from stdin
+	var err error
+	// Create reader for stdin and writer for stdout
 	reader := bufio.NewReader(os.Stdin)
-	test_str, err := reader.ReadString('\n')
-	if err != nil && err != io.EOF {
-		panic(err)
-	}
-	//fmt.Scanln(&test_str)
+	out := bufio.NewWriter(os.Stdout)
+
 	re_postfix := shuntingYard(re)
 	startState := thompson(re_postfix)
-	matchIndices := findAllMatches(startState, test_str)
-
-	inColor := false
-	if len(matchIndices) > 0 {
-		for i, c := range test_str {
-			for _, indices := range matchIndices {
-				if i >= indices.startIdx && i < indices.endIdx {
-					color.New(color.FgRed).Printf("%c", c)
-					inColor = true
-					break
+	// Read every string from stdin until we encounter an error. If the error isn't EOF, panic.'
+	for test_str, err = reader.ReadString('\n'); err == nil; test_str, err = reader.ReadString('\n') {
+		matchIndices := findAllMatches(startState, test_str)
+		// Decompose the array of matchIndex structs into a flat unique array of ints - if matchIndex is {4,7}, flat array will contain 4,5,6
+		// This should make checking O(1) instead of O(n)
+		indicesToPrint := new_uniq_arr[int]()
+		for _, idx := range matchIndices {
+			indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...)
+		}
+		if len(matchIndices) > 0 {
+			for i, c := range test_str {
+				if indicesToPrint.contains(i) {
+					color.New(color.FgRed).Fprintf(out, "%c", c)
+				} else {
+					fmt.Fprintf(out, "%c", c)
 				}
 			}
-			if inColor == false {
-				fmt.Printf("%c", c)
-			}
-			inColor = false
+		} else {
+			fmt.Fprint(out, test_str)
+		}
+		err = out.Flush()
+		if err != nil {
+			panic(err)
 		}
-	} else {
-		fmt.Print(test_str)
+	}
+	if err != io.EOF {
+		panic(err)
 	}
 }