Created
September 4, 2013 15:59
-
-
Save flc/6439105 to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Rot13 Reader
http://tour.golang.org/#61
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" | |
//"fmt" | |
"bytes" | |
) | |
var ascii_uppercase = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
var ascii_lowercase = []byte("abcdefghijklmnopqrstuvwxyz") | |
var ascii_uppercase_len = len(ascii_uppercase) | |
var ascii_lowercase_len = len(ascii_lowercase) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func rot13(b byte) byte { | |
pos := bytes.IndexByte(ascii_uppercase, b) | |
if pos != -1 { | |
return ascii_uppercase[(pos+13) % ascii_uppercase_len] | |
} | |
pos = bytes.IndexByte(ascii_lowercase, b) | |
if pos != -1 { | |
return ascii_lowercase[(pos+13) % ascii_lowercase_len] | |
} | |
return b | |
} | |
func (r rot13Reader) Read(p []byte) (n int, err error) { | |
n, err = r.r.Read(p) | |
for i := 0; i < n; i++ { | |
p[i] = rot13(p[i]) | |
} | |
return n, err | |
} | |
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
Hey, looks like almost nobody noticed that there's an exclamation mark at the end of the string :)