Skip to content

Commit

Permalink
types: add Stringer implementation for Tuple
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastien Binet <[email protected]>
  • Loading branch information
sbinet committed Nov 24, 2023
1 parent 62f65b4 commit cd99eb4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
24 changes: 24 additions & 0 deletions types/tuple.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@

package types

import (
"fmt"
"strings"
)

type Tuple []interface{}

func NewTupleFromSlice(slice []interface{}) *Tuple {
Expand All @@ -18,3 +23,22 @@ func (t *Tuple) Get(i int) interface{} {
func (t *Tuple) Len() int {
return len(*t)
}

func (t *Tuple) String() string {
if t == nil {
return "nil"
}
o := new(strings.Builder)
o.WriteString("(")
for i, v := range *t {
if i > 0 {
o.WriteString(", ")
}
fmt.Fprintf(o, "%v", v)
}
if t.Len() == 1 {
o.WriteString(",")
}
o.WriteString(")")
return o.String()
}
28 changes: 28 additions & 0 deletions types/tuple_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// 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 (
"bytes"
"fmt"
"testing"
)

func TestTupleStringer(t *testing.T) {
tuple := func(sli ...interface{}) *Tuple {
return NewTupleFromSlice(sli)
}

tup := tuple(tuple(), tuple(1), tuple(2, 3), tuple(tuple(4, 5), 6))

buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%v", tup)
got := buf.String()
want := "((), (1,), (2, 3), ((4, 5), 6))"

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

0 comments on commit cd99eb4

Please sign in to comment.