MCPcopy Create free account
hub / github.com/cel-expr/cel-go / formatMap

Function formatMap

ext/formatting.go:119–185  ·  view source on GitHub ↗
(arg ref.Val, locale string)

Source from the content-addressed store, hash-verified

117}
118
119func formatMap(arg ref.Val, locale string) (string, error) {
120 argMap := arg.(traits.Mapper)
121 argIterator := argMap.Iterator()
122 type mapPair struct {
123 key string
124 value string
125 }
126 argPairs := make([]mapPair, argMap.Size().Value().(int64))
127 i := 0
128 for argIterator.HasNext() == types.True {
129 key := argIterator.Next()
130 var keyFormat clauseImpl
131 switch key.Type() {
132 case types.StringType, types.BoolType:
133 keyFormat = FormatString
134 case types.IntType, types.UintType:
135 keyFormat = formatDecimal
136 default:
137 return "", fmt.Errorf("no formatting function for map key of type %s", key.Type().TypeName())
138 }
139 unquotedKeyStr, err := keyFormat(key, locale)
140 if err != nil {
141 return "", err
142 }
143 keyStr := quoteForCEL(key, unquotedKeyStr)
144 value, found := argMap.Find(key)
145 if !found {
146 return "", fmt.Errorf("could not find key: %q", key)
147 }
148 valueFormat, err := clauseForType(value.Type())
149 if err != nil {
150 return "", err
151 }
152 unquotedValueStr, err := valueFormat(value, locale)
153 if err != nil {
154 return "", err
155 }
156 valueStr := quoteForCEL(value, unquotedValueStr)
157 argPairs[i] = mapPair{keyStr, valueStr}
158 i++
159 }
160 sort.SliceStable(argPairs, func(x, y int) bool {
161 return argPairs[x].key < argPairs[y].key
162 })
163 var mapStrBuilder strings.Builder
164 _, err := mapStrBuilder.WriteRune('{')
165 if err != nil {
166 return "", fmt.Errorf("error writing to map string: %w", err)
167 }
168 for i, entry := range argPairs {
169 _, err = mapStrBuilder.WriteString(fmt.Sprintf("%s:%s", entry.key, entry.value))
170 if err != nil {
171 return "", fmt.Errorf("error writing to map string: %w", err)
172 }
173 if i < len(argPairs)-1 {
174 _, err = mapStrBuilder.WriteString(", ")
175 if err != nil {
176 return "", fmt.Errorf("error writing to map string: %w", err)

Callers 1

FormatStringFunction · 0.70

Calls 11

quoteForCELFunction · 0.85
clauseForTypeFunction · 0.85
IteratorMethod · 0.65
ValueMethod · 0.65
SizeMethod · 0.65
HasNextMethod · 0.65
NextMethod · 0.65
TypeMethod · 0.65
TypeNameMethod · 0.65
FindMethod · 0.65
StringMethod · 0.65

Tested by

no test coverage detected