Created
March 23, 2014 09:37
-
-
Save dz1984/9720784 to your computer and use it in GitHub Desktop.
"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
/* | |
Exercise: Rot13 Reader | |
A common pattern is an io.Reader that wraps another io.Reader, modifying the stream in some way. | |
For example, the gzip.NewReader function takes an io.Reader (a stream of gzipped data) and returns a *gzip.Reader that also implements io.Reader (a stream of the decompressed data). | |
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. | |
The rot13Reader type is provided for you. Make it an io.Reader by implementing its Read method. | |
*/ | |
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func (rot *rot13Reader) Read(p []byte) (n int, err error){ | |
n,err = rot.r.Read(p) | |
for i,b := range p { | |
p[i] = rot.Rot13(b); | |
} | |
return | |
} | |
func (rot *rot13Reader) Rot13 (b byte) byte { | |
var a, z byte | |
switch { | |
case 'a' <= b && b <= 'z': | |
a, z = 'a', 'z' | |
case 'A' <= b && b <= 'Z': | |
a, z = 'A', 'Z' | |
default: | |
return b | |
} | |
return (b-a+13)%(z-a+1) + a | |
} | |
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