cache.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package chat
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "hash/fnv"
  6. "sync"
  7. )
  8. // PartCache caches rendered messages to avoid re-rendering
  9. type PartCache struct {
  10. mu sync.RWMutex
  11. cache map[string]string
  12. }
  13. // NewPartCache creates a new message cache
  14. func NewPartCache() *PartCache {
  15. return &PartCache{
  16. cache: make(map[string]string),
  17. }
  18. }
  19. // generateKey creates a unique key for a message based on its content and rendering parameters
  20. func (c *PartCache) GenerateKey(params ...any) string {
  21. h := fnv.New64a()
  22. for _, param := range params {
  23. h.Write(fmt.Appendf(nil, ":%v", param))
  24. }
  25. return hex.EncodeToString(h.Sum(nil))
  26. }
  27. // Get retrieves a cached rendered message
  28. func (c *PartCache) Get(key string) (string, bool) {
  29. c.mu.RLock()
  30. defer c.mu.RUnlock()
  31. content, exists := c.cache[key]
  32. return content, exists
  33. }
  34. // Set stores a rendered message in the cache
  35. func (c *PartCache) Set(key string, content string) {
  36. c.mu.Lock()
  37. defer c.mu.Unlock()
  38. c.cache[key] = content
  39. }
  40. // Clear removes all entries from the cache
  41. func (c *PartCache) Clear() {
  42. c.mu.Lock()
  43. defer c.mu.Unlock()
  44. c.cache = make(map[string]string)
  45. }
  46. // Size returns the number of cached entries
  47. func (c *PartCache) Size() int {
  48. c.mu.RLock()
  49. defer c.mu.RUnlock()
  50. return len(c.cache)
  51. }