diff --git a/types/int_string.go b/types/int_string.go new file mode 100644 index 0000000..780644d --- /dev/null +++ b/types/int_string.go @@ -0,0 +1,51 @@ +package types + +import "fmt" + +type IntOrString struct { + intVal int + strVal string + isInt bool +} + +func (is *IntOrString) Set(val any) error { + switch v := val.(type) { + case int: + case int8: + case int16: + case int32: + case int64: + case uint: + case uint8: + case uint16: + case uint32: + is.isInt = true + is.intVal = int(v) + return nil + case string: + is.isInt = false + is.strVal = v + return nil + case []byte: + is.isInt = false + is.strVal = string(v) + return nil + } + + //nolint:err113 // Temp skip + return fmt.Errorf("invalid type: %T", val) +} + +func (is IntOrString) IsZero() bool { + if is.isInt { + return is.intVal == 0 + } + return is.strVal == "" +} + +func (is IntOrString) Value() any { + if is.isInt { + return is.intVal + } + return is.strVal +} diff --git a/types/toml.go b/types/toml.go new file mode 100644 index 0000000..cc50593 --- /dev/null +++ b/types/toml.go @@ -0,0 +1,25 @@ +package types + +import "fmt" + +type TomlTypeError struct { + Value any +} + +func (te *TomlTypeError) Error() string { + return fmt.Sprintf("unsupported type: %T", te.Value) +} + +func (is *IntOrString) UnmarshalTOML(val any) error { + switch v := val.(type) { + case string: + is.isInt = false + is.strVal = v + return nil + case int64: + is.isInt = true + is.intVal = int(v) + return nil + } + return &TomlTypeError{Value: val} +} diff --git a/types/yaml.go b/types/yaml.go index 4fa1d1b..d0b7d6d 100644 --- a/types/yaml.go +++ b/types/yaml.go @@ -10,17 +10,8 @@ func (ye *YamlTypeError) Error() string { return ye.Node.Tag + " is not a valid type for this field" } -type IntOrString struct { - intVal int - strVal string - isInt bool -} - func (is IntOrString) MarshalYAML() (any, error) { - if is.isInt { - return is.intVal, nil - } - return is.strVal, nil + return is.Value(), nil } func (is *IntOrString) UnmarshalYAML(value *yaml.Node) error { @@ -36,10 +27,3 @@ func (is *IntOrString) UnmarshalYAML(value *yaml.Node) error { return &YamlTypeError{Node: value} } - -func (is IntOrString) IsZero() bool { - if is.isInt { - return is.intVal == 0 - } - return is.strVal == "" -}