hi, guys,
var s:string="a\0b\0c"
echo s
I just get "a", while the left part, I mean "b" and "c', is missing. The similar situation is in seq[string] or seq[char]. I guess it's probably because the first '0' is taken as the end of the string. But is there any way to get around and print the whole string like "a b c"?You could replace the 0 with something printable or remove them:
import strutils
var s = "a\0b\0c"
echo s.replace("\0", "\\0")
echo s.replace("\0", "")
echo s.repr
for c in s: write(stdout, c)
write(stdout, "\n")
proc stringToHex(s: string): string =
result = ""
for o,c in s:
if o != 0:
result.add ' '
result.add c.int.toHex(2)
echo s.stringToHex
It's not that simple to fix without rewriting the IO layer so that 'echo' remains thread-safe.
@Araq
Challenges are to be overcome by the brilliants. @Araq, you're one of them. We all expect nim to be better. :P
What about:
proc echoBinSafe*(args: varargs[string, `$`]) =
proc fwrite (buf: cstring, size, n: int, f: File) {.importc, noDecl.}
proc flockfile(f: File) {.importc, noDecl.}
proc funlockfile(f: File) {.importc, noDecl.}
flockfile(stdout)
for s in args:
fwrite(s.cstring, s.len, 1, stdout)
const linefeed = "\n" # can be 1 or more chars
fwrite(linefeed.cstring, linefeed.len, 1, stdout)
funlockfile(stdout)
var s = "a\0b\0c"
echoBinSafe s, "Hello World!"
echo "done"
Afaik this is thread safe and does not alloc ram.. and handles newlines. I guess it will not work on windows though. But who uses windows anyway (little joke).