value.go

 1package ini
 2
 3import (
 4	"fmt"
 5	"strconv"
 6	"strings"
 7)
 8
 9// ValueType is an enum that will signify what type
10// the Value is
11type ValueType int
12
13func (v ValueType) String() string {
14	switch v {
15	case NoneType:
16		return "NONE"
17	case StringType:
18		return "STRING"
19	}
20
21	return ""
22}
23
24// ValueType enums
25const (
26	NoneType = ValueType(iota)
27	StringType
28	QuotedStringType
29)
30
31// Value is a union container
32type Value struct {
33	Type ValueType
34
35	str string
36	mp  map[string]string
37}
38
39// NewStringValue returns a Value type generated using a string input.
40func NewStringValue(str string) (Value, error) {
41	return Value{str: str}, nil
42}
43
44func (v Value) String() string {
45	switch v.Type {
46	case StringType:
47		return fmt.Sprintf("string: %s", string(v.str))
48	case QuotedStringType:
49		return fmt.Sprintf("quoted string: %s", string(v.str))
50	default:
51		return "union not set"
52	}
53}
54
55// MapValue returns a map value for sub properties
56func (v Value) MapValue() map[string]string {
57	return v.mp
58}
59
60// IntValue returns an integer value
61func (v Value) IntValue() (int64, bool) {
62	i, err := strconv.ParseInt(string(v.str), 0, 64)
63	if err != nil {
64		return 0, false
65	}
66	return i, true
67}
68
69// FloatValue returns a float value
70func (v Value) FloatValue() (float64, bool) {
71	f, err := strconv.ParseFloat(string(v.str), 64)
72	if err != nil {
73		return 0, false
74	}
75	return f, true
76}
77
78// BoolValue returns a bool value
79func (v Value) BoolValue() (bool, bool) {
80	// we don't use ParseBool as it recognizes more than what we've
81	// historically supported
82	if strings.EqualFold(v.str, "true") {
83		return true, true
84	} else if strings.EqualFold(v.str, "false") {
85		return false, true
86	}
87	return false, false
88}
89
90// StringValue returns the string value
91func (v Value) StringValue() string {
92	return v.str
93}