Repository navigation
Expand file tree
/
Copy pathcached.go
More file actions
300 lines (254 loc) · 7.03 KB
/
Copy pathcached.go
File metadata and controls
300 lines (254 loc) · 7.03 KB
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
package miya
import (
"strings"
"sync"
)
// StringBuilderPool provides a pool of strings.Builder instances to reduce allocations
var StringBuilderPool = sync.Pool{
New: func() interface{} {
return &strings.Builder{}
},
}
// GetStringBuilder gets a strings.Builder from the pool
func GetStringBuilder() *strings.Builder {
return StringBuilderPool.Get().(*strings.Builder)
}
// PutStringBuilder returns a strings.Builder to the pool after resetting it
func PutStringBuilder(sb *strings.Builder) {
sb.Reset()
StringBuilderPool.Put(sb)
}
// ContextPool provides a pool of Context instances to reduce allocations
var ContextPool = sync.Pool{
New: func() interface{} {
return NewContext()
},
}
// GetContext gets a Context from the pool
func GetContext() Context {
return ContextPool.Get().(Context)
}
// PutContext returns a Context to the pool
func PutContext(ctx Context) {
// Reset the context before returning to pool
// Clear all variables to avoid data leakage between uses
if ctx != nil {
// Create a fresh context to replace the used one
// This ensures no stale data remains
ContextPool.Put(NewContext())
}
}
// CachedTemplate wraps Template with caching optimizations
type CachedTemplate struct {
*Template
renderPool sync.Pool
}
// NewCachedTemplate creates a new cached template wrapper
func NewCachedTemplate(tmpl *Template) *CachedTemplate {
return &CachedTemplate{
Template: tmpl,
renderPool: sync.Pool{
New: func() interface{} {
return &renderContext{
builder: &strings.Builder{},
visited: make(map[string]bool),
}
},
},
}
}
type renderContext struct {
builder *strings.Builder
visited map[string]bool
}
func (rc *renderContext) reset() {
rc.builder.Reset()
for k := range rc.visited {
delete(rc.visited, k)
}
}
// RenderCached renders the template with caching optimizations
func (ct *CachedTemplate) RenderCached(ctx Context) (string, error) {
rc := ct.renderPool.Get().(*renderContext)
defer func() {
rc.reset()
ct.renderPool.Put(rc)
}()
// Use the existing render method but with cached context
return ct.Template.Render(ctx)
}
// SlicePool provides pools for commonly used slice types
type SlicePool struct {
stringPool sync.Pool
intPool sync.Pool
}
var GlobalSlicePool = &SlicePool{
stringPool: sync.Pool{
New: func() interface{} {
return make([]string, 0, 16)
},
},
intPool: sync.Pool{
New: func() interface{} {
return make([]int, 0, 16)
},
},
}
// GetStringSlice gets a string slice from the pool
func (sp *SlicePool) GetStringSlice() []string {
return sp.stringPool.Get().([]string)
}
// PutStringSlice returns a string slice to the pool
func (sp *SlicePool) PutStringSlice(slice []string) {
slice = slice[:0] // Reset length but keep capacity
sp.stringPool.Put(slice)
}
// GetIntSlice gets an int slice from the pool
func (sp *SlicePool) GetIntSlice() []int {
return sp.intPool.Get().([]int)
}
// PutIntSlice returns an int slice to the pool
func (sp *SlicePool) PutIntSlice(slice []int) {
slice = slice[:0] // Reset length but keep capacity
sp.intPool.Put(slice)
}
// FastStringBuilder is an optimized string builder for template rendering
type FastStringBuilder struct {
buf []byte
}
// NewFastStringBuilder creates a new fast string builder
func NewFastStringBuilder(capacity int) *FastStringBuilder {
return &FastStringBuilder{
buf: make([]byte, 0, capacity),
}
}
// WriteString appends a string to the buffer
func (fsb *FastStringBuilder) WriteString(s string) {
fsb.buf = append(fsb.buf, s...)
}
// WriteByte appends a byte to the buffer
func (fsb *FastStringBuilder) WriteByte(b byte) error {
fsb.buf = append(fsb.buf, b)
return nil
}
// String returns the accumulated string
func (fsb *FastStringBuilder) String() string {
return string(fsb.buf)
}
// Reset clears the buffer
func (fsb *FastStringBuilder) Reset() {
fsb.buf = fsb.buf[:0]
}
// Len returns the current length
func (fsb *FastStringBuilder) Len() int {
return len(fsb.buf)
}
// FastStringBuilderPool provides pooled FastStringBuilder instances
var FastStringBuilderPool = sync.Pool{
New: func() interface{} {
return NewFastStringBuilder(1024) // Start with 1KB capacity
},
}
// GetFastStringBuilder gets a FastStringBuilder from the pool
func GetFastStringBuilder() *FastStringBuilder {
return FastStringBuilderPool.Get().(*FastStringBuilder)
}
// PutFastStringBuilder returns a FastStringBuilder to the pool
func PutFastStringBuilder(fsb *FastStringBuilder) {
if fsb.Len() < 64*1024 { // Only reuse if buffer is reasonable size
fsb.Reset()
FastStringBuilderPool.Put(fsb)
}
}
// CacheKey represents a cache key for templates
type CacheKey struct {
Template string
Hash uint64
}
// TemplateCache is a thread-safe LRU cache for compiled templates
type TemplateCache struct {
mutex sync.RWMutex
cache map[string]*Template
order []string
maxSize int
}
// NewTemplateCache creates a new template cache holding at most maxSize templates.
// A maxSize of 0 disables caching (Put stores nothing) and a negative maxSize means
// the cache is unbounded.
func NewTemplateCache(maxSize int) *TemplateCache {
return &TemplateCache{
cache: make(map[string]*Template),
order: make([]string, 0, max(maxSize, 0)),
maxSize: maxSize,
}
}
// Get retrieves a template from the cache
func (tc *TemplateCache) Get(key string) (*Template, bool) {
tc.mutex.RLock()
tmpl, exists := tc.cache[key]
tc.mutex.RUnlock()
if exists {
// Move to front (LRU)
tc.mutex.Lock()
tc.moveToFront(key)
tc.mutex.Unlock()
}
return tmpl, exists
}
// Put stores a template in the cache
func (tc *TemplateCache) Put(key string, tmpl *Template) {
if tc.maxSize == 0 {
return
}
tc.mutex.Lock()
defer tc.mutex.Unlock()
if _, exists := tc.cache[key]; exists {
tc.moveToFront(key)
tc.cache[key] = tmpl
return
}
if tc.maxSize > 0 && len(tc.cache) >= tc.maxSize {
// Remove least recently used
oldest := tc.order[len(tc.order)-1]
delete(tc.cache, oldest)
tc.order = tc.order[:len(tc.order)-1]
}
tc.cache[key] = tmpl
tc.order = append([]string{key}, tc.order...)
}
func (tc *TemplateCache) moveToFront(key string) {
for i, k := range tc.order {
if k == key {
// Move to front
copy(tc.order[1:i+1], tc.order[0:i])
tc.order[0] = key
break
}
}
}
// CachedEnvironment wraps Environment with caching optimizations
type CachedEnvironment struct {
*Environment
templateCache *TemplateCache
}
// NewCachedEnvironment creates a cached environment
func NewCachedEnvironment(opts ...EnvironmentOption) *CachedEnvironment {
env := NewEnvironment(opts...)
return &CachedEnvironment{
Environment: env,
templateCache: NewTemplateCache(100), // Cache up to 100 templates
}
}
// FromStringCached compiles a template with caching
func (ce *CachedEnvironment) FromStringCached(source string) (*Template, error) {
// Use source as cache key (in production, you might want to hash this)
if tmpl, exists := ce.templateCache.Get(source); exists {
return tmpl, nil
}
tmpl, err := ce.Environment.FromString(source)
if err != nil {
return nil, err
}
ce.templateCache.Put(source, tmpl)
return tmpl, nil
}