Skip to content

Commit

Permalink
improve rdstdin: fix genode bug, remove duplication, improve docs
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Jul 7, 2021
1 parent ffce6de commit db88d5b
Showing 1 changed file with 22 additions and 32 deletions.
54 changes: 22 additions & 32 deletions lib/impure/rdstdin.nim
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,24 @@ runnableExamples("-r:off"):
if line.len > 0: echo line
echo "exiting"

when defined(windows):
proc readLineFromStdin*(prompt: string): string {.
tags: [ReadIOEffect, WriteIOEffect].} =
## Reads a line from stdin.
stdout.write(prompt)
result = readLine(stdin)

proc readLineFromStdin*(prompt: string, line: var string): bool {.
tags: [ReadIOEffect, WriteIOEffect].} =
## Reads a `line` from stdin. `line` must not be
## `nil`! May throw an IO exception.
## A line of text may be delimited by `CR`, `LF` or
## `CRLF`. The newline character(s) are not part of the returned string.
## Returns `false` if the end of the file has been reached, `true`
## otherwise. If `false` is returned `line` contains no new data.
stdout.write(prompt)
result = readLine(stdin, line)
const useLinenoise = not (defined(windows) or defined(genode))

elif defined(genode):
proc readLineFromStdin*(prompt: string): string {.
tags: [ReadIOEffect, WriteIOEffect].} =
stdin.readLine()

proc readLineFromStdin*(prompt: string, line: var string): bool {.
tags: [ReadIOEffect, WriteIOEffect].} =
stdin.readLine(line)

else:
when useLinenoise:
import linenoise

proc readLineFromStdin*(prompt: string, line: var string): bool {.
tags: [ReadIOEffect, WriteIOEffect].} =
proc readLineFromStdin*(prompt: string, line: var string): bool {.
tags: [ReadIOEffect, WriteIOEffect].} =
## Reads a `line` from stdin. May raise `IOError`.
##
## A line of text may be delimited by ``\r``, ``\n`` or ``\r\n``, which are not
## part of the returned string.
##
## On platforms that support `linenoise`, it will be used.
##
## Returns `false` if the end of the file has been reached (or `^C` was entered),
## in which case `line.len == 0`. Entering an empty string would still return
## true.
when useLinenoise:
var buffer = linenoise.readLine(prompt)
if isNil(buffer):
line.setLen(0)
Expand All @@ -63,7 +49,11 @@ else:
historyAdd(buffer)
linenoise.free(buffer)
result = true
else:
stdout.write(prompt)
result = readLine(stdin, line)

proc readLineFromStdin*(prompt: string): string {.inline.} =
if not readLineFromStdin(prompt, result):
raise newException(IOError, "Linenoise returned nil")
proc readLineFromStdin*(prompt: string): string {.inline.} =
## Outplace overload.
if not readLineFromStdin(prompt, result):
raise newException(IOError, "no data returned by `readLineFromStdin`")

0 comments on commit db88d5b

Please sign in to comment.