-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexpiration.go
71 lines (60 loc) · 2.21 KB
/
expiration.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package imcache
import "time"
const noExp = -1
type expiration struct {
date int64
sliding time.Duration
}
// Expiration is the expiration time of an entry.
type Expiration interface {
new(now time.Time, defaultExp time.Duration, sliding bool) expiration
}
type expirationf func(time.Time, time.Duration, bool) expiration
func (f expirationf) new(now time.Time, defaultExp time.Duration, sliding bool) expiration {
return f(now, defaultExp, sliding)
}
// WithExpiration returns an Expiration that sets the expiration time
// to now + d.
func WithExpiration(d time.Duration) Expiration {
return expirationf(func(now time.Time, _ time.Duration, _ bool) expiration {
return expiration{date: now.Add(d).UnixNano()}
})
}
// WithExpirationDate returns an Expiration that sets the expiration time to t.
func WithExpirationDate(t time.Time) Expiration {
return expirationf(func(_ time.Time, _ time.Duration, _ bool) expiration {
return expiration{date: t.UnixNano()}
})
}
// WithSlidingExpiration returns an Expiration that sets the expiration time to
// now + d and sets the sliding expiration to d.
//
// The sliding expiration is the time after which the entry is considered
// expired if it has not been accessed. If the entry has been accessed,
// the expiration time is reset to now + d where now is the time of the access.
func WithSlidingExpiration(d time.Duration) Expiration {
return expirationf(func(now time.Time, _ time.Duration, _ bool) expiration {
return expiration{date: now.Add(d).UnixNano(), sliding: d}
})
}
// WithNoExpiration returns an Expiration that sets the expiration time
// to never expire.
func WithNoExpiration() Expiration {
return expirationf(func(_ time.Time, _ time.Duration, _ bool) expiration {
return expiration{date: noExp}
})
}
// WithDefaultExpiration returns an Expiration that sets the expiration time
// to the default expiration time.
func WithDefaultExpiration() Expiration {
return expirationf(func(now time.Time, defaultExp time.Duration, sliding bool) expiration {
if defaultExp == noExp {
return expiration{date: noExp}
}
var slidingExp time.Duration
if sliding {
slidingExp = defaultExp
}
return expiration{date: now.Add(defaultExp).UnixNano(), sliding: slidingExp}
})
}