cache.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. package cache
  2. import (
  3. "encoding/gob"
  4. "fmt"
  5. "io"
  6. "os"
  7. "runtime"
  8. "sync"
  9. "time"
  10. )
  11. type Item struct {
  12. Object interface{}
  13. Expiration int64
  14. Accessed int64
  15. }
  16. // Returns true if the item has expired.
  17. func (item Item) Expired() bool {
  18. if item.Expiration == 0 {
  19. return false
  20. }
  21. return time.Now().UnixNano() > item.Expiration
  22. }
  23. // Return the time at which this item was last accessed.
  24. func (item Item) LastAccessed() time.Time {
  25. return time.Unix(0, item.Accessed)
  26. }
  27. const (
  28. // For use with functions that take an expiration time.
  29. NoExpiration time.Duration = -1
  30. // For use with functions that take an expiration time. Equivalent to
  31. // passing in the same expiration duration as was given to New() or
  32. // NewFrom() when the cache was created (e.g. 5 minutes.)
  33. DefaultExpiration time.Duration = 0
  34. )
  35. type Cache struct {
  36. *cache
  37. // If this is confusing, see the comment at the bottom of New()
  38. }
  39. type cache struct {
  40. defaultExpiration time.Duration
  41. items map[string]Item
  42. mu sync.RWMutex
  43. onEvicted func(string, interface{})
  44. janitor *janitor
  45. maxItems int
  46. }
  47. // Add an item to the cache, replacing any existing item. If the duration is 0
  48. // (DefaultExpiration), the cache's default expiration time is used. If it is -1
  49. // (NoExpiration), the item never expires.
  50. func (c *cache) Set(k string, x interface{}, d time.Duration) {
  51. // "Inlining" of set
  52. var (
  53. now time.Time
  54. e int64
  55. )
  56. if d == DefaultExpiration {
  57. d = c.defaultExpiration
  58. }
  59. if d > 0 {
  60. now = time.Now()
  61. e = now.Add(d).UnixNano()
  62. }
  63. if c.maxItems > 0 {
  64. if d <= 0 {
  65. // d <= 0 means we didn't set now above
  66. now = time.Now()
  67. }
  68. c.mu.Lock()
  69. c.items[k] = Item{
  70. Object: x,
  71. Expiration: e,
  72. Accessed: now.UnixNano(),
  73. }
  74. // TODO: Calls to mu.Unlock are currently not deferred because
  75. // defer adds ~200 ns (as of go1.)
  76. c.mu.Unlock()
  77. } else {
  78. c.mu.Lock()
  79. c.items[k] = Item{
  80. Object: x,
  81. Expiration: e,
  82. }
  83. c.mu.Unlock()
  84. }
  85. }
  86. func (c *cache) set(k string, x interface{}, d time.Duration) {
  87. var (
  88. now time.Time
  89. e int64
  90. )
  91. if d == DefaultExpiration {
  92. d = c.defaultExpiration
  93. }
  94. if d > 0 {
  95. now = time.Now()
  96. e = now.Add(d).UnixNano()
  97. }
  98. if c.maxItems > 0 {
  99. if d <= 0 {
  100. // d <= 0 means we didn't set now above
  101. now = time.Now()
  102. }
  103. c.items[k] = Item{
  104. Object: x,
  105. Expiration: e,
  106. Accessed: now.UnixNano(),
  107. }
  108. } else {
  109. c.items[k] = Item{
  110. Object: x,
  111. Expiration: e,
  112. }
  113. }
  114. }
  115. // Add an item to the cache, replacing any existing item, using the default
  116. // expiration.
  117. func (c *cache) SetDefault(k string, x interface{}) {
  118. c.Set(k, x, DefaultExpiration)
  119. }
  120. // Add an item to the cache only if an item doesn't already exist for the given
  121. // key, or if the existing item has expired. Returns an error otherwise.
  122. func (c *cache) Add(k string, x interface{}, d time.Duration) error {
  123. c.mu.Lock()
  124. _, found := c.get(k)
  125. if found {
  126. c.mu.Unlock()
  127. return fmt.Errorf("Item %s already exists", k)
  128. }
  129. c.set(k, x, d)
  130. c.mu.Unlock()
  131. return nil
  132. }
  133. // Set a new value for the cache key only if it already exists, and the existing
  134. // item hasn't expired. Returns an error otherwise.
  135. func (c *cache) Replace(k string, x interface{}, d time.Duration) error {
  136. c.mu.Lock()
  137. _, found := c.get(k)
  138. if !found {
  139. c.mu.Unlock()
  140. return fmt.Errorf("Item %s doesn't exist", k)
  141. }
  142. c.set(k, x, d)
  143. c.mu.Unlock()
  144. return nil
  145. }
  146. // Get an item from the cache. Returns the item or nil, and a bool indicating
  147. // whether the key was found.
  148. func (c *cache) Get(k string) (interface{}, bool) {
  149. if c.maxItems > 0 {
  150. // LRU enabled; Get implies write
  151. c.mu.Lock()
  152. } else {
  153. // LRU not enabled; Get is read-only
  154. c.mu.RLock()
  155. }
  156. // "Inlining" of get and Expired
  157. item, found := c.items[k]
  158. if !found {
  159. if c.maxItems > 0 {
  160. c.mu.Unlock()
  161. } else {
  162. c.mu.RUnlock()
  163. }
  164. return nil, false
  165. }
  166. var now int64
  167. if item.Expiration > 0 {
  168. now = time.Now().UnixNano()
  169. if now > item.Expiration {
  170. if c.maxItems > 0 {
  171. c.mu.Unlock()
  172. } else {
  173. c.mu.RUnlock()
  174. }
  175. return nil, false
  176. }
  177. }
  178. if c.maxItems > 0 {
  179. if now == 0 {
  180. now = time.Now().UnixNano()
  181. }
  182. item.Accessed = now
  183. c.items[k] = item
  184. c.mu.Unlock()
  185. } else {
  186. c.mu.RUnlock()
  187. }
  188. return item.Object, true
  189. }
  190. // If LRU functionality is being used (and get implies updating item.Accessed,)
  191. // this function must be write-locked.
  192. func (c *cache) get(k string) (interface{}, bool) {
  193. item, found := c.items[k]
  194. if !found {
  195. return nil, false
  196. }
  197. // "Inlining" of Expired
  198. var now int64
  199. if item.Expiration > 0 {
  200. now = time.Now().UnixNano()
  201. if now > item.Expiration {
  202. return nil, false
  203. }
  204. }
  205. if c.maxItems > 0 {
  206. if now == 0 {
  207. now = time.Now().UnixNano()
  208. }
  209. item.Accessed = now
  210. c.items[k] = item
  211. }
  212. return item.Object, true
  213. }
  214. // GetWithExpiration returns an item and its expiration time from the cache.
  215. // It returns the item or nil, the expiration time if one is set (if the item
  216. // never expires a zero value for time.Time is returned), and a bool indicating
  217. // whether the key was found.
  218. func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) {
  219. if c.maxItems > 0 {
  220. // LRU enabled; GetWithExpiration implies write
  221. c.mu.Lock()
  222. } else {
  223. // LRU not enabled; GetWithExpiration is read-only
  224. c.mu.RLock()
  225. }
  226. // "Inlining" of get and Expired
  227. item, found := c.items[k]
  228. if !found {
  229. if c.maxItems > 0 {
  230. c.mu.Unlock()
  231. } else {
  232. c.mu.RUnlock()
  233. }
  234. return nil, time.Time{}, false
  235. }
  236. var now int64
  237. if item.Expiration > 0 {
  238. now = time.Now().UnixNano()
  239. if now > item.Expiration {
  240. if c.maxItems > 0 {
  241. c.mu.Unlock()
  242. } else {
  243. c.mu.RUnlock()
  244. }
  245. return nil, time.Time{}, false
  246. }
  247. if c.maxItems > 0 {
  248. if now == 0 {
  249. now = time.Now().UnixNano()
  250. }
  251. item.Accessed = now
  252. c.items[k] = item
  253. c.mu.Unlock()
  254. } else {
  255. c.mu.RUnlock()
  256. }
  257. return item.Object, time.Unix(0, item.Expiration), true
  258. }
  259. if c.maxItems > 0 {
  260. if now == 0 {
  261. now = time.Now().UnixNano()
  262. }
  263. item.Accessed = now
  264. c.items[k] = item
  265. c.mu.Unlock()
  266. } else {
  267. c.mu.RUnlock()
  268. }
  269. // If expiration <= 0 (i.e. no expiration time set) then return the item
  270. // and a zeroed time.Time
  271. return item.Object, time.Time{}, true
  272. }
  273. // Increment an item of type int, int8, int16, int32, int64, uintptr, uint,
  274. // uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the
  275. // item's value is not an integer, if it was not found, or if it is not
  276. // possible to increment it by n. To retrieve the incremented value, use one
  277. // of the specialized methods, e.g. IncrementInt64.
  278. func (c *cache) Increment(k string, n int64) error {
  279. c.mu.Lock()
  280. v, found := c.items[k]
  281. if !found || v.Expired() {
  282. c.mu.Unlock()
  283. return fmt.Errorf("Item %s not found", k)
  284. }
  285. if c.maxItems > 0 {
  286. v.Accessed = time.Now().UnixNano()
  287. }
  288. switch v.Object.(type) {
  289. case int:
  290. v.Object = v.Object.(int) + int(n)
  291. case int8:
  292. v.Object = v.Object.(int8) + int8(n)
  293. case int16:
  294. v.Object = v.Object.(int16) + int16(n)
  295. case int32:
  296. v.Object = v.Object.(int32) + int32(n)
  297. case int64:
  298. v.Object = v.Object.(int64) + n
  299. case uint:
  300. v.Object = v.Object.(uint) + uint(n)
  301. case uintptr:
  302. v.Object = v.Object.(uintptr) + uintptr(n)
  303. case uint8:
  304. v.Object = v.Object.(uint8) + uint8(n)
  305. case uint16:
  306. v.Object = v.Object.(uint16) + uint16(n)
  307. case uint32:
  308. v.Object = v.Object.(uint32) + uint32(n)
  309. case uint64:
  310. v.Object = v.Object.(uint64) + uint64(n)
  311. case float32:
  312. v.Object = v.Object.(float32) + float32(n)
  313. case float64:
  314. v.Object = v.Object.(float64) + float64(n)
  315. default:
  316. c.mu.Unlock()
  317. return fmt.Errorf("The value for %s is not an integer", k)
  318. }
  319. c.items[k] = v
  320. c.mu.Unlock()
  321. return nil
  322. }
  323. // Increment an item of type float32 or float64 by n. Returns an error if the
  324. // item's value is not floating point, if it was not found, or if it is not
  325. // possible to increment it by n. Pass a negative number to decrement the
  326. // value. To retrieve the incremented value, use one of the specialized methods,
  327. // e.g. IncrementFloat64.
  328. func (c *cache) IncrementFloat(k string, n float64) error {
  329. c.mu.Lock()
  330. v, found := c.items[k]
  331. if !found || v.Expired() {
  332. c.mu.Unlock()
  333. return fmt.Errorf("Item %s not found", k)
  334. }
  335. if c.maxItems > 0 {
  336. v.Accessed = time.Now().UnixNano()
  337. }
  338. switch v.Object.(type) {
  339. case float32:
  340. v.Object = v.Object.(float32) + float32(n)
  341. case float64:
  342. v.Object = v.Object.(float64) + n
  343. default:
  344. c.mu.Unlock()
  345. return fmt.Errorf("The value for %s does not have type float32 or float64", k)
  346. }
  347. c.items[k] = v
  348. c.mu.Unlock()
  349. return nil
  350. }
  351. // Increment an item of type int by n. Returns an error if the item's value is
  352. // not an int, or if it was not found. If there is no error, the incremented
  353. // value is returned.
  354. func (c *cache) IncrementInt(k string, n int) (int, error) {
  355. c.mu.Lock()
  356. v, found := c.items[k]
  357. if !found || v.Expired() {
  358. c.mu.Unlock()
  359. return 0, fmt.Errorf("Item %s not found", k)
  360. }
  361. if c.maxItems > 0 {
  362. v.Accessed = time.Now().UnixNano()
  363. }
  364. rv, ok := v.Object.(int)
  365. if !ok {
  366. c.mu.Unlock()
  367. return 0, fmt.Errorf("The value for %s is not an int", k)
  368. }
  369. nv := rv + n
  370. v.Object = nv
  371. c.items[k] = v
  372. c.mu.Unlock()
  373. return nv, nil
  374. }
  375. // Increment an item of type int8 by n. Returns an error if the item's value is
  376. // not an int8, or if it was not found. If there is no error, the incremented
  377. // value is returned.
  378. func (c *cache) IncrementInt8(k string, n int8) (int8, error) {
  379. c.mu.Lock()
  380. v, found := c.items[k]
  381. if !found || v.Expired() {
  382. c.mu.Unlock()
  383. return 0, fmt.Errorf("Item %s not found", k)
  384. }
  385. if c.maxItems > 0 {
  386. v.Accessed = time.Now().UnixNano()
  387. }
  388. rv, ok := v.Object.(int8)
  389. if !ok {
  390. c.mu.Unlock()
  391. return 0, fmt.Errorf("The value for %s is not an int8", k)
  392. }
  393. nv := rv + n
  394. v.Object = nv
  395. c.items[k] = v
  396. c.mu.Unlock()
  397. return nv, nil
  398. }
  399. // Increment an item of type int16 by n. Returns an error if the item's value is
  400. // not an int16, or if it was not found. If there is no error, the incremented
  401. // value is returned.
  402. func (c *cache) IncrementInt16(k string, n int16) (int16, error) {
  403. c.mu.Lock()
  404. v, found := c.items[k]
  405. if !found || v.Expired() {
  406. c.mu.Unlock()
  407. return 0, fmt.Errorf("Item %s not found", k)
  408. }
  409. if c.maxItems > 0 {
  410. v.Accessed = time.Now().UnixNano()
  411. }
  412. rv, ok := v.Object.(int16)
  413. if !ok {
  414. c.mu.Unlock()
  415. return 0, fmt.Errorf("The value for %s is not an int16", k)
  416. }
  417. nv := rv + n
  418. v.Object = nv
  419. c.items[k] = v
  420. c.mu.Unlock()
  421. return nv, nil
  422. }
  423. // Increment an item of type int32 by n. Returns an error if the item's value is
  424. // not an int32, or if it was not found. If there is no error, the incremented
  425. // value is returned.
  426. func (c *cache) IncrementInt32(k string, n int32) (int32, error) {
  427. c.mu.Lock()
  428. v, found := c.items[k]
  429. if !found || v.Expired() {
  430. c.mu.Unlock()
  431. return 0, fmt.Errorf("Item %s not found", k)
  432. }
  433. if c.maxItems > 0 {
  434. v.Accessed = time.Now().UnixNano()
  435. }
  436. rv, ok := v.Object.(int32)
  437. if !ok {
  438. c.mu.Unlock()
  439. return 0, fmt.Errorf("The value for %s is not an int32", k)
  440. }
  441. nv := rv + n
  442. v.Object = nv
  443. c.items[k] = v
  444. c.mu.Unlock()
  445. return nv, nil
  446. }
  447. // Increment an item of type int64 by n. Returns an error if the item's value is
  448. // not an int64, or if it was not found. If there is no error, the incremented
  449. // value is returned.
  450. func (c *cache) IncrementInt64(k string, n int64) (int64, error) {
  451. c.mu.Lock()
  452. v, found := c.items[k]
  453. if !found || v.Expired() {
  454. c.mu.Unlock()
  455. return 0, fmt.Errorf("Item %s not found", k)
  456. }
  457. if c.maxItems > 0 {
  458. v.Accessed = time.Now().UnixNano()
  459. }
  460. rv, ok := v.Object.(int64)
  461. if !ok {
  462. c.mu.Unlock()
  463. return 0, fmt.Errorf("The value for %s is not an int64", k)
  464. }
  465. nv := rv + n
  466. v.Object = nv
  467. c.items[k] = v
  468. c.mu.Unlock()
  469. return nv, nil
  470. }
  471. // Increment an item of type uint by n. Returns an error if the item's value is
  472. // not an uint, or if it was not found. If there is no error, the incremented
  473. // value is returned.
  474. func (c *cache) IncrementUint(k string, n uint) (uint, error) {
  475. c.mu.Lock()
  476. v, found := c.items[k]
  477. if !found || v.Expired() {
  478. c.mu.Unlock()
  479. return 0, fmt.Errorf("Item %s not found", k)
  480. }
  481. if c.maxItems > 0 {
  482. v.Accessed = time.Now().UnixNano()
  483. }
  484. rv, ok := v.Object.(uint)
  485. if !ok {
  486. c.mu.Unlock()
  487. return 0, fmt.Errorf("The value for %s is not an uint", k)
  488. }
  489. nv := rv + n
  490. v.Object = nv
  491. c.items[k] = v
  492. c.mu.Unlock()
  493. return nv, nil
  494. }
  495. // Increment an item of type uintptr by n. Returns an error if the item's value
  496. // is not an uintptr, or if it was not found. If there is no error, the
  497. // incremented value is returned.
  498. func (c *cache) IncrementUintptr(k string, n uintptr) (uintptr, error) {
  499. c.mu.Lock()
  500. v, found := c.items[k]
  501. if !found || v.Expired() {
  502. c.mu.Unlock()
  503. return 0, fmt.Errorf("Item %s not found", k)
  504. }
  505. if c.maxItems > 0 {
  506. v.Accessed = time.Now().UnixNano()
  507. }
  508. rv, ok := v.Object.(uintptr)
  509. if !ok {
  510. c.mu.Unlock()
  511. return 0, fmt.Errorf("The value for %s is not an uintptr", k)
  512. }
  513. nv := rv + n
  514. v.Object = nv
  515. c.items[k] = v
  516. c.mu.Unlock()
  517. return nv, nil
  518. }
  519. // Increment an item of type uint8 by n. Returns an error if the item's value
  520. // is not an uint8, or if it was not found. If there is no error, the
  521. // incremented value is returned.
  522. func (c *cache) IncrementUint8(k string, n uint8) (uint8, error) {
  523. c.mu.Lock()
  524. v, found := c.items[k]
  525. if !found || v.Expired() {
  526. c.mu.Unlock()
  527. return 0, fmt.Errorf("Item %s not found", k)
  528. }
  529. if c.maxItems > 0 {
  530. v.Accessed = time.Now().UnixNano()
  531. }
  532. rv, ok := v.Object.(uint8)
  533. if !ok {
  534. c.mu.Unlock()
  535. return 0, fmt.Errorf("The value for %s is not an uint8", k)
  536. }
  537. nv := rv + n
  538. v.Object = nv
  539. c.items[k] = v
  540. c.mu.Unlock()
  541. return nv, nil
  542. }
  543. // Increment an item of type uint16 by n. Returns an error if the item's value
  544. // is not an uint16, or if it was not found. If there is no error, the
  545. // incremented value is returned.
  546. func (c *cache) IncrementUint16(k string, n uint16) (uint16, error) {
  547. c.mu.Lock()
  548. v, found := c.items[k]
  549. if !found || v.Expired() {
  550. c.mu.Unlock()
  551. return 0, fmt.Errorf("Item %s not found", k)
  552. }
  553. if c.maxItems > 0 {
  554. v.Accessed = time.Now().UnixNano()
  555. }
  556. rv, ok := v.Object.(uint16)
  557. if !ok {
  558. c.mu.Unlock()
  559. return 0, fmt.Errorf("The value for %s is not an uint16", k)
  560. }
  561. nv := rv + n
  562. v.Object = nv
  563. c.items[k] = v
  564. c.mu.Unlock()
  565. return nv, nil
  566. }
  567. // Increment an item of type uint32 by n. Returns an error if the item's value
  568. // is not an uint32, or if it was not found. If there is no error, the
  569. // incremented value is returned.
  570. func (c *cache) IncrementUint32(k string, n uint32) (uint32, error) {
  571. c.mu.Lock()
  572. v, found := c.items[k]
  573. if !found || v.Expired() {
  574. c.mu.Unlock()
  575. return 0, fmt.Errorf("Item %s not found", k)
  576. }
  577. if c.maxItems > 0 {
  578. v.Accessed = time.Now().UnixNano()
  579. }
  580. rv, ok := v.Object.(uint32)
  581. if !ok {
  582. c.mu.Unlock()
  583. return 0, fmt.Errorf("The value for %s is not an uint32", k)
  584. }
  585. nv := rv + n
  586. v.Object = nv
  587. c.items[k] = v
  588. c.mu.Unlock()
  589. return nv, nil
  590. }
  591. // Increment an item of type uint64 by n. Returns an error if the item's value
  592. // is not an uint64, or if it was not found. If there is no error, the
  593. // incremented value is returned.
  594. func (c *cache) IncrementUint64(k string, n uint64) (uint64, error) {
  595. c.mu.Lock()
  596. v, found := c.items[k]
  597. if !found || v.Expired() {
  598. c.mu.Unlock()
  599. return 0, fmt.Errorf("Item %s not found", k)
  600. }
  601. if c.maxItems > 0 {
  602. v.Accessed = time.Now().UnixNano()
  603. }
  604. rv, ok := v.Object.(uint64)
  605. if !ok {
  606. c.mu.Unlock()
  607. return 0, fmt.Errorf("The value for %s is not an uint64", k)
  608. }
  609. nv := rv + n
  610. v.Object = nv
  611. c.items[k] = v
  612. c.mu.Unlock()
  613. return nv, nil
  614. }
  615. // Increment an item of type float32 by n. Returns an error if the item's value
  616. // is not an float32, or if it was not found. If there is no error, the
  617. // incremented value is returned.
  618. func (c *cache) IncrementFloat32(k string, n float32) (float32, error) {
  619. c.mu.Lock()
  620. v, found := c.items[k]
  621. if !found || v.Expired() {
  622. c.mu.Unlock()
  623. return 0, fmt.Errorf("Item %s not found", k)
  624. }
  625. if c.maxItems > 0 {
  626. v.Accessed = time.Now().UnixNano()
  627. }
  628. rv, ok := v.Object.(float32)
  629. if !ok {
  630. c.mu.Unlock()
  631. return 0, fmt.Errorf("The value for %s is not an float32", k)
  632. }
  633. nv := rv + n
  634. v.Object = nv
  635. c.items[k] = v
  636. c.mu.Unlock()
  637. return nv, nil
  638. }
  639. // Increment an item of type float64 by n. Returns an error if the item's value
  640. // is not an float64, or if it was not found. If there is no error, the
  641. // incremented value is returned.
  642. func (c *cache) IncrementFloat64(k string, n float64) (float64, error) {
  643. c.mu.Lock()
  644. v, found := c.items[k]
  645. if !found || v.Expired() {
  646. c.mu.Unlock()
  647. return 0, fmt.Errorf("Item %s not found", k)
  648. }
  649. if c.maxItems > 0 {
  650. v.Accessed = time.Now().UnixNano()
  651. }
  652. rv, ok := v.Object.(float64)
  653. if !ok {
  654. c.mu.Unlock()
  655. return 0, fmt.Errorf("The value for %s is not an float64", k)
  656. }
  657. nv := rv + n
  658. v.Object = nv
  659. c.items[k] = v
  660. c.mu.Unlock()
  661. return nv, nil
  662. }
  663. // Decrement an item of type int, int8, int16, int32, int64, uintptr, uint,
  664. // uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the
  665. // item's value is not an integer, if it was not found, or if it is not
  666. // possible to decrement it by n. To retrieve the decremented value, use one
  667. // of the specialized methods, e.g. DecrementInt64.
  668. func (c *cache) Decrement(k string, n int64) error {
  669. // TODO: Implement Increment and Decrement more cleanly.
  670. // (Cannot do Increment(k, n*-1) for uints.)
  671. c.mu.Lock()
  672. v, found := c.items[k]
  673. if !found || v.Expired() {
  674. c.mu.Unlock()
  675. return fmt.Errorf("Item not found")
  676. }
  677. if c.maxItems > 0 {
  678. v.Accessed = time.Now().UnixNano()
  679. }
  680. switch v.Object.(type) {
  681. case int:
  682. v.Object = v.Object.(int) - int(n)
  683. case int8:
  684. v.Object = v.Object.(int8) - int8(n)
  685. case int16:
  686. v.Object = v.Object.(int16) - int16(n)
  687. case int32:
  688. v.Object = v.Object.(int32) - int32(n)
  689. case int64:
  690. v.Object = v.Object.(int64) - n
  691. case uint:
  692. v.Object = v.Object.(uint) - uint(n)
  693. case uintptr:
  694. v.Object = v.Object.(uintptr) - uintptr(n)
  695. case uint8:
  696. v.Object = v.Object.(uint8) - uint8(n)
  697. case uint16:
  698. v.Object = v.Object.(uint16) - uint16(n)
  699. case uint32:
  700. v.Object = v.Object.(uint32) - uint32(n)
  701. case uint64:
  702. v.Object = v.Object.(uint64) - uint64(n)
  703. case float32:
  704. v.Object = v.Object.(float32) - float32(n)
  705. case float64:
  706. v.Object = v.Object.(float64) - float64(n)
  707. default:
  708. c.mu.Unlock()
  709. return fmt.Errorf("The value for %s is not an integer", k)
  710. }
  711. c.items[k] = v
  712. c.mu.Unlock()
  713. return nil
  714. }
  715. // Decrement an item of type float32 or float64 by n. Returns an error if the
  716. // item's value is not floating point, if it was not found, or if it is not
  717. // possible to decrement it by n. Pass a negative number to decrement the
  718. // value. To retrieve the decremented value, use one of the specialized methods,
  719. // e.g. DecrementFloat64.
  720. func (c *cache) DecrementFloat(k string, n float64) error {
  721. c.mu.Lock()
  722. v, found := c.items[k]
  723. if !found || v.Expired() {
  724. c.mu.Unlock()
  725. return fmt.Errorf("Item %s not found", k)
  726. }
  727. if c.maxItems > 0 {
  728. v.Accessed = time.Now().UnixNano()
  729. }
  730. switch v.Object.(type) {
  731. case float32:
  732. v.Object = v.Object.(float32) - float32(n)
  733. case float64:
  734. v.Object = v.Object.(float64) - n
  735. default:
  736. c.mu.Unlock()
  737. return fmt.Errorf("The value for %s does not have type float32 or float64", k)
  738. }
  739. c.items[k] = v
  740. c.mu.Unlock()
  741. return nil
  742. }
  743. // Decrement an item of type int by n. Returns an error if the item's value is
  744. // not an int, or if it was not found. If there is no error, the decremented
  745. // value is returned.
  746. func (c *cache) DecrementInt(k string, n int) (int, error) {
  747. c.mu.Lock()
  748. v, found := c.items[k]
  749. if !found || v.Expired() {
  750. c.mu.Unlock()
  751. return 0, fmt.Errorf("Item %s not found", k)
  752. }
  753. if c.maxItems > 0 {
  754. v.Accessed = time.Now().UnixNano()
  755. }
  756. rv, ok := v.Object.(int)
  757. if !ok {
  758. c.mu.Unlock()
  759. return 0, fmt.Errorf("The value for %s is not an int", k)
  760. }
  761. nv := rv - n
  762. v.Object = nv
  763. c.items[k] = v
  764. c.mu.Unlock()
  765. return nv, nil
  766. }
  767. // Decrement an item of type int8 by n. Returns an error if the item's value is
  768. // not an int8, or if it was not found. If there is no error, the decremented
  769. // value is returned.
  770. func (c *cache) DecrementInt8(k string, n int8) (int8, error) {
  771. c.mu.Lock()
  772. v, found := c.items[k]
  773. if !found || v.Expired() {
  774. c.mu.Unlock()
  775. return 0, fmt.Errorf("Item %s not found", k)
  776. }
  777. if c.maxItems > 0 {
  778. v.Accessed = time.Now().UnixNano()
  779. }
  780. rv, ok := v.Object.(int8)
  781. if !ok {
  782. c.mu.Unlock()
  783. return 0, fmt.Errorf("The value for %s is not an int8", k)
  784. }
  785. nv := rv - n
  786. v.Object = nv
  787. c.items[k] = v
  788. c.mu.Unlock()
  789. return nv, nil
  790. }
  791. // Decrement an item of type int16 by n. Returns an error if the item's value is
  792. // not an int16, or if it was not found. If there is no error, the decremented
  793. // value is returned.
  794. func (c *cache) DecrementInt16(k string, n int16) (int16, error) {
  795. c.mu.Lock()
  796. v, found := c.items[k]
  797. if !found || v.Expired() {
  798. c.mu.Unlock()
  799. return 0, fmt.Errorf("Item %s not found", k)
  800. }
  801. if c.maxItems > 0 {
  802. v.Accessed = time.Now().UnixNano()
  803. }
  804. rv, ok := v.Object.(int16)
  805. if !ok {
  806. c.mu.Unlock()
  807. return 0, fmt.Errorf("The value for %s is not an int16", k)
  808. }
  809. nv := rv - n
  810. v.Object = nv
  811. c.items[k] = v
  812. c.mu.Unlock()
  813. return nv, nil
  814. }
  815. // Decrement an item of type int32 by n. Returns an error if the item's value is
  816. // not an int32, or if it was not found. If there is no error, the decremented
  817. // value is returned.
  818. func (c *cache) DecrementInt32(k string, n int32) (int32, error) {
  819. c.mu.Lock()
  820. v, found := c.items[k]
  821. if !found || v.Expired() {
  822. c.mu.Unlock()
  823. return 0, fmt.Errorf("Item %s not found", k)
  824. }
  825. if c.maxItems > 0 {
  826. v.Accessed = time.Now().UnixNano()
  827. }
  828. rv, ok := v.Object.(int32)
  829. if !ok {
  830. c.mu.Unlock()
  831. return 0, fmt.Errorf("The value for %s is not an int32", k)
  832. }
  833. nv := rv - n
  834. v.Object = nv
  835. c.items[k] = v
  836. c.mu.Unlock()
  837. return nv, nil
  838. }
  839. // Decrement an item of type int64 by n. Returns an error if the item's value is
  840. // not an int64, or if it was not found. If there is no error, the decremented
  841. // value is returned.
  842. func (c *cache) DecrementInt64(k string, n int64) (int64, error) {
  843. c.mu.Lock()
  844. v, found := c.items[k]
  845. if !found || v.Expired() {
  846. c.mu.Unlock()
  847. return 0, fmt.Errorf("Item %s not found", k)
  848. }
  849. if c.maxItems > 0 {
  850. v.Accessed = time.Now().UnixNano()
  851. }
  852. rv, ok := v.Object.(int64)
  853. if !ok {
  854. c.mu.Unlock()
  855. return 0, fmt.Errorf("The value for %s is not an int64", k)
  856. }
  857. nv := rv - n
  858. v.Object = nv
  859. c.items[k] = v
  860. c.mu.Unlock()
  861. return nv, nil
  862. }
  863. // Decrement an item of type uint by n. Returns an error if the item's value is
  864. // not an uint, or if it was not found. If there is no error, the decremented
  865. // value is returned.
  866. func (c *cache) DecrementUint(k string, n uint) (uint, error) {
  867. c.mu.Lock()
  868. v, found := c.items[k]
  869. if !found || v.Expired() {
  870. c.mu.Unlock()
  871. return 0, fmt.Errorf("Item %s not found", k)
  872. }
  873. if c.maxItems > 0 {
  874. v.Accessed = time.Now().UnixNano()
  875. }
  876. rv, ok := v.Object.(uint)
  877. if !ok {
  878. c.mu.Unlock()
  879. return 0, fmt.Errorf("The value for %s is not an uint", k)
  880. }
  881. nv := rv - n
  882. v.Object = nv
  883. c.items[k] = v
  884. c.mu.Unlock()
  885. return nv, nil
  886. }
  887. // Decrement an item of type uintptr by n. Returns an error if the item's value
  888. // is not an uintptr, or if it was not found. If there is no error, the
  889. // decremented value is returned.
  890. func (c *cache) DecrementUintptr(k string, n uintptr) (uintptr, error) {
  891. c.mu.Lock()
  892. v, found := c.items[k]
  893. if !found || v.Expired() {
  894. c.mu.Unlock()
  895. return 0, fmt.Errorf("Item %s not found", k)
  896. }
  897. if c.maxItems > 0 {
  898. v.Accessed = time.Now().UnixNano()
  899. }
  900. rv, ok := v.Object.(uintptr)
  901. if !ok {
  902. c.mu.Unlock()
  903. return 0, fmt.Errorf("The value for %s is not an uintptr", k)
  904. }
  905. nv := rv - n
  906. v.Object = nv
  907. c.items[k] = v
  908. c.mu.Unlock()
  909. return nv, nil
  910. }
  911. // Decrement an item of type uint8 by n. Returns an error if the item's value is
  912. // not an uint8, or if it was not found. If there is no error, the decremented
  913. // value is returned.
  914. func (c *cache) DecrementUint8(k string, n uint8) (uint8, error) {
  915. c.mu.Lock()
  916. v, found := c.items[k]
  917. if !found || v.Expired() {
  918. c.mu.Unlock()
  919. return 0, fmt.Errorf("Item %s not found", k)
  920. }
  921. if c.maxItems > 0 {
  922. v.Accessed = time.Now().UnixNano()
  923. }
  924. rv, ok := v.Object.(uint8)
  925. if !ok {
  926. c.mu.Unlock()
  927. return 0, fmt.Errorf("The value for %s is not an uint8", k)
  928. }
  929. nv := rv - n
  930. v.Object = nv
  931. c.items[k] = v
  932. c.mu.Unlock()
  933. return nv, nil
  934. }
  935. // Decrement an item of type uint16 by n. Returns an error if the item's value
  936. // is not an uint16, or if it was not found. If there is no error, the
  937. // decremented value is returned.
  938. func (c *cache) DecrementUint16(k string, n uint16) (uint16, error) {
  939. c.mu.Lock()
  940. v, found := c.items[k]
  941. if !found || v.Expired() {
  942. c.mu.Unlock()
  943. return 0, fmt.Errorf("Item %s not found", k)
  944. }
  945. if c.maxItems > 0 {
  946. v.Accessed = time.Now().UnixNano()
  947. }
  948. rv, ok := v.Object.(uint16)
  949. if !ok {
  950. c.mu.Unlock()
  951. return 0, fmt.Errorf("The value for %s is not an uint16", k)
  952. }
  953. nv := rv - n
  954. v.Object = nv
  955. c.items[k] = v
  956. c.mu.Unlock()
  957. return nv, nil
  958. }
  959. // Decrement an item of type uint32 by n. Returns an error if the item's value
  960. // is not an uint32, or if it was not found. If there is no error, the
  961. // decremented value is returned.
  962. func (c *cache) DecrementUint32(k string, n uint32) (uint32, error) {
  963. c.mu.Lock()
  964. v, found := c.items[k]
  965. if !found || v.Expired() {
  966. c.mu.Unlock()
  967. return 0, fmt.Errorf("Item %s not found", k)
  968. }
  969. if c.maxItems > 0 {
  970. v.Accessed = time.Now().UnixNano()
  971. }
  972. rv, ok := v.Object.(uint32)
  973. if !ok {
  974. c.mu.Unlock()
  975. return 0, fmt.Errorf("The value for %s is not an uint32", k)
  976. }
  977. nv := rv - n
  978. v.Object = nv
  979. c.items[k] = v
  980. c.mu.Unlock()
  981. return nv, nil
  982. }
  983. // Decrement an item of type uint64 by n. Returns an error if the item's value
  984. // is not an uint64, or if it was not found. If there is no error, the
  985. // decremented value is returned.
  986. func (c *cache) DecrementUint64(k string, n uint64) (uint64, error) {
  987. c.mu.Lock()
  988. v, found := c.items[k]
  989. if !found || v.Expired() {
  990. c.mu.Unlock()
  991. return 0, fmt.Errorf("Item %s not found", k)
  992. }
  993. if c.maxItems > 0 {
  994. v.Accessed = time.Now().UnixNano()
  995. }
  996. rv, ok := v.Object.(uint64)
  997. if !ok {
  998. c.mu.Unlock()
  999. return 0, fmt.Errorf("The value for %s is not an uint64", k)
  1000. }
  1001. nv := rv - n
  1002. v.Object = nv
  1003. c.items[k] = v
  1004. c.mu.Unlock()
  1005. return nv, nil
  1006. }
  1007. // Decrement an item of type float32 by n. Returns an error if the item's value
  1008. // is not an float32, or if it was not found. If there is no error, the
  1009. // decremented value is returned.
  1010. func (c *cache) DecrementFloat32(k string, n float32) (float32, error) {
  1011. c.mu.Lock()
  1012. v, found := c.items[k]
  1013. if !found || v.Expired() {
  1014. c.mu.Unlock()
  1015. return 0, fmt.Errorf("Item %s not found", k)
  1016. }
  1017. if c.maxItems > 0 {
  1018. v.Accessed = time.Now().UnixNano()
  1019. }
  1020. rv, ok := v.Object.(float32)
  1021. if !ok {
  1022. c.mu.Unlock()
  1023. return 0, fmt.Errorf("The value for %s is not an float32", k)
  1024. }
  1025. nv := rv - n
  1026. v.Object = nv
  1027. c.items[k] = v
  1028. c.mu.Unlock()
  1029. return nv, nil
  1030. }
  1031. // Decrement an item of type float64 by n. Returns an error if the item's value
  1032. // is not an float64, or if it was not found. If there is no error, the
  1033. // decremented value is returned.
  1034. func (c *cache) DecrementFloat64(k string, n float64) (float64, error) {
  1035. c.mu.Lock()
  1036. v, found := c.items[k]
  1037. if !found || v.Expired() {
  1038. c.mu.Unlock()
  1039. return 0, fmt.Errorf("Item %s not found", k)
  1040. }
  1041. if c.maxItems > 0 {
  1042. v.Accessed = time.Now().UnixNano()
  1043. }
  1044. rv, ok := v.Object.(float64)
  1045. if !ok {
  1046. c.mu.Unlock()
  1047. return 0, fmt.Errorf("The value for %s is not an float64", k)
  1048. }
  1049. nv := rv - n
  1050. v.Object = nv
  1051. c.items[k] = v
  1052. c.mu.Unlock()
  1053. return nv, nil
  1054. }
  1055. // Delete an item from the cache. Does nothing if the key is not in the cache.
  1056. func (c *cache) Delete(k string) {
  1057. c.mu.Lock()
  1058. v, evicted := c.delete(k)
  1059. evictFunc := c.onEvicted
  1060. c.mu.Unlock()
  1061. if evicted {
  1062. evictFunc(k, v)
  1063. }
  1064. }
  1065. func (c *cache) delete(k string) (interface{}, bool) {
  1066. if c.onEvicted != nil {
  1067. if v, found := c.items[k]; found {
  1068. delete(c.items, k)
  1069. return v.Object, true
  1070. }
  1071. }
  1072. delete(c.items, k)
  1073. return nil, false
  1074. }
  1075. type keyAndValue struct {
  1076. key string
  1077. value interface{}
  1078. }
  1079. // Delete all expired items from the cache.
  1080. func (c *cache) DeleteExpired() {
  1081. var evictedItems []keyAndValue
  1082. now := time.Now().UnixNano()
  1083. c.mu.Lock()
  1084. evictFunc := c.onEvicted
  1085. for k, v := range c.items {
  1086. // "Inlining" of Expired
  1087. if v.Expiration > 0 && now > v.Expiration {
  1088. ov, evicted := c.delete(k)
  1089. if evicted {
  1090. evictedItems = append(evictedItems, keyAndValue{k, ov})
  1091. }
  1092. }
  1093. }
  1094. c.mu.Unlock()
  1095. for _, v := range evictedItems {
  1096. evictFunc(v.key, v.value)
  1097. }
  1098. }
  1099. // Sets an (optional) function that is called with the key and value when an
  1100. // item is evicted from the cache. (Including when it is deleted manually, but
  1101. // not when it is overwritten.) Set to nil to disable.
  1102. func (c *cache) OnEvicted(f func(string, interface{})) {
  1103. c.mu.Lock()
  1104. c.onEvicted = f
  1105. c.mu.Unlock()
  1106. }
  1107. // Delete some of the oldest items in the cache if the soft size limit has been
  1108. // exceeded.
  1109. func (c *cache) DeleteLRU() {
  1110. c.mu.Lock()
  1111. var (
  1112. overCount = c.itemCount() - c.maxItems
  1113. evictFunc = c.onEvicted
  1114. )
  1115. evicted := c.deleteLRUAmount(overCount)
  1116. c.mu.Unlock()
  1117. for _, v := range evicted {
  1118. evictFunc(v.key, v.value)
  1119. }
  1120. }
  1121. // Delete a number of the oldest items from the cache.
  1122. func (c *cache) DeleteLRUAmount(numItems int) {
  1123. c.mu.Lock()
  1124. evictFunc := c.onEvicted
  1125. evicted := c.deleteLRUAmount(numItems)
  1126. c.mu.Unlock()
  1127. for _, v := range evicted {
  1128. evictFunc(v.key, v.value)
  1129. }
  1130. }
  1131. func (c *cache) deleteLRUAmount(numItems int) []keyAndValue {
  1132. if numItems <= 0 {
  1133. return nil
  1134. }
  1135. var (
  1136. lastTime int64 = 0
  1137. lastItems = make([]string, numItems) // Ring buffer
  1138. liCount = 0
  1139. full = false
  1140. evictedItems []keyAndValue
  1141. now = time.Now().UnixNano()
  1142. )
  1143. if c.onEvicted != nil {
  1144. evictedItems = make([]keyAndValue, 0, numItems)
  1145. }
  1146. for k, v := range c.items {
  1147. // "Inlining" of !Expired
  1148. if v.Expiration == 0 || now <= v.Expiration {
  1149. if full == false || v.Accessed < lastTime {
  1150. // We found a least-recently-used item, or our
  1151. // purge buffer isn't full yet
  1152. lastTime = v.Accessed
  1153. // Append it to the buffer, or start overwriting
  1154. // it
  1155. if liCount < numItems {
  1156. lastItems[liCount] = k
  1157. liCount++
  1158. } else {
  1159. lastItems[0] = k
  1160. liCount = 1
  1161. full = true
  1162. }
  1163. }
  1164. }
  1165. }
  1166. if lastTime > 0 {
  1167. for _, v := range lastItems {
  1168. if v != "" {
  1169. ov, evicted := c.delete(v)
  1170. if evicted {
  1171. evictedItems = append(evictedItems, keyAndValue{v, ov})
  1172. }
  1173. }
  1174. }
  1175. }
  1176. return evictedItems
  1177. }
  1178. // Write the cache's items (using Gob) to an io.Writer.
  1179. //
  1180. // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
  1181. // documentation for NewFrom().)
  1182. func (c *cache) Save(w io.Writer) (err error) {
  1183. enc := gob.NewEncoder(w)
  1184. defer func() {
  1185. if x := recover(); x != nil {
  1186. err = fmt.Errorf("Error registering item types with Gob library")
  1187. }
  1188. }()
  1189. c.mu.RLock()
  1190. defer c.mu.RUnlock()
  1191. for _, v := range c.items {
  1192. gob.Register(v.Object)
  1193. }
  1194. err = enc.Encode(&c.items)
  1195. return
  1196. }
  1197. // Save the cache's items to the given filename, creating the file if it
  1198. // doesn't exist, and overwriting it if it does.
  1199. //
  1200. // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
  1201. // documentation for NewFrom().)
  1202. func (c *cache) SaveFile(fname string) error {
  1203. fp, err := os.Create(fname)
  1204. if err != nil {
  1205. return err
  1206. }
  1207. err = c.Save(fp)
  1208. if err != nil {
  1209. fp.Close()
  1210. return err
  1211. }
  1212. return fp.Close()
  1213. }
  1214. // Add (Gob-serialized) cache items from an io.Reader, excluding any items with
  1215. // keys that already exist (and haven't expired) in the current cache.
  1216. //
  1217. // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
  1218. // documentation for NewFrom().)
  1219. func (c *cache) Load(r io.Reader) error {
  1220. dec := gob.NewDecoder(r)
  1221. items := map[string]Item{}
  1222. err := dec.Decode(&items)
  1223. if err == nil {
  1224. c.mu.Lock()
  1225. defer c.mu.Unlock()
  1226. for k, v := range items {
  1227. ov, found := c.items[k]
  1228. if !found || ov.Expired() {
  1229. c.items[k] = v
  1230. }
  1231. }
  1232. }
  1233. return err
  1234. }
  1235. // Load and add cache items from the given filename, excluding any items with
  1236. // keys that already exist in the current cache.
  1237. //
  1238. // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
  1239. // documentation for NewFrom().)
  1240. func (c *cache) LoadFile(fname string) error {
  1241. fp, err := os.Open(fname)
  1242. if err != nil {
  1243. return err
  1244. }
  1245. err = c.Load(fp)
  1246. if err != nil {
  1247. fp.Close()
  1248. return err
  1249. }
  1250. return fp.Close()
  1251. }
  1252. // Copies all unexpired items in the cache into a new map and returns it.
  1253. func (c *cache) Items() map[string]Item {
  1254. c.mu.RLock()
  1255. defer c.mu.RUnlock()
  1256. m := make(map[string]Item, len(c.items))
  1257. now := time.Now().UnixNano()
  1258. for k, v := range c.items {
  1259. // "Inlining" of Expired
  1260. if v.Expiration > 0 {
  1261. if now > v.Expiration {
  1262. continue
  1263. }
  1264. }
  1265. m[k] = v
  1266. }
  1267. return m
  1268. }
  1269. // Returns the number of items in the cache. This may include items that have
  1270. // expired, but have not yet been cleaned up.
  1271. func (c *cache) ItemCount() int {
  1272. c.mu.RLock()
  1273. n := len(c.items)
  1274. c.mu.RUnlock()
  1275. return n
  1276. }
  1277. // Returns the number of items in the cache without locking. This may include
  1278. // items that have expired, but have not yet been cleaned up. Equivalent to
  1279. // len(c.Items()).
  1280. func (c *cache) itemCount() int {
  1281. n := len(c.items)
  1282. return n
  1283. }
  1284. // Delete all items from the cache.
  1285. func (c *cache) Flush() {
  1286. c.mu.Lock()
  1287. c.items = map[string]Item{}
  1288. c.mu.Unlock()
  1289. }
  1290. type janitor struct {
  1291. Interval time.Duration
  1292. stop chan bool
  1293. }
  1294. func (j *janitor) Run(c *cache) {
  1295. j.stop = make(chan bool)
  1296. ticker := time.NewTicker(j.Interval)
  1297. for {
  1298. select {
  1299. case <-ticker.C:
  1300. c.DeleteExpired()
  1301. if c.maxItems > 0 {
  1302. c.DeleteLRU()
  1303. }
  1304. case <-j.stop:
  1305. ticker.Stop()
  1306. return
  1307. }
  1308. }
  1309. }
  1310. func stopJanitor(c *Cache) {
  1311. c.janitor.stop <- true
  1312. }
  1313. func runJanitor(c *cache, ci time.Duration) {
  1314. j := &janitor{
  1315. Interval: ci,
  1316. }
  1317. c.janitor = j
  1318. go j.Run(c)
  1319. }
  1320. func newCache(de time.Duration, m map[string]Item, mi int) *cache {
  1321. if de == 0 {
  1322. de = -1
  1323. }
  1324. c := &cache{
  1325. defaultExpiration: de,
  1326. maxItems: mi,
  1327. items: m,
  1328. }
  1329. return c
  1330. }
  1331. func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item, mi int) *Cache {
  1332. c := newCache(de, m, mi)
  1333. // This trick ensures that the janitor goroutine (which--granted it
  1334. // was enabled--is running DeleteExpired on c forever) does not keep
  1335. // the returned C object from being garbage collected. When it is
  1336. // garbage collected, the finalizer stops the janitor goroutine, after
  1337. // which c can be collected.
  1338. C := &Cache{c}
  1339. if ci > 0 {
  1340. runJanitor(c, ci)
  1341. runtime.SetFinalizer(C, stopJanitor)
  1342. }
  1343. return C
  1344. }
  1345. // Return a new cache with a given default expiration duration and cleanup
  1346. // interval. If the expiration duration is less than one (or NoExpiration),
  1347. // the items in the cache never expire (by default), and must be deleted
  1348. // manually. If the cleanup interval is less than one, expired items are not
  1349. // deleted from the cache before calling c.DeleteExpired().
  1350. func New(defaultExpiration, cleanupInterval time.Duration) *Cache {
  1351. items := make(map[string]Item)
  1352. return newCacheWithJanitor(defaultExpiration, cleanupInterval, items, 0)
  1353. }
  1354. // Return a new cache with a given default expiration duration, cleanup
  1355. // interval, and maximum-ish number of items. If the expiration duration
  1356. // is less than one (or NoExpiration), the items in the cache never expire
  1357. // (by default), and must be deleted manually. If the cleanup interval is
  1358. // less than one, expired items are not deleted from the cache before
  1359. // calling c.DeleteExpired(), c.DeleteLRU(), or c.DeleteLRUAmount(). If maxItems
  1360. // is not greater than zero, then there will be no soft cap on the number of
  1361. // items in the cache.
  1362. //
  1363. // Using the LRU functionality makes Get() a slower, write-locked operation.
  1364. func NewWithLRU(defaultExpiration, cleanupInterval time.Duration, maxItems int) *Cache {
  1365. items := make(map[string]Item)
  1366. return newCacheWithJanitor(defaultExpiration, cleanupInterval, items, maxItems)
  1367. }
  1368. // Return a new cache with a given default expiration duration and cleanup
  1369. // interval. If the expiration duration is less than one (or NoExpiration),
  1370. // the items in the cache never expire (by default), and must be deleted
  1371. // manually. If the cleanup interval is less than one, expired items are not
  1372. // deleted from the cache before calling c.DeleteExpired().
  1373. //
  1374. // NewFrom() also accepts an items map which will serve as the underlying map
  1375. // for the cache. This is useful for starting from a deserialized cache
  1376. // (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g.
  1377. // make(map[string]Item, 500) to improve startup performance when the cache
  1378. // is expected to reach a certain minimum size.
  1379. //
  1380. // Only the cache's methods synchronize access to this map, so it is not
  1381. // recommended to keep any references to the map around after creating a cache.
  1382. // If need be, the map can be accessed at a later point using c.Items() (subject
  1383. // to the same caveat.)
  1384. //
  1385. // Note regarding serialization: When using e.g. gob, make sure to
  1386. // gob.Register() the individual types stored in the cache before encoding a
  1387. // map retrieved with c.Items(), and to register those same types before
  1388. // decoding a blob containing an items map.
  1389. func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache {
  1390. return newCacheWithJanitor(defaultExpiration, cleanupInterval, items, 0)
  1391. }
  1392. // Similar to NewFrom, but creates a cache with LRU functionality enabled.
  1393. func NewFromWithLRU(defaultExpiration, cleanupInterval time.Duration, items map[string]Item, maxItems int) *Cache {
  1394. return newCacheWithJanitor(defaultExpiration, cleanupInterval, items, maxItems)
  1395. }