arshal_time.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. // Copyright 2020 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package json
  5. import (
  6. "bytes"
  7. "cmp"
  8. "errors"
  9. "fmt"
  10. "math"
  11. "math/bits"
  12. "reflect"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/go-json-experiment/json/internal"
  17. "github.com/go-json-experiment/json/internal/jsonflags"
  18. "github.com/go-json-experiment/json/internal/jsonopts"
  19. "github.com/go-json-experiment/json/internal/jsonwire"
  20. "github.com/go-json-experiment/json/jsontext"
  21. )
  22. var (
  23. timeDurationType = reflect.TypeFor[time.Duration]()
  24. timeTimeType = reflect.TypeFor[time.Time]()
  25. )
  26. func makeTimeArshaler(fncs *arshaler, t reflect.Type) *arshaler {
  27. // Ideally, time types would implement MarshalerTo and UnmarshalerFrom,
  28. // but that would incur a dependency on package json from package time.
  29. // Given how widely used time is, it is more acceptable that we incur a
  30. // dependency on time from json.
  31. //
  32. // Injecting the arshaling functionality like this will not be identical
  33. // to actually declaring methods on the time types since embedding of the
  34. // time types will not be able to forward this functionality.
  35. switch t {
  36. case timeDurationType:
  37. fncs.nonDefault = true
  38. marshalNano := fncs.marshal
  39. fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
  40. xe := export.Encoder(enc)
  41. var m durationArshaler
  42. if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
  43. if !m.initFormat(mo.Format) {
  44. return newInvalidFormatError(enc, t, mo)
  45. }
  46. } else if mo.Flags.Get(jsonflags.FormatTimeWithLegacySemantics) {
  47. return marshalNano(enc, va, mo)
  48. }
  49. // TODO(https://go.dev/issue/62121): Use reflect.Value.AssertTo.
  50. m.td = *va.Addr().Interface().(*time.Duration)
  51. k := stringOrNumberKind(!m.isNumeric() || xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers))
  52. if err := xe.AppendRaw(k, true, m.appendMarshal); err != nil {
  53. if !isSyntacticError(err) && !export.IsIOError(err) {
  54. err = newMarshalErrorBefore(enc, t, err)
  55. }
  56. return err
  57. }
  58. return nil
  59. }
  60. unmarshalNano := fncs.unmarshal
  61. fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
  62. xd := export.Decoder(dec)
  63. var u durationArshaler
  64. if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
  65. if !u.initFormat(uo.Format) {
  66. return newInvalidFormatError(dec, t, uo)
  67. }
  68. } else if uo.Flags.Get(jsonflags.FormatTimeWithLegacySemantics) {
  69. return unmarshalNano(dec, va, uo)
  70. }
  71. stringify := !u.isNumeric() || xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers)
  72. var flags jsonwire.ValueFlags
  73. td := va.Addr().Interface().(*time.Duration)
  74. val, err := xd.ReadValue(&flags)
  75. if err != nil {
  76. return err
  77. }
  78. switch k := val.Kind(); k {
  79. case 'n':
  80. if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) {
  81. *td = time.Duration(0)
  82. }
  83. return nil
  84. case '"':
  85. if !stringify {
  86. break
  87. }
  88. val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
  89. if err := u.unmarshal(val); err != nil {
  90. return newUnmarshalErrorAfter(dec, t, err)
  91. }
  92. *td = u.td
  93. return nil
  94. case '0':
  95. if stringify {
  96. break
  97. }
  98. if err := u.unmarshal(val); err != nil {
  99. return newUnmarshalErrorAfter(dec, t, err)
  100. }
  101. *td = u.td
  102. return nil
  103. }
  104. return newUnmarshalErrorAfter(dec, t, nil)
  105. }
  106. case timeTimeType:
  107. fncs.nonDefault = true
  108. fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) (err error) {
  109. xe := export.Encoder(enc)
  110. var m timeArshaler
  111. if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
  112. if !m.initFormat(mo.Format) {
  113. return newInvalidFormatError(enc, t, mo)
  114. }
  115. }
  116. // TODO(https://go.dev/issue/62121): Use reflect.Value.AssertTo.
  117. m.tt = *va.Addr().Interface().(*time.Time)
  118. k := stringOrNumberKind(!m.isNumeric() || xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers))
  119. if err := xe.AppendRaw(k, !m.hasCustomFormat(), m.appendMarshal); err != nil {
  120. if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
  121. return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSON") // unlike unmarshal, always wrapped
  122. }
  123. if !isSyntacticError(err) && !export.IsIOError(err) {
  124. err = newMarshalErrorBefore(enc, t, err)
  125. }
  126. return err
  127. }
  128. return nil
  129. }
  130. fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) (err error) {
  131. xd := export.Decoder(dec)
  132. var u timeArshaler
  133. if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
  134. if !u.initFormat(uo.Format) {
  135. return newInvalidFormatError(dec, t, uo)
  136. }
  137. } else if uo.Flags.Get(jsonflags.FormatTimeWithLegacySemantics) {
  138. u.looseRFC3339 = true
  139. }
  140. stringify := !u.isNumeric() || xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers)
  141. var flags jsonwire.ValueFlags
  142. tt := va.Addr().Interface().(*time.Time)
  143. val, err := xd.ReadValue(&flags)
  144. if err != nil {
  145. return err
  146. }
  147. switch k := val.Kind(); k {
  148. case 'n':
  149. if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) {
  150. *tt = time.Time{}
  151. }
  152. return nil
  153. case '"':
  154. if !stringify {
  155. break
  156. }
  157. val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
  158. if err := u.unmarshal(val); err != nil {
  159. if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
  160. return err // unlike marshal, never wrapped
  161. }
  162. return newUnmarshalErrorAfter(dec, t, err)
  163. }
  164. *tt = u.tt
  165. return nil
  166. case '0':
  167. if stringify {
  168. break
  169. }
  170. if err := u.unmarshal(val); err != nil {
  171. if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
  172. return err // unlike marshal, never wrapped
  173. }
  174. return newUnmarshalErrorAfter(dec, t, err)
  175. }
  176. *tt = u.tt
  177. return nil
  178. }
  179. return newUnmarshalErrorAfter(dec, t, nil)
  180. }
  181. }
  182. return fncs
  183. }
  184. type durationArshaler struct {
  185. td time.Duration
  186. // base records the representation where:
  187. // - 0 uses time.Duration.String
  188. // - 1e0, 1e3, 1e6, or 1e9 use a decimal encoding of the duration as
  189. // nanoseconds, microseconds, milliseconds, or seconds.
  190. // - 60 uses a "H:MM:SS.SSSSSSSSS" encoding
  191. base uint64
  192. }
  193. func (a *durationArshaler) initFormat(format string) (ok bool) {
  194. switch format {
  195. case "units":
  196. a.base = 0
  197. case "sec":
  198. a.base = 1e9
  199. case "milli":
  200. a.base = 1e6
  201. case "micro":
  202. a.base = 1e3
  203. case "nano":
  204. a.base = 1e0
  205. case "base60": // see https://en.wikipedia.org/wiki/Sexagesimal#Modern_usage
  206. a.base = 60
  207. default:
  208. return false
  209. }
  210. return true
  211. }
  212. func (a *durationArshaler) isNumeric() bool {
  213. return a.base != 0 && a.base != 60
  214. }
  215. func (a *durationArshaler) appendMarshal(b []byte) ([]byte, error) {
  216. switch a.base {
  217. case 0:
  218. return append(b, a.td.String()...), nil
  219. case 60:
  220. return appendDurationBase60(b, a.td), nil
  221. default:
  222. return appendDurationBase10(b, a.td, a.base), nil
  223. }
  224. }
  225. func (a *durationArshaler) unmarshal(b []byte) (err error) {
  226. switch a.base {
  227. case 0:
  228. a.td, err = time.ParseDuration(string(b))
  229. case 60:
  230. a.td, err = parseDurationBase60(b)
  231. default:
  232. a.td, err = parseDurationBase10(b, a.base)
  233. }
  234. return err
  235. }
  236. type timeArshaler struct {
  237. tt time.Time
  238. // base records the representation where:
  239. // - 0 uses RFC 3339 encoding of the timestamp
  240. // - 1e0, 1e3, 1e6, or 1e9 use a decimal encoding of the timestamp as
  241. // seconds, milliseconds, microseconds, or nanoseconds since Unix epoch.
  242. // - math.MaxUint uses time.Time.Format to encode the timestamp
  243. base uint64
  244. format string // time format passed to time.Parse
  245. looseRFC3339 bool
  246. }
  247. func (a *timeArshaler) initFormat(format string) bool {
  248. // We assume that an exported constant in the time package will
  249. // always start with an uppercase ASCII letter.
  250. if len(format) == 0 {
  251. return false
  252. }
  253. a.base = math.MaxUint // implies custom format
  254. if c := format[0]; !('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z') {
  255. a.format = format
  256. return true
  257. }
  258. switch format {
  259. case "ANSIC":
  260. a.format = time.ANSIC
  261. case "UnixDate":
  262. a.format = time.UnixDate
  263. case "RubyDate":
  264. a.format = time.RubyDate
  265. case "RFC822":
  266. a.format = time.RFC822
  267. case "RFC822Z":
  268. a.format = time.RFC822Z
  269. case "RFC850":
  270. a.format = time.RFC850
  271. case "RFC1123":
  272. a.format = time.RFC1123
  273. case "RFC1123Z":
  274. a.format = time.RFC1123Z
  275. case "RFC3339":
  276. a.base = 0
  277. a.format = time.RFC3339
  278. case "RFC3339Nano":
  279. a.base = 0
  280. a.format = time.RFC3339Nano
  281. case "Kitchen":
  282. a.format = time.Kitchen
  283. case "Stamp":
  284. a.format = time.Stamp
  285. case "StampMilli":
  286. a.format = time.StampMilli
  287. case "StampMicro":
  288. a.format = time.StampMicro
  289. case "StampNano":
  290. a.format = time.StampNano
  291. case "DateTime":
  292. a.format = time.DateTime
  293. case "DateOnly":
  294. a.format = time.DateOnly
  295. case "TimeOnly":
  296. a.format = time.TimeOnly
  297. case "unix":
  298. a.base = 1e0
  299. case "unixmilli":
  300. a.base = 1e3
  301. case "unixmicro":
  302. a.base = 1e6
  303. case "unixnano":
  304. a.base = 1e9
  305. default:
  306. // Reject any Go identifier in case new constants are supported.
  307. if strings.TrimFunc(format, isLetterOrDigit) == "" {
  308. return false
  309. }
  310. a.format = format
  311. }
  312. return true
  313. }
  314. func (a *timeArshaler) isNumeric() bool {
  315. return int(a.base) > 0
  316. }
  317. func (a *timeArshaler) hasCustomFormat() bool {
  318. return a.base == math.MaxUint
  319. }
  320. func (a *timeArshaler) appendMarshal(b []byte) ([]byte, error) {
  321. switch a.base {
  322. case 0:
  323. format := cmp.Or(a.format, time.RFC3339Nano)
  324. n0 := len(b)
  325. b = a.tt.AppendFormat(b, format)
  326. // Not all Go timestamps can be represented as valid RFC 3339.
  327. // Explicitly check for these edge cases.
  328. // See https://go.dev/issue/4556 and https://go.dev/issue/54580.
  329. switch b := b[n0:]; {
  330. case b[len("9999")] != '-': // year must be exactly 4 digits wide
  331. return b, errors.New("year outside of range [0,9999]")
  332. case b[len(b)-1] != 'Z':
  333. c := b[len(b)-len("Z07:00")]
  334. if ('0' <= c && c <= '9') || parseDec2(b[len(b)-len("07:00"):]) >= 24 {
  335. return b, errors.New("timezone hour outside of range [0,23]")
  336. }
  337. }
  338. return b, nil
  339. case math.MaxUint:
  340. return a.tt.AppendFormat(b, a.format), nil
  341. default:
  342. return appendTimeUnix(b, a.tt, a.base), nil
  343. }
  344. }
  345. func (a *timeArshaler) unmarshal(b []byte) (err error) {
  346. switch a.base {
  347. case 0:
  348. // Use time.Time.UnmarshalText to avoid possible string allocation.
  349. if err := a.tt.UnmarshalText(b); err != nil {
  350. return err
  351. }
  352. // TODO(https://go.dev/issue/57912):
  353. // RFC 3339 specifies the grammar for a valid timestamp.
  354. // However, the parsing functionality in "time" is too loose and
  355. // incorrectly accepts invalid timestamps as valid.
  356. // Remove these manual checks when "time" checks it for us.
  357. newParseError := func(layout, value, layoutElem, valueElem, message string) error {
  358. return &time.ParseError{Layout: layout, Value: value, LayoutElem: layoutElem, ValueElem: valueElem, Message: message}
  359. }
  360. switch {
  361. case a.looseRFC3339:
  362. return nil
  363. case b[len("2006-01-02T")+1] == ':': // hour must be two digits
  364. return newParseError(time.RFC3339, string(b), "15", string(b[len("2006-01-02T"):][:1]), "")
  365. case b[len("2006-01-02T15:04:05")] == ',': // sub-second separator must be a period
  366. return newParseError(time.RFC3339, string(b), ".", ",", "")
  367. case b[len(b)-1] != 'Z':
  368. switch {
  369. case parseDec2(b[len(b)-len("07:00"):]) >= 24: // timezone hour must be in range
  370. return newParseError(time.RFC3339, string(b), "Z07:00", string(b[len(b)-len("Z07:00"):]), ": timezone hour out of range")
  371. case parseDec2(b[len(b)-len("00"):]) >= 60: // timezone minute must be in range
  372. return newParseError(time.RFC3339, string(b), "Z07:00", string(b[len(b)-len("Z07:00"):]), ": timezone minute out of range")
  373. }
  374. }
  375. return nil
  376. case math.MaxUint:
  377. a.tt, err = time.Parse(a.format, string(b))
  378. return err
  379. default:
  380. a.tt, err = parseTimeUnix(b, a.base)
  381. return err
  382. }
  383. }
  384. // appendDurationBase10 appends d formatted as a decimal fractional number,
  385. // where pow10 is a power-of-10 used to scale down the number.
  386. func appendDurationBase10(b []byte, d time.Duration, pow10 uint64) []byte {
  387. b, n := mayAppendDurationSign(b, d) // append sign
  388. whole, frac := bits.Div64(0, n, uint64(pow10)) // compute whole and frac fields
  389. b = strconv.AppendUint(b, whole, 10) // append whole field
  390. return appendFracBase10(b, frac, pow10) // append frac field
  391. }
  392. // parseDurationBase10 parses d from a decimal fractional number,
  393. // where pow10 is a power-of-10 used to scale up the number.
  394. func parseDurationBase10(b []byte, pow10 uint64) (time.Duration, error) {
  395. suffix, neg := consumeSign(b) // consume sign
  396. wholeBytes, fracBytes := bytesCutByte(suffix, '.', true) // consume whole and frac fields
  397. whole, okWhole := jsonwire.ParseUint(wholeBytes) // parse whole field; may overflow
  398. frac, okFrac := parseFracBase10(fracBytes, pow10) // parse frac field
  399. hi, lo := bits.Mul64(whole, uint64(pow10)) // overflow if hi > 0
  400. sum, co := bits.Add64(lo, uint64(frac), 0) // overflow if co > 0
  401. switch d := mayApplyDurationSign(sum, neg); { // overflow if neg != (d < 0)
  402. case (!okWhole && whole != math.MaxUint64) || !okFrac:
  403. return 0, fmt.Errorf("invalid duration %q: %w", b, strconv.ErrSyntax)
  404. case !okWhole || hi > 0 || co > 0 || neg != (d < 0):
  405. return 0, fmt.Errorf("invalid duration %q: %w", b, strconv.ErrRange)
  406. default:
  407. return d, nil
  408. }
  409. }
  410. // appendDurationBase60 appends d formatted with H:MM:SS.SSS notation.
  411. func appendDurationBase60(b []byte, d time.Duration) []byte {
  412. b, n := mayAppendDurationSign(b, d) // append sign
  413. n, nsec := bits.Div64(0, n, 1e9) // compute nsec field
  414. n, sec := bits.Div64(0, n, 60) // compute sec field
  415. hour, min := bits.Div64(0, n, 60) // compute hour and min fields
  416. b = strconv.AppendUint(b, hour, 10) // append hour field
  417. b = append(b, ':', '0'+byte(min/10), '0'+byte(min%10)) // append min field
  418. b = append(b, ':', '0'+byte(sec/10), '0'+byte(sec%10)) // append sec field
  419. return appendFracBase10(b, nsec, 1e9) // append nsec field
  420. }
  421. // parseDurationBase60 parses d formatted with H:MM:SS.SSS notation.
  422. // The exact grammar is `-?(0|[1-9][0-9]*):[0-5][0-9]:[0-5][0-9]([.][0-9]+)?`.
  423. func parseDurationBase60(b []byte) (time.Duration, error) {
  424. checkBase60 := func(b []byte) bool {
  425. return len(b) == 2 && ('0' <= b[0] && b[0] <= '5') && '0' <= b[1] && b[1] <= '9'
  426. }
  427. suffix, neg := consumeSign(b) // consume sign
  428. hourBytes, suffix := bytesCutByte(suffix, ':', false) // consume hour field
  429. minBytes, suffix := bytesCutByte(suffix, ':', false) // consume min field
  430. secBytes, nsecBytes := bytesCutByte(suffix, '.', true) // consume sec and nsec fields
  431. hour, okHour := jsonwire.ParseUint(hourBytes) // parse hour field; may overflow
  432. min := parseDec2(minBytes) // parse min field
  433. sec := parseDec2(secBytes) // parse sec field
  434. nsec, okNsec := parseFracBase10(nsecBytes, 1e9) // parse nsec field
  435. n := uint64(min)*60*1e9 + uint64(sec)*1e9 + uint64(nsec) // cannot overflow
  436. hi, lo := bits.Mul64(hour, 60*60*1e9) // overflow if hi > 0
  437. sum, co := bits.Add64(lo, n, 0) // overflow if co > 0
  438. switch d := mayApplyDurationSign(sum, neg); { // overflow if neg != (d < 0)
  439. case (!okHour && hour != math.MaxUint64) || !checkBase60(minBytes) || !checkBase60(secBytes) || !okNsec:
  440. return 0, fmt.Errorf("invalid duration %q: %w", b, strconv.ErrSyntax)
  441. case !okHour || hi > 0 || co > 0 || neg != (d < 0):
  442. return 0, fmt.Errorf("invalid duration %q: %w", b, strconv.ErrRange)
  443. default:
  444. return d, nil
  445. }
  446. }
  447. // mayAppendDurationSign appends a negative sign if n is negative.
  448. func mayAppendDurationSign(b []byte, d time.Duration) ([]byte, uint64) {
  449. if d < 0 {
  450. b = append(b, '-')
  451. d *= -1
  452. }
  453. return b, uint64(d)
  454. }
  455. // mayApplyDurationSign inverts n if neg is specified.
  456. func mayApplyDurationSign(n uint64, neg bool) time.Duration {
  457. if neg {
  458. return -1 * time.Duration(n)
  459. } else {
  460. return +1 * time.Duration(n)
  461. }
  462. }
  463. // appendTimeUnix appends t formatted as a decimal fractional number,
  464. // where pow10 is a power-of-10 used to scale up the number.
  465. func appendTimeUnix(b []byte, t time.Time, pow10 uint64) []byte {
  466. sec, nsec := t.Unix(), int64(t.Nanosecond())
  467. if sec < 0 {
  468. b = append(b, '-')
  469. sec, nsec = negateSecNano(sec, nsec)
  470. }
  471. switch {
  472. case pow10 == 1e0: // fast case where units is in seconds
  473. b = strconv.AppendUint(b, uint64(sec), 10)
  474. return appendFracBase10(b, uint64(nsec), 1e9)
  475. case uint64(sec) < 1e9: // intermediate case where units is not seconds, but no overflow
  476. b = strconv.AppendUint(b, uint64(sec)*uint64(pow10)+uint64(uint64(nsec)/(1e9/pow10)), 10)
  477. return appendFracBase10(b, (uint64(nsec)*pow10)%1e9, 1e9)
  478. default: // slow case where units is not seconds and overflow would occur
  479. b = strconv.AppendUint(b, uint64(sec), 10)
  480. b = appendPaddedBase10(b, uint64(nsec)/(1e9/pow10), pow10)
  481. return appendFracBase10(b, (uint64(nsec)*pow10)%1e9, 1e9)
  482. }
  483. }
  484. // parseTimeUnix parses t formatted as a decimal fractional number,
  485. // where pow10 is a power-of-10 used to scale down the number.
  486. func parseTimeUnix(b []byte, pow10 uint64) (time.Time, error) {
  487. suffix, neg := consumeSign(b) // consume sign
  488. wholeBytes, fracBytes := bytesCutByte(suffix, '.', true) // consume whole and frac fields
  489. whole, okWhole := jsonwire.ParseUint(wholeBytes) // parse whole field; may overflow
  490. frac, okFrac := parseFracBase10(fracBytes, 1e9/pow10) // parse frac field
  491. var sec, nsec int64
  492. switch {
  493. case pow10 == 1e0: // fast case where units is in seconds
  494. sec = int64(whole) // check overflow later after negation
  495. nsec = int64(frac) // cannot overflow
  496. case okWhole: // intermediate case where units is not seconds, but no overflow
  497. sec = int64(whole / pow10) // check overflow later after negation
  498. nsec = int64((whole%pow10)*(1e9/pow10) + frac) // cannot overflow
  499. case !okWhole && whole == math.MaxUint64: // slow case where units is not seconds and overflow occurred
  500. width := int(math.Log10(float64(pow10))) // compute len(strconv.Itoa(pow10-1))
  501. whole, okWhole = jsonwire.ParseUint(wholeBytes[:len(wholeBytes)-width]) // parse the upper whole field
  502. mid, _ := parsePaddedBase10(wholeBytes[len(wholeBytes)-width:], pow10) // parse the lower whole field
  503. sec = int64(whole) // check overflow later after negation
  504. nsec = int64(mid*(1e9/pow10) + frac) // cannot overflow
  505. }
  506. if neg {
  507. sec, nsec = negateSecNano(sec, nsec)
  508. }
  509. switch t := time.Unix(sec, nsec).UTC(); {
  510. case (!okWhole && whole != math.MaxUint64) || !okFrac:
  511. return time.Time{}, fmt.Errorf("invalid time %q: %w", b, strconv.ErrSyntax)
  512. case !okWhole || neg != (t.Unix() < 0):
  513. return time.Time{}, fmt.Errorf("invalid time %q: %w", b, strconv.ErrRange)
  514. default:
  515. return t, nil
  516. }
  517. }
  518. // negateSecNano negates a Unix timestamp, where nsec must be within [0, 1e9).
  519. func negateSecNano(sec, nsec int64) (int64, int64) {
  520. sec = ^sec // twos-complement negation (i.e., -1*sec + 1)
  521. nsec = -nsec + 1e9 // negate nsec and add 1e9 (which is the extra +1 from sec negation)
  522. sec += int64(nsec / 1e9) // handle possible overflow of nsec if it started as zero
  523. nsec %= 1e9 // ensure nsec stays within [0, 1e9)
  524. return sec, nsec
  525. }
  526. // appendFracBase10 appends the fraction of n/max10,
  527. // where max10 is a power-of-10 that is larger than n.
  528. func appendFracBase10(b []byte, n, max10 uint64) []byte {
  529. if n == 0 {
  530. return b
  531. }
  532. return bytes.TrimRight(appendPaddedBase10(append(b, '.'), n, max10), "0")
  533. }
  534. // parseFracBase10 parses the fraction of n/max10,
  535. // where max10 is a power-of-10 that is larger than n.
  536. func parseFracBase10(b []byte, max10 uint64) (n uint64, ok bool) {
  537. switch {
  538. case len(b) == 0:
  539. return 0, true
  540. case len(b) < len(".0") || b[0] != '.':
  541. return 0, false
  542. }
  543. return parsePaddedBase10(b[len("."):], max10)
  544. }
  545. // appendPaddedBase10 appends a zero-padded encoding of n,
  546. // where max10 is a power-of-10 that is larger than n.
  547. func appendPaddedBase10(b []byte, n, max10 uint64) []byte {
  548. if n < max10/10 {
  549. // Formatting of n is shorter than log10(max10),
  550. // so add max10/10 to ensure the length is equal to log10(max10).
  551. i := len(b)
  552. b = strconv.AppendUint(b, n+max10/10, 10)
  553. b[i]-- // subtract the addition of max10/10
  554. return b
  555. }
  556. return strconv.AppendUint(b, n, 10)
  557. }
  558. // parsePaddedBase10 parses b as the zero-padded encoding of n,
  559. // where max10 is a power-of-10 that is larger than n.
  560. // Truncated suffix is treated as implicit zeros.
  561. // Extended suffix is ignored, but verified to contain only digits.
  562. func parsePaddedBase10(b []byte, max10 uint64) (n uint64, ok bool) {
  563. pow10 := uint64(1)
  564. for pow10 < max10 {
  565. n *= 10
  566. if len(b) > 0 {
  567. if b[0] < '0' || '9' < b[0] {
  568. return n, false
  569. }
  570. n += uint64(b[0] - '0')
  571. b = b[1:]
  572. }
  573. pow10 *= 10
  574. }
  575. if len(b) > 0 && len(bytes.TrimRight(b, "0123456789")) > 0 {
  576. return n, false // trailing characters are not digits
  577. }
  578. return n, true
  579. }
  580. // consumeSign consumes an optional leading negative sign.
  581. func consumeSign(b []byte) ([]byte, bool) {
  582. if len(b) > 0 && b[0] == '-' {
  583. return b[len("-"):], true
  584. }
  585. return b, false
  586. }
  587. // bytesCutByte is similar to bytes.Cut(b, []byte{c}),
  588. // except c may optionally be included as part of the suffix.
  589. func bytesCutByte(b []byte, c byte, include bool) ([]byte, []byte) {
  590. if i := bytes.IndexByte(b, c); i >= 0 {
  591. if include {
  592. return b[:i], b[i:]
  593. }
  594. return b[:i], b[i+1:]
  595. }
  596. return b, nil
  597. }
  598. // parseDec2 parses b as an unsigned, base-10, 2-digit number.
  599. // The result is undefined if digits are not base-10.
  600. func parseDec2(b []byte) byte {
  601. if len(b) < 2 {
  602. return 0
  603. }
  604. return 10*(b[0]-'0') + (b[1] - '0')
  605. }