| 1 |
package encoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding" |
| 6 |
"encoding/base64" |
| 7 |
"encoding/json" |
| 8 |
"fmt" |
| 9 |
"math" |
| 10 |
"reflect" |
| 11 |
"slices" |
| 12 |
"strconv" |
| 13 |
"strings" |
| 14 |
"sync" |
| 15 |
"unicode/utf8" |
| 16 |
"unsafe" |
| 17 |
|
| 18 |
"github.com/goccy/go-json/internal/errors" |
| 19 |
"github.com/goccy/go-json/internal/runtime" |
| 20 |
) |
| 21 |
|
| 22 |
func (t OpType) IsMultipleOpField() bool { |
| 23 |
switch t { |
| 24 |
case OpStructField: |
| 25 |
return true |
| 26 |
case OpStructFieldSlice: |
| 27 |
return true |
| 28 |
case OpStructFieldArray: |
| 29 |
return true |
| 30 |
case OpStructFieldMap: |
| 31 |
return true |
| 32 |
case OpStructFieldStruct: |
| 33 |
return true |
| 34 |
case OpStructFieldOmitEmpty: |
| 35 |
return true |
| 36 |
case OpStructFieldOmitEmptySlice: |
| 37 |
return true |
| 38 |
case OpStructFieldOmitEmptyArray: |
| 39 |
return true |
| 40 |
case OpStructFieldOmitEmptyMap: |
| 41 |
return true |
| 42 |
case OpStructFieldOmitEmptyStruct: |
| 43 |
return true |
| 44 |
case OpStructFieldSlicePtr: |
| 45 |
return true |
| 46 |
case OpStructFieldOmitEmptySlicePtr: |
| 47 |
return true |
| 48 |
case OpStructFieldArrayPtr: |
| 49 |
return true |
| 50 |
case OpStructFieldOmitEmptyArrayPtr: |
| 51 |
return true |
| 52 |
case OpStructFieldMapPtr: |
| 53 |
return true |
| 54 |
case OpStructFieldOmitEmptyMapPtr: |
| 55 |
return true |
| 56 |
} |
| 57 |
return false |
| 58 |
} |
| 59 |
|
| 60 |
type OpcodeSet struct { |
| 61 |
Type reflect.Type |
| 62 |
// IfaceIndir is whether a value of Type is stored indirectly in an interface value. |
| 63 |
// It is decided when the type is compiled, because deciding it is not cheap. |
| 64 |
IfaceIndir bool |
| 65 |
// DataWordIsAddr is whether the data word of an interface value of Type is the address of the value |
| 66 |
// which the opcodes take: the type is stored indirectly, or it is a pointer, which is the address of |
| 67 |
// the value it points to. |
| 68 |
DataWordIsAddr bool |
| 69 |
NoescapeKeyCode *Opcode |
| 70 |
EscapeKeyCode *Opcode |
| 71 |
InterfaceNoescapeKeyCode *Opcode |
| 72 |
InterfaceEscapeKeyCode *Opcode |
| 73 |
CodeLength int |
| 74 |
EndCode *Opcode |
| 75 |
// Scalar is the opcode of the value if the type is encoded by a single opcode of a scalar ( a number, |
| 76 |
// a string, a bool, ... ), or nil. Such a value held by an interface value is encoded without a frame. |
| 77 |
Scalar *Opcode |
| 78 |
Code Code |
| 79 |
QueryCache map[string]*OpcodeSet |
| 80 |
// values is the pool of the values of Type in the heap, which MarshalOf copies its argument to. |
| 81 |
values sync.Pool |
| 82 |
cacheMu sync.RWMutex |
| 83 |
} |
| 84 |
|
| 85 |
// ValueShape classifies a type by what a nil data word of an interface value of the type means. |
| 86 |
type ValueShape uint |
| 87 |
|
| 88 |
const ( |
| 89 |
// ValueShapePointer is the type whose nil data word is encoded as null: a pointer, a map, ... |
| 90 |
ValueShapePointer ValueShape = iota |
| 91 |
// ValueShapeAggregate is the type whose nil data word is a value to encode, if the type is stored directly |
| 92 |
// in an interface value: |
| 93 |
// - a struct or an array which consists of a single pointer. The pointer is nil, not the value. |
| 94 |
// - a map which has a marshaler. encoding/json writes null instead of calling the marshaler |
| 95 |
// only for a nil pointer, so the marshaler of a nil map is called. |
| 96 |
ValueShapeAggregate |
| 97 |
) |
| 98 |
|
| 99 |
// ShapeOf returns the shape of the type given by the pointer to its type descriptor. |
| 100 |
// |
| 101 |
// ShapeOf and IfaceIndir are functions of their own, not a part of the VM, and the VM calls them in the |
| 102 |
// same form as it did before, because any change of the code of the VM changes the register allocation |
| 103 |
// of the whole VM. |
| 104 |
// |
| 105 |
//go:noinline |
| 106 |
func ShapeOf(typ unsafe.Pointer) ValueShape { |
| 107 |
switch runtime.TypeOfPtr(typ).Kind() { |
| 108 |
case reflect.Struct, reflect.Array: |
| 109 |
return ValueShapeAggregate |
| 110 |
case reflect.Map: |
| 111 |
// whether the type has a marshaler was decided when the type was compiled. |
| 112 |
codeSet, err := compileToGetUnfilteredCodeSet(uintptr(typ), false) |
| 113 |
if err != nil { |
| 114 |
// the VM compiles the type right after this, and it reports the error. |
| 115 |
return ValueShapeAggregate |
| 116 |
} |
| 117 |
switch codeSet.Code.Kind() { |
| 118 |
case CodeKindMarshalJSON, CodeKindMarshalText: |
| 119 |
return ValueShapeAggregate |
| 120 |
} |
| 121 |
} |
| 122 |
return ValueShapePointer |
| 123 |
} |
| 124 |
|
| 125 |
// IfaceIndir reports whether a value of the type is stored indirectly in an interface value. |
| 126 |
// It is decided only once per type, when the type is compiled. |
| 127 |
// |
| 128 |
//go:noinline |
| 129 |
func IfaceIndir(typ unsafe.Pointer) bool { |
| 130 |
codeSet, err := compileToGetUnfilteredCodeSet(uintptr(typ), false) |
| 131 |
if err != nil { |
| 132 |
// the VM compiles the type right after this, and it reports the error. |
| 133 |
return false |
| 134 |
} |
| 135 |
return codeSet.IfaceIndir |
| 136 |
} |
| 137 |
|
| 138 |
// TakeValue returns the address of a zero value of Type in the heap. |
| 139 |
// |
| 140 |
// The runtime context keeps the value of the type it encoded last, because taking one from a sync.Pool costs |
| 141 |
// as much as a small allocation, and a runtime context is already taken from a pool. |
| 142 |
func (s *OpcodeSet) TakeValue(ctx *RuntimeContext) unsafe.Pointer { |
| 143 |
if ctx.valueCodeSet == s { |
| 144 |
return ctx.value |
| 145 |
} |
| 146 |
if ctx.valueCodeSet != nil { |
| 147 |
ctx.valueCodeSet.values.Put(ctx.value) |
| 148 |
} |
| 149 |
ctx.valueCodeSet = s |
| 150 |
if p := s.values.Get(); p != nil { |
| 151 |
ctx.value = p.(unsafe.Pointer) |
| 152 |
} else { |
| 153 |
ctx.value = reflect.New(s.Type).UnsafePointer() |
| 154 |
} |
| 155 |
return ctx.value |
| 156 |
} |
| 157 |
|
| 158 |
func (s *OpcodeSet) getQueryCache(hash string) *OpcodeSet { |
| 159 |
s.cacheMu.RLock() |
| 160 |
codeSet := s.QueryCache[hash] |
| 161 |
s.cacheMu.RUnlock() |
| 162 |
return codeSet |
| 163 |
} |
| 164 |
|
| 165 |
func (s *OpcodeSet) setQueryCache(hash string, codeSet *OpcodeSet) { |
| 166 |
s.cacheMu.Lock() |
| 167 |
s.QueryCache[hash] = codeSet |
| 168 |
s.cacheMu.Unlock() |
| 169 |
} |
| 170 |
|
| 171 |
type CompiledCode struct { |
| 172 |
Code *Opcode |
| 173 |
Linked bool // whether recursive code already have linked |
| 174 |
CurLen uintptr |
| 175 |
NextLen uintptr |
| 176 |
// Embedded is whether the recursive struct is embedded in the struct which jumps to it. |
| 177 |
// The code to jump to is only the fields of the struct then: it has neither the braces nor the check of nil. |
| 178 |
Embedded bool |
| 179 |
} |
| 180 |
|
| 181 |
const StartDetectingCyclesAfter = 1000 |
| 182 |
|
| 183 |
func ErrUnsupportedValue(code *Opcode, ptr unsafe.Pointer) *errors.UnsupportedValueError { |
| 184 |
v := *(*any)(unsafe.Pointer(&emptyInterface{ |
| 185 |
typ: code.Type, |
| 186 |
ptr: ptr, |
| 187 |
})) |
| 188 |
return &errors.UnsupportedValueError{ |
| 189 |
Value: reflect.ValueOf(v), |
| 190 |
Str: fmt.Sprintf("encountered a cycle via %s", runtime.TypeOfPtr(code.Type)), |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
func ErrUnsupportedFloat(v float64) *errors.UnsupportedValueError { |
| 195 |
return &errors.UnsupportedValueError{ |
| 196 |
Value: reflect.ValueOf(v), |
| 197 |
Str: strconv.FormatFloat(v, 'g', -1, 64), |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
func ErrMarshalerWithCode(code *Opcode, err error) *errors.MarshalerError { |
| 202 |
return &errors.MarshalerError{ |
| 203 |
Type: runtime.TypeOfPtr(code.Type), |
| 204 |
Err: err, |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
type emptyInterface struct { |
| 209 |
typ unsafe.Pointer |
| 210 |
ptr unsafe.Pointer |
| 211 |
} |
| 212 |
|
| 213 |
type MapItem struct { |
| 214 |
Key []byte |
| 215 |
Value []byte |
| 216 |
} |
| 217 |
|
| 218 |
type Mapslice struct { |
| 219 |
Items []MapItem |
| 220 |
// escaped is whether a text was escaped while the entries of a map whose keys are texts were encoded ( see |
| 221 |
// appendText ): a key, or a text of a value, which tells that a key may have an escape. |
| 222 |
escaped bool |
| 223 |
} |
| 224 |
|
| 225 |
// Sort sorts the items by their keys, which are the names of the keys as encoding/json sorts them: an encoded |
| 226 |
// key is in the order of its name unless it has an escape, and then the names are decoded to be sorted by. |
| 227 |
// A text which was escaped while the entries were encoded tells that a key may have one ( see appendText ). |
| 228 |
// |
| 229 |
// It is not sort.Sort, which calls Less and Swap through an interface for every comparison: |
| 230 |
// the maps to encode are small in most cases, and the sort was a tenth of the time to encode one. |
| 231 |
func (m *Mapslice) Sort() { |
| 232 |
items := m.Items |
| 233 |
if m.escaped { |
| 234 |
sortMapItemsByNames(items) |
| 235 |
return |
| 236 |
} |
| 237 |
if len(items) > maxItemsOfInsertionSort { |
| 238 |
slices.SortFunc(items, func(a, b MapItem) int { |
| 239 |
return bytes.Compare(a.Key, b.Key) |
| 240 |
}) |
| 241 |
return |
| 242 |
} |
| 243 |
insertionSortMapItems(items) |
| 244 |
} |
| 245 |
|
| 246 |
func insertionSortMapItems(items []MapItem) { |
| 247 |
for i := 1; i < len(items); i++ { |
| 248 |
if bytes.Compare(items[i-1].Key, items[i].Key) <= 0 { |
| 249 |
continue |
| 250 |
} |
| 251 |
item := items[i] |
| 252 |
j := i |
| 253 |
for ; j > 0 && bytes.Compare(items[j-1].Key, item.Key) > 0; j-- { |
| 254 |
items[j] = items[j-1] |
| 255 |
} |
| 256 |
items[j] = item |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
// sortMapItemsByNames sorts the items by the names their encoded keys are of, which one of them has an escape |
| 261 |
// for: the escape of a character is not in the order of the character. |
| 262 |
func sortMapItemsByNames(items []MapItem) { |
| 263 |
type named struct { |
| 264 |
name string |
| 265 |
item MapItem |
| 266 |
} |
| 267 |
byName := make([]named, len(items)) |
| 268 |
for i, item := range items { |
| 269 |
byName[i] = named{name: encodedKeyName(item.Key), item: item} |
| 270 |
} |
| 271 |
slices.SortStableFunc(byName, func(a, b named) int { |
| 272 |
return strings.Compare(a.name, b.name) |
| 273 |
}) |
| 274 |
for i := range byName { |
| 275 |
items[i] = byName[i].item |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
// encodedKeyName returns the name of an encoded key: the string from its first quote, whose escapes are the |
| 280 |
// ones AppendString writes, decoded. What follows the string, and what precedes its quote, as the codes of a |
| 281 |
// color, is not of the name. |
| 282 |
func encodedKeyName(key []byte) string { |
| 283 |
start := bytes.IndexByte(key, '"') |
| 284 |
if start < 0 { |
| 285 |
return string(key) |
| 286 |
} |
| 287 |
var name []byte |
| 288 |
for i := start + 1; i < len(key); i++ { |
| 289 |
c := key[i] |
| 290 |
switch { |
| 291 |
case c == '"': |
| 292 |
return string(name) |
| 293 |
case c != '\\' || i+1 == len(key): |
| 294 |
name = append(name, c) |
| 295 |
case key[i+1] == 'u' && i+5 < len(key): |
| 296 |
r, err := strconv.ParseUint(string(key[i+2:i+6]), 16, 16) |
| 297 |
if err != nil { |
| 298 |
name = append(name, c) |
| 299 |
continue |
| 300 |
} |
| 301 |
name = utf8.AppendRune(name, rune(r)) |
| 302 |
i += 5 |
| 303 |
default: |
| 304 |
i++ |
| 305 |
switch e := key[i]; e { |
| 306 |
case 'n': |
| 307 |
name = append(name, '\n') |
| 308 |
case 'r': |
| 309 |
name = append(name, '\r') |
| 310 |
case 't': |
| 311 |
name = append(name, '\t') |
| 312 |
case 'b': |
| 313 |
name = append(name, '\b') |
| 314 |
case 'f': |
| 315 |
name = append(name, '\f') |
| 316 |
default: |
| 317 |
name = append(name, e) |
| 318 |
} |
| 319 |
} |
| 320 |
} |
| 321 |
return string(name) |
| 322 |
} |
| 323 |
|
| 324 |
// maxItemsOfInsertionSort is the number of the items up to which the insertion sort is used. |
| 325 |
// With keys which are random in their content and in their length, it is faster than slices.SortFunc up to |
| 326 |
// 24 items and slower from 32 items ( BenchmarkVariant_MapSort ). |
| 327 |
const maxItemsOfInsertionSort = 16 |
| 328 |
|
| 329 |
// MapContext is what the VM encodes a map from: the entries read from the map ( MapLayout.Collect ), and |
| 330 |
// the state of the entry being encoded. |
| 331 |
type MapContext struct { |
| 332 |
layout *MapLayout |
| 333 |
// Keys are the keys of the entries, for keys of a string kind; RawKeys are the bytes of the keys of another |
| 334 |
// kind, keySize each; Values are the bytes of the values, valueSize each. The copies of the values may hold |
| 335 |
// pointers which the GC doesn't see, as the slots of the VM do: the map holds the values while they are |
| 336 |
// encoded. |
| 337 |
Keys []string |
| 338 |
RawKeys []byte |
| 339 |
Values []byte |
| 340 |
// Order is the entries sorted by their keys ( SortKeys ), for keys of a string kind; Sorted is whether |
| 341 |
// the entries are encoded in that order. |
| 342 |
Order []int32 |
| 343 |
prefixes []uint64 // the first bytes of the keys as numbers, while they are sorted |
| 344 |
Sorted bool |
| 345 |
// DirectEntries is whether the entries of a sorted map are written directly by one call of the VM, up to one |
| 346 |
// whose value is left to its opcodes, as the entries of a map which is not sorted are written as it is read: |
| 347 |
// the values are written by one opcode of a scalar, or are of interface{} ( see MapLayout ). |
| 348 |
DirectEntries bool |
| 349 |
Len int |
| 350 |
Idx int |
| 351 |
// The entries of a sorted map whose keys are not of a string kind are encoded as they come and put in |
| 352 |
// the order of their encoded keys after: Start is where the key or the value being written starts, |
| 353 |
// First is where the entries start in the buffer, Slice has the entries and Buf is where they are copied. |
| 354 |
Start int |
| 355 |
First int |
| 356 |
Slice *Mapslice |
| 357 |
items []MapItem // what Slice.Items is made of, kept between the maps |
| 358 |
Buf []byte |
| 359 |
// what the collector by reflect.MapIter works with: here so that nothing is allocated for a map. |
| 360 |
iter reflect.MapIter |
| 361 |
keyIface any |
| 362 |
valueIface any |
| 363 |
} |
| 364 |
|
| 365 |
// NewMapContext returns the context to encode a map: the runtime context has one for each level of the maps |
| 366 |
// nested in each other, kept from a call to the next, and refers to it while the VM has it in a slot, which |
| 367 |
// the GC doesn't see. |
| 368 |
func NewMapContext(rctx *RuntimeContext) *MapContext { |
| 369 |
if rctx.mapDepth == len(rctx.mapContexts) { |
| 370 |
rctx.mapContexts = append(rctx.mapContexts, &MapContext{Slice: &Mapslice{}}) |
| 371 |
} |
| 372 |
ctx := rctx.mapContexts[rctx.mapDepth] |
| 373 |
rctx.mapDepth++ |
| 374 |
ctx.Buf = ctx.Buf[:0] |
| 375 |
ctx.Idx = 0 |
| 376 |
ctx.Sorted = false |
| 377 |
ctx.DirectEntries = false |
| 378 |
// Items is set by SortByEncodedKeys, and tells the VM the entries are put in that order. |
| 379 |
ctx.Slice.Items = nil |
| 380 |
return ctx |
| 381 |
} |
| 382 |
|
| 383 |
// ScalarValue is whether the values of the map are written by one opcode of a scalar ( MapLayout.ScalarValue ). |
| 384 |
func (c *MapContext) ScalarValue() bool { |
| 385 |
return c.layout.ScalarValue |
| 386 |
} |
| 387 |
|
| 388 |
// SortByEncodedKeys makes the context put the entries in the order of their encoded keys, for a sorted map |
| 389 |
// whose keys are not of a string kind: the VM records the entries in Slice as it encodes them. |
| 390 |
func (c *MapContext) SortByEncodedKeys() { |
| 391 |
if cap(c.items) < c.Len { |
| 392 |
c.items = make([]MapItem, c.Len) |
| 393 |
} |
| 394 |
c.Slice.Items = c.items[:c.Len] |
| 395 |
c.Slice.escaped = false |
| 396 |
} |
| 397 |
|
| 398 |
// appendText appends the text of a marshaler or of the key of a map as a string. A text which is escaped is |
| 399 |
// written longer than itself and its quotes: that tells the map being encoded, if any, that its keys are to be |
| 400 |
// sorted by their names ( see Mapslice.Sort ). |
| 401 |
func appendText(ctx *RuntimeContext, b []byte, text string) []byte { |
| 402 |
n := len(b) |
| 403 |
b = AppendString(ctx, b, text) |
| 404 |
if len(b)-n != len(text)+2 { |
| 405 |
ctx.textEscaped() |
| 406 |
} |
| 407 |
return b |
| 408 |
} |
| 409 |
|
| 410 |
// textEscaped tells the map being encoded, if any, that a text was escaped ( see appendText ). |
| 411 |
func (c *RuntimeContext) textEscaped() { |
| 412 |
if c.mapDepth == 0 { |
| 413 |
return |
| 414 |
} |
| 415 |
if m := c.mapContexts[c.mapDepth-1]; m.layout != nil && m.layout.KeysMayEscape { |
| 416 |
m.Slice.escaped = true |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
func ReleaseMapContext(rctx *RuntimeContext, c *MapContext) { |
| 421 |
// a map is always released before the maps it is in. |
| 422 |
rctx.mapDepth-- |
| 423 |
// the keys refer to the map, which the context must not keep alive. |
| 424 |
clear(c.Keys) |
| 425 |
c.Keys = c.Keys[:0] |
| 426 |
} |
| 427 |
|
| 428 |
func AppendByteSlice(_ *RuntimeContext, b []byte, src []byte) []byte { |
| 429 |
if src == nil { |
| 430 |
return append(b, `null`...) |
| 431 |
} |
| 432 |
encodedLen := base64.StdEncoding.EncodedLen(len(src)) |
| 433 |
b = append(b, '"') |
| 434 |
pos := len(b) |
| 435 |
remainLen := cap(b[pos:]) |
| 436 |
var buf []byte |
| 437 |
if remainLen > encodedLen { |
| 438 |
buf = b[pos : pos+encodedLen] |
| 439 |
} else { |
| 440 |
buf = make([]byte, encodedLen) |
| 441 |
} |
| 442 |
base64.StdEncoding.Encode(buf, src) |
| 443 |
return append(append(b, buf...), '"') |
| 444 |
} |
| 445 |
|
| 446 |
func AppendFloat32(_ *RuntimeContext, b []byte, v float32) []byte { |
| 447 |
f64 := float64(v) |
| 448 |
abs := math.Abs(f64) |
| 449 |
fmt := byte('f') |
| 450 |
// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. |
| 451 |
if abs != 0 { |
| 452 |
f32 := float32(abs) |
| 453 |
if f32 < 1e-6 || f32 >= 1e21 { |
| 454 |
fmt = 'e' |
| 455 |
} |
| 456 |
} |
| 457 |
return appendFloatOfFormat(b, f64, fmt, 32) |
| 458 |
} |
| 459 |
|
| 460 |
func AppendFloat64(_ *RuntimeContext, b []byte, v float64) []byte { |
| 461 |
abs := math.Abs(v) |
| 462 |
fmt := byte('f') |
| 463 |
// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. |
| 464 |
if abs != 0 { |
| 465 |
if abs < 1e-6 || abs >= 1e21 { |
| 466 |
fmt = 'e' |
| 467 |
} |
| 468 |
} |
| 469 |
return appendFloatOfFormat(b, v, fmt, 64) |
| 470 |
} |
| 471 |
|
| 472 |
// appendFloatOfFormat appends the float in the format, as encoding/json does: the exponent of the 'e' format |
| 473 |
// has no leading zero, so 1e-07 is written as 1e-7. |
| 474 |
func appendFloatOfFormat(b []byte, v float64, fmt byte, bits int) []byte { |
| 475 |
b = strconv.AppendFloat(b, v, fmt, -1, bits) |
| 476 |
if fmt == 'e' { |
| 477 |
n := len(b) |
| 478 |
if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' { |
| 479 |
b[n-2] = b[n-1] |
| 480 |
b = b[:n-1] |
| 481 |
} |
| 482 |
} |
| 483 |
return b |
| 484 |
} |
| 485 |
|
| 486 |
func AppendBool(_ *RuntimeContext, b []byte, v bool) []byte { |
| 487 |
if v { |
| 488 |
return append(b, "true"...) |
| 489 |
} |
| 490 |
return append(b, "false"...) |
| 491 |
} |
| 492 |
|
| 493 |
var ( |
| 494 |
floatTable = [256]bool{ |
| 495 |
'0': true, |
| 496 |
'1': true, |
| 497 |
'2': true, |
| 498 |
'3': true, |
| 499 |
'4': true, |
| 500 |
'5': true, |
| 501 |
'6': true, |
| 502 |
'7': true, |
| 503 |
'8': true, |
| 504 |
'9': true, |
| 505 |
'.': true, |
| 506 |
'e': true, |
| 507 |
'E': true, |
| 508 |
'+': true, |
| 509 |
'-': true, |
| 510 |
} |
| 511 |
) |
| 512 |
|
| 513 |
func AppendNumber(_ *RuntimeContext, b []byte, n json.Number) ([]byte, error) { |
| 514 |
if len(n) == 0 { |
| 515 |
return append(b, '0'), nil |
| 516 |
} |
| 517 |
for i := 0; i < len(n); i++ { |
| 518 |
if !floatTable[n[i]] { |
| 519 |
return nil, fmt.Errorf("json: invalid number literal %q", n) |
| 520 |
} |
| 521 |
} |
| 522 |
b = append(b, n...) |
| 523 |
return b, nil |
| 524 |
} |
| 525 |
|
| 526 |
// addrForMarshaler returns the pointer to the value held by v, to call a marshaler with a pointer receiver. |
| 527 |
// |
| 528 |
// The VM makes v from the address of the value, so the data word of v is that address unless the type is |
| 529 |
// stored directly in an interface value. Only a pointer-sized type can be stored directly, so for the other |
| 530 |
// sizes the pointer is made from the data word: the marshaler is called with the original value, as |
| 531 |
// encoding/json does, and nothing is allocated. A pointer-sized value is copied, because its data word |
| 532 |
// may be the value itself. |
| 533 |
func addrForMarshaler(v any, rv reflect.Value) reflect.Value { |
| 534 |
if rv.CanAddr() { |
| 535 |
return rv.Addr() |
| 536 |
} |
| 537 |
typ := rv.Type() |
| 538 |
if typ.Size() != unsafe.Sizeof(unsafe.Pointer(nil)) { |
| 539 |
return reflect.NewAt(typ, (*emptyInterface)(unsafe.Pointer(&v)).ptr) |
| 540 |
} |
| 541 |
newV := reflect.New(typ) |
| 542 |
newV.Elem().Set(rv) |
| 543 |
return newV |
| 544 |
} |
| 545 |
|
| 546 |
// AppendMarshalJSON appends what MarshalJSON of the value returns, compacted. p is the data word of the |
| 547 |
// interface value of the type of the opcode: the address of the value, or the pointer for a pointer type. |
| 548 |
func AppendMarshalJSON(ctx *RuntimeContext, code *Opcode, b []byte, p unsafe.Pointer) ([]byte, error) { |
| 549 |
m := code.Marshaler |
| 550 |
if m == nil { |
| 551 |
return appendMarshalJSONByInterface(ctx, code, b, interfaceOf(code, p)) |
| 552 |
} |
| 553 |
if m.nilIsNull && p == nil { |
| 554 |
return AppendNull(ctx, b), nil |
| 555 |
} |
| 556 |
if m.appendOutput != nil { |
| 557 |
// the output of a type of the standard library is valid and compact: it is written as it is. |
| 558 |
if out, ok := m.appendOutput(b, p); ok { |
| 559 |
return out, nil |
| 560 |
} |
| 561 |
} |
| 562 |
var bb []byte |
| 563 |
var err error |
| 564 |
if (code.Flags & MarshalerContextFlags) != 0 { |
| 565 |
stdctx := ctx.marshalerContext() |
| 566 |
if ctx.Option.Flag&FieldQueryOption != 0 { |
| 567 |
stdctx = SetFieldQueryToContext(stdctx, code.FieldQuery) |
| 568 |
} |
| 569 |
bb, err = m.callContext(p, stdctx) |
| 570 |
} else { |
| 571 |
bb, err = m.call(p) |
| 572 |
} |
| 573 |
if err != nil { |
| 574 |
return nil, &errors.MarshalerError{Type: m.recv, Err: err} |
| 575 |
} |
| 576 |
escape := (ctx.Option.Flag & HTMLEscapeOption) != 0 |
| 577 |
if out, ok := appendCompactOutput(b, bb, escape, m.trusted); ok { |
| 578 |
// the output is compact and valid: it is copied as it is. |
| 579 |
return out, nil |
| 580 |
} |
| 581 |
marshalBuf := ctx.MarshalBuf[:0] |
| 582 |
marshalBuf = append(append(marshalBuf, bb...), nul) |
| 583 |
compactedBuf, err := compact(b, marshalBuf, escape) |
| 584 |
if err != nil { |
| 585 |
return nil, err |
| 586 |
} |
| 587 |
ctx.MarshalBuf = marshalBuf |
| 588 |
return compactedBuf, nil |
| 589 |
} |
| 590 |
|
| 591 |
// interfaceOf returns the interface value of the type of the opcode whose data word is p. |
| 592 |
func interfaceOf(code *Opcode, p unsafe.Pointer) any { |
| 593 |
return *(*any)(unsafe.Pointer(&emptyInterface{typ: code.Type, ptr: p})) |
| 594 |
} |
| 595 |
|
| 596 |
func appendMarshalJSONByInterface(ctx *RuntimeContext, code *Opcode, b []byte, v any) ([]byte, error) { |
| 597 |
rv := reflect.ValueOf(v) // convert by dynamic interface type |
| 598 |
if (code.Flags & AddrForMarshalerFlags) != 0 { |
| 599 |
rv = addrForMarshaler(v, rv) |
| 600 |
} |
| 601 |
|
| 602 |
if rv.Kind() == reflect.Ptr && rv.IsNil() { |
| 603 |
return AppendNull(ctx, b), nil |
| 604 |
} |
| 605 |
|
| 606 |
v = rv.Interface() |
| 607 |
var bb []byte |
| 608 |
if (code.Flags & MarshalerContextFlags) != 0 { |
| 609 |
marshaler, ok := v.(marshalerContext) |
| 610 |
if !ok { |
| 611 |
return AppendNull(ctx, b), nil |
| 612 |
} |
| 613 |
stdctx := ctx.marshalerContext() |
| 614 |
if ctx.Option.Flag&FieldQueryOption != 0 { |
| 615 |
stdctx = SetFieldQueryToContext(stdctx, code.FieldQuery) |
| 616 |
} |
| 617 |
b, err := marshaler.MarshalJSON(stdctx) |
| 618 |
if err != nil { |
| 619 |
return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} |
| 620 |
} |
| 621 |
bb = b |
| 622 |
} else { |
| 623 |
marshaler, ok := v.(json.Marshaler) |
| 624 |
if !ok { |
| 625 |
return AppendNull(ctx, b), nil |
| 626 |
} |
| 627 |
b, err := marshaler.MarshalJSON() |
| 628 |
if err != nil { |
| 629 |
return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} |
| 630 |
} |
| 631 |
bb = b |
| 632 |
} |
| 633 |
marshalBuf := ctx.MarshalBuf[:0] |
| 634 |
marshalBuf = append(append(marshalBuf, bb...), nul) |
| 635 |
compactedBuf, err := compact(b, marshalBuf, (ctx.Option.Flag&HTMLEscapeOption) != 0) |
| 636 |
if err != nil { |
| 637 |
return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} |
| 638 |
} |
| 639 |
ctx.MarshalBuf = marshalBuf |
| 640 |
return compactedBuf, nil |
| 641 |
} |
| 642 |
|
| 643 |
func AppendMarshalJSONIndent(ctx *RuntimeContext, code *Opcode, b []byte, p unsafe.Pointer) ([]byte, error) { |
| 644 |
m := code.Marshaler |
| 645 |
if m == nil { |
| 646 |
return appendMarshalJSONIndentByInterface(ctx, code, b, interfaceOf(code, p)) |
| 647 |
} |
| 648 |
if m.nilIsNull && p == nil { |
| 649 |
return AppendNull(ctx, b), nil |
| 650 |
} |
| 651 |
if m.appendOutput != nil { |
| 652 |
// the output of a type of the standard library is one token, which has nothing to indent. |
| 653 |
if out, ok := m.appendOutput(b, p); ok { |
| 654 |
return out, nil |
| 655 |
} |
| 656 |
} |
| 657 |
var bb []byte |
| 658 |
var err error |
| 659 |
if (code.Flags & MarshalerContextFlags) != 0 { |
| 660 |
bb, err = m.callContext(p, ctx.marshalerContext()) |
| 661 |
} else { |
| 662 |
bb, err = m.call(p) |
| 663 |
} |
| 664 |
if err != nil { |
| 665 |
return nil, &errors.MarshalerError{Type: m.recv, Err: err} |
| 666 |
} |
| 667 |
return appendIndentedMarshalJSON(ctx, code, b, bb) |
| 668 |
} |
| 669 |
|
| 670 |
func appendMarshalJSONIndentByInterface(ctx *RuntimeContext, code *Opcode, b []byte, v any) ([]byte, error) { |
| 671 |
rv := reflect.ValueOf(v) // convert by dynamic interface type |
| 672 |
if (code.Flags & AddrForMarshalerFlags) != 0 { |
| 673 |
rv = addrForMarshaler(v, rv) |
| 674 |
} |
| 675 |
// a nil pointer is null, as encoding/json does. The VM gives the address of the pointer, |
| 676 |
// so it is not known to be nil until here. |
| 677 |
if rv.Kind() == reflect.Ptr && rv.IsNil() { |
| 678 |
return AppendNull(ctx, b), nil |
| 679 |
} |
| 680 |
v = rv.Interface() |
| 681 |
var bb []byte |
| 682 |
if (code.Flags & MarshalerContextFlags) != 0 { |
| 683 |
marshaler, ok := v.(marshalerContext) |
| 684 |
if !ok { |
| 685 |
return AppendNull(ctx, b), nil |
| 686 |
} |
| 687 |
b, err := marshaler.MarshalJSON(ctx.marshalerContext()) |
| 688 |
if err != nil { |
| 689 |
return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} |
| 690 |
} |
| 691 |
bb = b |
| 692 |
} else { |
| 693 |
marshaler, ok := v.(json.Marshaler) |
| 694 |
if !ok { |
| 695 |
return AppendNull(ctx, b), nil |
| 696 |
} |
| 697 |
b, err := marshaler.MarshalJSON() |
| 698 |
if err != nil { |
| 699 |
return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} |
| 700 |
} |
| 701 |
bb = b |
| 702 |
} |
| 703 |
return appendIndentedMarshalJSON(ctx, code, b, bb) |
| 704 |
} |
| 705 |
|
| 706 |
func appendIndentedMarshalJSON(ctx *RuntimeContext, code *Opcode, b []byte, bb []byte) ([]byte, error) { |
| 707 |
marshalBuf := ctx.MarshalBuf[:0] |
| 708 |
marshalBuf = append(append(marshalBuf, bb...), nul) |
| 709 |
indentedBuf, err := doIndent( |
| 710 |
b, |
| 711 |
marshalBuf, |
| 712 |
string(ctx.Prefix)+strings.Repeat(string(ctx.IndentStr), int(ctx.BaseIndent+code.Indent)), |
| 713 |
string(ctx.IndentStr), |
| 714 |
(ctx.Option.Flag&HTMLEscapeOption) != 0, |
| 715 |
) |
| 716 |
if err != nil { |
| 717 |
return nil, &errors.MarshalerError{Type: runtime.TypeOfPtr(code.Type), Err: err} |
| 718 |
} |
| 719 |
ctx.MarshalBuf = marshalBuf |
| 720 |
return indentedBuf, nil |
| 721 |
} |
| 722 |
|
| 723 |
// AppendMarshalText appends what MarshalText of the value returns, as a string. p is the data word of the |
| 724 |
// interface value of the type of the opcode: the address of the value, or the pointer for a pointer type. |
| 725 |
func AppendMarshalText(ctx *RuntimeContext, code *Opcode, b []byte, p unsafe.Pointer) ([]byte, error) { |
| 726 |
m := code.Marshaler |
| 727 |
if m == nil { |
| 728 |
if code.Flags&InterfaceMapKeyFlags != 0 { |
| 729 |
return appendInterfaceMapKey(ctx, code, b, p) |
| 730 |
} |
| 731 |
return appendMarshalTextByInterface(ctx, code, b, interfaceOf(code, p)) |
| 732 |
} |
| 733 |
if m.nilIsNull && p == nil { |
| 734 |
return appendNilText(ctx, code, b), nil |
| 735 |
} |
| 736 |
var bytes []byte |
| 737 |
appended := false |
| 738 |
if m.appendOutput != nil { |
| 739 |
// the text of a type of the standard library is appended to a buffer of the context, not allocated. |
| 740 |
bytes, appended = m.appendOutput(ctx.MarshalBuf[:0], p) |
| 741 |
if appended { |
| 742 |
ctx.MarshalBuf = bytes |
| 743 |
} |
| 744 |
} |
| 745 |
if !appended { |
| 746 |
var err error |
| 747 |
if bytes, err = m.call(p); err != nil { |
| 748 |
return nil, &errors.MarshalerError{Type: m.recv, Err: err} |
| 749 |
} |
| 750 |
} |
| 751 |
// appendText, written here: it is not inlined, and this is the text of the key of most maps of texts. |
| 752 |
n := len(b) |
| 753 |
b = AppendString(ctx, b, *(*string)(unsafe.Pointer(&bytes))) |
| 754 |
if len(b)-n != len(bytes)+2 { |
| 755 |
ctx.textEscaped() |
| 756 |
} |
| 757 |
return b, nil |
| 758 |
} |
| 759 |
|
| 760 |
func appendMarshalTextByInterface(ctx *RuntimeContext, code *Opcode, b []byte, v any) ([]byte, error) { |
| 761 |
rv := reflect.ValueOf(v) // convert by dynamic interface type |
| 762 |
if (code.Flags & AddrForMarshalerFlags) != 0 { |
| 763 |
rv = addrForMarshaler(v, rv) |
| 764 |
} |
| 765 |
// a nil pointer is null, or "" as the name of a key, as encoding/json does. The VM gives the address of |
| 766 |
// the pointer, so it is not known to be nil until here. |
| 767 |
if rv.Kind() == reflect.Ptr && rv.IsNil() { |
| 768 |
return appendNilText(ctx, code, b), nil |
| 769 |
} |
| 770 |
v = rv.Interface() |
| 771 |
marshaler, ok := v.(encoding.TextMarshaler) |
| 772 |
if !ok { |
| 773 |
return AppendNull(ctx, b), nil |
| 774 |
} |
| 775 |
bytes, err := marshaler.MarshalText() |
| 776 |
if err != nil { |
| 777 |
return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} |
| 778 |
} |
| 779 |
return appendText(ctx, b, *(*string)(unsafe.Pointer(&bytes))), nil |
| 780 |
} |
| 781 |
|
| 782 |
// appendNilText appends the text of a nil pointer: null, or "" as the name of a key of a map, as |
| 783 |
// encoding/json writes them. |
| 784 |
func appendNilText(ctx *RuntimeContext, code *Opcode, b []byte) []byte { |
| 785 |
if code.Flags&MapKeyFlags != 0 { |
| 786 |
return append(b, `""`...) |
| 787 |
} |
| 788 |
return AppendNull(ctx, b) |
| 789 |
} |
| 790 |
|
| 791 |
// AppendMarshalTextIndent is AppendMarshalText: the text has no indent. |
| 792 |
func AppendMarshalTextIndent(ctx *RuntimeContext, code *Opcode, b []byte, p unsafe.Pointer) ([]byte, error) { |
| 793 |
return AppendMarshalText(ctx, code, b, p) |
| 794 |
} |
| 795 |
|
| 796 |
func AppendNull(_ *RuntimeContext, b []byte) []byte { |
| 797 |
return append(b, "null"...) |
| 798 |
} |
| 799 |
|
| 800 |
func AppendComma(_ *RuntimeContext, b []byte) []byte { |
| 801 |
return append(b, ',') |
| 802 |
} |
| 803 |
|
| 804 |
func AppendCommaIndent(_ *RuntimeContext, b []byte) []byte { |
| 805 |
return append(b, ',', '\n') |
| 806 |
} |
| 807 |
|
| 808 |
func AppendStructEnd(_ *RuntimeContext, b []byte) []byte { |
| 809 |
return append(b, '}', ',') |
| 810 |
} |
| 811 |
|
| 812 |
func AppendStructEndIndent(ctx *RuntimeContext, code *Opcode, b []byte) []byte { |
| 813 |
b = append(b, '\n') |
| 814 |
b = append(b, ctx.Prefix...) |
| 815 |
indentNum := ctx.BaseIndent + code.Indent - 1 |
| 816 |
for i := uint32(0); i < indentNum; i++ { |
| 817 |
b = append(b, ctx.IndentStr...) |
| 818 |
} |
| 819 |
return append(b, '}', ',', '\n') |
| 820 |
} |
| 821 |
|
| 822 |
func AppendIndent(ctx *RuntimeContext, b []byte, indent uint32) []byte { |
| 823 |
b = append(b, ctx.Prefix...) |
| 824 |
indentNum := ctx.BaseIndent + indent |
| 825 |
for i := uint32(0); i < indentNum; i++ { |
| 826 |
b = append(b, ctx.IndentStr...) |
| 827 |
} |
| 828 |
return b |
| 829 |
} |
| 830 |
|
| 831 |
func IsNilForMarshaler(v any) bool { |
| 832 |
rv := reflect.ValueOf(v) |
| 833 |
switch rv.Kind() { |
| 834 |
case reflect.Bool: |
| 835 |
return !rv.Bool() |
| 836 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 837 |
return rv.Int() == 0 |
| 838 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 839 |
return rv.Uint() == 0 |
| 840 |
case reflect.Float32, reflect.Float64: |
| 841 |
return math.Float64bits(rv.Float()) == 0 |
| 842 |
case reflect.Interface, reflect.Ptr, reflect.Func: |
| 843 |
return rv.IsNil() |
| 844 |
case reflect.Array, reflect.Map, reflect.Slice, reflect.String: |
| 845 |
// the same as encoding/json: they are empty if the length is zero, even if they are not nil. |
| 846 |
return rv.Len() == 0 |
| 847 |
} |
| 848 |
return false |
| 849 |
} |