github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/src/time/time.go (about) 1 // Copyright 2009 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 5 // Package time provides functionality for measuring and displaying time. 6 // 7 // The calendrical calculations always assume a Gregorian calendar, with 8 // no leap seconds. 9 // 10 // Monotonic Clocks 11 // 12 // Operating systems provide both a “wall clock,” which is subject to 13 // changes for clock synchronization, and a “monotonic clock,” which is 14 // not. The general rule is that the wall clock is for telling time and 15 // the monotonic clock is for measuring time. Rather than split the API, 16 // in this package the Time returned by time.Now contains both a wall 17 // clock reading and a monotonic clock reading; later time-telling 18 // operations use the wall clock reading, but later time-measuring 19 // operations, specifically comparisons and subtractions, use the 20 // monotonic clock reading. 21 // 22 // For example, this code always computes a positive elapsed time of 23 // approximately 20 milliseconds, even if the wall clock is changed during 24 // the operation being timed: 25 // 26 // t := time.Now() 27 // ... operation that takes 20 milliseconds ... 28 // u := time.Now() 29 // elapsed := t.Sub(u) 30 // 31 // Other idioms, such as time.Since(start), time.Until(deadline), and 32 // time.Now().Before(deadline), are similarly robust against wall clock 33 // resets. 34 // 35 // The rest of this section gives the precise details of how operations 36 // use monotonic clocks, but understanding those details is not required 37 // to use this package. 38 // 39 // The Time returned by time.Now contains a monotonic clock reading. 40 // If Time t has a monotonic clock reading, t.Add, t.Round, and 41 // t.Truncate add the same duration to both the wall clock and 42 // monotonic clock readings to compute the result. Similarly, t.In, 43 // t.Local, and t.UTC, which are defined to change only the Time's 44 // Location, pass any monotonic clock reading through unmodified. 45 // Because t.AddDate(y, m, d) is a wall time computation, it always 46 // strips any monotonic clock reading from its result. 47 // 48 // If Times t and u both contain monotonic clock readings, the operations 49 // t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out 50 // using the monotonic clock readings alone, ignoring the wall clock 51 // readings. If either t or u contains no monotonic clock reading, these 52 // operations fall back to using the wall clock readings. 53 // 54 // Because the monotonic clock reading has no meaning outside 55 // the current process, the serialized forms generated by t.GobEncode, 56 // t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic 57 // clock reading, and t.Format provides no format for it. Similarly, the 58 // constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, 59 // as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. 60 // t.UnmarshalJSON, and t.UnmarshalText always create times with 61 // no monotonic clock reading. 62 // 63 // Note that the Go == operator includes the monotonic clock reading in 64 // its comparison. If time values returned from time.Now and time values 65 // constructed by other means (for example, by time.Parse or time.Unix) 66 // are meant to compare equal when used as map keys, the times returned 67 // by time.Now must have the monotonic clock reading stripped, by setting 68 // t = t.AddDate(0, 0, 0). In general, prefer t.Equal(u) to t == u, since 69 // t.Equal uses the most accurate comparison available and correctly 70 // handles the case when only one of its arguments has a monotonic clock 71 // reading. 72 // 73 // For debugging, the result of t.String does include the monotonic 74 // clock reading if present. If t != u because of different monotonic clock readings, 75 // that difference will be visible when printing t.String() and u.String(). 76 // 77 package time 78 79 import "errors" 80 81 // A Time represents an instant in time with nanosecond precision. 82 // 83 // Programs using times should typically store and pass them as values, 84 // not pointers. That is, time variables and struct fields should be of 85 // type time.Time, not *time.Time. A Time value can be used by 86 // multiple goroutines simultaneously. 87 // 88 // Time instants can be compared using the Before, After, and Equal methods. 89 // The Sub method subtracts two instants, producing a Duration. 90 // The Add method adds a Time and a Duration, producing a Time. 91 // 92 // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. 93 // As this time is unlikely to come up in practice, the IsZero method gives 94 // a simple way of detecting a time that has not been initialized explicitly. 95 // 96 // Each Time has associated with it a Location, consulted when computing the 97 // presentation form of the time, such as in the Format, Hour, and Year methods. 98 // The methods Local, UTC, and In return a Time with a specific location. 99 // Changing the location in this way changes only the presentation; it does not 100 // change the instant in time being denoted and therefore does not affect the 101 // computations described in earlier paragraphs. 102 // 103 // Note that the Go == operator compares not just the time instant but also the 104 // Location. Therefore, Time values should not be used as map or database keys 105 // without first guaranteeing that the identical Location has been set for all 106 // values, which can be achieved through use of the UTC or Local method. 107 // 108 // In addition to the required “wall clock” reading, a Time may contain an optional 109 // reading of the current process's monotonic clock, to provide additional precision 110 // for comparison or subtraction. 111 // See the “Monotonic Clocks” section in the package documentation for details. 112 // 113 type Time struct { 114 // wall and ext encode the wall time seconds, wall time nanoseconds, 115 // and optional monotonic clock reading in nanoseconds. 116 // 117 // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic), 118 // a 33-bit seconds field, and a 30-bit wall time nanoseconds field. 119 // The nanoseconds field is in the range [0, 999999999]. 120 // If the hasMonotonic bit is 0, then the 33-bit field must be zero 121 // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext. 122 // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit 123 // unsigned wall seconds since Jan 1 year 1885, and ext holds a 124 // signed 64-bit monotonic clock reading, nanoseconds since process start. 125 wall uint64 126 ext int64 127 128 // loc specifies the Location that should be used to 129 // determine the minute, hour, month, day, and year 130 // that correspond to this Time. 131 // The nil location means UTC. 132 // All UTC times are represented with loc==nil, never loc==&utcLoc. 133 loc *Location 134 } 135 136 const ( 137 hasMonotonic = 1 << 63 138 maxWall = wallToInternal + (1<<33 - 1) // year 2157 139 minWall = wallToInternal // year 1885 140 nsecMask = 1<<30 - 1 141 nsecShift = 30 142 ) 143 144 // These helpers for manipulating the wall and monotonic clock readings 145 // take pointer receivers, even when they don't modify the time, 146 // to make them cheaper to call. 147 148 // nsec returns the time's nanoseconds. 149 func (t *Time) nsec() int32 { 150 return int32(t.wall & nsecMask) 151 } 152 153 // sec returns the time's seconds since Jan 1 year 1. 154 func (t *Time) sec() int64 { 155 if t.wall&hasMonotonic != 0 { 156 return wallToInternal + int64(t.wall<<1>>(nsecShift+1)) 157 } 158 return int64(t.ext) 159 } 160 161 // unixSec returns the time's seconds since Jan 1 1970 (Unix time). 162 func (t *Time) unixSec() int64 { return t.sec() + internalToUnix } 163 164 // addSec adds d seconds to the time. 165 func (t *Time) addSec(d int64) { 166 if t.wall&hasMonotonic != 0 { 167 sec := int64(t.wall << 1 >> (nsecShift + 1)) 168 dsec := sec + d 169 if 0 <= dsec && dsec <= 1<<33-1 { 170 t.wall = t.wall&nsecMask | uint64(dsec)<<nsecShift | hasMonotonic 171 return 172 } 173 // Wall second now out of range for packed field. 174 // Move to ext. 175 t.ext = t.sec() 176 t.wall &= nsecMask 177 } 178 179 // TODO: Check for overflow. 180 t.ext += d 181 } 182 183 // setLoc sets the location associated with the time. 184 func (t *Time) setLoc(loc *Location) { 185 if loc == &utcLoc { 186 loc = nil 187 } 188 t.loc = loc 189 } 190 191 // setMono sets the monotonic clock reading in t. 192 // If t cannot hold a monotonic clock reading, 193 // because its wall time is too large, 194 // setMono is a no-op. 195 func (t *Time) setMono(m int64) { 196 if t.wall&hasMonotonic == 0 { 197 sec := int64(t.ext) 198 if sec < minWall || maxWall < sec { 199 return 200 } 201 t.wall |= hasMonotonic | uint64(sec-minWall)<<nsecShift 202 } 203 t.ext = m 204 } 205 206 // mono returns t's monotonic clock reading. 207 // It returns 0 for a missing reading. 208 // This function is used only for testing, 209 // so it's OK that technically 0 is a valid 210 // monotonic clock reading as well. 211 func (t *Time) mono() int64 { 212 if t.wall&hasMonotonic == 0 { 213 return 0 214 } 215 return t.ext 216 } 217 218 // After reports whether the time instant t is after u. 219 func (t Time) After(u Time) bool { 220 if t.wall&u.wall&hasMonotonic != 0 { 221 return t.ext > u.ext 222 } 223 ts := t.sec() 224 us := u.sec() 225 return ts > us || ts == us && t.nsec() > u.nsec() 226 } 227 228 // Before reports whether the time instant t is before u. 229 func (t Time) Before(u Time) bool { 230 if t.wall&u.wall&hasMonotonic != 0 { 231 return t.ext < u.ext 232 } 233 return t.sec() < u.sec() || t.sec() == u.sec() && t.nsec() < u.nsec() 234 } 235 236 // Equal reports whether t and u represent the same time instant. 237 // Two times can be equal even if they are in different locations. 238 // For example, 6:00 +0200 CEST and 4:00 UTC are Equal. 239 // Do not use == with Time values. 240 func (t Time) Equal(u Time) bool { 241 if t.wall&u.wall&hasMonotonic != 0 { 242 return t.ext == u.ext 243 } 244 return t.sec() == u.sec() && t.nsec() == u.nsec() 245 } 246 247 // A Month specifies a month of the year (January = 1, ...). 248 type Month int 249 250 const ( 251 January Month = 1 + iota 252 February 253 March 254 April 255 May 256 June 257 July 258 August 259 September 260 October 261 November 262 December 263 ) 264 265 var months = [...]string{ 266 "January", 267 "February", 268 "March", 269 "April", 270 "May", 271 "June", 272 "July", 273 "August", 274 "September", 275 "October", 276 "November", 277 "December", 278 } 279 280 // String returns the English name of the month ("January", "February", ...). 281 func (m Month) String() string { 282 if January <= m && m <= December { 283 return months[m-1] 284 } 285 buf := make([]byte, 20) 286 n := fmtInt(buf, uint64(m)) 287 return "%!Month(" + string(buf[n:]) + ")" 288 } 289 290 // A Weekday specifies a day of the week (Sunday = 0, ...). 291 type Weekday int 292 293 const ( 294 Sunday Weekday = iota 295 Monday 296 Tuesday 297 Wednesday 298 Thursday 299 Friday 300 Saturday 301 ) 302 303 var days = [...]string{ 304 "Sunday", 305 "Monday", 306 "Tuesday", 307 "Wednesday", 308 "Thursday", 309 "Friday", 310 "Saturday", 311 } 312 313 // String returns the English name of the day ("Sunday", "Monday", ...). 314 func (d Weekday) String() string { return days[d] } 315 316 // Computations on time. 317 // 318 // The zero value for a Time is defined to be 319 // January 1, year 1, 00:00:00.000000000 UTC 320 // which (1) looks like a zero, or as close as you can get in a date 321 // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to 322 // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a 323 // non-negative year even in time zones west of UTC, unlike 1-1-0 324 // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York. 325 // 326 // The zero Time value does not force a specific epoch for the time 327 // representation. For example, to use the Unix epoch internally, we 328 // could define that to distinguish a zero value from Jan 1 1970, that 329 // time would be represented by sec=-1, nsec=1e9. However, it does 330 // suggest a representation, namely using 1-1-1 00:00:00 UTC as the 331 // epoch, and that's what we do. 332 // 333 // The Add and Sub computations are oblivious to the choice of epoch. 334 // 335 // The presentation computations - year, month, minute, and so on - all 336 // rely heavily on division and modulus by positive constants. For 337 // calendrical calculations we want these divisions to round down, even 338 // for negative values, so that the remainder is always positive, but 339 // Go's division (like most hardware division instructions) rounds to 340 // zero. We can still do those computations and then adjust the result 341 // for a negative numerator, but it's annoying to write the adjustment 342 // over and over. Instead, we can change to a different epoch so long 343 // ago that all the times we care about will be positive, and then round 344 // to zero and round down coincide. These presentation routines already 345 // have to add the zone offset, so adding the translation to the 346 // alternate epoch is cheap. For example, having a non-negative time t 347 // means that we can write 348 // 349 // sec = t % 60 350 // 351 // instead of 352 // 353 // sec = t % 60 354 // if sec < 0 { 355 // sec += 60 356 // } 357 // 358 // everywhere. 359 // 360 // The calendar runs on an exact 400 year cycle: a 400-year calendar 361 // printed for 1970-2469 will apply as well to 2370-2769. Even the days 362 // of the week match up. It simplifies the computations to choose the 363 // cycle boundaries so that the exceptional years are always delayed as 364 // long as possible. That means choosing a year equal to 1 mod 400, so 365 // that the first leap year is the 4th year, the first missed leap year 366 // is the 100th year, and the missed missed leap year is the 400th year. 367 // So we'd prefer instead to print a calendar for 2001-2400 and reuse it 368 // for 2401-2800. 369 // 370 // Finally, it's convenient if the delta between the Unix epoch and 371 // long-ago epoch is representable by an int64 constant. 372 // 373 // These three considerations—choose an epoch as early as possible, that 374 // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds 375 // earlier than 1970—bring us to the year -292277022399. We refer to 376 // this year as the absolute zero year, and to times measured as a uint64 377 // seconds since this year as absolute times. 378 // 379 // Times measured as an int64 seconds since the year 1—the representation 380 // used for Time's sec field—are called internal times. 381 // 382 // Times measured as an int64 seconds since the year 1970 are called Unix 383 // times. 384 // 385 // It is tempting to just use the year 1 as the absolute epoch, defining 386 // that the routines are only valid for years >= 1. However, the 387 // routines would then be invalid when displaying the epoch in time zones 388 // west of UTC, since it is year 0. It doesn't seem tenable to say that 389 // printing the zero time correctly isn't supported in half the time 390 // zones. By comparison, it's reasonable to mishandle some times in 391 // the year -292277022399. 392 // 393 // All this is opaque to clients of the API and can be changed if a 394 // better implementation presents itself. 395 396 const ( 397 // The unsigned zero year for internal calculations. 398 // Must be 1 mod 400, and times before it will not compute correctly, 399 // but otherwise can be changed at will. 400 absoluteZeroYear = -292277022399 401 402 // The year of the zero Time. 403 // Assumed by the unixToInternal computation below. 404 internalYear = 1 405 406 // Offsets to convert between internal and absolute or Unix times. 407 absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay 408 internalToAbsolute = -absoluteToInternal 409 410 unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay 411 internalToUnix int64 = -unixToInternal 412 413 wallToInternal int64 = (1884*365 + 1884/4 - 1884/100 + 1884/400) * secondsPerDay 414 internalToWall int64 = -wallToInternal 415 ) 416 417 // IsZero reports whether t represents the zero time instant, 418 // January 1, year 1, 00:00:00 UTC. 419 func (t Time) IsZero() bool { 420 return t.sec() == 0 && t.nsec() == 0 421 } 422 423 // abs returns the time t as an absolute time, adjusted by the zone offset. 424 // It is called when computing a presentation property like Month or Hour. 425 func (t Time) abs() uint64 { 426 l := t.loc 427 // Avoid function calls when possible. 428 if l == nil || l == &localLoc { 429 l = l.get() 430 } 431 sec := t.unixSec() 432 if l != &utcLoc { 433 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { 434 sec += int64(l.cacheZone.offset) 435 } else { 436 _, offset, _, _, _ := l.lookup(sec) 437 sec += int64(offset) 438 } 439 } 440 return uint64(sec + (unixToInternal + internalToAbsolute)) 441 } 442 443 // locabs is a combination of the Zone and abs methods, 444 // extracting both return values from a single zone lookup. 445 func (t Time) locabs() (name string, offset int, abs uint64) { 446 l := t.loc 447 if l == nil || l == &localLoc { 448 l = l.get() 449 } 450 // Avoid function call if we hit the local time cache. 451 sec := t.unixSec() 452 if l != &utcLoc { 453 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { 454 name = l.cacheZone.name 455 offset = l.cacheZone.offset 456 } else { 457 name, offset, _, _, _ = l.lookup(sec) 458 } 459 sec += int64(offset) 460 } else { 461 name = "UTC" 462 } 463 abs = uint64(sec + (unixToInternal + internalToAbsolute)) 464 return 465 } 466 467 // Date returns the year, month, and day in which t occurs. 468 func (t Time) Date() (year int, month Month, day int) { 469 year, month, day, _ = t.date(true) 470 return 471 } 472 473 // Year returns the year in which t occurs. 474 func (t Time) Year() int { 475 year, _, _, _ := t.date(false) 476 return year 477 } 478 479 // Month returns the month of the year specified by t. 480 func (t Time) Month() Month { 481 _, month, _, _ := t.date(true) 482 return month 483 } 484 485 // Day returns the day of the month specified by t. 486 func (t Time) Day() int { 487 _, _, day, _ := t.date(true) 488 return day 489 } 490 491 // Weekday returns the day of the week specified by t. 492 func (t Time) Weekday() Weekday { 493 return absWeekday(t.abs()) 494 } 495 496 // absWeekday is like Weekday but operates on an absolute time. 497 func absWeekday(abs uint64) Weekday { 498 // January 1 of the absolute year, like January 1 of 2001, was a Monday. 499 sec := (abs + uint64(Monday)*secondsPerDay) % secondsPerWeek 500 return Weekday(int(sec) / secondsPerDay) 501 } 502 503 // ISOWeek returns the ISO 8601 year and week number in which t occurs. 504 // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to 505 // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 506 // of year n+1. 507 func (t Time) ISOWeek() (year, week int) { 508 year, month, day, yday := t.date(true) 509 wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0. 510 const ( 511 Mon int = iota 512 Tue 513 Wed 514 Thu 515 Fri 516 Sat 517 Sun 518 ) 519 520 // Calculate week as number of Mondays in year up to 521 // and including today, plus 1 because the first week is week 0. 522 // Putting the + 1 inside the numerator as a + 7 keeps the 523 // numerator from being negative, which would cause it to 524 // round incorrectly. 525 week = (yday - wday + 7) / 7 526 527 // The week number is now correct under the assumption 528 // that the first Monday of the year is in week 1. 529 // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday 530 // is actually in week 2. 531 jan1wday := (wday - yday + 7*53) % 7 532 if Tue <= jan1wday && jan1wday <= Thu { 533 week++ 534 } 535 536 // If the week number is still 0, we're in early January but in 537 // the last week of last year. 538 if week == 0 { 539 year-- 540 week = 52 541 // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday, 542 // meaning Jan 1 of the next year is a Friday 543 // or it was a leap year and Jan 1 of the next year is a Saturday. 544 if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) { 545 week++ 546 } 547 } 548 549 // December 29 to 31 are in week 1 of next year if 550 // they are after the last Thursday of the year and 551 // December 31 is a Monday, Tuesday, or Wednesday. 552 if month == December && day >= 29 && wday < Thu { 553 if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed { 554 year++ 555 week = 1 556 } 557 } 558 559 return 560 } 561 562 // Clock returns the hour, minute, and second within the day specified by t. 563 func (t Time) Clock() (hour, min, sec int) { 564 return absClock(t.abs()) 565 } 566 567 // absClock is like clock but operates on an absolute time. 568 func absClock(abs uint64) (hour, min, sec int) { 569 sec = int(abs % secondsPerDay) 570 hour = sec / secondsPerHour 571 sec -= hour * secondsPerHour 572 min = sec / secondsPerMinute 573 sec -= min * secondsPerMinute 574 return 575 } 576 577 // Hour returns the hour within the day specified by t, in the range [0, 23]. 578 func (t Time) Hour() int { 579 return int(t.abs()%secondsPerDay) / secondsPerHour 580 } 581 582 // Minute returns the minute offset within the hour specified by t, in the range [0, 59]. 583 func (t Time) Minute() int { 584 return int(t.abs()%secondsPerHour) / secondsPerMinute 585 } 586 587 // Second returns the second offset within the minute specified by t, in the range [0, 59]. 588 func (t Time) Second() int { 589 return int(t.abs() % secondsPerMinute) 590 } 591 592 // Nanosecond returns the nanosecond offset within the second specified by t, 593 // in the range [0, 999999999]. 594 func (t Time) Nanosecond() int { 595 return int(t.nsec()) 596 } 597 598 // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, 599 // and [1,366] in leap years. 600 func (t Time) YearDay() int { 601 _, _, _, yday := t.date(false) 602 return yday + 1 603 } 604 605 // A Duration represents the elapsed time between two instants 606 // as an int64 nanosecond count. The representation limits the 607 // largest representable duration to approximately 290 years. 608 type Duration int64 609 610 const ( 611 minDuration Duration = -1 << 63 612 maxDuration Duration = 1<<63 - 1 613 ) 614 615 // Common durations. There is no definition for units of Day or larger 616 // to avoid confusion across daylight savings time zone transitions. 617 // 618 // To count the number of units in a Duration, divide: 619 // second := time.Second 620 // fmt.Print(int64(second/time.Millisecond)) // prints 1000 621 // 622 // To convert an integer number of units to a Duration, multiply: 623 // seconds := 10 624 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s 625 // 626 const ( 627 Nanosecond Duration = 1 628 Microsecond = 1000 * Nanosecond 629 Millisecond = 1000 * Microsecond 630 Second = 1000 * Millisecond 631 Minute = 60 * Second 632 Hour = 60 * Minute 633 ) 634 635 // String returns a string representing the duration in the form "72h3m0.5s". 636 // Leading zero units are omitted. As a special case, durations less than one 637 // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure 638 // that the leading digit is non-zero. The zero duration formats as 0s. 639 func (d Duration) String() string { 640 // Largest time is 2540400h10m10.000000000s 641 var buf [32]byte 642 w := len(buf) 643 644 u := uint64(d) 645 neg := d < 0 646 if neg { 647 u = -u 648 } 649 650 if u < uint64(Second) { 651 // Special case: if duration is smaller than a second, 652 // use smaller units, like 1.2ms 653 var prec int 654 w-- 655 buf[w] = 's' 656 w-- 657 switch { 658 case u == 0: 659 return "0s" 660 case u < uint64(Microsecond): 661 // print nanoseconds 662 prec = 0 663 buf[w] = 'n' 664 case u < uint64(Millisecond): 665 // print microseconds 666 prec = 3 667 // U+00B5 'µ' micro sign == 0xC2 0xB5 668 w-- // Need room for two bytes. 669 copy(buf[w:], "µ") 670 default: 671 // print milliseconds 672 prec = 6 673 buf[w] = 'm' 674 } 675 w, u = fmtFrac(buf[:w], u, prec) 676 w = fmtInt(buf[:w], u) 677 } else { 678 w-- 679 buf[w] = 's' 680 681 w, u = fmtFrac(buf[:w], u, 9) 682 683 // u is now integer seconds 684 w = fmtInt(buf[:w], u%60) 685 u /= 60 686 687 // u is now integer minutes 688 if u > 0 { 689 w-- 690 buf[w] = 'm' 691 w = fmtInt(buf[:w], u%60) 692 u /= 60 693 694 // u is now integer hours 695 // Stop at hours because days can be different lengths. 696 if u > 0 { 697 w-- 698 buf[w] = 'h' 699 w = fmtInt(buf[:w], u) 700 } 701 } 702 } 703 704 if neg { 705 w-- 706 buf[w] = '-' 707 } 708 709 return string(buf[w:]) 710 } 711 712 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the 713 // tail of buf, omitting trailing zeros. it omits the decimal 714 // point too when the fraction is 0. It returns the index where the 715 // output bytes begin and the value v/10**prec. 716 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) { 717 // Omit trailing zeros up to and including decimal point. 718 w := len(buf) 719 print := false 720 for i := 0; i < prec; i++ { 721 digit := v % 10 722 print = print || digit != 0 723 if print { 724 w-- 725 buf[w] = byte(digit) + '0' 726 } 727 v /= 10 728 } 729 if print { 730 w-- 731 buf[w] = '.' 732 } 733 return w, v 734 } 735 736 // fmtInt formats v into the tail of buf. 737 // It returns the index where the output begins. 738 func fmtInt(buf []byte, v uint64) int { 739 w := len(buf) 740 if v == 0 { 741 w-- 742 buf[w] = '0' 743 } else { 744 for v > 0 { 745 w-- 746 buf[w] = byte(v%10) + '0' 747 v /= 10 748 } 749 } 750 return w 751 } 752 753 // Nanoseconds returns the duration as an integer nanosecond count. 754 func (d Duration) Nanoseconds() int64 { return int64(d) } 755 756 // These methods return float64 because the dominant 757 // use case is for printing a floating point number like 1.5s, and 758 // a truncation to integer would make them not useful in those cases. 759 // Splitting the integer and fraction ourselves guarantees that 760 // converting the returned float64 to an integer rounds the same 761 // way that a pure integer conversion would have, even in cases 762 // where, say, float64(d.Nanoseconds())/1e9 would have rounded 763 // differently. 764 765 // Seconds returns the duration as a floating point number of seconds. 766 func (d Duration) Seconds() float64 { 767 sec := d / Second 768 nsec := d % Second 769 return float64(sec) + float64(nsec)/1e9 770 } 771 772 // Minutes returns the duration as a floating point number of minutes. 773 func (d Duration) Minutes() float64 { 774 min := d / Minute 775 nsec := d % Minute 776 return float64(min) + float64(nsec)/(60*1e9) 777 } 778 779 // Hours returns the duration as a floating point number of hours. 780 func (d Duration) Hours() float64 { 781 hour := d / Hour 782 nsec := d % Hour 783 return float64(hour) + float64(nsec)/(60*60*1e9) 784 } 785 786 // Add returns the time t+d. 787 func (t Time) Add(d Duration) Time { 788 dsec := int64(d / 1e9) 789 nsec := t.nsec() + int32(d%1e9) 790 if nsec >= 1e9 { 791 dsec++ 792 nsec -= 1e9 793 } else if nsec < 0 { 794 dsec-- 795 nsec += 1e9 796 } 797 t.wall = t.wall&^nsecMask | uint64(nsec) // update nsec 798 t.addSec(dsec) 799 if t.wall&hasMonotonic != 0 { 800 te := t.ext + int64(d) 801 if d < 0 && te > int64(t.ext) || d > 0 && te < int64(t.ext) { 802 // Monotonic clock reading now out of range; degrade to wall-only. 803 t.ext = t.sec() 804 t.wall &= nsecMask 805 } else { 806 t.ext = te 807 } 808 } 809 return t 810 } 811 812 // Sub returns the duration t-u. If the result exceeds the maximum (or minimum) 813 // value that can be stored in a Duration, the maximum (or minimum) duration 814 // will be returned. 815 // To compute t-d for a duration d, use t.Add(-d). 816 func (t Time) Sub(u Time) Duration { 817 if t.wall&u.wall&hasMonotonic != 0 { 818 te := int64(t.ext) 819 ue := int64(u.ext) 820 d := Duration(te - ue) 821 if d < 0 && te > ue { 822 return maxDuration // t - u is positive out of range 823 } 824 if d > 0 && te < ue { 825 return minDuration // t - u is negative out of range 826 } 827 return d 828 } 829 d := Duration(t.sec()-u.sec())*Second + Duration(t.nsec()-u.nsec()) 830 // Check for overflow or underflow. 831 switch { 832 case u.Add(d).Equal(t): 833 return d // d is correct 834 case t.Before(u): 835 return minDuration // t - u is negative out of range 836 default: 837 return maxDuration // t - u is positive out of range 838 } 839 } 840 841 // Since returns the time elapsed since t. 842 // It is shorthand for time.Now().Sub(t). 843 func Since(t Time) Duration { 844 return Now().Sub(t) 845 } 846 847 // Until returns the duration until t. 848 // It is shorthand for t.Sub(time.Now()). 849 func Until(t Time) Duration { 850 return t.Sub(Now()) 851 } 852 853 // AddDate returns the time corresponding to adding the 854 // given number of years, months, and days to t. 855 // For example, AddDate(-1, 2, 3) applied to January 1, 2011 856 // returns March 4, 2010. 857 // 858 // AddDate normalizes its result in the same way that Date does, 859 // so, for example, adding one month to October 31 yields 860 // December 1, the normalized form for November 31. 861 func (t Time) AddDate(years int, months int, days int) Time { 862 year, month, day := t.Date() 863 hour, min, sec := t.Clock() 864 return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec()), t.Location()) 865 } 866 867 const ( 868 secondsPerMinute = 60 869 secondsPerHour = 60 * 60 870 secondsPerDay = 24 * secondsPerHour 871 secondsPerWeek = 7 * secondsPerDay 872 daysPer400Years = 365*400 + 97 873 daysPer100Years = 365*100 + 24 874 daysPer4Years = 365*4 + 1 875 ) 876 877 // date computes the year, day of year, and when full=true, 878 // the month and day in which t occurs. 879 func (t Time) date(full bool) (year int, month Month, day int, yday int) { 880 return absDate(t.abs(), full) 881 } 882 883 // absDate is like date but operates on an absolute time. 884 func absDate(abs uint64, full bool) (year int, month Month, day int, yday int) { 885 // Split into time and day. 886 d := abs / secondsPerDay 887 888 // Account for 400 year cycles. 889 n := d / daysPer400Years 890 y := 400 * n 891 d -= daysPer400Years * n 892 893 // Cut off 100-year cycles. 894 // The last cycle has one extra leap year, so on the last day 895 // of that year, day / daysPer100Years will be 4 instead of 3. 896 // Cut it back down to 3 by subtracting n>>2. 897 n = d / daysPer100Years 898 n -= n >> 2 899 y += 100 * n 900 d -= daysPer100Years * n 901 902 // Cut off 4-year cycles. 903 // The last cycle has a missing leap year, which does not 904 // affect the computation. 905 n = d / daysPer4Years 906 y += 4 * n 907 d -= daysPer4Years * n 908 909 // Cut off years within a 4-year cycle. 910 // The last year is a leap year, so on the last day of that year, 911 // day / 365 will be 4 instead of 3. Cut it back down to 3 912 // by subtracting n>>2. 913 n = d / 365 914 n -= n >> 2 915 y += n 916 d -= 365 * n 917 918 year = int(int64(y) + absoluteZeroYear) 919 yday = int(d) 920 921 if !full { 922 return 923 } 924 925 day = yday 926 if isLeap(year) { 927 // Leap year 928 switch { 929 case day > 31+29-1: 930 // After leap day; pretend it wasn't there. 931 day-- 932 case day == 31+29-1: 933 // Leap day. 934 month = February 935 day = 29 936 return 937 } 938 } 939 940 // Estimate month on assumption that every month has 31 days. 941 // The estimate may be too low by at most one month, so adjust. 942 month = Month(day / 31) 943 end := int(daysBefore[month+1]) 944 var begin int 945 if day >= end { 946 month++ 947 begin = end 948 } else { 949 begin = int(daysBefore[month]) 950 } 951 952 month++ // because January is 1 953 day = day - begin + 1 954 return 955 } 956 957 // daysBefore[m] counts the number of days in a non-leap year 958 // before month m begins. There is an entry for m=12, counting 959 // the number of days before January of next year (365). 960 var daysBefore = [...]int32{ 961 0, 962 31, 963 31 + 28, 964 31 + 28 + 31, 965 31 + 28 + 31 + 30, 966 31 + 28 + 31 + 30 + 31, 967 31 + 28 + 31 + 30 + 31 + 30, 968 31 + 28 + 31 + 30 + 31 + 30 + 31, 969 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, 970 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, 971 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, 972 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, 973 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31, 974 } 975 976 func daysIn(m Month, year int) int { 977 if m == February && isLeap(year) { 978 return 29 979 } 980 return int(daysBefore[m] - daysBefore[m-1]) 981 } 982 983 // Provided by package runtime. 984 func now() (sec int64, nsec int32, mono uint64) 985 986 // Now returns the current local time. 987 func Now() Time { 988 sec, nsec, mono := now() 989 t := unixTime(sec, nsec) 990 t.setMono(int64(mono)) 991 return t 992 } 993 994 func unixTime(sec int64, nsec int32) Time { 995 return Time{uint64(nsec), sec + unixToInternal, Local} 996 } 997 998 // UTC returns t with the location set to UTC. 999 func (t Time) UTC() Time { 1000 t.setLoc(&utcLoc) 1001 return t 1002 } 1003 1004 // Local returns t with the location set to local time. 1005 func (t Time) Local() Time { 1006 t.setLoc(Local) 1007 return t 1008 } 1009 1010 // In returns t with the location information set to loc. 1011 // 1012 // In panics if loc is nil. 1013 func (t Time) In(loc *Location) Time { 1014 if loc == nil { 1015 panic("time: missing Location in call to Time.In") 1016 } 1017 t.setLoc(loc) 1018 return t 1019 } 1020 1021 // Location returns the time zone information associated with t. 1022 func (t Time) Location() *Location { 1023 l := t.loc 1024 if l == nil { 1025 l = UTC 1026 } 1027 return l 1028 } 1029 1030 // Zone computes the time zone in effect at time t, returning the abbreviated 1031 // name of the zone (such as "CET") and its offset in seconds east of UTC. 1032 func (t Time) Zone() (name string, offset int) { 1033 name, offset, _, _, _ = t.loc.lookup(t.unixSec()) 1034 return 1035 } 1036 1037 // Unix returns t as a Unix time, the number of seconds elapsed 1038 // since January 1, 1970 UTC. 1039 func (t Time) Unix() int64 { 1040 return t.unixSec() 1041 } 1042 1043 // UnixNano returns t as a Unix time, the number of nanoseconds elapsed 1044 // since January 1, 1970 UTC. The result is undefined if the Unix time 1045 // in nanoseconds cannot be represented by an int64 (a date before the year 1046 // 1678 or after 2262). Note that this means the result of calling UnixNano 1047 // on the zero Time is undefined. 1048 func (t Time) UnixNano() int64 { 1049 return (t.unixSec())*1e9 + int64(t.nsec()) 1050 } 1051 1052 const timeBinaryVersion byte = 1 1053 1054 // MarshalBinary implements the encoding.BinaryMarshaler interface. 1055 func (t Time) MarshalBinary() ([]byte, error) { 1056 var offsetMin int16 // minutes east of UTC. -1 is UTC. 1057 1058 if t.Location() == UTC { 1059 offsetMin = -1 1060 } else { 1061 _, offset := t.Zone() 1062 if offset%60 != 0 { 1063 return nil, errors.New("Time.MarshalBinary: zone offset has fractional minute") 1064 } 1065 offset /= 60 1066 if offset < -32768 || offset == -1 || offset > 32767 { 1067 return nil, errors.New("Time.MarshalBinary: unexpected zone offset") 1068 } 1069 offsetMin = int16(offset) 1070 } 1071 1072 sec := t.sec() 1073 nsec := t.nsec() 1074 enc := []byte{ 1075 timeBinaryVersion, // byte 0 : version 1076 byte(sec >> 56), // bytes 1-8: seconds 1077 byte(sec >> 48), 1078 byte(sec >> 40), 1079 byte(sec >> 32), 1080 byte(sec >> 24), 1081 byte(sec >> 16), 1082 byte(sec >> 8), 1083 byte(sec), 1084 byte(nsec >> 24), // bytes 9-12: nanoseconds 1085 byte(nsec >> 16), 1086 byte(nsec >> 8), 1087 byte(nsec), 1088 byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes 1089 byte(offsetMin), 1090 } 1091 1092 return enc, nil 1093 } 1094 1095 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. 1096 func (t *Time) UnmarshalBinary(data []byte) error { 1097 buf := data 1098 if len(buf) == 0 { 1099 return errors.New("Time.UnmarshalBinary: no data") 1100 } 1101 1102 if buf[0] != timeBinaryVersion { 1103 return errors.New("Time.UnmarshalBinary: unsupported version") 1104 } 1105 1106 if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 { 1107 return errors.New("Time.UnmarshalBinary: invalid length") 1108 } 1109 1110 buf = buf[1:] 1111 sec := int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 | 1112 int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56 1113 1114 buf = buf[8:] 1115 nsec := int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24 1116 1117 buf = buf[4:] 1118 offset := int(int16(buf[1])|int16(buf[0])<<8) * 60 1119 1120 *t = Time{} 1121 t.wall = uint64(nsec) 1122 t.ext = sec 1123 1124 if offset == -1*60 { 1125 t.setLoc(&utcLoc) 1126 } else if _, localoff, _, _, _ := Local.lookup(t.unixSec()); offset == localoff { 1127 t.setLoc(Local) 1128 } else { 1129 t.setLoc(FixedZone("", offset)) 1130 } 1131 1132 return nil 1133 } 1134 1135 // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2. 1136 // The same semantics will be provided by the generic MarshalBinary, MarshalText, 1137 // UnmarshalBinary, UnmarshalText. 1138 1139 // GobEncode implements the gob.GobEncoder interface. 1140 func (t Time) GobEncode() ([]byte, error) { 1141 return t.MarshalBinary() 1142 } 1143 1144 // GobDecode implements the gob.GobDecoder interface. 1145 func (t *Time) GobDecode(data []byte) error { 1146 return t.UnmarshalBinary(data) 1147 } 1148 1149 // MarshalJSON implements the json.Marshaler interface. 1150 // The time is a quoted string in RFC 3339 format, with sub-second precision added if present. 1151 func (t Time) MarshalJSON() ([]byte, error) { 1152 if y := t.Year(); y < 0 || y >= 10000 { 1153 // RFC 3339 is clear that years are 4 digits exactly. 1154 // See golang.org/issue/4556#c15 for more discussion. 1155 return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") 1156 } 1157 1158 b := make([]byte, 0, len(RFC3339Nano)+2) 1159 b = append(b, '"') 1160 b = t.AppendFormat(b, RFC3339Nano) 1161 b = append(b, '"') 1162 return b, nil 1163 } 1164 1165 // UnmarshalJSON implements the json.Unmarshaler interface. 1166 // The time is expected to be a quoted string in RFC 3339 format. 1167 func (t *Time) UnmarshalJSON(data []byte) error { 1168 // Ignore null, like in the main JSON package. 1169 if string(data) == "null" { 1170 return nil 1171 } 1172 // Fractional seconds are handled implicitly by Parse. 1173 var err error 1174 *t, err = Parse(`"`+RFC3339+`"`, string(data)) 1175 return err 1176 } 1177 1178 // MarshalText implements the encoding.TextMarshaler interface. 1179 // The time is formatted in RFC 3339 format, with sub-second precision added if present. 1180 func (t Time) MarshalText() ([]byte, error) { 1181 if y := t.Year(); y < 0 || y >= 10000 { 1182 return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") 1183 } 1184 1185 b := make([]byte, 0, len(RFC3339Nano)) 1186 return t.AppendFormat(b, RFC3339Nano), nil 1187 } 1188 1189 // UnmarshalText implements the encoding.TextUnmarshaler interface. 1190 // The time is expected to be in RFC 3339 format. 1191 func (t *Time) UnmarshalText(data []byte) error { 1192 // Fractional seconds are handled implicitly by Parse. 1193 var err error 1194 *t, err = Parse(RFC3339, string(data)) 1195 return err 1196 } 1197 1198 // Unix returns the local Time corresponding to the given Unix time, 1199 // sec seconds and nsec nanoseconds since January 1, 1970 UTC. 1200 // It is valid to pass nsec outside the range [0, 999999999]. 1201 // Not all sec values have a corresponding time value. One such 1202 // value is 1<<63-1 (the largest int64 value). 1203 func Unix(sec int64, nsec int64) Time { 1204 if nsec < 0 || nsec >= 1e9 { 1205 n := nsec / 1e9 1206 sec += n 1207 nsec -= n * 1e9 1208 if nsec < 0 { 1209 nsec += 1e9 1210 sec-- 1211 } 1212 } 1213 return unixTime(sec, int32(nsec)) 1214 } 1215 1216 func isLeap(year int) bool { 1217 return year%4 == 0 && (year%100 != 0 || year%400 == 0) 1218 } 1219 1220 // norm returns nhi, nlo such that 1221 // hi * base + lo == nhi * base + nlo 1222 // 0 <= nlo < base 1223 func norm(hi, lo, base int) (nhi, nlo int) { 1224 if lo < 0 { 1225 n := (-lo-1)/base + 1 1226 hi -= n 1227 lo += n * base 1228 } 1229 if lo >= base { 1230 n := lo / base 1231 hi += n 1232 lo -= n * base 1233 } 1234 return hi, lo 1235 } 1236 1237 // Date returns the Time corresponding to 1238 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds 1239 // in the appropriate zone for that time in the given location. 1240 // 1241 // The month, day, hour, min, sec, and nsec values may be outside 1242 // their usual ranges and will be normalized during the conversion. 1243 // For example, October 32 converts to November 1. 1244 // 1245 // A daylight savings time transition skips or repeats times. 1246 // For example, in the United States, March 13, 2011 2:15am never occurred, 1247 // while November 6, 2011 1:15am occurred twice. In such cases, the 1248 // choice of time zone, and therefore the time, is not well-defined. 1249 // Date returns a time that is correct in one of the two zones involved 1250 // in the transition, but it does not guarantee which. 1251 // 1252 // Date panics if loc is nil. 1253 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time { 1254 if loc == nil { 1255 panic("time: missing Location in call to Date") 1256 } 1257 1258 // Normalize month, overflowing into year. 1259 m := int(month) - 1 1260 year, m = norm(year, m, 12) 1261 month = Month(m) + 1 1262 1263 // Normalize nsec, sec, min, hour, overflowing into day. 1264 sec, nsec = norm(sec, nsec, 1e9) 1265 min, sec = norm(min, sec, 60) 1266 hour, min = norm(hour, min, 60) 1267 day, hour = norm(day, hour, 24) 1268 1269 y := uint64(int64(year) - absoluteZeroYear) 1270 1271 // Compute days since the absolute epoch. 1272 1273 // Add in days from 400-year cycles. 1274 n := y / 400 1275 y -= 400 * n 1276 d := daysPer400Years * n 1277 1278 // Add in 100-year cycles. 1279 n = y / 100 1280 y -= 100 * n 1281 d += daysPer100Years * n 1282 1283 // Add in 4-year cycles. 1284 n = y / 4 1285 y -= 4 * n 1286 d += daysPer4Years * n 1287 1288 // Add in non-leap years. 1289 n = y 1290 d += 365 * n 1291 1292 // Add in days before this month. 1293 d += uint64(daysBefore[month-1]) 1294 if isLeap(year) && month >= March { 1295 d++ // February 29 1296 } 1297 1298 // Add in days before today. 1299 d += uint64(day - 1) 1300 1301 // Add in time elapsed today. 1302 abs := d * secondsPerDay 1303 abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec) 1304 1305 unix := int64(abs) + (absoluteToInternal + internalToUnix) 1306 1307 // Look for zone offset for t, so we can adjust to UTC. 1308 // The lookup function expects UTC, so we pass t in the 1309 // hope that it will not be too close to a zone transition, 1310 // and then adjust if it is. 1311 _, offset, _, start, end := loc.lookup(unix) 1312 if offset != 0 { 1313 switch utc := unix - int64(offset); { 1314 case utc < start: 1315 _, offset, _, _, _ = loc.lookup(start - 1) 1316 case utc >= end: 1317 _, offset, _, _, _ = loc.lookup(end) 1318 } 1319 unix -= int64(offset) 1320 } 1321 1322 t := unixTime(unix, int32(nsec)) 1323 t.setLoc(loc) 1324 return t 1325 } 1326 1327 // Truncate returns the result of rounding t down to a multiple of d (since the zero time). 1328 // If d <= 0, Truncate returns t unchanged. 1329 // 1330 // Truncate operates on the time as an absolute duration since the 1331 // zero time; it does not operate on the presentation form of the 1332 // time. Thus, Truncate(Hour) may return a time with a non-zero 1333 // minute, depending on the time's Location. 1334 func (t Time) Truncate(d Duration) Time { 1335 if d <= 0 { 1336 return t 1337 } 1338 _, r := div(t, d) 1339 return t.Add(-r) 1340 } 1341 1342 // Round returns the result of rounding t to the nearest multiple of d (since the zero time). 1343 // The rounding behavior for halfway values is to round up. 1344 // If d <= 0, Round returns t unchanged. 1345 // 1346 // Round operates on the time as an absolute duration since the 1347 // zero time; it does not operate on the presentation form of the 1348 // time. Thus, Round(Hour) may return a time with a non-zero 1349 // minute, depending on the time's Location. 1350 func (t Time) Round(d Duration) Time { 1351 if d <= 0 { 1352 return t 1353 } 1354 _, r := div(t, d) 1355 if r+r < d { 1356 return t.Add(-r) 1357 } 1358 return t.Add(d - r) 1359 } 1360 1361 // div divides t by d and returns the quotient parity and remainder. 1362 // We don't use the quotient parity anymore (round half up instead of round to even) 1363 // but it's still here in case we change our minds. 1364 func div(t Time, d Duration) (qmod2 int, r Duration) { 1365 neg := false 1366 nsec := t.nsec() 1367 sec := t.sec() 1368 if sec < 0 { 1369 // Operate on absolute value. 1370 neg = true 1371 sec = -sec 1372 nsec = -nsec 1373 if nsec < 0 { 1374 nsec += 1e9 1375 sec-- // sec >= 1 before the -- so safe 1376 } 1377 } 1378 1379 switch { 1380 // Special case: 2d divides 1 second. 1381 case d < Second && Second%(d+d) == 0: 1382 qmod2 = int(nsec/int32(d)) & 1 1383 r = Duration(nsec % int32(d)) 1384 1385 // Special case: d is a multiple of 1 second. 1386 case d%Second == 0: 1387 d1 := int64(d / Second) 1388 qmod2 = int(sec/d1) & 1 1389 r = Duration(sec%d1)*Second + Duration(nsec) 1390 1391 // General case. 1392 // This could be faster if more cleverness were applied, 1393 // but it's really only here to avoid special case restrictions in the API. 1394 // No one will care about these cases. 1395 default: 1396 // Compute nanoseconds as 128-bit number. 1397 sec := uint64(sec) 1398 tmp := (sec >> 32) * 1e9 1399 u1 := tmp >> 32 1400 u0 := tmp << 32 1401 tmp = (sec & 0xFFFFFFFF) * 1e9 1402 u0x, u0 := u0, u0+tmp 1403 if u0 < u0x { 1404 u1++ 1405 } 1406 u0x, u0 = u0, u0+uint64(nsec) 1407 if u0 < u0x { 1408 u1++ 1409 } 1410 1411 // Compute remainder by subtracting r<<k for decreasing k. 1412 // Quotient parity is whether we subtract on last round. 1413 d1 := uint64(d) 1414 for d1>>63 != 1 { 1415 d1 <<= 1 1416 } 1417 d0 := uint64(0) 1418 for { 1419 qmod2 = 0 1420 if u1 > d1 || u1 == d1 && u0 >= d0 { 1421 // subtract 1422 qmod2 = 1 1423 u0x, u0 = u0, u0-d0 1424 if u0 > u0x { 1425 u1-- 1426 } 1427 u1 -= d1 1428 } 1429 if d1 == 0 && d0 == uint64(d) { 1430 break 1431 } 1432 d0 >>= 1 1433 d0 |= (d1 & 1) << 63 1434 d1 >>= 1 1435 } 1436 r = Duration(u0) 1437 } 1438 1439 if neg && r != 0 { 1440 // If input was negative and not an exact multiple of d, we computed q, r such that 1441 // q*d + r = -t 1442 // But the right answers are given by -(q-1), d-r: 1443 // q*d + r = -t 1444 // -q*d - r = t 1445 // -(q-1)*d + (d - r) = t 1446 qmod2 ^= 1 1447 r = d - r 1448 } 1449 return 1450 }