ROT13 using bytes rather than strings

273 Views Asked by At

I'm trying to add a rot13 translation to my tool. Client basic code:

....
buf := make([]byte, 1024)

for {

    n, err := in.Read(buf)
    .....

    for _, chunk := range split(r, buf[:n], sizes) {
        if _, err := out.Write(chunk); err != nil {
        ......

Since I want it to work with bytes rather than strings, I came up with this:

https://play.golang.org/p/m3NvoZIyS8g

This example works, expect for some extra bytes which I don't understand, they are underlined with ***:

bytes after  ***{***[89 111 117 32 99 114 97 99 107 101 100 32 116 104 101 32 99 111 
100 101 
32 32 32 32 32 32 32 239 191 189 85 239 191 189 239 191 189 239 191 189 74 40 239 191 
189 47 239 191 189 86 239 191 189 45 239 191 189 33] ***0 0}***

string after ***{***You cracked the code       �U���J(�/�V�-�! ***%!s(int=0)*** 
***%!s(bytes.readOp=0)}***

Please ignore the part with "�U���J(�/�V�-�!", I just needed some confirmation with this "string"

How do I get rid of this extra "stuff"? Is there any way to do my idea in a better way?

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

Those are remaining available bytes into the backing array of fub.

And because you print it raw, it shows all its internal.

You want to write : fmt.Printf("bytes after %v\n", fub.Bytes()) to get only the portion written onto it.

The same aplpies for the string representation, use fmt.Printf("string after %s\n\n", fub.String())

0
colm.anseo On

What you are seeing is fmt.Printf's best attempt via reflection to render this struct type's value as a string.

You want:

var fub bytes.Buffer

// fmt.Printf("string after  %s\n\n", fub)

fmt.Printf("string after  %s\n\n", &fub) // fix
fmt.Printf("string after  %s\n\n", fub.String()) // or this

Why does this work? Checking the bytes.Bufferdocs you can see the String() string method expects a pointer receiver, so if you want to avail of this with a reflection-based function like fmt.Printf, you must pass in a *bytes.Buffer typed value.