Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

byte[] is a bytes buffer, a sequence of bytes. io.Reader is an abstraction around a read stream. You can adapt a byte[] to a Reader by wrapping it in a bytes.Reader, that way if a function needs a reader and you have bytes, you can give them your bytes.

The problem TFA has, is that bytes.Reader implies a copy: it's going to read data into a second internal slice. So when all their library needs is the bytes, they could use the bytes themselves, and avoid a potentially expensive copy.

Obviously you could just have a second entry point which takes straight byte[] instead of a reader, but in this case they're trying to conform to the standard library's image module[1] which does not expose a bytes interface and conditionally adds further indirection layers.

[1]: https://pkg.go.dev/image



> is that bytes.Reader implies a copy

Yes, that's what "smelled" wrong to me too. Is it avoidable or does Go's stdlib force you to go through xxx.Reader reading from yyy.Reader that is made from a zzz.Reader and a ttt.Reader?


Unless you know the concrete reader types and they expose their underlying reader or concrete type, short of unsafe yes. And as the essay points out, neither bytes.Reader nor bufio.Reader expose the underlying type.


There's io.ReaderFrom and io.WriterTo, which can avoid internal buffering.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: