From b5202b28c519215490805407928285c05a058575 Mon Sep 17 00:00:00 2001 From: Parnic Date: Sun, 12 Jun 2022 23:49:13 -0500 Subject: [PATCH] Allow intcode programs to be halted externally This is simplest to do during an input or output callback, but could potentially also be done to a program running on a goroutine. --- utilities/intcode.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/utilities/intcode.go b/utilities/intcode.go index efdeb44..f0bf4b4 100644 --- a/utilities/intcode.go +++ b/utilities/intcode.go @@ -24,9 +24,10 @@ const ( ) type IntcodeProgram struct { - memory []int64 - program []int64 - relativeBase int + memory []int64 + program []int64 + relativeBase int + haltRequested bool } type IntcodeProgramState struct { @@ -141,7 +142,7 @@ func (p *IntcodeProgram) RunIn(inputFunc ProvideInputFunc, outputFunc ReceiveOut p.init() inputsRequested := 0 - for instructionPointer := 0; instructionPointer < len(p.program); { + for instructionPointer := 0; instructionPointer < len(p.program) && !p.haltRequested; { instruction := p.GetMemory(instructionPointer) instructionPointer++ @@ -247,4 +248,10 @@ func (p *IntcodeProgram) RunIn(inputFunc ProvideInputFunc, outputFunc ReceiveOut panic(fmt.Sprintf("exception executing program - unhandled opcode %d", opcode)) } } + + p.haltRequested = false +} + +func (p *IntcodeProgram) Stop() { + p.haltRequested = true }