summaryrefslogtreecommitdiff
path: root/vendor/github.com/vmihailenco/msgpack/v5/decode_typgen.go
blob: 0b4c1d04aedf4c02e53987d13ebdcd8921c8fa16 (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
package msgpack

import (
	"reflect"
	"sync"
)

var cachedValues struct {
	m map[reflect.Type]chan reflect.Value
	sync.RWMutex
}

func cachedValue(t reflect.Type) reflect.Value {
	cachedValues.RLock()
	ch := cachedValues.m[t]
	cachedValues.RUnlock()
	if ch != nil {
		return <-ch
	}

	cachedValues.Lock()
	defer cachedValues.Unlock()
	if ch = cachedValues.m[t]; ch != nil {
		return <-ch
	}

	ch = make(chan reflect.Value, 256)
	go func() {
		for {
			ch <- reflect.New(t)
		}
	}()
	if cachedValues.m == nil {
		cachedValues.m = make(map[reflect.Type]chan reflect.Value, 8)
	}
	cachedValues.m[t] = ch
	return <-ch
}

func (d *Decoder) newValue(t reflect.Type) reflect.Value {
	if d.flags&usePreallocateValues == 0 {
		return reflect.New(t)
	}

	return cachedValue(t)
}