aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/pquerna/ffjson/inception/encoder.go
blob: 3e37a2814adf9b63ea95f26f3358d22ad3816c42 (plain)
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
/**
 *  Copyright 2014 Paul Querna
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package ffjsoninception

import (
	"fmt"
	"reflect"

	"github.com/pquerna/ffjson/shared"
)

func typeInInception(ic *Inception, typ reflect.Type, f shared.Feature) bool {
	for _, v := range ic.objs {
		if v.Typ == typ {
			return v.Options.HasFeature(f)
		}
		if typ.Kind() == reflect.Ptr {
			if v.Typ == typ.Elem() {
				return v.Options.HasFeature(f)
			}
		}
	}

	return false
}

func getOmitEmpty(ic *Inception, sf *StructField) string {
	ptname := "j." + sf.Name
	if sf.Pointer {
		ptname = "*" + ptname
		return "if true {\n"
	}
	switch sf.Typ.Kind() {

	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		return "if len(" + ptname + ") != 0 {" + "\n"

	case reflect.Int,
		reflect.Int8,
		reflect.Int16,
		reflect.Int32,
		reflect.Int64,
		reflect.Uint,
		reflect.Uint8,
		reflect.Uint16,
		reflect.Uint32,
		reflect.Uint64,
		reflect.Uintptr,
		reflect.Float32,
		reflect.Float64:
		return "if " + ptname + " != 0 {" + "\n"

	case reflect.Bool:
		return "if " + ptname + " != false {" + "\n"

	case reflect.Interface, reflect.Ptr:
		return "if " + ptname + " != nil {" + "\n"

	default:
		// TODO(pquerna): fix types
		return "if true {" + "\n"
	}
}

func getMapValue(ic *Inception, name string, typ reflect.Type, ptr bool, forceString bool) string {
	var out = ""

	if typ.Key().Kind() != reflect.String {
		out += fmt.Sprintf("/* Falling back. type=%v kind=%v */\n", typ, typ.Kind())
		out += ic.q.Flush()
		out += "err = buf.Encode(" + name + ")" + "\n"
		out += "if err != nil {" + "\n"
		out += "  return err" + "\n"
		out += "}" + "\n"
		return out
	}

	var elemKind reflect.Kind
	elemKind = typ.Elem().Kind()

	switch elemKind {
	case reflect.String,
		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
		reflect.Float32,
		reflect.Float64,
		reflect.Bool:

		ic.OutputImports[`fflib "github.com/pquerna/ffjson/fflib/v1"`] = true

		out += "if " + name + " == nil  {" + "\n"
		ic.q.Write("null")
		out += ic.q.GetQueued()
		ic.q.DeleteLast()
		out += "} else {" + "\n"
		out += ic.q.WriteFlush("{ ")
		out += "  for key, value := range " + name + " {" + "\n"
		out += "    fflib.WriteJsonString(buf, key)" + "\n"
		out += "    buf.WriteString(`:`)" + "\n"
		out += getGetInnerValue(ic, "value", typ.Elem(), false, forceString)
		out += "    buf.WriteByte(',')" + "\n"
		out += "  }" + "\n"
		out += "buf.Rewind(1)" + "\n"
		out += ic.q.WriteFlush("}")
		out += "}" + "\n"

	default:
		out += ic.q.Flush()
		out += fmt.Sprintf("/* Falling back. type=%v kind=%v */\n", typ, typ.Kind())
		out += "err = buf.Encode(" + name + ")" + "\n"
		out += "if err != nil {" + "\n"
		out += "  return err" + "\n"
		out += "}" + "\n"
	}
	return out
}

