decoder [WIP]

Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
2023-09-01 22:43:36 +00:00
parent 652f7a7aa0
commit 8557ef9a7e
3 changed files with 161 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
package ini
import (
"bytes"
"io"
"strings"
"asciigoat.org/core"
"asciigoat.org/core/reflection"
"asciigoat.org/ini/parser"
)
// Decoder ...
type Decoder[T any] struct {
io.Closer
out *reflection.Reflection[T]
p *parser.Parser
queue []*token
}
// Decode ...
func (dec *Decoder[T]) Decode(v *T) error {
defer dec.Close()
r, err := reflection.New(v)
switch e := err.(type) {
case *reflection.InvalidUnmarshalError:
// customize error
e.Prefix = "ini"
e.Method = "Decode"
case nil:
// good reflection. Go!
dec.out = r
err = dec.p.Run()
}
return err
}
// NewDecoder creates a Decoder using the provided [io.Reader]
// as source
func NewDecoder[T any](r io.Reader) *Decoder[T] {
rc := core.NewReadCloser(r)
switch {
case rc == nil:
return nil
default:
dec := &Decoder[T]{
p: parser.NewParser(rc),
Closer: rc,
}
dec.init()
return dec
}
}
func (dec *Decoder[T]) init() {
dec.p.OnToken = dec.parserOnToken
dec.p.OnError = dec.parserOnError
}
// NewDecoderBytes creates a Decoder using the provided bytes array
// as source
func NewDecoderBytes[T any](b []byte) *Decoder[T] {
return NewDecoder[T](bytes.NewReader(b))
}
// NewDecoderString creates a Decoder over a provided string of data
func NewDecoderString[T any](s string) *Decoder[T] {
return NewDecoder[T](strings.NewReader(s))
}