Created
February 9, 2016 23:38
-
-
Save jion/ae53f2ef443ceb0aa644 to your computer and use it in GitHub Desktop.
My solution to "rot13Reader" excercise of "A Tour of Go"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func (rot *rot13Reader) Read(b []byte) (int, error) { | |
n, err := rot.r.Read(b) | |
for i := 0; i < n; i++ { | |
b[i] = rot13(b[i]) | |
} | |
return n, err | |
} | |
func rot13(c byte) byte { | |
var offset int | |
switch { | |
case c <= 'Z' && c >= 'A': | |
offset = int('A') | |
case c <= 'z' && c >= 'a': | |
offset = int('a') | |
default: | |
return c | |
} | |
return byte(offset + (int(c)-offset+13)%26) | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment