/
substr.go
80 lines (71 loc) · 1.97 KB
/
substr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Code generated by __generator__/interpreter.go at once
package builtin
import (
"github.com/ysugimoto/falco/interpreter/context"
"github.com/ysugimoto/falco/interpreter/function/errors"
"github.com/ysugimoto/falco/interpreter/value"
)
const Substr_Name = "substr"
var Substr_ArgumentTypes = []value.Type{value.StringType, value.IntegerType, value.IntegerType}
func Substr_Validate(args []value.Value) error {
if len(args) < 2 || len(args) > 3 {
return errors.ArgumentNotInRange(Substr_Name, 2, 3, args)
}
for i := range args {
if args[i].Type() != Substr_ArgumentTypes[i] {
return errors.TypeMismatch(Substr_Name, i+1, Substr_ArgumentTypes[i], args[i].Type())
}
}
return nil
}
// Fastly built-in function implementation of substr
// Arguments may be:
// - STRING, INTEGER, INTEGER
// - STRING, INTEGER
// Reference: https://developer.fastly.com/reference/vcl/functions/strings/substr/
func Substr(ctx *context.Context, args ...value.Value) (value.Value, error) {
// Argument validations
if err := Substr_Validate(args); err != nil {
return value.Null, err
}
input := []byte(value.Unwrap[*value.String](args[0]).Value)
offset := int(value.Unwrap[*value.Integer](args[1]).Value)
var length *int
if len(args) > 2 {
v := int(value.Unwrap[*value.Integer](args[2]).Value)
length = &v
}
var start, end int
if offset < 0 {
start = len(input) + offset
} else {
start = offset
}
if length == nil {
end = len(input)
} else if *length < 0 {
if offset < 0 {
end = len(input) + *length + 1
} else {
end = len(input) + *length
}
} else {
if offset < 0 {
end = start + *length
} else {
end = start + *length + 1
}
}
if end > len(input) {
end = len(input)
}
if start > len(input) {
return &value.String{IsNotSet: true}, errors.New(Substr_Name,
"Invalid start offset %d against input string %s", offset, input,
)
}
if end <= start {
return &value.String{Value: ""}, nil
}
return &value.String{Value: string(input[start:end])}, nil
}