Debian Codegraph @

common/types/format.go

raw symbols SCIP
1 package types
2
3 import (
4 "fmt"
5 "strings"
6
7 "github.com/google/cel-go/common/types/ref"
8 "github.com/google/cel-go/common/types/traits"
9 )
10
11 type formattable interface {
12 format(*strings.Builder)
13 }
14
15 // Format formats the value as a string. The result is only intended for human consumption and ignores errors.
16 // Do not depend on the output being stable. It may change at any time.
17 func Format(val ref.Val) string {
18 var sb strings.Builder
19 formatTo(&sb, val)
20 return sb.String()
21 }
22
23 func formatTo(sb *strings.Builder, val ref.Val) {
24 if fmtable, ok := val.(formattable); ok {
25 fmtable.format(sb)
26 return
27 }
28 // All of the builtins implement formattable. Try to deal with traits.
29 if l, ok := val.(traits.Lister); ok {
30 formatList(l, sb)
31 return
32 }
33 if m, ok := val.(traits.Mapper); ok {
34 formatMap(m, sb)
35 return
36 }
37 // This could be an error, unknown, opaque or object.
38 // Unfortunately we have no consistent way of inspecting
39 // opaque and object. So we just fallback to fmt.Stringer
40 // and hope it is relavent.
41 fmt.Fprintf(sb, "%s", val)
42 }