previewcache.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package email
  2. /*
  3. previewcache.go
  4. Message list previews need a partial body fetch per message. A message's
  5. body never changes (IMAP messages are immutable for a given UIDVALIDITY),
  6. so previews are cached in memory and refreshing a folder only fetches
  7. snippets for mail that arrived since.
  8. */
  9. import (
  10. "container/list"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. )
  15. type previewEntry struct {
  16. key string
  17. preview string
  18. }
  19. type previewCache struct {
  20. mutex sync.Mutex
  21. capacity int
  22. order *list.List
  23. entries map[string]*list.Element
  24. }
  25. func newPreviewCache(capacity int) *previewCache {
  26. return &previewCache{capacity: capacity, order: list.New(), entries: map[string]*list.Element{}}
  27. }
  28. func previewKey(owner string, accountID string, folder string, uidValidity uint32, uid uint32) string {
  29. return owner + "/" + accountID + "\x00" + folder + "\x00" + strconv.FormatUint(uint64(uidValidity), 10) + "\x00" + strconv.FormatUint(uint64(uid), 10)
  30. }
  31. func (c *previewCache) get(key string) (string, bool) {
  32. c.mutex.Lock()
  33. defer c.mutex.Unlock()
  34. if element, ok := c.entries[key]; ok {
  35. c.order.MoveToFront(element)
  36. return element.Value.(*previewEntry).preview, true
  37. }
  38. return "", false
  39. }
  40. func (c *previewCache) put(key string, preview string) {
  41. c.mutex.Lock()
  42. defer c.mutex.Unlock()
  43. if element, ok := c.entries[key]; ok {
  44. element.Value.(*previewEntry).preview = preview
  45. c.order.MoveToFront(element)
  46. return
  47. }
  48. c.entries[key] = c.order.PushFront(&previewEntry{key: key, preview: preview})
  49. for c.order.Len() > c.capacity {
  50. oldest := c.order.Back()
  51. c.order.Remove(oldest)
  52. delete(c.entries, oldest.Value.(*previewEntry).key)
  53. }
  54. }
  55. // dropAccount forgets every preview of an account.
  56. func (c *previewCache) dropAccount(owner string, accountID string) {
  57. prefix := owner + "/" + accountID + "\x00"
  58. c.mutex.Lock()
  59. defer c.mutex.Unlock()
  60. for key, element := range c.entries {
  61. if strings.HasPrefix(key, prefix) {
  62. c.order.Remove(element)
  63. delete(c.entries, key)
  64. }
  65. }
  66. }