Debian Codegraph @

td/tuple.go

raw
1 // Copyright (c) 2020, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "reflect"
11
12 "github.com/maxatome/go-testdeep/internal/flat"
13 )
14
15 var tupleType = reflect.TypeOf(tuple{})
16
17 // A Tuple is an immutable container. It is used to easily compare
18 // several values at once, typically when a function returns several
19 // values:
20 //
21 // price := func(p float64) (float64, string, error) {
22 // if p < 0 {
23 // return 0, "", errors.New("negative price not supported")
24 // }
25 // return p * 1.2, "€", nil
26 // }
27 //
28 // td.Cmp(t,
29 // td.TupleFrom(price(10)),
30 // td.TupleFrom(float64(12), "€", nil),
31 // )
32 //
33 // td.Cmp(t,
34 // td.TupleFrom(price(-10)),
35 // td.TupleFrom(float64(0), "", td.Not(nil)),
36 // )
37 //
38 // Once initialized with [TupleFrom], a Tuple is immutable.
39 type Tuple interface {
40 // Len returns t length, aka the number of items the tuple contains.
41 Len() int
42 // Index returns t's i'th element. It panics if i is out of range.
43 Index(int) any
44 }
45
46 // TupleFrom returns a new [Tuple] initialized to the values of vals.
47 //
48 // td.TupleFrom(float64(0), "", td.Not(nil))
49 //
50 // [Flatten] can be used to flatten non-[]any slice/array into a
51 // new [Tuple]:
52 //
53 // ints := []int64{1, 2, 3}
54 // td.TupleFrom(td.Flatten(ints), "OK", nil)
55 //
56 // is the same as:
57 //
58 // td.TupleFrom(int64(1), int64(2), int64(3), "OK", nil)
59 func TupleFrom(vals ...any) Tuple {
60 return tuple(flat.Interfaces(vals...))
61 }
62
63 type tuple []any
64
65 func (t tuple) Len() int {
66 return len(t)
67 }
68
69 func (t tuple) Index(i int) any {
70 return t[i]
71 }