Reputation: 2792
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?
Upvotes: 11
Views: 7388
Reputation: 1329662
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.
Upvotes: 7