|
| 1 | +/* |
| 2 | +Copyright 2024 the Unikorn Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package cache |
| 18 | + |
| 19 | +import ( |
| 20 | + "time" |
| 21 | +) |
| 22 | + |
| 23 | +// TimeoutCache provides a cache with timeout. |
| 24 | +type TimeoutCache[V any] struct { |
| 25 | + value V |
| 26 | + refresh time.Duration |
| 27 | + invalid time.Time |
| 28 | +} |
| 29 | + |
| 30 | +// New gets a new cache. |
| 31 | +func New[V any](refresh time.Duration) *TimeoutCache[V] { |
| 32 | + return &TimeoutCache[V]{ |
| 33 | + refresh: refresh, |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// Get returns the cached value if set and it hasn't timed out |
| 38 | +// and returns true. If it has timed out, it will return V's |
| 39 | +// zero value and false, and will need to be set again. |
| 40 | +// |
| 41 | +//nolint:nonamedreturns |
| 42 | +func (m *TimeoutCache[V]) Get() (value V, ok bool) { |
| 43 | + if time.Now().After(m.invalid) { |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + return m.value, true |
| 48 | +} |
| 49 | + |
| 50 | +// Set remembers the value and resets the invalid time based |
| 51 | +// on when the cache was set. |
| 52 | +func (m *TimeoutCache[V]) Set(value V) { |
| 53 | + m.invalid = time.Now().Add(m.refresh) |
| 54 | + m.value = value |
| 55 | +} |
0 commit comments