tidy up, add docs

This commit is contained in:
Dmitry Fedotov
2025-04-13 22:46:22 +03:00
parent 1465e4cc4c
commit 85452e3dea
10 changed files with 433 additions and 517 deletions

View File

@@ -2,7 +2,7 @@ package conf
import (
"errors"
"fmt"
"net/url"
"strconv"
"strings"
)
@@ -18,20 +18,23 @@ const (
type Value string
func (v Value) Map() (map[string]Value, error) {
// Map tries to interpret value as "key: value" pairs
// separated by comma like in the following string:
// "key1: value1, key2: value2, key3: value3".
func (v Value) Map() (Map, error) {
split := tidySplit(v, separatorSlice)
m := make(map[string]Value, len(split))
m := make(Map, 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")
return nil, ErrCouldNotConvert
}
m[k] = Value(v)
}
return m, nil
}
@@ -43,37 +46,37 @@ func (v Value) String() string {
// 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)
return parseValue(v, strconv.Atoi) // Atoi in fact checks int size, no need to use ParseInt
}
// IntSlice splits Value (separator is ",") and adds
// each of resulting values to []int if possible.
// Returns non-nil error on first failure to convert.
// Returns nil and 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
// Float64 converts 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
// Float64Slice splits Value (separator is ",") and adds
// each of resulting values to []float64 if possible.
// Returns non-nil error on first failure to convert.
// Returns nil and 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
// StringSlice splits 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
// Bool tries to interpret 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.
@@ -81,6 +84,11 @@ func (v Value) Bool() (bool, error) {
return parseValue(v, strconv.ParseBool)
}
// URL tries to interpret value as url.URL
func (v Value) URL() (*url.URL, error) {
return parseValue(v, url.Parse)
}
func parseSlice[T any, S ~string](s S, f func(string) (T, error)) ([]T, error) {
split := tidySplit(s, separatorSlice)