Skip to content

Commit

Permalink
types: add Stringer implementation for Dict
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastien Binet <[email protected]>
  • Loading branch information
sbinet committed Nov 28, 2023
1 parent 2139434 commit 15e0f17
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
17 changes: 17 additions & 0 deletions types/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package types
import (
"fmt"
"reflect"
"strings"
)

// DictSetter is implemented by any value that exhibits a dict-like behaviour,
Expand Down Expand Up @@ -88,3 +89,19 @@ func (*Dict) Call(args ...interface{}) (interface{}, error) {
}
return nil, fmt.Errorf("Dict: invalid arguments: %#v", args)
}

func (d *Dict) String() string {
if d == nil {
return "nil"
}
o := new(strings.Builder)
o.WriteString("{")
for i, e := range *d {
if i > 0 {
o.WriteString(", ")
}
fmt.Fprintf(o, "%v: %v", e.Key, e.Value)
}
o.WriteString("}")
return o.String()
}
34 changes: 33 additions & 1 deletion types/dict_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
// Copyright 2023 NLP Odyssey Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package types

import "testing"
import (
"bytes"
"fmt"
"testing"
)

func TestDictCall(t *testing.T) {
d := NewDict()
Expand All @@ -14,3 +22,27 @@ func TestDictCall(t *testing.T) {
t.Errorf("expected %v, actual: %v", expected, actual)
}
}

func TestDictStringer(t *testing.T) {
dct := NewDict()
dct.Set("empty", NewDict())
dct.Set("one", "un")
dct.Set("two", "deux")
sub := NewDict()
sub.Set("eins", "one")
sub.Set("zwei", []string{"two", "deux"})
sub.Set(2, []int{2 * 2, 2 * 3, 2 * 4})
dct.Set("sub", sub)

buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%v", dct)

var (
got = buf.String()
want = "{empty: {}, one: un, two: deux, sub: {eins: one, zwei: [two deux], 2: [4 6 8]}}"
)

if got != want {
t.Fatalf("got= %q\nwant=%q", got, want)
}
}

0 comments on commit 15e0f17

Please sign in to comment.