Created
December 25, 2013 02:21
-
-
Save kaipakartik/8119695 to your computer and use it in GitHub Desktop.
Exercise: Rot13 Reader A common pattern is an io.Reader that wraps another io.Reader, modifying the stream in some way.
This file contains hidden or 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(reader *rot13Reader) Read(p []byte) (n int, err error) { | |
n, err = reader.r.Read(p) | |
for i := range(p) { | |
p[i] = rot13(p[i]) | |
} | |
return | |
} | |
func rot13(b byte) (c byte) { | |
switch { | |
case b >= 'A' && b <= 'Z': | |
c = (b - 'A' + 13) % 26 + 'A' | |
case b >= 'a' && b <= 'z': | |
c = (b - 'a' + 13) % 26 + 'a' | |
default: | |
c = b | |
} | |
return | |
} | |
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