23 May 2012 12:07
Wierd behavior of bytes.Join
Hi,
I have a test that I give as an input to my test program, I then use
readLine to read from the stdin with a buffer of 20 bytes. I have two
different versions of this, the first one [Version 1] uses a
two-dimensional slice which is appended and the joined via bytes.Join.
The second one [Version 2] uses a one-dimensional slice which is
appended to and then printed. The wierd thing is that they give
different output. See code below.
Is my code flawed or is this a bug?
Regards,
Josef
$ cat test
asdfghijklmnopqrstuvxyz
$ cat test | ./test-bug-readline
2012/05/23 10:58:23 asdfghijklmnopqrstuv
2012/05/23 10:58:23 xyz
2012/05/23 10:58:23 "xyz\nghijklmnopqrstuvxyz"
2012/05/23 10:58:23 Line was nil while reading from stdin
$ cat test | ./test-bug-readline
2012/05/23 11:00:39 asdfghijklmnopqrstuv
2012/05/23 11:00:39 xyz
2012/05/23 11:00:39 "asdfghijklmnopqrstuvxyz"
2012/05/23 11:00:39 Line was nil while reading from stdin
[version 1]
$ cat test-bug-readline.go
package main
import (
"bufio"
"bytes"
"io"
"log"
"os"
)
func main() {
r := bufio.NewReaderSize(os.Stdin, 20)
alive := true
lines := make([][]byte, 0)
for alive {
line, isPrefix, err := r.ReadLine()
if line == nil {
alive = false
log.Fatalf("Line was nil while reading from stdin")
}
if err != nil {
if err != io.EOF {
log.Fatalf("Error was cought while reading from stdin, err: %s", err)
}
alive = false
}
if len(line) > 0 {
log.Println(string(line))
lines = append(lines, line)
}
if isPrefix {
continue
}
if alive {
log.Printf("%#v", string(bytes.Join(lines,nil)))
}
lines = make([][]byte, 0)
}
}
[version 2]
$ cat test-bug-readline.go
package main
import (
"bufio"
"io"
"log"
"os"
)
func main() {
r := bufio.NewReaderSize(os.Stdin, 20)
alive := true
lines := make([]byte, 0)
for alive {
line, isPrefix, err := r.ReadLine()
if line == nil {
alive = false
log.Fatalf("Line was nil while reading from stdin")
}
if err != nil {
if err != io.EOF {
log.Fatalf("Error was cought while reading from stdin, err: %s", err)
}
alive = false
}
if len(line) > 0 {
log.Println(string(line))
lines = append(lines, line...)
}
if isPrefix {
continue
}
if alive {
log.Printf("%#v", string(lines))
}
lines = make([]byte, 0)
}
}
RSS Feed