Hackish first attempt at the rot13Reader
exercise of the go tour.
Not as concise or elegant as the official solution.
Hackish first attempt at the rot13Reader
exercise of the go tour.
Not as concise or elegant as the official solution.
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
// rot13Map constructor used in rot13 method | |
// m["A"] == "N" | |
// m["z"] == "m" | |
func NewRot13Map() map[byte]byte { | |
p := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
q := "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" | |
m := make(map[byte]byte) | |
for i, c := range p { | |
m[byte(c)] = q[byte(i)] | |
} | |
return m | |
} | |
var rot13Map = NewRot13Map() | |
type rot13Reader struct { | |
reader io.Reader | |
rot13Map map[byte]byte | |
} | |
// rotate alphabetic byte chars by 13 positions (A to N, z to m) | |
func (r *rot13Reader) rot13(c byte) byte { | |
if c >= 'A' && c <= 'z' { | |
return r.rot13Map[c] | |
} | |
return c | |
} | |
func (r *rot13Reader) Read(b []byte) (int, error) { | |
n, err := r.reader.Read(b) | |
for i, c := range b { | |
b[i] = r.rot13(c) | |
} | |
return n, err | |
} | |
// rot13Reader construtor | |
func NewRot13Reader(r io.Reader) *rot13Reader { | |
return &rot13Reader{r, rot13Map} | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := NewRot13Reader(s) | |
io.Copy(os.Stdout, r) //You cracked the code! | |
} |