Skip to content

Instantly share code, notes, and snippets.

@flc
Created September 4, 2013 15:59
Show Gist options
  • Save flc/6439105 to your computer and use it in GitHub Desktop.
Save flc/6439105 to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Rot13 Reader http://tour.golang.org/#61
package main
import (
"io"
"os"
"strings"
//"fmt"
"bytes"
)
var ascii_uppercase = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
var ascii_lowercase = []byte("abcdefghijklmnopqrstuvwxyz")
var ascii_uppercase_len = len(ascii_uppercase)
var ascii_lowercase_len = len(ascii_lowercase)
type rot13Reader struct {
r io.Reader
}
func rot13(b byte) byte {
pos := bytes.IndexByte(ascii_uppercase, b)
if pos != -1 {
return ascii_uppercase[(pos+13) % ascii_uppercase_len]
}
pos = bytes.IndexByte(ascii_lowercase, b)
if pos != -1 {
return ascii_lowercase[(pos+13) % ascii_lowercase_len]
}
return b
}
func (r rot13Reader) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p)
for i := 0; i < n; i++ {
p[i] = rot13(p[i])
}
return n, err
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
@Spaider
Copy link

Spaider commented Jun 7, 2022

Hey, looks like almost nobody noticed that there's an exclamation mark at the end of the string :)

package main

import (
	"io"
	"os"
	"strings"
)

type rot13Reader struct {
	r io.Reader
}

func (r13 rot13Reader) Read(p []byte) (int, error) {
	var n, err = r13.r.Read(p)

	for i := 0; i < n; i++ {
		var inp = p[i]
		if (inp >= 65 && inp <= 77) ||
			(inp >= 97 && inp <= 109) {
			p[i] = inp + 13
		} else if (inp >= 78 && inp <= 90) ||
			(inp >= 110 && inp <= 122) {
			p[i] = inp - 13
		}
	}

	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