I was following the golang tour and I have been asked to:
Implement a rot13Reader that implements io.Reader and reads from an io.Reader, modifying the stream by applying the ROT13 substitution cipher to all alphabetical characters.
I first implemented the method to the *rot13Reader
type rot13Reader struct {
r io.Reader
}
func (r *rot13Reader) Read(p []byte) (n int, e error){
}
However I can't get my head around this Read method.
Does the p
contain all of the bytes read? And hence all I should do is iterate over them and apply the ROT13 substitution ?
I understand that it should return the number of bytes read and an EOF error at the end of the file however I'm not sure when and how this method is called. So coming back to my original question does the p
contain all of the data read ? If not then how can I get to it?
The io.Reader interface is used by many packages in the Go standard library and it represents the ability to read a stream of data. More specifically allows you to read data from something that implements the io.Reader interface into a slice of bytes.
Reader/Writer are basic interfaces designed in Golang. For example, if a struct have a function like: type Example struct { }func (e *Example) Write(p byte[]) (n int, err error) {}func (e *Example) Read(p byte[]) (n int, err error) {}
It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF.
The io package in Go provides input-output primitives as well as interfaces to them. It is one of the most essential packages in all of GoLang.
You should scan and "rot13" only n
bytes (the one read by the io.Reader
within rot13Reader
).
func (r *rot13Reader) Read(p []byte) (n int, e error){
n, e = r.r.Read(p)
for i:=range(p[:n]) {
p[i]=rot13(p[i])
}
return
}
The rot13Reader
encapsulate any reader and call Read
on said encapsulated Reader.
It returns the rot13'ed content, and the number of byte read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With