Gary
Gary

Reputation: 483

Go io reader wrapper

I have written the following code which tries to cipher the alpha numberic characters by 13. This is an example in the tour of go. I have used the log library to check out the values in the byte array p, after the cipher, and they seem to be rotated by 13. For some reason when it prints to STDOUT, the characters are not ciphered. I am altering byte array p incorrectly?

package main

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

type rot13Reader struct {
    r io.Reader
}

func cipher(in byte) (out byte) {
    out = in
    if in > 64 && in < 91 {
        out = in - 64
        out = out + 13
        out = out % 26
        out = out + 64
    }
    if in > 96 && in < 123 {
        out = in - 96
        out = out + 13
        out = out % 26
        out = out + 96
    }
    return
}

func (reader rot13Reader) Read(p []byte) (n int, err error) {
    for index := range p {
        p[index] = cipher(p[index])
    }
    n, err = reader.r.Read(p)
    return
}

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

Upvotes: 1

Views: 1533

Answers (1)

James Henstridge
James Henstridge

Reputation: 43899

In your rot13Reader.Read method, you are first applying cipher to whatever data was in p and then overwriting that data by reading from the sub-Reader.

If the aim is to decode what you read, you should perform these two operations in the opposite order.

Upvotes: 1

Related Questions