Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created December 18, 2017 07:22
Show Gist options
  • Save limboinf/bfb52656dee4fcee7d7ee43604082c30 to your computer and use it in GitHub Desktop.
Save limboinf/bfb52656dee4fcee7d7ee43604082c30 to your computer and use it in GitHub Desktop.
Implement Read like Reader interface, you can get inspiration from buffer.go
package main
import (
"io"
"fmt"
)
type Data struct {
stream string
idx int
}
func NewData(stream string) *Data {
return &Data{stream, 0}
}
func (d *Data) Len() int {
return len(d.stream)
}
// Implement Read interface
// Lowercase to uppercase
// The return value n is the number of bytes read.
// If no data to return, err is io.EOF (unless len(p) is zero);
// otherwise it is nil.)
func (d *Data) Read(s []byte) (n int, err error) {
for ; d.idx < d.Len() && n < len(s); d.idx ++ {
chr := d.stream[d.idx]
if 'a' <= chr && chr <= 'z' {
s[n] = chr + 'A' - 'a'
} else {
s[n] = chr
}
n++
}
if n == 0 {
return n, io.EOF
}
return n, nil
}
func main() {
d := NewData("hello world")
buf := make([]byte, d.Len())
n, err := io.ReadFull(d, buf)
fmt.Printf("%s\n", buf)
fmt.Println(n, err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment