Skip to content

Instantly share code, notes, and snippets.

@mtso
Last active December 14, 2016 20:46
Show Gist options
  • Save mtso/10d712f354d579a88a05d168ce32f50d to your computer and use it in GitHub Desktop.
Save mtso/10d712f354d579a88a05d168ce32f50d to your computer and use it in GitHub Desktop.
// rot13Reader's `Read([]byte) (int, error)` implementation
// following the go tool tour
// mtso, 2016
// would be interesting to try a ternary with:
// https://play.golang.org/p/ZgLwC_DHm0
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (r13 rot13Reader) Read(b []byte) (l int, e error) {
// pass the byte slice into the reader value
l, e = r13.r.Read(b)
// ROT13 on the characters in the buffer
for i := 0; i < l; i++ {
// temp var c
c := b[i]
// if the byte is a space, skip
if c == 32 {
continue
}
// If A-Z, limit is 90 (Z)
limit := byte(90)
// c is greater than 90,
// c is lowercase a-z, where z is 122
if c > limit {
limit = 122
}
// Shift the byte by 13 positions
b[i] += 13
// If the byte is greater than Z or z
// shift the byte back 26 positions
if b[i] > limit {
b[i] -= 26
}
}
return
}
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