go-tour/exercise-rot-reader.go
2020-02-09 10:44:41 -06:00

43 lines
835 B
Go

package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
var rot13Input []byte = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
var rot13Output []byte = []byte("NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")
func indexOf(s []byte, b byte) int {
for i, v := range s {
if v == b {
return i
}
}
return -1
}
func (r rot13Reader) Read(b []byte) (n int, err error) {
n, err = r.r.Read(b)
if err == nil {
for i := 0; i < n; i++ {
c := b[i]
if j := indexOf(rot13Input, c); j > -1 {
b[i] = rot13Output[j]
}
}
}
return n, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}