I'm trying to implement a proxy pattern to chain transformations on io.Reader, in order to handle chunk of bytes efficiently.
We cannot use pointers on receivers, so my solution seem not very efficient
The code below say "process take too long"
Complete example at: https://play.golang.org/p/KhM0VXLq4CO
b := bytes.NewBufferString(text)
t := transformReaderHandler(*b)
readByChunk(t)
type transformReaderHandler bytes.Buffer
func (t transformReaderHandler) Read(p []byte) (n int, err error) {
n, err = (*bytes.Buffer)(&t).Read(p)
//if n > 0 {
// Do Something on the chunk
//}
return
}
Do you have any more efficient (memory efficient, computationally efficient) solution ?
Why do this code is not working ?
EDIT: The implementation of @svsd solution : https://play.golang.org/p/VUpJcyKLB6D
package main
import (
"io"
"fmt"
"bytes"
)
const text = "Reaaaaally long and complex text to read in chunk"
func main() {
b := bytes.NewBufferString(text)
t := (*transformReaderHandler)(b)
readByChunk(t)
}
type transformReaderHandler bytes.Buffer
func (t *transformReaderHandler) Read(p []byte) (n int, err error) {
n, err = (*bytes.Buffer)(t).Read(p)
if n > 0 {
p[0] = 'X'
}
return
}
func readByChunk(r io.Reader) {
var p = make([]byte, 4)
for {
n, err := r.Read(p)
if err == io.EOF {
break
}
fmt.Println(string(p[:n]))
}
}