time.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. import (
  5. "fmt"
  6. "time"
  7. )
  8. var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  9. type timeExt struct{}
  10. func (x timeExt) WriteExt(v interface{}) (bs []byte) {
  11. switch v2 := v.(type) {
  12. case time.Time:
  13. bs = encodeTime(v2)
  14. case *time.Time:
  15. bs = encodeTime(*v2)
  16. default:
  17. panic(fmt.Errorf("unsupported format for time conversion: expecting time.Time; got %T", v2))
  18. }
  19. return
  20. }
  21. func (x timeExt) ReadExt(v interface{}, bs []byte) {
  22. tt, err := decodeTime(bs)
  23. if err != nil {
  24. panic(err)
  25. }
  26. *(v.(*time.Time)) = tt
  27. }
  28. func (x timeExt) ConvertExt(v interface{}) interface{} {
  29. return x.WriteExt(v)
  30. }
  31. func (x timeExt) UpdateExt(v interface{}, src interface{}) {
  32. x.ReadExt(v, src.([]byte))
  33. }
  34. // EncodeTime encodes a time.Time as a []byte, including
  35. // information on the instant in time and UTC offset.
  36. //
  37. // Format Description
  38. //
  39. // A timestamp is composed of 3 components:
  40. //
  41. // - secs: signed integer representing seconds since unix epoch
  42. // - nsces: unsigned integer representing fractional seconds as a
  43. // nanosecond offset within secs, in the range 0 <= nsecs < 1e9
  44. // - tz: signed integer representing timezone offset in minutes east of UTC,
  45. // and a dst (daylight savings time) flag
  46. //
  47. // When encoding a timestamp, the first byte is the descriptor, which
  48. // defines which components are encoded and how many bytes are used to
  49. // encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
  50. // is not encoded in the byte array explicitly*.
  51. //
  52. // Descriptor 8 bits are of the form `A B C DDD EE`:
  53. // A: Is secs component encoded? 1 = true
  54. // B: Is nsecs component encoded? 1 = true
  55. // C: Is tz component encoded? 1 = true
  56. // DDD: Number of extra bytes for secs (range 0-7).
  57. // If A = 1, secs encoded in DDD+1 bytes.
  58. // If A = 0, secs is not encoded, and is assumed to be 0.
  59. // If A = 1, then we need at least 1 byte to encode secs.
  60. // DDD says the number of extra bytes beyond that 1.
  61. // E.g. if DDD=0, then secs is represented in 1 byte.
  62. // if DDD=2, then secs is represented in 3 bytes.
  63. // EE: Number of extra bytes for nsecs (range 0-3).
  64. // If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
  65. //
  66. // Following the descriptor bytes, subsequent bytes are:
  67. //
  68. // secs component encoded in `DDD + 1` bytes (if A == 1)
  69. // nsecs component encoded in `EE + 1` bytes (if B == 1)
  70. // tz component encoded in 2 bytes (if C == 1)
  71. //
  72. // secs and nsecs components are integers encoded in a BigEndian
  73. // 2-complement encoding format.
  74. //
  75. // tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
  76. // Least significant bit 0 are described below:
  77. //
  78. // Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
  79. // Bit 15 = have\_dst: set to 1 if we set the dst flag.
  80. // Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
  81. // Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
  82. //
  83. func encodeTime(t time.Time) []byte {
  84. //t := rv.Interface().(time.Time)
  85. tsecs, tnsecs := t.Unix(), t.Nanosecond()
  86. var (
  87. bd byte
  88. btmp [8]byte
  89. bs [16]byte
  90. i int = 1
  91. )
  92. l := t.Location()
  93. if l == time.UTC {
  94. l = nil
  95. }
  96. if tsecs != 0 {
  97. bd = bd | 0x80
  98. bigen.PutUint64(btmp[:], uint64(tsecs))
  99. f := pruneSignExt(btmp[:], tsecs >= 0)
  100. bd = bd | (byte(7-f) << 2)
  101. copy(bs[i:], btmp[f:])
  102. i = i + (8 - f)
  103. }
  104. if tnsecs != 0 {
  105. bd = bd | 0x40
  106. bigen.PutUint32(btmp[:4], uint32(tnsecs))
  107. f := pruneSignExt(btmp[:4], true)
  108. bd = bd | byte(3-f)
  109. copy(bs[i:], btmp[f:4])
  110. i = i + (4 - f)
  111. }
  112. if l != nil {
  113. bd = bd | 0x20
  114. // Note that Go Libs do not give access to dst flag.
  115. _, zoneOffset := t.Zone()
  116. //zoneName, zoneOffset := t.Zone()
  117. zoneOffset /= 60
  118. z := uint16(zoneOffset)
  119. bigen.PutUint16(btmp[:2], z)
  120. // clear dst flags
  121. bs[i] = btmp[0] & 0x3f
  122. bs[i+1] = btmp[1]
  123. i = i + 2
  124. }
  125. bs[0] = bd
  126. return bs[0:i]
  127. }
  128. // DecodeTime decodes a []byte into a time.Time.
  129. func decodeTime(bs []byte) (tt time.Time, err error) {
  130. bd := bs[0]
  131. var (
  132. tsec int64
  133. tnsec uint32
  134. tz uint16
  135. i byte = 1
  136. i2 byte
  137. n byte
  138. )
  139. if bd&(1<<7) != 0 {
  140. var btmp [8]byte
  141. n = ((bd >> 2) & 0x7) + 1
  142. i2 = i + n
  143. copy(btmp[8-n:], bs[i:i2])
  144. //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
  145. if bs[i]&(1<<7) != 0 {
  146. copy(btmp[0:8-n], bsAll0xff)
  147. //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff }
  148. }
  149. i = i2
  150. tsec = int64(bigen.Uint64(btmp[:]))
  151. }
  152. if bd&(1<<6) != 0 {
  153. var btmp [4]byte
  154. n = (bd & 0x3) + 1
  155. i2 = i + n
  156. copy(btmp[4-n:], bs[i:i2])
  157. i = i2
  158. tnsec = bigen.Uint32(btmp[:])
  159. }
  160. if bd&(1<<5) == 0 {
  161. tt = time.Unix(tsec, int64(tnsec)).UTC()
  162. return
  163. }
  164. // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
  165. // However, we need name here, so it can be shown when time is printed.
  166. // Zone name is in form: UTC-08:00.
  167. // Note that Go Libs do not give access to dst flag, so we ignore dst bits
  168. i2 = i + 2
  169. tz = bigen.Uint16(bs[i:i2])
  170. i = i2
  171. // sign extend sign bit into top 2 MSB (which were dst bits):
  172. if tz&(1<<13) == 0 { // positive
  173. tz = tz & 0x3fff //clear 2 MSBs: dst bits
  174. } else { // negative
  175. tz = tz | 0xc000 //set 2 MSBs: dst bits
  176. //tzname[3] = '-' (TODO: verify. this works here)
  177. }
  178. tzint := int16(tz)
  179. if tzint == 0 {
  180. tt = time.Unix(tsec, int64(tnsec)).UTC()
  181. } else {
  182. // For Go Time, do not use a descriptive timezone.
  183. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  184. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  185. // var zoneName = timeLocUTCName(tzint)
  186. tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
  187. }
  188. return
  189. }
  190. func timeLocUTCName(tzint int16) string {
  191. if tzint == 0 {
  192. return "UTC"
  193. }
  194. var tzname = []byte("UTC+00:00")
  195. //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below.
  196. //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
  197. var tzhr, tzmin int16
  198. if tzint < 0 {
  199. tzname[3] = '-' // (TODO: verify. this works here)
  200. tzhr, tzmin = -tzint/60, (-tzint)%60
  201. } else {
  202. tzhr, tzmin = tzint/60, tzint%60
  203. }
  204. tzname[4] = timeDigits[tzhr/10]
  205. tzname[5] = timeDigits[tzhr%10]
  206. tzname[7] = timeDigits[tzmin/10]
  207. tzname[8] = timeDigits[tzmin%10]
  208. return string(tzname)
  209. //return time.FixedZone(string(tzname), int(tzint)*60)
  210. }