memio - string.go
1 package memio
2
3 import (
4 "io"
5 "unicode/utf8"
6 )
7
8 // String grants a string Read-Only methods.
9 type String string
10
11 // Read satisfies the io.Reader interface
12 func (s *String) Read(p []byte) (int, error) {
13 if len(p) == 0 {
14 return 0, nil
15 }
16 if len(*s) == 0 {
17 return 0, io.EOF
18 }
19 n := copy(p, *s)
20 *s = (*s)[n:]
21 return n, nil
22 }
23
24 // WriteTo satisfies the io.WriterTo interface
25 func (s *String) WriteTo(w io.Writer) (int64, error) {
26 if len(*s) == 0 {
27 return 0, io.EOF
28 }
29 n, err := io.WriteString(w, string(*s))
30 *s = (*s)[n:]
31 return int64(n), err
32 }
33
34 // ReadByte satisfies the io.ByteReader interface
35 func (s *String) ReadByte() (byte, error) {
36 if len(*s) == 0 {
37 return 0, io.EOF
38 }
39 b := (*s)[0]
40 *s = (*s)[1:]
41 return b, nil
42 }
43
44 // ReadRune satisfies the io.RuneReader interface
45 func (s *String) ReadRune() (rune, int, error) {
46 if len(*s) == 0 {
47 return 0, 0, io.EOF
48 }
49 r, n := utf8.DecodeRuneInString(string(*s))
50 *s = (*s)[n:]
51 return r, n, nil
52 }
53
54 // Peek reads the next n bytes without advancing the position
55 func (s *String) Peek(n int) ([]byte, error) {
56 if n > len(*s) {
57 return []byte(*s), io.EOF
58 }
59 return []byte((*s)[:n]), nil
60 }
61
62 // Close satisfies the io.Closer interface
63 func (s *String) Close() error {
64 *s = ""
65 return nil
66 }