svg.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package cache
  2. import (
  3. "image"
  4. "sync"
  5. "time"
  6. )
  7. var svgs = &sync.Map{} // make(map[string]*svgInfo)
  8. // GetSvg gets svg image from cache if it exists.
  9. func GetSvg(name string, w int, h int) *image.NRGBA {
  10. sinfo, ok := svgs.Load(name)
  11. if !ok || sinfo == nil {
  12. return nil
  13. }
  14. svginfo := sinfo.(*svgInfo)
  15. if svginfo.w != w || svginfo.h != h {
  16. return nil
  17. }
  18. svginfo.setAlive()
  19. return svginfo.pix
  20. }
  21. // SetSvg sets a svg into the cache map.
  22. func SetSvg(name string, pix *image.NRGBA, w int, h int) {
  23. sinfo := &svgInfo{
  24. pix: pix,
  25. w: w,
  26. h: h,
  27. }
  28. sinfo.setAlive()
  29. svgs.Store(name, sinfo)
  30. }
  31. type svgInfo struct {
  32. expiringCacheNoLock
  33. pix *image.NRGBA
  34. w, h int
  35. }
  36. // destroyExpiredSvgs destroys expired svgs cache data.
  37. func destroyExpiredSvgs(now time.Time) {
  38. expiredSvgs := make([]string, 0, 20)
  39. svgs.Range(func(key, value interface{}) bool {
  40. s, sinfo := key.(string), value.(*svgInfo)
  41. if sinfo.isExpired(now) {
  42. expiredSvgs = append(expiredSvgs, s)
  43. }
  44. return true
  45. })
  46. for _, exp := range expiredSvgs {
  47. svgs.Delete(exp)
  48. }
  49. }