Created
August 30, 2021 02:48
-
-
Save Version2beta/2b988e23be906abe042f8cf3a8e6da76 to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: rot13Reader
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 ( | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
type Rot13ReaderError struct { | |
Why string | |
} | |
func (e Rot13ReaderError) Error() string { | |
return e.Why | |
} | |
func rot13(s []byte) []byte { | |
rotator := func(c, start byte) byte { return ((c - start + 13) % 26) + start } | |
for i, c := range s { | |
if c >= 'A' && c <= 'Z' { | |
s[i] = rotator(c, 'A') | |
} else if c >= 'a' && c <= 'z' { | |
s[i] = rotator(c, 'a') | |
} | |
} | |
return s | |
} | |
func (r13r *rot13Reader) Read(s []byte) (int, error) { | |
n, err := r13r.r.Read(s) | |
if err != nil { | |
return 0, &Rot13ReaderError{fmt.Sprintf("Could not read the stream: %v", err)} | |
} | |
s = rot13(s) | |
return n, nil | |
} | |
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