Skip to content

Commit

Permalink
feat: add Marshal and Unmarshal method to encoder and parser
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Aug 18, 2022
1 parent c3fb05f commit 4779af4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 5 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ func NewEncoder() *Encoder {
}
}

// Marshal data(struct, map) to properties text
func (e *Encoder) Marshal(v interface{}) ([]byte, error) {
return e.Encode(v)
}

// Encode data(struct, map) to properties text
func (e *Encoder) Encode(v interface{}) ([]byte, error) {
mp, ok := v.(map[string]interface{})
Expand Down
15 changes: 12 additions & 3 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ const (
const (
// TokInvalid invalid token
TokInvalid rune = 0
// TokOLComments one line comments
// TokOLComments one line comments start by !,#
TokOLComments = 'c'
// TokMLComments multi line comments
// TokMLComments multi line comments by /* */
TokMLComments = 'C'
// TokILComments inline comments
TokILComments = 'i'
Expand Down Expand Up @@ -140,6 +140,15 @@ func (p *Parser) WithOptions(optFns ...OpFunc) *Parser {
return p
}

// Unmarshal parse properties text and decode to struct
func (p *Parser) Unmarshal(v []byte, ptr interface{}) error {
if err := p.ParseBytes(v); err != nil {
return err
}

return p.MapStruct("", ptr)
}

// Parse text contents
func (p *Parser) Parse(text string) error {
if text = strings.TrimSpace(text); text == "" {
Expand Down Expand Up @@ -230,7 +239,7 @@ func (p *Parser) ParseFrom(r io.Reader) error {
}

// a line comments
if str[0] == '#' {
if str[0] == '#' || str[0] == '!' {
tok = TokOLComments
comments += raw
continue
Expand Down
4 changes: 3 additions & 1 deletion parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ top.sub.key2 = 'a quote value2'
/* comments 1.1 */
top.sub.key3 = 234
# inline list
! inline list
top2.inline.list.ids = [234, 345, 456]
# use var refer
Expand All @@ -46,10 +46,12 @@ top.sub.key4[1] = def
top.sub.key5[0].f1 = ab
top.sub.key5[1].f2 = de
# multi line value
top.sub2.mline1 = """multi line
value
"""
# multi line value2
top.sub2.mline2 = this is \
multi line2 \
value
Expand Down

0 comments on commit 4779af4

Please sign in to comment.