package conf import ( "errors" "fmt" "strconv" "strings" ) var ( ErrCouldNotConvert = errors.New("conf: could not cast one or more values to required type") ) const ( separatorSlice = "," separatorMap = ":" ) type Value string func (v Value) Map() (map[string]Value, error) { split := tidySplit(v, separatorSlice) m := make(map[string]Value, len(split)) for i := range split { k, v, ok := toKV(split[i], separatorMap) if !ok { // TODO return nil, fmt.Errorf("could not convert to map") } m[k] = Value(v) } return m, nil } // String returns Value as string func (v Value) String() string { return string(v) } // Int converts Value to int. Returned error // will be non nil if convesion failed. func (v Value) Int() (int, error) { return parseValue(v, strconv.Atoi) } // IntSlice splits Value (separator is ",") and adds // each of resulting values to []int if possible. // Returns non-nil error on first failure to convert. func (v Value) IntSlice() ([]int, error) { return parseSlice(v, strconv.Atoi) } // Float64 converts Setting Value to float64. Returned error // will be non nil if convesion failed. func (v Value) Float64() (float64, error) { return parseValue(v, parseFloat64) } // Float64Slice splits Setting Value (separator is ",") and adds // each of resulting values to []float64 if possible. // Returns non-nil error on first failure to convert. func (v Value) Float64Slice() ([]float64, error) { return parseSlice(v, parseFloat64) } // StringSlice splits Setting's Value (separator is ",") and adds // each of resulting values to []string trimming leading and trailing spaces // from each string. func (v Value) StringSlice() []string { return tidySplit(v, separatorSlice) } // Bool tries to interpret Setting's Value as bool // "1", "t", "T", true", "True", "TRUE" yields true // "0", "f", "F, "false", "False", "FALSE" yields false // If nothing matches will return false and conf.ErrCouldNotConvert. func (v Value) Bool() (bool, error) { return parseValue(v, strconv.ParseBool) } func parseSlice[T any, S ~string](s S, f func(string) (T, error)) ([]T, error) { split := tidySplit(s, separatorSlice) list := make([]T, 0, len(split)) for _, str := range split { v, err := parseValue(str, f) if err != nil { return list, err } list = append(list, v) } return list, nil } func parseValue[T any, S ~string](s S, f func(string) (T, error)) (T, error) { v, err := f(string(s)) if err != nil { return v, errors.Join(ErrCouldNotConvert, err) } return v, err } func tidySplit[S ~string](s S, sep string) []string { splitted := strings.Split(string(s), sep) for i, str := range splitted { splitted[i] = strings.TrimSpace(str) } return splitted } func parseFloat64(s string) (float64, error) { return strconv.ParseFloat(s, 64) }