-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
613 lines (545 loc) · 12.8 KB
/
marshal.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
// Copyright © 2021 The Things Industries B.V.
// SPDX-License-Identifier: Apache-2.0
package json
import (
"bytes"
"encoding/base64"
"fmt"
"math"
"strconv"
"strings"
"time"
anypb_resolver "github.com/aperturerobotics/protobuf-go-lite/types/known/anypb/resolver"
)
// Marshaler is the interface implemented by types that are supported by this plugin.
type Marshaler interface {
MarshalProtoJSON(*MarshalState)
}
type marshalError struct {
Err error
Path *path
}
func (e *marshalError) Error() string {
if e.Path != nil {
return fmt.Sprintf("marshal error at path %q: %v", e.Path, e.Err)
}
return fmt.Sprintf("marshal error: %v", e.Err)
}
func (e *marshalError) Unwrap() error {
return e.Err
}
// MarshalerConfig is the configuration for the Marshaler.
type MarshalerConfig struct {
EnumsAsInts bool
// AnyTypeResolver is the resolver function for the any well-known type.
AnyTypeResolver anypb_resolver.AnyTypeResolver
}
// DefaultMarshalerConfig is the default configuration for the Marshaler.
var DefaultMarshalerConfig = MarshalerConfig{
EnumsAsInts: true,
}
// Marshal marshals a message.
func (c MarshalerConfig) Marshal(m Marshaler) ([]byte, error) {
var buf bytes.Buffer
s := NewMarshalState(c, NewJsonStream(&buf))
m.MarshalProtoJSON(s)
if err := s.Err(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// MarshalState is the internal state of the Marshaler.
type MarshalState struct {
inner *JsonStream
config *MarshalerConfig
err *marshalError
path *path
paths *pathSlice
}
// NewMarshalState creates a new MarshalState.
func NewMarshalState(config MarshalerConfig, stream *JsonStream) *MarshalState {
return &MarshalState{
inner: stream,
config: &config,
err: &marshalError{},
path: nil,
paths: &pathSlice{},
}
}
// Config returns a copy of the marshaler configuration.
func (s *MarshalState) Config() MarshalerConfig {
return *s.config
}
// AnyTypeResolver returns the any type resolver.
func (s *MarshalState) AnyTypeResolver() anypb_resolver.AnyTypeResolver {
if s.config.AnyTypeResolver != nil {
return s.config.AnyTypeResolver
}
return anypb_resolver.NewErrAnyTypeResolver(anypb_resolver.ErrNoAnyTypeResolver)
}
// Sub returns a sub-marshaler with a new buffer, but with the same configuration, error and path info.
func (s *MarshalState) Sub(js *JsonStream) *MarshalState {
return &MarshalState{
inner: js,
config: s.config,
err: s.err,
path: s.path,
paths: &pathSlice{},
}
}
// Err returns an error from the marshaler, if any.
func (s *MarshalState) Err() error {
if s.err.Err != nil {
return s.err
}
if err := s.inner.Error(); err != nil {
return err
}
return nil
}
// SetError sets an error in the marshaler state.
// Subsequent operations become no-ops.
func (s *MarshalState) SetError(err error) {
if s.Err() != nil {
return
}
s.err.Err = err
s.err.Path = s.path
}
// SetErrorf calls SetError with a formatted error.
func (s *MarshalState) SetErrorf(format string, a ...interface{}) {
s.SetError(fmt.Errorf(format, a...))
}
// WithFieldMask returns a MarshalState for the given field mask.
func (s *MarshalState) WithFieldMask(paths ...string) *MarshalState {
return &MarshalState{
inner: s.inner,
config: s.config,
err: s.err,
path: s.path,
paths: newPathSlice(paths...),
}
}
// WithField returns a MarshalState for the given subfield.
func (s *MarshalState) WithField(field string) *MarshalState {
return &MarshalState{
inner: s.inner,
config: s.config,
err: s.err,
path: s.path.push(field),
paths: s.paths,
}
}
// HasField returns whether the field mask contains the given field.
func (s *MarshalState) HasField(field string) bool {
return s.paths.contains(*s.path.push(field))
}
// Write writes raw data.
func (s *MarshalState) Write(v []byte) (nn int, err error) {
if s.Err() != nil {
return
}
return s.inner.Write(v)
}
// WriteFloat32 writes a float32 value.
func (s *MarshalState) WriteFloat32(v float32) {
if s.Err() != nil {
return
}
switch {
case math.IsInf(float64(v), 1):
s.inner.WriteString("Infinity")
return
case math.IsInf(float64(v), -1):
s.inner.WriteString("-Infinity")
return
case math.IsNaN(float64(v)):
s.inner.WriteString("NaN")
return
}
s.inner.WriteFloat32(v)
}
// WriteFloat64 writes a float64 value.
func (s *MarshalState) WriteFloat64(v float64) {
if s.Err() != nil {
return
}
switch {
case math.IsInf(v, 1):
s.inner.WriteString("Infinity")
return
case math.IsInf(v, -1):
s.inner.WriteString("-Infinity")
return
case math.IsNaN(v):
s.inner.WriteString("NaN")
return
}
s.inner.WriteFloat64(v)
}
// WriteFloat32Array writes an array of float32 values.
func (s *MarshalState) WriteFloat32Array(vs []float32) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteFloat32(v)
}
s.WriteArrayEnd()
}
// WriteFloat64Array writes an array of float64 values.
func (s *MarshalState) WriteFloat64Array(vs []float64) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteFloat64(v)
}
s.WriteArrayEnd()
}
// WriteInt32 writes an int32 value.
func (s *MarshalState) WriteInt32(v int32) {
if s.Err() != nil {
return
}
s.inner.WriteInt32(v)
}
// WriteInt64 writes an int64 value as a string.
func (s *MarshalState) WriteInt64(v int64) {
if s.Err() != nil {
return
}
s.inner.WriteString(strconv.FormatInt(v, 10))
}
// WriteInt32Array writes an array of int32 values.
func (s *MarshalState) WriteInt32Array(vs []int32) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteInt32(v)
}
s.WriteArrayEnd()
}
// WriteInt64Array writes an array of int64 values.
func (s *MarshalState) WriteInt64Array(vs []int64) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteInt64(v)
}
s.WriteArrayEnd()
}
// WriteUint32 writes a uint32 value.
func (s *MarshalState) WriteUint32(v uint32) {
if s.Err() != nil {
return
}
s.inner.WriteUint32(v)
}
// WriteUint64 writes a uint64 value as a string.
func (s *MarshalState) WriteUint64(v uint64) {
if s.Err() != nil {
return
}
s.inner.WriteString(strconv.FormatUint(v, 10))
}
// WriteUint32Array writes an array of uint32 values.
func (s *MarshalState) WriteUint32Array(vs []uint32) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteUint32(v)
}
s.WriteArrayEnd()
}
// WriteUint64Array writes an array of uint64 values.
func (s *MarshalState) WriteUint64Array(vs []uint64) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteUint64(v)
}
s.WriteArrayEnd()
}
// WriteBool writes a bool value.
func (s *MarshalState) WriteBool(v bool) {
if s.Err() != nil {
return
}
s.inner.WriteBool(v)
}
// WriteBoolArray writes an array of bool values.
func (s *MarshalState) WriteBoolArray(vs []bool) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteBool(v)
}
s.WriteArrayEnd()
}
// WriteString writes a string.
func (s *MarshalState) WriteString(v string) {
if s.Err() != nil {
return
}
s.inner.WriteString(v)
}
// WriteStringArray writes an array of string values.
func (s *MarshalState) WriteStringArray(vs []string) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteString(v)
}
s.WriteArrayEnd()
}
// WriteBytes writes a binary value.
func (s *MarshalState) WriteBytes(v []byte) {
if s.Err() != nil {
return
}
if v == nil {
s.WriteNil()
return
}
s.WriteString(base64.StdEncoding.EncodeToString(v))
}
// WriteBytesArray writes an array of binary values.
func (s *MarshalState) WriteBytesArray(vs [][]byte) {
if s.Err() != nil {
return
}
s.WriteArrayStart()
for i, v := range vs {
if i > 0 {
s.WriteMore()
}
s.WriteBytes(v)
}
s.WriteArrayEnd()
}
// WriteNil writes a null.
func (s *MarshalState) WriteNil() {
if s.Err() != nil {
return
}
s.inner.WriteNil()
}
// WriteObjectStart writes the starting { of an object.
func (s *MarshalState) WriteObjectStart() {
if s.Err() != nil {
return
}
s.inner.WriteObjectStart()
}
// WriteObjectField writes a field name and colon.
func (s *MarshalState) WriteObjectField(field string) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(field)
}
// WriteObjectBoolField writes a field name and colon.
func (s *MarshalState) WriteObjectBoolField(field bool) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(strconv.FormatBool(field))
}
// WriteObjectInt32Field writes a field name and colon.
func (s *MarshalState) WriteObjectInt32Field(field int32) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(strconv.FormatInt(int64(field), 10))
}
// WriteObjectUint32Field writes a field name and colon.
func (s *MarshalState) WriteObjectUint32Field(field uint32) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(strconv.FormatUint(uint64(field), 10))
}
// WriteObjectInt64Field writes a field name and colon.
func (s *MarshalState) WriteObjectInt64Field(field int64) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(strconv.FormatInt(field, 10))
}
// WriteObjectUint64Field writes a field name and colon.
func (s *MarshalState) WriteObjectUint64Field(field uint64) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(strconv.FormatUint(field, 10))
}
// WriteObjectStringField writes a field name and colon.
func (s *MarshalState) WriteObjectStringField(field string) {
if s.Err() != nil {
return
}
s.inner.WriteObjectField(field)
}
// WriteObjectEnd writes the ending } of an object.
func (s *MarshalState) WriteObjectEnd() {
if s.Err() != nil {
return
}
s.inner.WriteObjectEnd()
}
// WriteArrayStart writes the starting [ of an array.
func (s *MarshalState) WriteArrayStart() {
if s.Err() != nil {
return
}
s.inner.WriteArrayStart()
}
// WriteArrayEnd writes the ending ] of an array.
func (s *MarshalState) WriteArrayEnd() {
if s.Err() != nil {
return
}
s.inner.WriteArrayEnd()
}
// WriteMore writes a comma.
func (s *MarshalState) WriteMore() {
if s.Err() != nil {
return
}
s.inner.WriteMore()
}
// WriteMoreIf writes a comma if b is false, and sets b to true.
func (s *MarshalState) WriteMoreIf(b *bool) {
if s.Err() != nil {
return
}
if *b {
s.WriteMore()
}
*b = true
}
// WriteEnum writes an enum value.
// If config.EnumsAsInts is true or a string value is not found for the value, this writes a number.
func (s *MarshalState) WriteEnum(x int32, valueMaps ...map[int32]string) {
if s.Err() != nil {
return
}
if s.config.EnumsAsInts {
s.WriteEnumNumber(x)
} else {
s.WriteEnumString(x, valueMaps...)
}
}
// GetEnumString gets the string representation of the enum using the value maps.
// If none of the value maps contains a mapping for the enum value,
// it returns the numeric value as a string.
func GetEnumString(x int32, valueMaps ...map[int32]string) string {
for _, valueMap := range valueMaps {
if v, ok := valueMap[x]; ok {
return v
}
}
return strconv.FormatInt(int64(x), 10)
}
// WriteEnumString writes an enum value as a string.
func (s *MarshalState) WriteEnumString(x int32, valueMaps ...map[int32]string) {
if s.Err() != nil {
return
}
s.WriteString(GetEnumString(x, valueMaps...))
}
// WriteEnumNumber writes an enum value as a number.
func (s *MarshalState) WriteEnumNumber(x int32) {
if s.Err() != nil {
return
}
s.WriteInt32(x)
}
// WriteTime writes a time value.
func (s *MarshalState) WriteTime(x time.Time) {
if s.Err() != nil {
return
}
v := x.UTC().Format("2006-01-02T15:04:05.000000000")
// According to the protobuf spec, nanoseconds in timestamps should be written as 3, 6 or 9 digits.
v = strings.TrimSuffix(v, "000")
v = strings.TrimSuffix(v, "000")
v = strings.TrimSuffix(v, ".000")
s.inner.WriteString(v + "Z")
}
// WriteDuration writes a duration value.
func (s *MarshalState) WriteDuration(x time.Duration) {
if s.Err() != nil {
return
}
v := fmt.Sprintf("%.09f", x.Seconds())
// According to the protobuf spec, nanoseconds in durations should be written as 3, 6 or 9 digits.
v = strings.TrimSuffix(v, "000")
v = strings.TrimSuffix(v, "000")
v = strings.TrimSuffix(v, ".000")
s.inner.WriteString(v + "s")
}
// WriteFieldMask writes a field mask value.
func (s *MarshalState) WriteFieldMask(x FieldMask) {
if s.Err() != nil {
return
}
paths := x.GetPaths()
s.inner.WriteString(strings.Join(paths, ","))
}
func (s *MarshalState) WriteLegacyFieldMask(x FieldMask) {
if s.Err() != nil {
return
}
paths := x.GetPaths()
s.inner.WriteObjectStart()
s.inner.WriteObjectField("paths")
s.inner.WriteArrayStart()
for i, path := range paths {
if i != 0 {
s.inner.WriteMore()
}
s.inner.WriteString(path)
}
s.inner.WriteArrayEnd()
s.inner.WriteObjectEnd()
}