Skip to content

Instantly share code, notes, and snippets.

@Version2beta
Created August 30, 2021 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Version2beta/2b988e23be906abe042f8cf3a8e6da76 to your computer and use it in GitHub Desktop.
Save Version2beta/2b988e23be906abe042f8cf3a8e6da76 to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: rot13Reader
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