-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
json_escape.go
85 lines (72 loc) · 2.19 KB
/
json_escape.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
81
82
83
84
85
// Code generated by __generator__/interpreter.go at once
package builtin
import (
"fmt"
"unicode/utf8"
"github.com/ysugimoto/falco/interpreter/context"
"github.com/ysugimoto/falco/interpreter/function/errors"
"github.com/ysugimoto/falco/interpreter/value"
)
const Json_escape_Name = "json.escape"
var Json_escape_ArgumentTypes = []value.Type{value.StringType}
func Json_escape_Validate(args []value.Value) error {
if len(args) != 1 {
return errors.ArgumentNotEnough(Json_escape_Name, 1, args)
}
for i := range args {
if args[i].Type() != Json_escape_ArgumentTypes[i] {
return errors.TypeMismatch(Json_escape_Name, i+1, Json_escape_ArgumentTypes[i], args[i].Type())
}
}
return nil
}
var Json_escape_CharacterMap = map[rune][]rune{
0x22: []rune("\""),
0x5C: []rune("\\"),
0x08: []rune("\\b"),
0x09: []rune("\\t"),
0x0A: []rune("\\n"),
0x0C: []rune("\\f"),
0x0D: []rune("\\r"),
}
// ref: http://www5d.biglobe.ne.jp/~noocyte/Programming/CharCode.html (JP)
func Json_escape_toUTF16SurrogatePair(r rune) []rune {
r -= 0x10000
upper := ((r >> 10) & 0x03FF) + 0xD800
lower := (r & 0x03FF) + 0xDC00
return []rune(fmt.Sprintf("\\u%04X\\u%04X", upper, lower))
}
// Fastly built-in function implementation of json.escape
// Arguments may be:
// - STRING
// Reference: https://developer.fastly.com/reference/vcl/functions/strings/json-escape/
func Json_escape(ctx *context.Context, args ...value.Value) (value.Value, error) {
// Argument validations
if err := Json_escape_Validate(args); err != nil {
return value.Null, err
}
str := value.Unwrap[*value.String](args[0])
// Preparation: check provided is valid in UTF-8 sequence
if !utf8.ValidString(str.Value) {
return &value.String{Value: ""}, nil
}
var escaped []rune
for _, r := range []rune(str.Value) {
if v, ok := Json_escape_CharacterMap[r]; ok {
escaped = append(escaped, v...)
continue
}
if r < 0x1F || r == 0x7F || r == 0x2028 || r == 0x2029 {
escaped = append(escaped, []rune(fmt.Sprintf("\\u%04x", r))...)
continue
}
if r > 0xFFFF {
escaped = append(escaped, Json_escape_toUTF16SurrogatePair(r)...)
continue
}
escaped = append(escaped, r)
}
return &value.String{
Value: string(escaped),
}, nil
}