/
duration.go
79 lines (67 loc) · 1.42 KB
/
duration.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
package types
import (
"encoding/json"
"fmt"
)
// Duration represents a duration between start and end
type Duration struct {
Start Timestamp `json:"s"`
End Timestamp `json:"e"`
}
func NewDuration(start Timestamp, end Timestamp) *Duration {
return &Duration{Start: start, End: end}
}
func (d *Duration) ContainTime(time Timestamp) bool {
if d.Start > time {
return false
}
return d.End >= time
}
func (d *Duration) Contain(other *Duration) bool {
if d.Start > other.Start {
return false
}
return d.End >= other.End
}
func (d *Duration) Contained(other *Duration) bool {
if d.Start < other.Start {
return false
}
return d.End <= other.End
}
func (d *Duration) ToJson() []byte {
durationJson, err := json.Marshal(d)
if err != nil {
fmt.Println(err)
}
return durationJson
}
func (d *Duration) ToBytes() []byte {
durBytes := append(d.Start.Bytes(), d.End.Bytes()...)
return durBytes
}
func (d *Duration) DeepCopy() *Duration {
dCopy := &Duration{
Start: d.Start.DeepCopy(),
End: d.End.DeepCopy(),
}
return dCopy
}
func (d *Duration) ToString() string {
return string(d.ToJson())
}
func (d *Duration) ToMap() map[string]interface{} {
dMap := make(map[string]interface{})
dMap["s"] = d.Start
dMap["e"] = d.End
return dMap
}
func GenerateTestDuration() *Duration {
start := RandomTimestamp()
end := RandomTimestamp()
if start > end {
start, end = end, start
}
d := NewDuration(start, end)
return d
}