value.go 1.7 KB

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