Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reader interface and the Read method in golang

Tags:

io

go

byte

I was following the golang tour and I have been asked to:

Implement a rot13Reader that implements io.Reader and reads from an io.Reader, modifying the stream by applying the ROT13 substitution cipher to all alphabetical characters.

I first implemented the method to the *rot13Reader

   type rot13Reader struct {
    r io.Reader
}

func (r *rot13Reader) Read(p []byte) (n int, e error){


}

However I can't get my head around this Read method.

Does the p contain all of the bytes read? And hence all I should do is iterate over them and apply the ROT13 substitution ?

I understand that it should return the number of bytes read and an EOF error at the end of the file however I'm not sure when and how this method is called. So coming back to my original question does the p contain all of the data read ? If not then how can I get to it?

like image 861
Bula Avatar asked Aug 27 '14 12:08

Bula


People also ask

What is a reader in GoLang?

The io.Reader interface is used by many packages in the Go standard library and it represents the ability to read a stream of data. More specifically allows you to read data from something that implements the io.Reader interface into a slice of bytes.

What is reader and Writer in GoLang?

Reader/Writer are basic interfaces designed in Golang. For example, if a struct have a function like: type Example struct { }func (e *Example) Write(p byte[]) (n int, err error) {}func (e *Example) Read(p byte[]) (n int, err error) {}

What is io EOF in GoLang?

It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF.

What is io package GoLang?

The io package in Go provides input-output primitives as well as interfaces to them. It is one of the most essential packages in all of GoLang.


1 Answers

You should scan and "rot13" only n bytes (the one read by the io.Reader within rot13Reader).

func (r *rot13Reader) Read(p []byte) (n int, e error){
    n, e = r.r.Read(p)
    for i:=range(p[:n]) {
       p[i]=rot13(p[i])
    }
    return
}

The rot13Reader encapsulate any reader and call Read on said encapsulated Reader.
It returns the rot13'ed content, and the number of byte read.

like image 62
VonC Avatar answered Oct 11 '22 03:10

VonC