From 15e0f179cabbce73a594e528685627f1fb77bd99 Mon Sep 17 00:00:00 2001 From: Sebastien Binet Date: Mon, 27 Nov 2023 15:02:34 +0100 Subject: [PATCH] types: add Stringer implementation for Dict Signed-off-by: Sebastien Binet --- types/dict.go | 17 +++++++++++++++++ types/dict_test.go | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/types/dict.go b/types/dict.go index a60b784..82d3efc 100644 --- a/types/dict.go +++ b/types/dict.go @@ -7,6 +7,7 @@ package types import ( "fmt" "reflect" + "strings" ) // DictSetter is implemented by any value that exhibits a dict-like behaviour, @@ -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() +} diff --git a/types/dict_test.go b/types/dict_test.go index fe4b41c..b199f37 100644 --- a/types/dict_test.go +++ b/types/dict_test.go @@ -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() @@ -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) + } +}