2024-03-13 02:27:15 +01:00
|
|
|
package templates
|
2021-08-28 00:15:28 +05:30
|
|
|
|
|
|
|
|
import (
|
2024-03-13 21:02:36 +01:00
|
|
|
"github.com/projectdiscovery/utils/conversion"
|
2024-03-10 22:29:55 +01:00
|
|
|
mapsutil "github.com/projectdiscovery/utils/maps"
|
2021-08-28 00:15:28 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Templates is a cache for caching and storing templates for reuse.
|
2024-03-13 02:27:15 +01:00
|
|
|
type Cache struct {
|
2024-03-13 21:02:36 +01:00
|
|
|
items *mapsutil.SyncLockMap[string, parsedTemplate]
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// New returns a new templates cache
|
2024-03-13 02:27:15 +01:00
|
|
|
func NewCache() *Cache {
|
2025-09-15 23:48:02 +05:30
|
|
|
return &Cache{
|
|
|
|
|
items: mapsutil.NewSyncLockMap[string, parsedTemplate](),
|
|
|
|
|
}
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
|
|
|
|
|
2024-03-13 21:02:36 +01:00
|
|
|
type parsedTemplate struct {
|
2024-03-13 02:27:15 +01:00
|
|
|
template *Template
|
2024-03-13 21:02:36 +01:00
|
|
|
raw string
|
2021-08-28 00:15:28 +05:30
|
|
|
err error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Has returns true if the cache has a template. The template
|
|
|
|
|
// is returned along with any errors if found.
|
2024-03-13 21:02:36 +01:00
|
|
|
func (t *Cache) Has(template string) (*Template, []byte, error) {
|
2024-03-10 22:29:55 +01:00
|
|
|
value, ok := t.items.Get(template)
|
2021-08-28 00:15:28 +05:30
|
|
|
if !ok {
|
2024-03-13 21:02:36 +01:00
|
|
|
return nil, nil, nil
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
2024-03-13 21:02:36 +01:00
|
|
|
return value.template, conversion.Bytes(value.raw), value.err
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Store stores a template with data and error
|
2024-03-13 21:02:36 +01:00
|
|
|
func (t *Cache) Store(id string, tpl *Template, raw []byte, err error) {
|
2025-09-15 23:48:02 +05:30
|
|
|
entry := parsedTemplate{
|
|
|
|
|
template: tpl,
|
|
|
|
|
err: err,
|
|
|
|
|
raw: conversion.String(raw),
|
|
|
|
|
}
|
|
|
|
|
_ = t.items.Set(id, entry)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// StoreWithoutRaw stores a template without raw data for memory efficiency
|
|
|
|
|
func (t *Cache) StoreWithoutRaw(id string, tpl *Template, err error) {
|
|
|
|
|
entry := parsedTemplate{
|
|
|
|
|
template: tpl,
|
|
|
|
|
err: err,
|
|
|
|
|
raw: "",
|
|
|
|
|
}
|
|
|
|
|
_ = t.items.Set(id, entry)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get returns only the template without raw bytes
|
|
|
|
|
func (t *Cache) Get(id string) (*Template, error) {
|
|
|
|
|
value, ok := t.items.Get(id)
|
|
|
|
|
if !ok {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return value.template, value.err
|
2024-03-10 22:29:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Purge the cache
|
2024-03-13 02:27:15 +01:00
|
|
|
func (t *Cache) Purge() {
|
2024-03-10 22:29:55 +01:00
|
|
|
t.items.Clear()
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|