| 1 |
package dnsstring |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"strings" |
| 6 |
) |
| 7 |
|
| 8 |
// Reader wraps a string and guarantees the stream ends with a '\n'. |
| 9 |
// If the string already ends with a newline, it behaves identically to |
| 10 |
// strings.NewReader. Otherwise it appends exactly one '\n' at EOF. |
| 11 |
type Reader struct { |
| 12 |
r *strings.Reader |
| 13 |
n bool |
| 14 |
} |
| 15 |
|
| 16 |
// NewReader returns a Reader for s. |
| 17 |
func NewReader(s string) *Reader { |
| 18 |
return &Reader{ |
| 19 |
r: strings.NewReader(s), |
| 20 |
n: len(s) == 0 || s[len(s)-1] != '\n', |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
// Read implements io.Reader. |
| 25 |
func (r *Reader) Read(p []byte) (int, error) { |
| 26 |
n, err := r.r.Read(p) |
| 27 |
|
| 28 |
if r.n && err != nil && err == io.EOF { |
| 29 |
if n < len(p) { |
| 30 |
p[n] = '\n' |
| 31 |
n++ |
| 32 |
return n, io.EOF |
| 33 |
} |
| 34 |
// p was fully consumed by the underlying read; the newline will be delivered on the next call |
| 35 |
// (err stays io.EOF, but we return n > 0 so the caller loops back). |
| 36 |
return n, nil |
| 37 |
} |
| 38 |
|
| 39 |
return n, err |
| 40 |
} |