Skip to content

Instantly share code, notes, and snippets.

@azec-pdx
Created September 19, 2020 00:32
Show Gist options
  • Save azec-pdx/0ab27a559d4369c81607b6e8a3f41942 to your computer and use it in GitHub Desktop.
Save azec-pdx/0ab27a559d4369c81607b6e8a3f41942 to your computer and use it in GitHub Desktop.
Implements A Tour of Golang challenge https://tour.golang.org/methods/23
package main
import (
"io"
"os"
"strings"
)
var rot13Lookup = map[byte]byte{ // All are ASCII (UTF-8) so safe to use 1 byte for representation of code point
'A': 'N', 'B': 'O', 'C': 'P', 'D': 'Q', 'E': 'R', 'F': 'S', 'G': 'T', 'H': 'U', 'I': 'V', 'J': 'W', 'K': 'X', 'L': 'Y', 'M': 'Z', 'N': 'A', 'O': 'B', 'P': 'C', 'Q': 'D', 'R': 'E', 'S': 'F', 'T': 'G', 'U': 'H', 'V': 'I', 'W': 'J', 'X': 'K', 'Y': 'L', 'Z': 'M', 'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u', 'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c', 'q': 'd', 'r': 'e', 's': 'f', 't': 'g', 'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k', 'y': 'l', 'z': 'm',
}
type rot13Reader struct {
r io.Reader
}
// Implements interface io.Reader
func (rot13 rot13Reader) Read(b []byte) (int, error) {
//Read the source readeri
sb := make([]byte, 1)
nRead, err := rot13.r.Read(sb)
if err == io.EOF {
return 0, err
} else if nRead > 0 {
//In case some bytes were read from the stream...do the cipher
for ind, by := range sb[:nRead] {
if val, ok := rot13Lookup[by]; ok {
b[ind] = val
} else {
b[ind] = sb[ind]
}
}
}
return len(b), 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