From c556fa9b7cd32fbb0b3a241c6f9ae434f18cb3bb Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Tue, 6 Nov 2012 07:35:11 -0500 Subject: [PATCH] Implementation of rot13 reader Although I'm sure there's a fancier way to do the lookup table. Hmmm... --- .../exercise-rot13-reader/main.go | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 gotime/src/meatballhat.com/gotour-artifacts/exercise-rot13-reader/main.go diff --git a/gotime/src/meatballhat.com/gotour-artifacts/exercise-rot13-reader/main.go b/gotime/src/meatballhat.com/gotour-artifacts/exercise-rot13-reader/main.go new file mode 100644 index 0000000..0e477a1 --- /dev/null +++ b/gotime/src/meatballhat.com/gotour-artifacts/exercise-rot13-reader/main.go @@ -0,0 +1,97 @@ +package main + +import ( + "fmt" + "io" + "os" + "strings" +) + +var lookupTable = map[byte]byte{ + '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 { + reader io.Reader +} + +func (rot *rot13Reader) Read(p []byte) (i int, err error) { + if len(p) == 0 { + return 0, nil + } + buf := make([]byte, len(p)) + i, err = rot.reader.Read(buf) + + var ( + b, c byte + found bool + ) + for i := range buf { + b = buf[i] + c, found = lookupTable[b] + if found { + p[i] = c + } else { + p[i] = b + } + } + return +} + +func main() { + s := strings.NewReader("Lbh penpxrq gur pbqr!") + r := rot13Reader{s} + io.Copy(os.Stdout, &r) + fmt.Println("") +}