Skip to content

Instantly share code, notes, and snippets.

@danzek
Created October 25, 2020 05:01
Show Gist options
  • Save danzek/1f4e1085cd7e92130e356840f9c1012d to your computer and use it in GitHub Desktop.
Save danzek/1f4e1085cd7e92130e356840f9c1012d to your computer and use it in GitHub Desktop.
// solution to rot13Reader exercise in golang tour
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (r rot13Reader) Read(p []byte) (int, error) {
n, err := r.r.Read(p)
for i := 0; i < n; i++ {
p[i] = rot13(p[i])
}
if err == io.EOF {
return n, err
}
return n, nil
}
// takes byte, validates ASCII alpha char, returns rot-13-encoded char (as byte)
func rot13(b byte) byte {
upperBound := byte('z')
// set proper upper bound
if b >= byte('a') && b <= byte('z') { // lowercase
// do nothing, upper bound is lowercase by default
} else if b >= byte('A') && b <= byte('Z') { // uppercase
// set upperBound to uppercase
upperBound = byte('Z')
} else {
// not ASCII alpha char, just return byte as is
return b
}
// rot 13 encode
b += 13
if b > upperBound {
b -= 26
}
return b
}
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