2021-12-26 23:23:41 +00:00
|
|
|
package gg
|
|
|
|
|
|
|
|
import (
|
2023-10-21 15:42:31 +00:00
|
|
|
"bufio"
|
2021-12-26 23:23:41 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
// Decoder reads Value's off of a byte stream.
|
|
|
|
type Decoder struct {
|
|
|
|
br *bufio.Reader
|
|
|
|
brNextLoc Location
|
2021-12-26 23:23:41 +00:00
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
unread []locatableRune
|
|
|
|
lastRead locatableRune
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
// NewDecoder returns a Decoder which will decode the given stream as a gg
|
|
|
|
// formatted stream of a Values.
|
|
|
|
func NewDecoder(r io.Reader) *Decoder {
|
|
|
|
return &Decoder{
|
|
|
|
br: bufio.NewReader(r),
|
|
|
|
brNextLoc: Location{Row: 1, Col: 1},
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
func (d *Decoder) readRune() (locatableRune, error) {
|
|
|
|
if len(d.unread) > 0 {
|
|
|
|
d.lastRead = d.unread[len(d.unread)-1]
|
|
|
|
d.unread = d.unread[:len(d.unread)-1]
|
|
|
|
return d.lastRead, nil
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
loc := d.brNextLoc
|
2021-12-26 23:23:41 +00:00
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
r, _, err := d.br.ReadRune()
|
2021-12-26 23:23:41 +00:00
|
|
|
if err != nil {
|
2023-10-21 15:42:31 +00:00
|
|
|
return d.lastRead, err
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
if r == '\n' {
|
|
|
|
d.brNextLoc.Row++
|
|
|
|
d.brNextLoc.Col = 1
|
|
|
|
} else {
|
|
|
|
d.brNextLoc.Col++
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
d.lastRead = locatableRune{loc, r}
|
|
|
|
return d.lastRead, nil
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
func (d *Decoder) unreadRune(lr locatableRune) {
|
|
|
|
if d.lastRead != lr {
|
|
|
|
panic(fmt.Sprintf(
|
|
|
|
"unreading rune %#v, but last read rune was %#v", lr, d.lastRead,
|
|
|
|
))
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
d.unread = append(d.unread, lr)
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
func (d *Decoder) nextLoc() Location {
|
|
|
|
if len(d.unread) > 0 {
|
|
|
|
return d.unread[len(d.unread)-1].Location
|
2021-12-26 23:23:41 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
return d.brNextLoc
|
2021-12-30 22:29:38 +00:00
|
|
|
}
|
|
|
|
|
2023-10-21 15:42:31 +00:00
|
|
|
// Next returns the next top-level value in the stream, or io.EOF.
|
|
|
|
func (d *Decoder) Next() (Value, error) {
|
|
|
|
return topLevelTerm.decodeFn(d)
|
2021-12-30 22:29:38 +00:00
|
|
|
}
|