-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrot13.go
54 lines (40 loc) · 1.08 KB
/
rot13.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"fmt"
"io"
"os"
"strings"
)
// Define a new type which has an internal io.Reader
type rot13Reader struct {
r io.Reader
}
// Implement the Read function, which is equivalent to decoding the string
func (rot13 *rot13Reader) Read(p []byte) (n int, err error) {
return rot13.Decode(p)
}
// Decode the byte slice, using ROT13
func (rot13 *rot13Reader) Decode(p []byte) (n int, err error) {
// Read from the internal io.Reader
num, err := rot13.r.Read(p)
// Iterate over the byte slice
for i, elem := range p {
if (elem >= 'A' && elem < 'N') || (elem >= 'a' && elem < 'n') {
// A through M (lowercase and uppercase) are rotated forward
p[i] += 13
} else if (elem >= 'N' && elem < 'Z') || (elem >= 'n' && elem < 'z') {
// N through Z (lowercase and uppercase) are rotated backward
p[i] -= 13
}
}
return num, err
}
func main() {
encodedString := "Lbh penpxrq gur pbqr!"
s := strings.NewReader(encodedString)
r := rot13Reader{s}
fmt.Println("Encoded String:", encodedString)
fmt.Print("Decoded String: ")
io.Copy(os.Stdout, &r)
fmt.Println()
}