Created
May 5, 2020 22:34
-
-
Save atemate/18350323136104a8d06c4a0496d60074 to your computer and use it in GitHub Desktop.
A Tour of Go: Exercise: rot13Reader https://tour.golang.org/methods/23
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 (r13 *rot13Reader) Read(s []byte) (int, error) { | |
r := r13.r | |
b := make([]byte, 1) | |
for i:=0 ;; i++ { | |
_, err := r.Read(b) | |
if err == io.EOF { | |
return i, io.EOF | |
} | |
c := b[0] | |
var a byte | |
switch { | |
case 'a' <= c && c <= 'z': | |
a = 'a' | |
case 'A' <= c && c <= 'Z': | |
a = 'A' | |
} | |
if a != 0 { | |
c = (c - a + 13) % 26 + a | |
} | |
s[i] = byte(c) | |
} | |
} | |
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