-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpool.go
82 lines (69 loc) · 1.5 KB
/
pool.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
// Copyright (C) 2018 Kun Zhong All rights reserved.
// Use of this source code is governed by a Licensed under the Apache License, Version 2.0 (the "License");
package grpcx
import (
"bytes"
"reflect"
"sync"
)
var typePool = make(map[reflect.Type]*sync.Pool)
var bufPool = make(map[reflect.Type]*sync.Pool)
var plock sync.RWMutex
func initTypePool(t reflect.Type) {
typePool[t] = &sync.Pool{
New: func() interface{} {
if t.Kind() == reflect.Ptr {
return reflect.New(t.Elem()).Interface()
}
return reflect.New(t).Interface()
},
}
bufPool[t] = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
}
func getTypeFromPool(t reflect.Type) interface{} {
if p, ok := typePool[t]; ok {
return p.Get()
}
if t.Kind() == reflect.Ptr {
return reflect.New(t.Elem()).Interface()
}
return reflect.New(t).Interface()
}
func putTypeToPool(t reflect.Type, v interface{}) {
if p, ok := typePool[t]; ok {
p.Put(v)
}
}
func getBufferFromPool(t reflect.Type) *bytes.Buffer {
plock.RLock()
if p, ok := bufPool[t]; ok {
plock.RUnlock()
return p.Get().(*bytes.Buffer)
}
plock.RUnlock()
plock.Lock()
if p, ok := bufPool[t]; ok {
plock.Unlock()
return p.Get().(*bytes.Buffer)
}
bufPool[t] = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
plock.Unlock()
return new(bytes.Buffer)
}
func putBufferToPool(t reflect.Type, buf *bytes.Buffer) {
buf.Reset()
plock.RLock()
defer plock.RUnlock()
if p, ok := bufPool[t]; ok {
p.Put(buf)
return
}
}