diff options
author | Julien Dessaux | 2021-10-04 23:47:22 +0200 |
---|---|---|
committer | Julien Dessaux | 2021-10-04 23:47:22 +0200 |
commit | 9e29dd5678d463426d224ad50014a37b04ff34cc (patch) | |
tree | 114dfe6e65f720b00cb4039bccf1ca8288e06779 | |
parent | Cosmetics (diff) | |
download | nimfunge98-9e29dd5678d463426d224ad50014a37b04ff34cc.tar.gz nimfunge98-9e29dd5678d463426d224ad50014a37b04ff34cc.tar.bz2 nimfunge98-9e29dd5678d463426d224ad50014a37b04ff34cc.zip |
Implemented Funge-98 IO procedures
-rw-r--r-- | src/defaultIO.nim | 40 | ||||
-rw-r--r-- | tests/defaultIO.nim | 25 |
2 files changed, 65 insertions, 0 deletions
diff --git a/src/defaultIO.nim b/src/defaultIO.nim new file mode 100644 index 0000000..52bcb83 --- /dev/null +++ b/src/defaultIO.nim @@ -0,0 +1,40 @@ +import strformat + +## We keep the last input char to handle a pain point in the funge-98 spec : +## when reading from the decimal input you need to read until you encounter a +## non numeric char, but not drop it +var defaultInputLastChar: ref int + +var stdIoUnbuffered = false + +proc defaultCharacterInput*(): int = + if defaultInputLastChar != nil: + result = defaultInputLastChar[] + defaultInputLastChar = nil + return result + if not stdIoUnbuffered: + setStdIoUnbuffered() + stdIoUnbuffered = true + return stdin.readChar().int() + +proc defaultDecimalInput*(): int = + while true: # First we need to find the next numeric char + let c = defaultCharacterInput() + if c >= int('0') and c <= int('9'): + result = c - int('0') + break + while true: # then we read until we encounter a non numeric char + let c = defaultCharacterInput() + if c >= int('0') and c <= int('9'): + result = result * 10 + c - int('0') + else: + new(defaultInputLastChar) + defaultInputLastChar[] = c + break + return result + +proc defaultCharacterOutput*(v: int) = + discard stdout.writeChars(@[v.char()], 0, 1) + +proc defaultDecimalOutput*(v: int) = + stdout.write(&"{v}") diff --git a/tests/defaultIO.nim b/tests/defaultIO.nim new file mode 100644 index 0000000..2de2330 --- /dev/null +++ b/tests/defaultIO.nim @@ -0,0 +1,25 @@ +discard """ + input: "ab1234cd12f" + output: ''' +[Suite] defaultIO +gh789 + ''' +""" + +import unittest + +include ../src/defaultIO + +suite "defaultIO": + test "defaultCharacterInput": + check defaultCharacterInput() == 'a'.int + check defaultCharacterInput() == 'b'.int + check defaultCharacterInput() == '1'.int + test "defaultDecimalInput": + check defaultDecimalInput() == 234 + check defaultCharacterInput() == 'c'.int + test "defaultCharacterOutput": + defaultCharacterOutput('g'.int) + defaultCharacterOutput('h'.int) + test "defaultDecimalOutput": + defaultDecimalOutput(789) |