Debian Codegraph @

common/types/string.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 "fmt"
19 "reflect"
20 "regexp"
21 "strconv"
22 "strings"
23 "time"
24
25 "github.com/google/cel-go/common/overloads"
26 "github.com/google/cel-go/common/types/ref"
27
28 anypb "google.golang.org/protobuf/types/known/anypb"
29 structpb "google.golang.org/protobuf/types/known/structpb"
30 wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
31 )
32
33 // String type implementation which supports addition, comparison, matching,
34 // and size functions.
35 type String string
36
37 var (
38 stringOneArgOverloads = map[string]func(ref.Val, ref.Val) ref.Val{
39 overloads.Contains: StringContains,
40 overloads.EndsWith: StringEndsWith,
41 overloads.StartsWith: StringStartsWith,
42 }
43
44 stringWrapperType = reflect.TypeOf(&wrapperspb.StringValue{})
45 )
46
47 // Add implements traits.Adder.Add.
48 func (s String) Add(other ref.Val) ref.Val {
49 otherString, ok := other.(String)
50 if !ok {
51 return MaybeNoSuchOverloadErr(other)
52 }
53 return s + otherString
54 }
55
56 // Compare implements traits.Comparer.Compare.
57 func (s String) Compare(other ref.Val) ref.Val {
58 otherString, ok := other.(String)
59 if !ok {
60 return MaybeNoSuchOverloadErr(other)
61 }
62 return Int(strings.Compare(s.Value().(string), otherString.Value().(string)))
63 }
64
65 // ConvertToNative implements ref.Val.ConvertToNative.
66 func (s String) ConvertToNative(typeDesc reflect.Type) (any, error) {
67 switch typeDesc.Kind() {
68 case reflect.String:
69 return reflect.ValueOf(s).Convert(typeDesc).Interface(), nil
70 case reflect.Ptr:
71 switch typeDesc {
72 case anyValueType:
73 // Primitives must be wrapped before being set on an Any field.
74 return anypb.New(wrapperspb.String(string(s)))
75 case JSONValueType:
76 // Convert to a protobuf representation of a JSON String.
77 return structpb.NewStringValue(string(s)), nil
78 case stringWrapperType:
79 // Convert to a wrapperspb.StringValue.
80 return wrapperspb.String(string(s)), nil
81 }
82 if typeDesc.Elem().Kind() == reflect.String {
83 p := s.Value().(string)
84 return &p, nil
85 }
86 case reflect.Interface:
87 sv := s.Value()
88 if reflect.TypeOf(sv).Implements(typeDesc) {
89 return sv, nil
90 }
91 if reflect.TypeOf(s).Implements(typeDesc) {
92 return s, nil
93 }
94 }
95 return nil, fmt.Errorf(
96 "unsupported native conversion from string to '%v'", typeDesc)
97 }
98
99 // ConvertToType implements ref.Val.ConvertToType.
100 func (s String) ConvertToType(typeVal ref.Type) ref.Val {
101 switch typeVal {
102 case IntType:
103 if n, err := strconv.ParseInt(s.Value().(string), 10, 64); err == nil {
104 return Int(n)
105 }
106 case UintType:
107 if n, err := strconv.ParseUint(s.Value().(string), 10, 64); err == nil {
108 return Uint(n)
109 }
110 case DoubleType:
111 if n, err := strconv.ParseFloat(s.Value().(string), 64); err == nil {
112 return Double(n)
113 }
114 case BoolType:
115 if b, err := strconv.ParseBool(s.Value().(string)); err == nil {
116 return Bool(b)
117 }
118 case BytesType:
119 return Bytes(s)
120 case DurationType:
121 if d, err := time.ParseDuration(s.Value().(string)); err == nil {
122 return durationOf(d)
123 }
124 case TimestampType:
125 if t, err := time.Parse(time.RFC3339, s.Value().(string)); err == nil {
126 if t.Unix() < minUnixTime || t.Unix() > maxUnixTime {
127 return celErrTimestampOverflow
128 }
129 return timestampOf(t)
130 }
131 case StringType:
132 return s
133 case TypeType:
134 return StringType
135 }
136 return NewErr("type conversion error from '%s' to '%s'", StringType, typeVal)
137 }
138
139 // Equal implements ref.Val.Equal.
140 func (s String) Equal(other ref.Val) ref.Val {
141 otherString, ok := other.(String)
142 return Bool(ok && s == otherString)
143 }
144
145 // IsZeroValue returns true if the string is empty.
146 func (s String) IsZeroValue() bool {
147 return len(s) == 0
148 }
149
150 // Match implements traits.Matcher.Match.
151 func (s String) Match(pattern ref.Val) ref.Val {
152 pat, ok := pattern.(String)
153 if !ok {
154 return MaybeNoSuchOverloadErr(pattern)
155 }
156 matched, err := regexp.MatchString(pat.Value().(string), s.Value().(string))
157 if err != nil {
158 return &Err{error: err}
159 }
160 return Bool(matched)
161 }
162
163 // Receive implements traits.Receiver.Receive.
164 func (s String) Receive(function string, overload string, args []ref.Val) ref.Val {
165 switch len(args) {
166 case 1:
167 if f, found := stringOneArgOverloads[function]; found {
168 return f(s, args[0])
169 }
170 }
171 return NoSuchOverloadErr()
172 }
173
174 // Size implements traits.Sizer.Size.
175 func (s String) Size() ref.Val {
176 return Int(len([]rune(s.Value().(string))))
177 }
178
179 // Type implements ref.Val.Type.
180 func (s String) Type() ref.Type {
181 return StringType
182 }
183
184 // Value implements ref.Val.Value.
185 func (s String) Value() any {
186 return string(s)
187 }
188
189 func (s String) format(sb *strings.Builder) {
190 sb.WriteString(strconv.Quote(string(s)))
191 }
192
193 // StringContains returns whether the string contains a substring.
194 func StringContains(s, sub ref.Val) ref.Val {
195 str, ok := s.(String)
196 if !ok {
197 return MaybeNoSuchOverloadErr(s)
198 }
199 subStr, ok := sub.(String)
200 if !ok {
201 return MaybeNoSuchOverloadErr(sub)
202 }
203 return Bool(strings.Contains(string(str), string(subStr)))
204 }
205
206 // StringEndsWith returns whether the target string contains the input suffix.
207 func StringEndsWith(s, suf ref.Val) ref.Val {
208 str, ok := s.(String)
209 if !ok {
210 return MaybeNoSuchOverloadErr(s)
211 }
212 sufStr, ok := suf.(String)
213 if !ok {
214 return MaybeNoSuchOverloadErr(suf)
215 }
216 return Bool(strings.HasSuffix(string(str), string(sufStr)))
217 }
218
219 // StringStartsWith returns whether the target string contains the input prefix.
220 func StringStartsWith(s, pre ref.Val) ref.Val {
221 str, ok := s.(String)
222 if !ok {
223 return MaybeNoSuchOverloadErr(s)
224 }
225 preStr, ok := pre.(String)
226 if !ok {
227 return MaybeNoSuchOverloadErr(pre)
228 }
229 return Bool(strings.HasPrefix(string(str), string(preStr)))
230 }