Last active
January 31, 2022 19:04
Go tour rot13Reader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func (reader *rot13Reader) Read(p []byte) (int, error) { | |
b := make([]byte, 8) | |
n, err := reader.r.Read(b) | |
//fmt.Printf("n=%v err=%v b=%s\n", n, err, b[:n]) | |
if err == io.EOF { | |
return 0, io.EOF | |
} | |
i := 0 | |
for ; i < n; i++ { | |
p[i] = rot13Decode(b[i]) | |
} | |
//fmt.Printf("decoded=%s\n", p[:n]) | |
return i, nil | |
} | |
func rot13Decode(b byte) byte { | |
if b >= 'A' && b <= 'Z' { | |
return ((b - 'A' + 13) % 26) + 'A' | |
} | |
if b >= 'a' && b <= 'z' { | |
return ((b - 'a' + 13) % 26) + 'a' | |
} | |
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