ValueAsProto converts between ref.Val and cel.expr.Value. The result Value is the serialized proto form. The ref.Val must not be error or unknown.
(res ref.Val)
| 178 | // ValueAsProto converts between ref.Val and cel.expr.Value. |
| 179 | // The result Value is the serialized proto form. The ref.Val must not be error or unknown. |
| 180 | func ValueAsProto(res ref.Val) (*celpb.Value, error) { |
| 181 | switch res.Type() { |
| 182 | case types.BoolType: |
| 183 | return &celpb.Value{ |
| 184 | Kind: &celpb.Value_BoolValue{BoolValue: res.Value().(bool)}}, nil |
| 185 | case types.BytesType: |
| 186 | return &celpb.Value{ |
| 187 | Kind: &celpb.Value_BytesValue{BytesValue: res.Value().([]byte)}}, nil |
| 188 | case types.DoubleType: |
| 189 | return &celpb.Value{ |
| 190 | Kind: &celpb.Value_DoubleValue{DoubleValue: res.Value().(float64)}}, nil |
| 191 | case types.IntType: |
| 192 | return &celpb.Value{ |
| 193 | Kind: &celpb.Value_Int64Value{Int64Value: res.Value().(int64)}}, nil |
| 194 | case types.ListType: |
| 195 | l := res.(traits.Lister) |
| 196 | sz := l.Size().(types.Int) |
| 197 | elts := make([]*celpb.Value, 0, int64(sz)) |
| 198 | for i := types.Int(0); i < sz; i++ { |
| 199 | v, err := ValueAsProto(l.Get(i)) |
| 200 | if err != nil { |
| 201 | return nil, err |
| 202 | } |
| 203 | elts = append(elts, v) |
| 204 | } |
| 205 | return &celpb.Value{ |
| 206 | Kind: &celpb.Value_ListValue{ |
| 207 | ListValue: &celpb.ListValue{Values: elts}}}, nil |
| 208 | case types.MapType: |
| 209 | mapper := res.(traits.Mapper) |
| 210 | sz := mapper.Size().(types.Int) |
| 211 | entries := make([]*celpb.MapValue_Entry, 0, int64(sz)) |
| 212 | for it := mapper.Iterator(); it.HasNext().(types.Bool); { |
| 213 | k := it.Next() |
| 214 | v := mapper.Get(k) |
| 215 | kv, err := ValueAsProto(k) |
| 216 | if err != nil { |
| 217 | return nil, err |
| 218 | } |
| 219 | vv, err := ValueAsProto(v) |
| 220 | if err != nil { |
| 221 | return nil, err |
| 222 | } |
| 223 | entries = append(entries, &celpb.MapValue_Entry{Key: kv, Value: vv}) |
| 224 | } |
| 225 | return &celpb.Value{ |
| 226 | Kind: &celpb.Value_MapValue{ |
| 227 | MapValue: &celpb.MapValue{Entries: entries}}}, nil |
| 228 | case types.NullType: |
| 229 | return &celpb.Value{ |
| 230 | Kind: &celpb.Value_NullValue{}}, nil |
| 231 | case types.StringType: |
| 232 | return &celpb.Value{ |
| 233 | Kind: &celpb.Value_StringValue{StringValue: res.Value().(string)}}, nil |
| 234 | case types.TypeType: |
| 235 | typeName := res.(ref.Type).TypeName() |
| 236 | return &celpb.Value{Kind: &celpb.Value_TypeValue{TypeValue: typeName}}, nil |
| 237 | case types.UintType: |