runes.Reader: introduce String(), Emit() and Discard()

Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
2023-08-28 04:45:25 +00:00
parent fad6357d91
commit fef0d81610
+26
View File
@@ -30,6 +30,32 @@ type Reader struct {
cursor int
}
// String returns what's already Read but not yet emitted or discarded
func (b *Reader) String() string {
return string(b.buf[b.off:b.cursor])
}
// Emit returns what's already being Read and discards it afterwards
func (b *Reader) Emit() string {
s := b.String()
b.Discard()
return s
}
// Discard removes from the buffer everything that has been Read
func (b *Reader) Discard() {
switch {
case b.ready() == 0:
// reset
b.buf = b.buf[:0]
b.cursor = 0
b.off = 0
default:
// step
b.off = b.cursor
}
}
// ready tells how many bytes are ready to decode
func (b *Reader) ready() int {
return len(b.buf) - b.cursor