go-dirty.git

ref: master

./main.go


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package dirty

import (
	"bufio"
	"fmt"
	"io"
	"reflect"
)

const DEBUG bool = true // build -X

func debugf(format string, a ...interface{}) {
	if DEBUG {
		fmt.Printf(format, a...)
	}
}
func debugln(a ...interface{}) {
	if DEBUG {
		fmt.Println(a...)
	}
}

// todo func LoadArray()
func Load(r io.Reader) (Array, error) {
	scanner := bufio.NewReader(r)
	array := []Element{}
	comment := token{ttype: COMMENT}
	lbrack := token{ttype: LBRACKET}
	eof := token{ttype: EOF}
	expected := lbrack
	for {
		t, err := nextToken(scanner)
		//debugf("in Load got %+v\n", t)
		if err != nil {
			return []Element{}, err
		}
		if t == comment {
			continue
		} else if t == lbrack {
			if expected != lbrack {
				//debugln("expected lbrac")
				return []Element{}, NewSyntaxError(t, []token{expected})
			}
			//debugf("in Load loading array\n")
			array, err = loadArray(scanner)
			if err != nil {
				return Array{}, err
			}
			expected = eof
		} else if t == eof {
			if expected != eof {
				//debugln("expected eof")
				return []Element{}, NewSyntaxError(t, []token{expected})
			}
			//debugf("in Load eofing\n")
			return array, nil
		} else {
			//debugln("garbage")
			return []Element{}, NewSyntaxError(t, []token{expected})
		}
	}
}

// todo func Load()
func LoadStruct(r io.Reader, s interface{}) error {
	array, err := Load(r)
	if err != nil {
		return err
	}
	v := reflect.ValueOf(s).Elem()
	return convertStruct(array, v)
}