time.go 6.9 KB

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