-
Notifications
You must be signed in to change notification settings - Fork 1
/
timed.go
94 lines (80 loc) · 2.28 KB
/
timed.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package gg
import (
"time"
)
/*
Shortcut for creating a `Timed` with the given value, using the current
timestamp.
*/
func TimedVal[A any](val A) (out Timed[A]) {
out.Set(val)
return
}
/*
Describes an arbitrary value with a timestamp. The timestamp indicates when the
value was obtained. In JSON encoding and decoding, acts as a transparent
proxy/reference/pointer to the inner value.
*/
type Timed[A any] struct {
Val A `role:"ref"`
Inst time.Time
}
// True if timestamp is unset.
func (self Timed[_]) IsNull() bool { return self.Inst.IsZero() }
// Inverse of `.IsNull`.
func (self Timed[_]) IsNotNull() bool { return !self.Inst.IsZero() }
// Implement `Clearer`. Zeroes the receiver.
func (self *Timed[_]) Clear() { PtrClear(self) }
// Implement `Getter`, returning the underlying value as-is.
func (self Timed[A]) Get() A { return self.Val }
/*
Implement `Setter`. Modifies the underlying value and sets the current
timestamp. The resulting state is considered non-null even if the value
is "zero".
*/
func (self *Timed[A]) Set(val A) {
self.Val = val
self.Inst = time.Now()
}
// Implement `Ptrer`, returning a pointer to the underlying value.
func (self *Timed[A]) Ptr() *A {
if self == nil {
return nil
}
return &self.Val
}
/*
Implement `json.Marshaler`. If `.IsNull`, returns a representation of JSON null.
Otherwise uses `json.Marshal` to encode the underlying value.
*/
func (self Timed[A]) MarshalJSON() ([]byte, error) {
return JsonBytesNullCatch[A](self)
}
/*
Implement `json.Unmarshaler`. If the input is empty or represents JSON null,
clears the receiver via `.Clear`. Otherwise uses `JsonDecodeCatch` to decode
into the underlying value, and sets the current timestamp on success.
*/
func (self *Timed[_]) UnmarshalJSON(src []byte) error {
if IsJsonEmpty(src) {
self.Clear()
return nil
}
return self.with(JsonDecodeCatch(src, &self.Val))
}
// True if the timestamp is unset, or if timestamp + duration > now.
func (self Timed[_]) IsExpired(dur time.Duration) bool {
return self.Inst.IsZero() || self.Inst.Add(dur).Before(time.Now())
}
// Inverse of `.IsExpired`.
func (self Timed[_]) IsLive(dur time.Duration) bool {
return !self.IsExpired(dur)
}
func (self *Timed[_]) with(err error) error {
if err != nil {
PtrClear(&self.Inst)
} else {
self.Inst = time.Now()
}
return err
}