Debian Codegraph @

common/types/bytes.go

raw
1 // Copyright 2018 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package types
16
17 import (
18 "bytes"
19 "encoding/base64"
20 "fmt"
21 "reflect"
22 "strings"
23 "unicode/utf8"
24
25 "github.com/google/cel-go/common/types/ref"
26
27 anypb "google.golang.org/protobuf/types/known/anypb"
28 structpb "google.golang.org/protobuf/types/known/structpb"
29 wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
30 )
31
32 // Bytes type that implements ref.Val and supports add, compare, and size
33 // operations.
34 type Bytes []byte
35
36 var (
37 // byteWrapperType golang reflected type for protobuf bytes wrapper type.
38 byteWrapperType = reflect.TypeOf(&wrapperspb.BytesValue{})
39 )
40
41 // Add implements traits.Adder interface method by concatenating byte sequences.
42 func (b Bytes) Add(other ref.Val) ref.Val {
43 otherBytes, ok := other.(Bytes)
44 if !ok {
45 return ValOrErr(other, "no such overload")
46 }
47 return append(b, otherBytes...)
48 }
49
50 // Compare implements traits.Comparer interface method by lexicographic ordering.
51 func (b Bytes) Compare(other ref.Val) ref.Val {
52 otherBytes, ok := other.(Bytes)
53 if !ok {
54 return ValOrErr(other, "no such overload")
55 }
56 return Int(bytes.Compare(b, otherBytes))
57 }
58
59 // ConvertToNative implements the ref.Val interface method.
60 func (b Bytes) ConvertToNative(typeDesc reflect.Type) (any, error) {
61 switch typeDesc.Kind() {
62 case reflect.Array:
63 if len(b) != typeDesc.Len() {
64 return nil, fmt.Errorf("[%d]byte not assignable to [%d]byte array", len(b), typeDesc.Len())
65 }
66 refArrPtr := reflect.New(reflect.ArrayOf(len(b), typeDesc.Elem()))
67 refArr := refArrPtr.Elem()
68 for i, byt := range b {
69 refArr.Index(i).Set(reflect.ValueOf(byt).Convert(typeDesc.Elem()))
70 }
71 return refArr.Interface(), nil
72 case reflect.Slice:
73 return reflect.ValueOf(b).Convert(typeDesc).Interface(), nil
74 case reflect.Ptr:
75 switch typeDesc {
76 case anyValueType:
77 // Primitives must be wrapped before being set on an Any field.
78 return anypb.New(wrapperspb.Bytes([]byte(b)))
79 case byteWrapperType:
80 // Convert the bytes to a wrapperspb.BytesValue.
81 return wrapperspb.Bytes([]byte(b)), nil
82 case JSONValueType:
83 // CEL follows the proto3 to JSON conversion by encoding bytes to a string via base64.
84 // The encoding below matches the golang 'encoding/json' behavior during marshaling,
85 // which uses base64.StdEncoding.
86 str := base64.StdEncoding.EncodeToString([]byte(b))
87 return structpb.NewStringValue(str), nil
88 }
89 case reflect.Interface:
90 bv := b.Value()
91 if reflect.TypeOf(bv).Implements(typeDesc) {
92 return bv, nil
93 }
94 if reflect.TypeOf(b).Implements(typeDesc) {
95 return b, nil
96 }
97 }
98 return nil, fmt.Errorf("type conversion error from Bytes to '%v'", typeDesc)
99 }
100
101 // ConvertToType implements the ref.Val interface method.
102 func (b Bytes) ConvertToType(typeVal ref.Type) ref.Val {
103 switch typeVal {
104 case StringType:
105 if !utf8.Valid(b) {
106 return NewErr("invalid UTF-8 in bytes, cannot convert to string")
107 }
108 return String(b)
109 case BytesType:
110 return b
111 case TypeType:
112 return BytesType
113 }
114 return NewErr("type conversion error from '%s' to '%s'", BytesType, typeVal)
115 }
116
117 // Equal implements the ref.Val interface method.
118 func (b Bytes) Equal(other ref.Val) ref.Val {
119 otherBytes, ok := other.(Bytes)
120 return Bool(ok && bytes.Equal(b, otherBytes))
121 }
122
123 // IsZeroValue returns true if the byte array is empty.
124 func (b Bytes) IsZeroValue() bool {
125 return len(b) == 0
126 }
127
128 // Size implements the traits.Sizer interface method.
129 func (b Bytes) Size() ref.Val {
130 return Int(len(b))
131 }
132
133 // Type implements the ref.Val interface method.
134 func (b Bytes) Type() ref.Type {
135 return BytesType
136 }
137
138 // Value implements the ref.Val interface method.
139 func (b Bytes) Value() any {
140 return []byte(b)
141 }
142
143 func (b Bytes) format(sb *strings.Builder) {
144 fmt.Fprintf(sb, "b\"%s\"", bytesToOctets([]byte(b)))
145 }
146
147 // bytesToOctets converts byte sequences to a string using a three digit octal encoded value
148 // per byte.
149 func bytesToOctets(byteVal []byte) string {
150 var b strings.Builder
151 for _, c := range byteVal {
152 fmt.Fprintf(&b, "\\%03o", c)
153 }
154 return b.String()
155 }