Skip to content

Commit

Permalink
Fix CountFields for arrays returning correct count
Browse files Browse the repository at this point in the history
  • Loading branch information
urso committed Jul 25, 2016
1 parent 8aff693 commit 81b3bba
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions getset.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
11 changes: 11 additions & 0 deletions getset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 9 additions & 1 deletion types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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
}
Expand Down

0 comments on commit 81b3bba

Please sign in to comment.