func getGetInnerValue(ic *Inception, name string, typ reflect.Type, ptr bool, forceString bool) string {
	var out = ""

	// Flush if not bool or maps
	if typ.Kind() != reflect.Bool && typ.Kind() != reflect.Map && typ.Kind() != reflect.Struct {
		out += ic.q.Flush()
	}

	if typ.Implements(marshalerFasterType) ||
		reflect.PtrTo(typ).Implements(marshalerFasterType) ||
		typeInInception(ic, typ, shared.MustEncoder) ||
		typ.Implements(marshalerType) ||
		reflect.PtrTo(typ).Implements(marshalerType) {

		out += ic.q.Flush()
		out += tplStr(encodeTpl["handleMarshaler"], handleMarshaler{
			IC:             ic,
			Name:           name,
			Typ:            typ,
			Ptr:            reflect.Ptr,
			MarshalJSONBuf: typ.Implements(marshalerFasterType) || reflect.PtrTo(typ).Implements(marshalerFasterType) || typeInInception(ic, typ, shared.MustEncoder),
			Marshaler:      typ.Implements(marshalerType) || reflect.PtrTo(typ).Implements(marshalerType),
		})
		return out
	}

	ptname := name
	if ptr {
		ptname = "*" + name
	}

	switch typ.Kind() {
	case reflect.Int,
		reflect.Int8,
		reflect.Int16,
		reflect.Int32,
		reflect.Int64:
		ic.OutputImports[`fflib "github.com/pquerna/ffjson/fflib/v1"`] = true
		out += "fflib.FormatBits2(buf, uint64(" + ptname + "), 10, " + ptname + " < 0)" + "\n"
	case reflect.Uint,
		reflect.Uint8,
		reflect.Uint16,
		reflect.Uint32,
		reflect.Uint64,
		reflect.Uintptr:
		ic.OutputImports[`fflib "github.com/pquerna/ffjson/fflib/v1"`] = true
		out += "fflib.FormatBits2(buf, uint64(" + ptname + "), 10, false)" + "\n"
	case reflect.Float32:
		ic.OutputImports[`fflib "github.com/pquerna/ffjson/fflib/v1"`] = true
		out += "fflib.AppendFloat(buf, float64(" + ptname + "), 'g', -1, 32)" + "\n"
	case reflect.Float64:
		ic.OutputImports[`fflib "github.com/pquerna/ffjson/fflib/v1"`] = true
		out += "fflib.AppendFloat(buf, float64(" + ptname + "), 'g', -1, 64)" + "\n"
	case reflect.Array,
		reflect.Slice:

		// Arrays cannot be nil
		if typ.Kind() != reflect.Array {
			out += "if " + name + "!= nil {" + "\n"
		}
		// Array and slice values encode as JSON arrays, except that
		// []byte encodes as a base64-encoded string, and a nil slice
		// encodes as the null JSON object.
		if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Uint8 {
			ic.OutputImports[`"encoding/base64"`] = true

			out += "buf.WriteString(`\"`)" + "\n"
			out += `{` + "\n"
			out += `enc := base64.NewEncoder(base64.StdEncoding, buf)` + "\n"
			if typ.Elem().Name() != "byte" {
				ic.OutputImports[`"reflect"`] = true
				out += `enc.Write(reflect.Indirect(reflect.ValueOf(` + ptname + `)).Bytes())` + "\n"

			} else {
				out += `enc.Write(` + ptname + `)` + "\n"
			}
			out += `enc.Close()` + "\n"
			out += `}` + "\n"
			out += "buf.WriteString(`\"`)" + "\n"
		} else {
			out += "buf.WriteString(`[`)" + "\n"
			out += "for i, v := range " + ptname + "{" + "\n"
			out += "if i != 0 {" + "\n"
			out += "buf.WriteString(`,`)" + "\n"
			out += "}" + "\n"
			out += getGetInnerValue(ic, "v", typ.Elem(), false, false)
			out += "}" + "\n"
			out += "buf.WriteString(`]`)" + "\n"
		}
		if typ.Kind() != reflect.Array {
			out += "} else {" + "\n"
			out += "buf.WriteString(`null`)" + "\n"
			out += "}" + "\n"
		}
	case reflect.String:
		// Is it a json.Number?
		if typ.PkgPath() == "encoding/json" && typ.Name() == "Number" {
			// Fall back to json package to rely on the valid number check.
			// See: https://github.com/golang/go/blob/92cd6e3af9f423ab4d8ac78f24e7fd81c31a8ce6/src/encoding/json/encode.go#L550
			out += fmt.Sprintf("/* json.Number */\n")
			out += "err = buf.Encode(" + name + ")" + "\n"
			out += "if err != nil {" + "\n"
			out += "  return err" + "\n"
			out += "}" + "\n"
		} else {
			ic.OutputImports[`fflib "github.com/pquerna/ffjson/fflib/v1"`] = true
			if forceString {
				// Forcestring on strings does double-escaping of the entire value.
				// We create a temporary buffer, encode to that an re-encode it.
				out += "{" + "\n"
				out += "tmpbuf := fflib.Buffer{}" + "\n"
				out += "tmpbuf.Grow(len(" + ptname + ") + 16)" + "\n"
				out += "fflib.WriteJsonString(&tmpbuf, string(" + ptname + "))" + "\n"
				out += "fflib.WriteJsonString(buf, string( tmpbuf.Bytes() " + `))` + "\n"
				out += "}" + "\n"
			} else {
				out += "fflib.WriteJsonString(buf, string(" + ptname + "))" + "\n"
			}
		}
	case reflect.Ptr:
		out += "if " + name + "!= nil {" + "\n"
		switch typ.Elem().Kind() {
		case reflect.Struct:
			out += getGetInnerValue(ic, name, typ.Elem(), false, false)
		default:
			out += getGetInnerValue(ic, "*"+name, typ.Elem(), false, false)
		}
		out += "} else {" + "\n"
		out += "buf.WriteString(`null`)" + "\n"
		out += "}" + "\n"
	case reflect.Bool:
		out += "if " + ptname + " {" + "\n"
		ic.q.Write("true")
		out += ic.q.GetQueued()
		out += "} else {" + "\n"
		// Delete 'true'
		ic.q.DeleteLast()
		out += ic.q.WriteFlush("false")
		out += "}" + "\n"
	case reflect.Interface:
		out += fmt.Sprintf("/* Interface types must use runtime reflection. type=%v kind=%v */\n", typ, typ.Kind())
		out += "err = buf.Encode(" + name + ")" + "\n"
		out += "if err != nil {" + "\n"
		out += "  return err" + "\n"
		out += "}" + "\n"
	case reflect.Map:
		out += getMapValue(ic, ptname, typ, ptr, forceString)
	case reflect.Struct:
		if typ.Name() == "" {
			ic.q.Write("{")
			ic.q.Write(" ")
			out += fmt.Sprintf("/* Inline struct. type=%v kind=%v */\n", typ, typ.Kind())
			newV := reflect.Indirect(reflect.New(typ)).Interface()
			fields := extractFields(newV)

			// Output all fields
			for _, field := range fields {
				// Adjust field name
				field.Name = name + "." + field.Name
				out += getField(ic, field, "")
			}

			if lastConditional(fields) {
				out += ic.q.Flush()
				out += `buf.Rewind(1)` + "\n"
			} else {
				ic.q.DeleteLast()
			}
			out += ic.q.WriteFlush("}")
		} else {
			out += fmt.Sprintf("/* Struct fall back. type=%v kind=%v */\n", typ, typ.Kind())
			out += ic.q.Flush()
			if ptr {
				out += "err = buf.Encode(" + name + ")" + "\n"
			} else {
				// We send pointer to avoid copying entire struct
				out += "err = buf.Encode(&" + name + ")" + "\n"
			}
			out += "if err != nil {" + "\n"
			out += "  return err" + "\n"
			out += "}" + "\n"
		}
	default:
		out += fmt.Sprintf("/* Falling back. type=%v kind=%v */\n", typ, typ.Kind())
		out += "err = buf.Encode(" + name + ")" + "\n"
		out += "if err != nil {" + "\n"
		out += "  return err" + "\n"
		out += "}" + "\n"
	}

	return out
}

