Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce NewDecoderWithParser with ability to provide a custom parser #994

Open
wants to merge 1 commit into
base: v3
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func (p *parser) anchor(n *Node, anchor []byte) {
}
}

func (p *parser) parse() *Node {
func (p *parser) Parse() *Node {
p.init()
switch p.peek() {
case yaml_SCALAR_EVENT:
Expand Down Expand Up @@ -194,7 +194,7 @@ func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node {
}

func (p *parser) parseChild(parent *Node) *Node {
child := p.parse()
child := p.Parse()
parent.Content = append(parent.Content, child)
return child
}
Expand Down
20 changes: 16 additions & 4 deletions yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,14 @@ func Unmarshal(in []byte, out interface{}) (err error) {
return unmarshal(in, out, false)
}

type Parser interface {
// Parse produces the document Node to be decoded into target struct
Parse() *Node
}

// A Decoder reads and decodes YAML values from an input stream.
type Decoder struct {
parser *parser
parser Parser
knownFields bool
}

Expand All @@ -105,6 +110,13 @@ func NewDecoder(r io.Reader) *Decoder {
}
}

// NewDecoderWithParser returns a new decoder that uses provided parser
func NewDecoderWithParser(p Parser) *Decoder {
return &Decoder{
parser: p,
}
}

// KnownFields ensures that the keys in decoded mappings to
// exist as fields in the struct being decoded into.
func (dec *Decoder) KnownFields(enable bool) {
Expand All @@ -120,7 +132,7 @@ func (dec *Decoder) Decode(v interface{}) (err error) {
d := newDecoder()
d.knownFields = dec.knownFields
defer handleErr(&err)
node := dec.parser.parse()
node := dec.parser.Parse()
if node == nil {
return io.EOF
}
Expand Down Expand Up @@ -158,7 +170,7 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) {
d := newDecoder()
p := newParser(in)
defer p.destroy()
node := p.parse()
node := p.Parse()
if node != nil {
v := reflect.ValueOf(out)
if v.Kind() == reflect.Ptr && !v.IsNil() {
Expand Down Expand Up @@ -265,7 +277,7 @@ func (n *Node) Encode(v interface{}) (err error) {
p := newParser(e.out)
p.textless = true
defer p.destroy()
doc := p.parse()
doc := p.Parse()
*n = *doc.Content[0]
return nil
}
Expand Down