Skip to content

Instantly share code, notes, and snippets.

@orimdominic
Last active May 11, 2024 08:06
Show Gist options
  • Save orimdominic/dfc53c89057a01eaace49dd5f97ec034 to your computer and use it in GitHub Desktop.
Save orimdominic/dfc53c89057a01eaace49dd5f97ec034 to your computer and use it in GitHub Desktop.
Go Tour Exercises
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot rot13Reader) Read(b []byte) (int, error) {
n, err := rot.r.Read(b) // this is what will be returned
if err != nil {
return 0, err
}
// got this from the linked Wkipedia article
input := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
output := "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
// build a map from `input` and `output`
inpOutMap := make(map[byte]byte)
for i := range input {
inpOutMap[input[i]] = output[i]
}
for i, c := range b {
mappedChar, ok := inpOutMap[c]
if !ok {
b[i] = c
continue
}
b[i] = mappedChar
}
return n, 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