Skip to content

Commit

Permalink
fixes nim-lang#21273; fixes an io.readLine off by one bug [backport 1…
Browse files Browse the repository at this point in the history
….0] (nim-lang#21276)

fixes nim-lang#21273; io.readLine off by one
  • Loading branch information
ringabout authored and bung87 committed Jul 29, 2023
1 parent 96334c4 commit 3edbfda
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/std/syncio.nim
Expand Up @@ -484,11 +484,12 @@ proc readLine*(f: File, line: var string): bool {.tags: [ReadIOEffect],
if last > 0 and line[last-1] == '\c':
line.setLen(last-1)
return last > 1 or fgetsSuccess
# We have to distinguish between two possible cases:
elif last > 0 and line[last-1] == '\0':
# We have to distinguish among three possible cases:
# \0\l\0 => line ending in a null character.
# \0\l\l => last line without newline, null was put there by fgets.
elif last > 0 and line[last-1] == '\0':
if last < pos + sp - 1 and line[last+1] != '\0':
# \0\l => last line without newline, null was put there by fgets.
if last >= pos + sp - 1 or line[last+1] != '\0': # bug #21273
dec last
line.setLen(last)
return last > 0 or fgetsSuccess
Expand Down
18 changes: 18 additions & 0 deletions tests/stdlib/tio.nim
Expand Up @@ -36,3 +36,21 @@ block: # readChars
break
doAssert n2s == @[2,2,2,1,0]
doAssert s2 == s


import std/strutils

block: # bug #21273
let FILE = buildDir / "D20220119T134305.txt"

let hex = "313632313920313632343720313632353920313632363020313632393020323035363520323037323120323131353020323239393820323331303520323332313020323332343820323332363820"


writeFile FILE, parseHexStr(hex)

doAssert readFile(FILE).toHex == hex

let f = open(FILE)
var s = newString(80)
while f.readLine(s):
doAssert s.toHex == hex

0 comments on commit 3edbfda

Please sign in to comment.