time.go 6.6 KB

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