blob: 739afffe2fd03ee113276b2556042bbc1855a1e6 [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001package json
2
3import (
4 "strconv"
5 "time"
6)
7
8// AppendTime formats the input time with the given format
9// and appends the encoded string to the input byte slice.
10func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte {
11 if format == "" {
12 return e.AppendInt64(dst, t.Unix())
13 }
14 return append(t.AppendFormat(append(dst, '"'), format), '"')
15}
16
17// AppendTimes converts the input times with the given format
18// and appends the encoded string list to the input byte slice.
19func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte {
20 if format == "" {
21 return appendUnixTimes(dst, vals)
22 }
23 if len(vals) == 0 {
24 return append(dst, '[', ']')
25 }
26 dst = append(dst, '[')
27 dst = append(vals[0].AppendFormat(append(dst, '"'), format), '"')
28 if len(vals) > 1 {
29 for _, t := range vals[1:] {
30 dst = append(t.AppendFormat(append(dst, ',', '"'), format), '"')
31 }
32 }
33 dst = append(dst, ']')
34 return dst
35}
36
37func appendUnixTimes(dst []byte, vals []time.Time) []byte {
38 if len(vals) == 0 {
39 return append(dst, '[', ']')
40 }
41 dst = append(dst, '[')
42 dst = strconv.AppendInt(dst, vals[0].Unix(), 10)
43 if len(vals) > 1 {
44 for _, t := range vals[1:] {
45 dst = strconv.AppendInt(append(dst, ','), t.Unix(), 10)
46 }
47 }
48 dst = append(dst, ']')
49 return dst
50}
51
52// AppendDuration formats the input duration with the given unit & format
53// and appends the encoded string to the input byte slice.
54func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte {
55 if useInt {
56 return strconv.AppendInt(dst, int64(d/unit), 10)
57 }
58 return e.AppendFloat64(dst, float64(d)/float64(unit))
59}
60
61// AppendDurations formats the input durations with the given unit & format
62// and appends the encoded string list to the input byte slice.
63func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte {
64 if len(vals) == 0 {
65 return append(dst, '[', ']')
66 }
67 dst = append(dst, '[')
68 dst = e.AppendDuration(dst, vals[0], unit, useInt)
69 if len(vals) > 1 {
70 for _, d := range vals[1:] {
71 dst = e.AppendDuration(append(dst, ','), d, unit, useInt)
72 }
73 }
74 dst = append(dst, ']')
75 return dst
76}