func getValue(ic *Inception, sf *StructField, prefix string) string {
	closequote := false
	if sf.ForceString {
		switch sf.Typ.Kind() {
		case reflect.Int,
			reflect.Int8,
			reflect.Int16,
			reflect.Int32,
			reflect.Int64,
			reflect.Uint,
			reflect.Uint8,
			reflect.Uint16,
			reflect.Uint32,
			reflect.Uint64,
			reflect.Uintptr,
			reflect.Float32,
			reflect.Float64,
			reflect.Bool:
			ic.q.Write(`"`)
			closequote = true
		}
	}
	out := getGetInnerValue(ic, prefix+sf.Name, sf.Typ, sf.Pointer, sf.ForceString)
	if closequote {
		if sf.Pointer {
			out += ic.q.WriteFlush(`"`)
		} else {
			ic.q.Write(`"`)
		}
	}

	return out
}

func p2(v uint32) uint32 {
	v--
	v |= v >> 1
	v |= v >> 2
	v |= v >> 4
	v |= v >> 8
	v |= v >> 16
	v++
	return v
}

func getTypeSize(t reflect.Type) uint32 {
	switch t.Kind() {
	case reflect.String:
		// TODO: consider runtime analysis.
		return 32
	case reflect.Array, reflect.Map, reflect.Slice:
		// TODO: consider runtime analysis.
		return 4 * getTypeSize(t.Elem())
	case reflect.Int,
		reflect.Int8,
		reflect.Int16,
		reflect.Int32,
		reflect.Uint,
		reflect.Uint8,
		reflect.Uint16,
		reflect.Uint32:
		return 8
	case reflect.Int64,
		reflect.Uint64,
		reflect.Uintptr:
		return 16
	case reflect.Float32,
		reflect.Float64:
		return 16
	case reflect.Bool:
		return 4
	case reflect.Ptr:
		return getTypeSize(t.Elem())
	default:
		return 16
	}
}

