Last active
April 19, 2025 05:50
-
-
Save edwardmp/3aca97114eb19089e18d to your computer and use it in GitHub Desktop.
A Tour of Go, exercise 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 (rot *rot13Reader) Read(p []byte) (n int, err error) { | |
n, err = rot.r.Read(p) | |
for i := 0; i < len(p); i++ { | |
if p[i] >= 'A' && p[i] < 'Z' { | |
p[i] = 65 + (((p[i] - 65) + 13) % 26) | |
} else if p[i] >= 'a' && p[i] <= 'z' { | |
p[i] = 97 + (((p[i] - 97) + 13) % 26) | |
} | |
} | |
return | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} |
Frequency21
commented
Feb 16, 2025
package main
import (
"io"
"os"
"strings"
"unicode"
)
type rot13Reader struct {
r io.Reader
}
const (
lowerMap = "nopqrstuvwxyzabcdefghijklm"
upperMap = "NOPQRSTUVWXYZABCDEFGHIJKLM"
)
func rotateBytes(bytes []byte) {
for i := range bytes {
if unicode.IsLower(rune(bytes[i])) {
bytes[i] = lowerMap[bytes[i]-'a']
} else if unicode.IsUpper(rune(bytes[i])) {
bytes[i] = upperMap[bytes[i]-'A']
}
}
}
func (rot13 *rot13Reader) Read(bytes []byte) (int, error) {
n, err := rot13.r.Read(bytes)
rotateBytes(bytes)
return n, err
}
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