Skip to content

Instantly share code, notes, and snippets.

@rbehrends
Created May 1, 2014 22:12
Show Gist options
  • Save rbehrends/c63debe2ee689ccd5ff3 to your computer and use it in GitHub Desktop.
Save rbehrends/c63debe2ee689ccd5ff3 to your computer and use it in GitHub Desktop.
import strutils
# similar to lc2.c
proc c_memchr(cstr: pointer, c:cint, p:csize): pointer {.
importc: "memchr", header: "<string.h>".}
const BufSize = 8192
type CharBuf = array[BufSize, char]
# XXX this doesn't seem to be working.
proc mycountLines*(s: var CharBuf, len:int): int =
let start = cast[int](addr(s))
var p: pointer = addr(s)
var off = 0
while off < len:
p = c_memchr(p, 10, len-off)
if p.isNil: break
p = cast[pointer](cast[int](p)+1)
off = cast[int](p) - start
inc result
proc main =
var
rlen = 0
totlen = 0
buf: CharBuf
lc = 0
totlines = 0
f = stdin
while true:
rlen = f.readBuffer(addr(buf), BufSize)
if rlen == 0: break
lc = buf.mycountLines(rlen)
totlines.inc(lc)
totlen.inc(rlen)
echo totlen
echo totlines
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment