File: pointer.go

package info (click to toggle)
golang-github-segmentio-encoding 0.5.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 14,468 kB
  • sloc: makefile: 286
file content (52 lines) | stat: -rw-r--r-- 1,172 bytes parent folder | download
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
package proto

import (
	"reflect"
	"unsafe"
)

func pointerCodecOf(t reflect.Type, seen map[reflect.Type]*codec) *codec {
	p := new(codec)
	seen[t] = p
	c := codecOf(t.Elem(), seen)
	p.wire = c.wire
	p.size = pointerSizeFuncOf(t, c)
	p.encode = pointerEncodeFuncOf(t, c)
	p.decode = pointerDecodeFuncOf(t, c)
	return p
}

func pointerSizeFuncOf(t reflect.Type, c *codec) sizeFunc {
	return func(p unsafe.Pointer, flags flags) int {
		if p != nil {
			if !flags.has(inline) {
				p = *(*unsafe.Pointer)(p)
			}
			return c.size(p, flags.without(inline).with(wantzero))
		}
		return 0
	}
}

func pointerEncodeFuncOf(t reflect.Type, c *codec) encodeFunc {
	return func(b []byte, p unsafe.Pointer, flags flags) (int, error) {
		if p != nil {
			if !flags.has(inline) {
				p = *(*unsafe.Pointer)(p)
			}
			return c.encode(b, p, flags.without(inline).with(wantzero))
		}
		return 0, nil
	}
}

func pointerDecodeFuncOf(t reflect.Type, c *codec) decodeFunc {
	t = t.Elem()
	return func(b []byte, p unsafe.Pointer, flags flags) (int, error) {
		v := (*unsafe.Pointer)(p)
		if *v == nil {
			*v = unsafe.Pointer(reflect.New(t).Pointer())
		}
		return c.decode(b, *v, flags)
	}
}