func getTotalSize(si *StructInfo) uint32 {
	rv := uint32(si.Typ.Size())
	for _, f := range si.Fields {
		rv += getTypeSize(f.Typ)
	}
	return rv
}

func getBufGrowSize(si *StructInfo) uint32 {

	// TOOD(pquerna): automatically calc a better grow size based on history
	// of a struct.
	return p2(getTotalSize(si))
}

func isIntish(t reflect.Type) bool {
	if t.Kind() >= reflect.Int && t.Kind() <= reflect.Uintptr {
		return true
	}
	if t.Kind() == reflect.Array || t.Kind() == reflect.Slice || t.Kind() == reflect.Ptr {
		if t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
			// base64 special case.
			return false
		} else {
			return isIntish(t.Elem())
		}
	}
	return false
}

func getField(ic *Inception, f *StructField, prefix string) string {
	out := ""
	if f.OmitEmpty {
		out += ic.q.Flush()
		if f.Pointer {
			out += "if " + prefix + f.Name + " != nil {" + "\n"
		}
		out += getOmitEmpty(ic, f)
	}

	if f.Pointer && !f.OmitEmpty {
		// Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON object.
		out += "if " + prefix + f.Name + " != nil {" + "\n"
	}

	// JsonName is already escaped and quoted.
	// getInnervalue should flush
	ic.q.Write(f.JsonName + ":")
	// We save a copy in case we need it
	t := ic.q

	out += getValue(ic, f, prefix)
	ic.q.Write(",")

	if f.Pointer && !f.OmitEmpty {
		out += "} else {" + "\n"
		out += t.WriteFlush("null")
		out += "}" + "\n"
	}

	if f.OmitEmpty {
		out += ic.q.Flush()
		if f.Pointer {
			out += "}" + "\n"
		}
		out += "}" + "\n"
	}
	return out
}

// We check if the last field is conditional.
func lastConditional(fields []*StructField) bool {
	if len(fields) > 0 {
		f := fields[len(fields)-1]
		return f.OmitEmpty
	}
	return false
}

func CreateMarshalJSON(ic *Inception, si *StructInfo) error {
	conditionalWrites := lastConditional(si.Fields)
	out := ""

	out += "// MarshalJSON marshal bytes to json - template\n"
	out += `func (j *` + si.Name + `) MarshalJSON() ([]byte, error) {` + "\n"
	out += `var buf fflib.Buffer` + "\n"

	out += `if j == nil {` + "\n"
	out += `  buf.WriteString("null")` + "\n"
	out += "  return buf.Bytes(), nil" + "\n"
	out += `}` + "\n"

	out += `err := j.MarshalJSONBuf(&buf)` + "\n"
	out += `if err != nil {` + "\n"
	out += "  return nil, err" + "\n"
	out += `}` + "\n"
	out += `return buf.Bytes(), nil` + "\n"
	out += `}` + "\n"

	out += "// MarshalJSONBuf marshal buff to json - template\n"
	out += `func (j *` + si.Name + `) MarshalJSONBuf(buf fflib.EncodingBuffer) (error) {` + "\n"
	out += `  if j == nil {` + "\n"
	out += `    buf.WriteString("null")` + "\n"
	out += "    return nil" + "\n"
	out += `  }` + "\n"

	out += `var err error` + "\n"
	out += `var obj []byte` + "\n"
	out += `_ = obj` + "\n"
	out += `_ = err` + "\n"

	ic.q.Write("{")

	// The extra space is inserted here.
	// If nothing is written to the field this will be deleted
	// instead of the last comma.
	if conditionalWrites || len(si.Fields) == 0 {
		ic.q.Write(" ")
	}

	for _, f := range si.Fields {
		out += getField(ic, f, "j.")
	}

	// Handling the last comma is tricky.
	// If the last field has omitempty, conditionalWrites is set.
	// If something has been written, we delete the last comma,
	// by backing up the buffer, otherwise it will delete a space.
	if conditionalWrites {
		out += ic.q.Flush()
		out += `buf.Rewind(1)` + "\n"
	} else {
		ic.q.DeleteLast()
	}

	out += ic.q.WriteFlush("}")
	out += `return nil` + "\n"
	out += `}` + "\n"
	ic.OutputFuncs = append(ic.OutputFuncs, out)
	return nil
}