diff --git a/CHANGELOG.md b/CHANGELOG.md index 74fe093..f6e9a0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). ### Removed ### Fixed +- Fix (*Config).CountField returning 1 for arrays of any size. #43 ## [0.3.0] diff --git a/getset.go b/getset.go index ce55819..42bc42d 100644 --- a/getset.go +++ b/getset.go @@ -14,6 +14,10 @@ func convertErr(opts *options, v value, err error, to string) Error { // number of elements for this field. If config value is a list, returns number // of elements in list func (c *Config) CountField(name string, opts ...Option) (int, error) { + if name == "" { + return len(c.fields.arr) + len(c.fields.fields), nil + } + if v, ok := c.fields.fields[name]; ok { return v.Len(makeOptions(opts)) } diff --git a/getset_test.go b/getset_test.go index e5742ee..fa6ae44 100644 --- a/getset_test.go +++ b/getset_test.go @@ -121,6 +121,17 @@ func TestSetGetArray(t *testing.T) { c.SetUint("a", 4, 12) c.SetChild("a", 5, child) + l, err := c.CountField("a") + assert.NoError(t, err) + assert.Equal(t, 6, l) + + a, err := c.Child("a", -1) + assert.NoError(t, err) + + l, err = a.CountField("") + assert.NoError(t, err) + assert.Equal(t, 6, l) + b, err := c.Bool("a", 0) assert.NoError(t, err) assert.Equal(t, true, b) diff --git a/types.go b/types.go index b3ea083..79ee39a 100644 --- a/types.go +++ b/types.go @@ -251,7 +251,6 @@ func (c *cfgString) reflect(*options) (reflect.Value, error) { func (c *cfgString) reify(*options) (interface{}, error) { return c.s, nil } func (c *cfgString) typ(*options) (typeInfo, error) { return typeInfo{"string", tString}, nil } -func (cfgSub) Len(*options) (int, error) { return 1, nil } func (c cfgSub) Context() context { return c.c.ctx } func (cfgSub) toBool(*options) (bool, error) { return false, ErrTypeMismatch } func (cfgSub) toString(*options) (string, error) { return "", ErrTypeMismatch } @@ -260,6 +259,15 @@ func (cfgSub) toUint(*options) (uint64, error) { return 0, ErrTypeMismatch func (cfgSub) toFloat(*options) (float64, error) { return 0, ErrTypeMismatch } func (c cfgSub) toConfig(*options) (*Config, error) { return c.c, nil } +func (c cfgSub) Len(*options) (int, error) { + arr := c.c.fields.arr + if arr != nil { + return len(arr), nil + } + + return 1, nil +} + func (c cfgSub) typ(*options) (typeInfo, error) { return typeInfo{"object", reflect.PtrTo(tConfig)}, nil }