opencode_offline/packages/tui/internal/components/chat/cache.go

63 lines
1.2 KiB
Go
Raw Normal View History

2025-06-06 02:10:15 +08:00
package chat
import (
"encoding/hex"
"fmt"
2025-07-16 04:21:25 +08:00
"hash/fnv"
2025-06-06 02:10:15 +08:00
"sync"
)
2025-07-16 08:09:16 +08:00
// PartCache caches rendered messages to avoid re-rendering
type PartCache struct {
2025-06-06 02:10:15 +08:00
mu sync.RWMutex
cache map[string]string
}
2025-07-16 08:09:16 +08:00
// NewPartCache creates a new message cache
func NewPartCache() *PartCache {
return &PartCache{
2025-06-06 02:10:15 +08:00
cache: make(map[string]string),
}
}
// generateKey creates a unique key for a message based on its content and rendering parameters
2025-07-16 08:09:16 +08:00
func (c *PartCache) GenerateKey(params ...any) string {
2025-07-16 04:21:25 +08:00
h := fnv.New64a()
2025-06-06 04:44:20 +08:00
for _, param := range params {
h.Write(fmt.Appendf(nil, ":%v", param))
2025-06-06 02:10:15 +08:00
}
return hex.EncodeToString(h.Sum(nil))
}
// Get retrieves a cached rendered message
2025-07-16 08:09:16 +08:00
func (c *PartCache) Get(key string) (string, bool) {
2025-06-06 02:10:15 +08:00
c.mu.RLock()
defer c.mu.RUnlock()
content, exists := c.cache[key]
return content, exists
}
// Set stores a rendered message in the cache
2025-07-16 08:09:16 +08:00
func (c *PartCache) Set(key string, content string) {
2025-06-06 02:10:15 +08:00
c.mu.Lock()
defer c.mu.Unlock()
c.cache[key] = content
}
// Clear removes all entries from the cache
2025-07-16 08:09:16 +08:00
func (c *PartCache) Clear() {
2025-06-06 02:10:15 +08:00
c.mu.Lock()
defer c.mu.Unlock()
c.cache = make(map[string]string)
}
// Size returns the number of cached entries
2025-07-16 08:09:16 +08:00
func (c *PartCache) Size() int {
2025-06-06 02:10:15 +08:00
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.cache)
}