Here is my implementation of the exercise using strings.Map (the rot13 function is straight out of golang's docs). The issue is that the buffer does not seem to be modified after the Read function returns. Here is the code:
package main
import (
"io"
"os"
"strings"
"fmt"
)
type rot13Reader struct {
r io.Reader
}
func (reader *rot13Reader) Read(b []byte) (int, error) {
rot13 := func(r rune) rune {
switch {
case r >= 'A' && r <= 'Z':
return 'A' + (r-'A'+13)%26
case r >= 'a' && r <= 'z':
return 'a' + (r-'a'+13)%26
}
return r
}
n, err := reader.r.Read(b)
result := []byte(strings.Map(rot13, string(b)))
b = []byte(result)
fmt.Println(string(b))
return n, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
and the output:
You cracked the code!
Lbh penpxrq gur pbqr!You cracked the code!
Clearly the buffer has been modified in the Read function, but it does not seem to be the case after it returns. If I were to comment out the fmt.Println(string(b))
, the output would just be:
Lbh penpxrq gur pbqr!
Is there something quirky about Readers and Writers that I should know about?