lib_ropes: better buffering in equalsFile, cleanups

This commit is contained in:
Jacek Sieka 2015-04-08 23:26:44 +08:00
commit 76a316bd35

View file

@ -340,29 +340,46 @@ proc addf*(c: var Rope, frmt: string, args: openArray[Rope]) {.
## shortcut for ``add(c, frmt % args)``. ## shortcut for ``add(c, frmt % args)``.
add(c, frmt % args) add(c, frmt % args)
const
bufSize = 1024 # 1 KB is reasonable
proc equalsFile*(r: Rope, f: File): bool {.rtl, extern: "nro$1File".} = proc equalsFile*(r: Rope, f: File): bool {.rtl, extern: "nro$1File".} =
## returns true if the contents of the file `f` equal `r`. ## returns true if the contents of the file `f` equal `r`.
var bufSize = 1024 # reasonable start value var
var buf = alloc(bufSize) buf: array[bufSize, char]
for s in leaves(r): bpos = buf.len
if s.len > bufSize: blen = buf.len
bufSize = max(bufSize * 2, s.len)
buf = realloc(buf, bufSize)
var readBytes = readBuffer(f, buf, s.len)
result = readBytes == s.len and equalMem(buf, cstring(s), s.len)
if not result: break
if result:
result = readBuffer(f, buf, 1) == 0 # really at the end of file?
dealloc(buf)
proc equalsFile*(r: Rope, f: string): bool {.rtl, extern: "nro$1Str".} = for s in leaves(r):
var spos = 0
let slen = s.len
while spos < slen:
if bpos == blen:
# Read more data
bpos = 0
blen = readBuffer(f, addr(buf[0]), buf.len)
if blen == 0: # no more data in file
result = false
return
let n = min(blen - bpos, slen - spos)
# TODO There's gotta be a better way of comparing here...
if not equalMem(addr(buf[bpos]),
cast[pointer](cast[int](cstring(s))+spos), n):
result = false
return
spos += n
bpos += n
result = readBuffer(f, addr(buf[0]), 1) == 0 # check that we've read all
proc equalsFile*(r: Rope, filename: string): bool {.rtl, extern: "nro$1Str".} =
## returns true if the contents of the file `f` equal `r`. If `f` does not ## returns true if the contents of the file `f` equal `r`. If `f` does not
## exist, false is returned. ## exist, false is returned.
var bin: File var f: File
result = open(bin, f) result = open(f, filename)
if result: if result:
result = equalsFile(r, bin) result = equalsFile(r, f)
close(bin) close(f)
new(N) # init dummy node for splay algorithm new(N) # init dummy node for splay algorithm