Skip to content

Instantly share code, notes, and snippets.

@edwardmp
Last active March 13, 2024 20:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save edwardmp/3aca97114eb19089e18d to your computer and use it in GitHub Desktop.
Save edwardmp/3aca97114eb19089e18d to your computer and use it in GitHub Desktop.
A Tour of Go, exercise rot13Reader
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)
}
@Atavixion
Copy link

Atavixion commented Jan 7, 2024

package main

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

type rot13Reader struct {
	r io.Reader
}

func (r *rot13Reader) Read(b []byte) (int, error) {
	if n, err := r.r.Read(b); err != nil {
		return n, err
	}
	
	for i, v := range b {
		if v > 64 && v < 91 {
			b[i] = (v - 65 + 13) % 26 + 65
		} else if v > 96 && v < 123 {
			b[i] = (v - 97 + 13) % 26 + 97
		}
	}
	return len(b), nil
}
	
func main() {
	s := strings.NewReader("Lbh penpxrq gur pbqr!")
	r := rot13Reader{s}
	io.Copy(os.Stdout, &r)
}

@PowerPixel
Copy link

package main

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

type rot13Reader struct {
	r io.Reader
}

func (rot13 rot13Reader) Read(out []byte) (int, error) {
	n, err := rot13.r.Read(out)
	if err != nil {
		return n, err	
	}
	
	for i := 0; i < len(out); i++ {
		if out[i] >= 'A' && out[i] <= 'Z' {
			out[i] = 'A' + (((out[i] - 'A') + 13) % 26)
		}
		if out[i] >= 'a' && out[i] <= 'z' {
			out[i] = 'a' + (((out[i] - 'a') + 13) % 26)
		}
	}
	return n, nil
}

func main() {
	s := strings.NewReader("Lbh penpxrq gur pbqr!")
	r := rot13Reader{s}
	io.Copy(os.Stdout, &r)
}

I wanted to do compact & efficient :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment