Created
November 5, 2014 01:11
-
-
Save squiidz/d4229ebba46fda0f751c to your computer and use it in GitHub Desktop.
Learn Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import( | |
"io" | |
"errors" | |
"fmt" | |
) | |
type Rabbit struct { | |
s string | |
i int64 // current reading index | |
prevRune int // index of previous rune; or < 0 | |
} | |
func NewRabbit(s string) *Rabbit { return &Rabbit{s, 0, -1} } | |
func (r *Rabbit) Read(b []byte) (n int, err error) { | |
if len(b) == 0 { | |
return 0, nil | |
} | |
if r.i >= int64(len(r.s)) { | |
return 0, io.EOF | |
} | |
r.prevRune = -1 | |
n = copy(b, r.s[r.i:]) | |
r.i += int64(n) | |
return | |
} | |
func (r *Rabbit) Write(b []byte) (n int, err error) { | |
if len(b) > 0 { | |
r.s = string(b) | |
return len(r.s), nil | |
} | |
return 0, errors.New("Empty") | |
} | |
func main() { | |
word := NewRabbit("Some Data") | |
data, _ := ReadFrom(word, 4) | |
wo := NewRabbit(string(data)) | |
n, _ := wo.Write([]byte("FROM WRITE FUNCTION")) | |
fmt.Println(n) | |
rev, _ := Reverse(wo) | |
fmt.Println(string(data)) | |
fmt.Println(string(rev)) | |
} | |
func ReadFrom(reader io.Reader, num int) ([]byte, error) { | |
p := make([]byte, num) | |
n, err := reader.Read(p) | |
if n > 0 { | |
return p[:n], nil | |
} | |
return p, err | |
} | |
func Reverse(reader io.Reader) ([]byte, error) { | |
var p = make([]byte, 19) | |
n, err := reader.Read(p) | |
var emp = make([]byte, n) | |
if n > 0 { | |
for i, t := range p { | |
emp[(len(p)-i)-1] = t | |
} | |
return emp, nil | |
} | |
return p, err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment