Skip to content

Commit

Permalink
Buffered IO.
Browse files Browse the repository at this point in the history
  • Loading branch information
tristanmorgan committed Feb 14, 2024
1 parent 30d378b commit 2e08c71
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
4 changes: 3 additions & 1 deletion cmd/bfg/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@ func main() {
}
inputBuf = bufio.NewReader(file)
}
outputBuf := bufio.NewWriter(os.Stdout)
defer outputBuf.Flush()

program, err := parser.Compile(sourceBuf)
if err != nil {
fmt.Println("error compiling program: err:", err)
os.Exit(1)
}
parser.Execute(program, inputBuf)
parser.Execute(program, inputBuf, outputBuf)
}
17 changes: 13 additions & 4 deletions parser/execute.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package parser

import (
"fmt"
"bufio"
"io"
"math"
)

const dataSize int = math.MaxUint16 + 1

func Execute(program []Instruction, reader io.ByteReader) []int16 {
func Execute(program []Instruction, reader io.ByteReader, writer *bufio.Writer) []int16 {
data := make([]int16, dataSize)
var dataPtr int = 0
var dataPtr, writeCount int = 0, 0
for pc := 0; pc < len(program); pc++ {
switch program[pc].operator {
case opAddDp:
Expand All @@ -19,8 +19,17 @@ func Execute(program []Instruction, reader io.ByteReader) []int16 {
case opAddVal:
data[dataPtr] += int16(program[pc].operand)
case opOut:
fmt.Printf("%c", data[dataPtr]&0xff)
writer.WriteByte(byte(data[dataPtr] & 0xff))
writeCount++
if data[dataPtr] == 10 || writeCount > 200 {
writer.Flush()
writeCount = 0
}
case opIn:
if writeCount > 0 {
writer.Flush()
writeCount = 0
}
readVal, err := reader.ReadByte()
data[dataPtr] = int16(readVal)
if err == io.EOF {
Expand Down
6 changes: 4 additions & 2 deletions parser/execute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package parser

import (
"bufio"
"os"
"reflect"
"strings"
"testing"
)

func TestExecuteSmall(t *testing.T) {
//func Execute(program []Instruction, reader io.ByteReader) []int16
program := []Instruction{
Instruction{opNoop, 0},
Instruction{opAddDp, 5},
Expand All @@ -17,7 +17,9 @@ func TestExecuteSmall(t *testing.T) {
Instruction{opMove, 2},
Instruction{opAddDp, 2},
}
data := Execute(program, bufio.NewReader(strings.NewReader("no input.")))[:10]
outputBuf := bufio.NewWriter(os.Stdout)
inputBuf := bufio.NewReader(strings.NewReader("no input."))
data := Execute(program, inputBuf, outputBuf)[:10]
want := []int16{0, 0, 0, 0, 0, 0, 0, 5, 0, 0}

if !reflect.DeepEqual(data, want) {
Expand Down

0 comments on commit 2e08c71

Please sign in to comment.