diff options
author | bstarynk <bstarynk@138bc75d-0d04-0410-961f-82ee72b054a4> | 2015-01-21 22:01:24 +0000 |
---|---|---|
committer | bstarynk <bstarynk@138bc75d-0d04-0410-961f-82ee72b054a4> | 2015-01-21 22:01:24 +0000 |
commit | ffde65b31066f17eef243be882bb89a6e19370aa (patch) | |
tree | ea876d041c0a63eefccdac5416a8678e75da4cfc /libgo/go/time | |
parent | a8c7acc4db08ce7c8ac3ddcb943f9219e2893792 (diff) | |
download | gcc-ffde65b31066f17eef243be882bb89a6e19370aa.tar.gz |
[.]
2015-01-21 Basile Starynkevitch <basile@starynkevitch.net>
{{merged with trunk -i.e. GCC5.0 in stage4- using
svn merge -r209216:219879 svn+ssh://bstarynk@gcc.gnu.org/svn/gcc/trunk
but should probably have used
svn merge -r209216:219879 ^/trunk
we don't use svnmerge.py anymore since our svn is version 1.8.10
}}
VERY UNSTABLE
2015-01-20 Basile Starynkevitch <basile@starynkevitch.net>
Move previous topdir ChangeLog.MELT to ChangeLog.MELT.2008-2014
[contrib/]
2015-01-21 Basile Starynkevitch <basile@starynkevitch.net>
* MELT-Plugin-Makefile: Able to make upgrade-melt as a
plugin. Works for GCC 5.0. Remove GCC 4.7 old stuff.
Move previous contrib/ChangeLog.MELT to ChangeLog.MELT.2008-2014
[gcc/]
2015-01-21 Basile Starynkevitch <basile@starynkevitch.net>
{{merged with trunk -i.e. GCC5.0 in stage4- using
svn merge -r209216:219879 svn+ssh://bstarynk@gcc.gnu.org/svn/gcc/trunk
but should probably have used
svn merge -r209216:219879 ^/trunk
**@@@ UNSTABLE since libmelt-ana-gimple.melt not compiling, but
translator painfully bootstrapping!!@@@@ }}
* toplev.c: Merged manually by keeping MELT extra stuff.
* toplev.h: Likewise.
* gengtype.c: Add "melt-runtime.h" in list, but merged with trunk.
* melt-runtime.h (MELT_VERSION_STRING): Bump to "1.2-pre-merged".
(meltgc_walk_gimple_seq): Remove.
(gt_ggc_mx_gimple_statement_d): Same for GCC 4.9 & 5.0
* melt-runtime.cc: Update copyright year.
(ggc_alloc_cleared_melt_valuevector_st, melt_resize_scangcvect):
Call ggc_internal_cleared_alloc.
(melt_val2passflag): Skip TODO_verify_ssa, TODO_verify_flow,
TODO_verify_stmts, TODO_verify_rtl_sharing for GCC 5.0.
(meltgc_walkstmt_cb, meltgc_walktree_cb)
(melt_tree_walk_frame_size, meltgc_walk_gimple_seq): Remove.
(melt_gt_ggc_mx_gimple_seq_d): Call
gt_ggc_mx_gimple_statement_base.
* melt-build-script.tpl: Update copyright year. Don't symlink
meltrunsup.h anymore.
* melt-build-script.sh: Regenerate.
* melt/warmelt-base.melt: Update copyright year.
(valdesc_object, valdesc_mapobjects, valdesc_mapstrings)
(valdesc_multiple, valdesc_closure, valdesc_routine, valdesc_hook)
(valdesc_bucketlongs, valdesc_jsonobject, valdesc_string)
(valdesc_strbuf, valdesc_pair, valdesc_list, valdesc_int)
(valdesc_double, valdesc_mixint, valdesc_mixloc)
(valdesc_mixbigint, valdesc_real, valdesc_special_data): Use
ggc_internal_alloc & ggc_internal_cleared_alloc for GCC 5.0.
(json_canonical_name): Use ISUPPER, ISALPHA, TOUPPER instead of
their standard <ctype.h> lowercase macros.
* melt/warmelt-modes.melt: Update copyright year.
(generate_runtypesupport_forwcopy_fun): Emit both GCC 4.9 & 5.0
compatible code.
* melt/libmelt-ana-base.melt: Update copyright year.
* melt/libmelt-ana-gimple.melt: TO BE IMPROVED
* melt/generated/*: Painfully regenerated several times thru GCC
4.9 MELT plugin.
git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/branches/melt-branch@219975 138bc75d-0d04-0410-961f-82ee72b054a4
Diffstat (limited to 'libgo/go/time')
-rw-r--r-- | libgo/go/time/example_test.go | 4 | ||||
-rw-r--r-- | libgo/go/time/format.go | 18 | ||||
-rw-r--r-- | libgo/go/time/format_test.go | 520 | ||||
-rw-r--r-- | libgo/go/time/genzabbrs.go | 20 | ||||
-rw-r--r-- | libgo/go/time/internal_test.go | 43 | ||||
-rw-r--r-- | libgo/go/time/sleep.go | 28 | ||||
-rw-r--r-- | libgo/go/time/sleep_test.go | 78 | ||||
-rw-r--r-- | libgo/go/time/sys_unix.go | 2 | ||||
-rw-r--r-- | libgo/go/time/tick.go | 3 | ||||
-rw-r--r-- | libgo/go/time/tick_test.go | 18 | ||||
-rw-r--r-- | libgo/go/time/time.go | 45 | ||||
-rw-r--r-- | libgo/go/time/time_test.go | 557 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo.go | 87 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo_abbrs_windows.go | 3 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo_plan9.go | 2 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo_read.go | 8 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo_test.go | 66 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo_unix.go | 2 | ||||
-rw-r--r-- | libgo/go/time/zoneinfo_windows.go | 10 |
19 files changed, 889 insertions, 625 deletions
diff --git a/libgo/go/time/example_test.go b/libgo/go/time/example_test.go index cfa5b38c5f1..a37e8b86ddc 100644 --- a/libgo/go/time/example_test.go +++ b/libgo/go/time/example_test.go @@ -122,7 +122,7 @@ func ExampleTime_Round() { } // Output: // t.Round( 1ns) = 12:15:30.918273645 - // t.Round( 1us) = 12:15:30.918274 + // t.Round( 1µs) = 12:15:30.918274 // t.Round( 1ms) = 12:15:30.918 // t.Round( 1s) = 12:15:31 // t.Round( 2s) = 12:15:30 @@ -150,7 +150,7 @@ func ExampleTime_Truncate() { // Output: // t.Truncate( 1ns) = 12:15:30.918273645 - // t.Truncate( 1us) = 12:15:30.918273 + // t.Truncate( 1µs) = 12:15:30.918273 // t.Truncate( 1ms) = 12:15:30.918 // t.Truncate( 1s) = 12:15:30 // t.Truncate( 2s) = 12:15:30 diff --git a/libgo/go/time/format.go b/libgo/go/time/format.go index 6f92c126268..04e79f32dcd 100644 --- a/libgo/go/time/format.go +++ b/libgo/go/time/format.go @@ -7,7 +7,7 @@ package time import "errors" // These are predefined layouts for use in Time.Format and Time.Parse. -// The reference time used in the layouts is: +// The reference time used in the layouts is the specific time: // Mon Jan 2 15:04:05 MST 2006 // which is Unix time 1136239445. Since MST is GMT-0700, // the reference time can be thought of as @@ -102,7 +102,7 @@ const ( // std0x records the std values for "01", "02", ..., "06". var std0x = [...]int{stdZeroMonth, stdZeroDay, stdZeroHour12, stdZeroMinute, stdZeroSecond, stdYear} -// startsWithLowerCase reports whether the the string has a lower-case letter at the beginning. +// startsWithLowerCase reports whether the string has a lower-case letter at the beginning. // Its purpose is to prevent matching strings like "Month" when looking for "Mon". func startsWithLowerCase(str string) bool { if len(str) == 0 { @@ -402,7 +402,7 @@ func (t Time) String() string { // Format returns a textual representation of the time value formatted // according to layout, which defines the format by showing how the reference -// time, +// time, defined to be // Mon Jan 2 15:04:05 -0700 MST 2006 // would be displayed if it were the value; it serves as an example of the // desired output. The same display rules will then be applied to the time @@ -556,7 +556,7 @@ func (t Time) Format(layout string) string { b = append(b, '+') } b = appendUint(b, uint(zone/60), '0') - if std == stdISO8601ColonTZ || std == stdNumColonTZ { + if std == stdISO8601ColonTZ || std == stdNumColonTZ || std == stdISO8601ColonSecondsTZ || std == stdNumColonSecondsTZ { b = append(b, ':') } b = appendUint(b, uint(zone%60), '0') @@ -676,6 +676,7 @@ func skip(value, prefix string) (string, error) { // Parse parses a formatted string and returns the time value it represents. // The layout defines the format by showing how the reference time, +// defined to be // Mon Jan 2 15:04:05 -0700 MST 2006 // would be interpreted if it were the value; it serves as an example of // the input format. The same interpretation will then be made to the @@ -704,7 +705,7 @@ func skip(value, prefix string) (string, error) { // The zone abbreviation "UTC" is recognized as UTC regardless of location. // If the zone abbreviation is unknown, Parse records the time as being // in a fabricated location with the given zone abbreviation and a zero offset. -// This choice means that such a time can be parse and reformatted with the +// This choice means that such a time can be parsed and reformatted with the // same layout losslessly, but the exact instant used in the representation will // differ by the actual zone offset. To avoid such problems, prefer time layouts // that use a numeric zone offset, or use ParseInLocation. @@ -1037,8 +1038,8 @@ func parseTimeZone(value string) (length int, ok bool) { if len(value) < 3 { return 0, false } - // Special case 1: This is the only zone with a lower-case letter. - if len(value) >= 4 && value[:4] == "ChST" { + // Special case 1: ChST and MeST are the only zones with a lower-case letter. + if len(value) >= 4 && (value[:4] == "ChST" || value[:4] == "MeST") { return 4, true } // Special case 2: GMT may have an hour offset; treat it specially. @@ -1240,5 +1241,8 @@ func ParseDuration(s string) (Duration, error) { if neg { f = -f } + if f < float64(-1<<63) || f > float64(1<<63-1) { + return 0, errors.New("time: overflow parsing duration") + } return Duration(f), nil } diff --git a/libgo/go/time/format_test.go b/libgo/go/time/format_test.go new file mode 100644 index 00000000000..75a08c74534 --- /dev/null +++ b/libgo/go/time/format_test.go @@ -0,0 +1,520 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package time_test + +import ( + "fmt" + "strconv" + "strings" + "testing" + "testing/quick" + . "time" +) + +type TimeFormatTest struct { + time Time + formattedValue string +} + +var rfc3339Formats = []TimeFormatTest{ + {Date(2008, 9, 17, 20, 4, 26, 0, UTC), "2008-09-17T20:04:26Z"}, + {Date(1994, 9, 17, 20, 4, 26, 0, FixedZone("EST", -18000)), "1994-09-17T20:04:26-05:00"}, + {Date(2000, 12, 26, 1, 15, 6, 0, FixedZone("OTO", 15600)), "2000-12-26T01:15:06+04:20"}, +} + +func TestRFC3339Conversion(t *testing.T) { + for _, f := range rfc3339Formats { + if f.time.Format(RFC3339) != f.formattedValue { + t.Error("RFC3339:") + t.Errorf(" want=%+v", f.formattedValue) + t.Errorf(" have=%+v", f.time.Format(RFC3339)) + } + } +} + +type FormatTest struct { + name string + format string + result string +} + +var formatTests = []FormatTest{ + {"ANSIC", ANSIC, "Wed Feb 4 21:00:57 2009"}, + {"UnixDate", UnixDate, "Wed Feb 4 21:00:57 PST 2009"}, + {"RubyDate", RubyDate, "Wed Feb 04 21:00:57 -0800 2009"}, + {"RFC822", RFC822, "04 Feb 09 21:00 PST"}, + {"RFC850", RFC850, "Wednesday, 04-Feb-09 21:00:57 PST"}, + {"RFC1123", RFC1123, "Wed, 04 Feb 2009 21:00:57 PST"}, + {"RFC1123Z", RFC1123Z, "Wed, 04 Feb 2009 21:00:57 -0800"}, + {"RFC3339", RFC3339, "2009-02-04T21:00:57-08:00"}, + {"RFC3339Nano", RFC3339Nano, "2009-02-04T21:00:57.0123456-08:00"}, + {"Kitchen", Kitchen, "9:00PM"}, + {"am/pm", "3pm", "9pm"}, + {"AM/PM", "3PM", "9PM"}, + {"two-digit year", "06 01 02", "09 02 04"}, + // Three-letter months and days must not be followed by lower-case letter. + {"Janet", "Hi Janet, the Month is January", "Hi Janet, the Month is February"}, + // Time stamps, Fractional seconds. + {"Stamp", Stamp, "Feb 4 21:00:57"}, + {"StampMilli", StampMilli, "Feb 4 21:00:57.012"}, + {"StampMicro", StampMicro, "Feb 4 21:00:57.012345"}, + {"StampNano", StampNano, "Feb 4 21:00:57.012345600"}, +} + +func TestFormat(t *testing.T) { + // The numeric time represents Thu Feb 4 21:00:57.012345600 PST 2010 + time := Unix(0, 1233810057012345600) + for _, test := range formatTests { + result := time.Format(test.format) + if result != test.result { + t.Errorf("%s expected %q got %q", test.name, test.result, result) + } + } +} + +func TestFormatShortYear(t *testing.T) { + years := []int{ + -100001, -100000, -99999, + -10001, -10000, -9999, + -1001, -1000, -999, + -101, -100, -99, + -11, -10, -9, + -1, 0, 1, + 9, 10, 11, + 99, 100, 101, + 999, 1000, 1001, + 9999, 10000, 10001, + 99999, 100000, 100001, + } + + for _, y := range years { + time := Date(y, January, 1, 0, 0, 0, 0, UTC) + result := time.Format("2006.01.02") + var want string + if y < 0 { + // The 4 in %04d counts the - sign, so print -y instead + // and introduce our own - sign. + want = fmt.Sprintf("-%04d.%02d.%02d", -y, 1, 1) + } else { + want = fmt.Sprintf("%04d.%02d.%02d", y, 1, 1) + } + if result != want { + t.Errorf("(jan 1 %d).Format(\"2006.01.02\") = %q, want %q", y, result, want) + } + } +} + +type ParseTest struct { + name string + format string + value string + hasTZ bool // contains a time zone + hasWD bool // contains a weekday + yearSign int // sign of year, -1 indicates the year is not present in the format + fracDigits int // number of digits of fractional second +} + +var parseTests = []ParseTest{ + {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, + {"UnixDate", UnixDate, "Thu Feb 4 21:00:57 PST 2010", true, true, 1, 0}, + {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, + {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57 PST", true, true, 1, 0}, + {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57 PST", true, true, 1, 0}, + {"RFC1123", RFC1123, "Thu, 04 Feb 2010 22:00:57 PDT", true, true, 1, 0}, + {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57 -0800", true, true, 1, 0}, + {"RFC3339", RFC3339, "2010-02-04T21:00:57-08:00", true, false, 1, 0}, + {"custom: \"2006-01-02 15:04:05-07\"", "2006-01-02 15:04:05-07", "2010-02-04 21:00:57-08", true, false, 1, 0}, + // Optional fractional seconds. + {"ANSIC", ANSIC, "Thu Feb 4 21:00:57.0 2010", false, true, 1, 1}, + {"UnixDate", UnixDate, "Thu Feb 4 21:00:57.01 PST 2010", true, true, 1, 2}, + {"RubyDate", RubyDate, "Thu Feb 04 21:00:57.012 -0800 2010", true, true, 1, 3}, + {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57.0123 PST", true, true, 1, 4}, + {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57.01234 PST", true, true, 1, 5}, + {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57.01234 -0800", true, true, 1, 5}, + {"RFC3339", RFC3339, "2010-02-04T21:00:57.012345678-08:00", true, false, 1, 9}, + {"custom: \"2006-01-02 15:04:05\"", "2006-01-02 15:04:05", "2010-02-04 21:00:57.0", false, false, 1, 0}, + // Amount of white space should not matter. + {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, + {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, + // Case should not matter + {"ANSIC", ANSIC, "THU FEB 4 21:00:57 2010", false, true, 1, 0}, + {"ANSIC", ANSIC, "thu feb 4 21:00:57 2010", false, true, 1, 0}, + // Fractional seconds. + {"millisecond", "Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 21:00:57.012 2010", false, true, 1, 3}, + {"microsecond", "Mon Jan _2 15:04:05.000000 2006", "Thu Feb 4 21:00:57.012345 2010", false, true, 1, 6}, + {"nanosecond", "Mon Jan _2 15:04:05.000000000 2006", "Thu Feb 4 21:00:57.012345678 2010", false, true, 1, 9}, + // Leading zeros in other places should not be taken as fractional seconds. + {"zero1", "2006.01.02.15.04.05.0", "2010.02.04.21.00.57.0", false, false, 1, 1}, + {"zero2", "2006.01.02.15.04.05.00", "2010.02.04.21.00.57.01", false, false, 1, 2}, + // Month and day names only match when not followed by a lower-case letter. + {"Janet", "Hi Janet, the Month is January: Jan _2 15:04:05 2006", "Hi Janet, the Month is February: Feb 4 21:00:57 2010", false, true, 1, 0}, + + // GMT with offset. + {"GMT-8", UnixDate, "Fri Feb 5 05:00:57 GMT-8 2010", true, true, 1, 0}, + + // Accept any number of fractional second digits (including none) for .999... + // In Go 1, .999... was completely ignored in the format, meaning the first two + // cases would succeed, but the next four would not. Go 1.1 accepts all six. + {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, + {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, + {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, + {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, + {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, + {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, + + // issue 4502. + {"", StampNano, "Feb 4 21:00:57.012345678", false, false, -1, 9}, + {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012300000", false, false, -1, 4}, + {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, + {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.0123", false, false, -1, 4}, + {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, +} + +func TestParse(t *testing.T) { + for _, test := range parseTests { + time, err := Parse(test.format, test.value) + if err != nil { + t.Errorf("%s error: %v", test.name, err) + } else { + checkTime(time, &test, t) + } + } +} + +func TestParseInLocation(t *testing.T) { + // Check that Parse (and ParseInLocation) understand that + // Feb 01 AST (Arabia Standard Time) and Feb 01 AST (Atlantic Standard Time) + // are in different time zones even though both are called AST + + baghdad, err := LoadLocation("Asia/Baghdad") + if err != nil { + t.Fatal(err) + } + + t1, err := ParseInLocation("Jan 02 2006 MST", "Feb 01 2013 AST", baghdad) + if err != nil { + t.Fatal(err) + } + t2 := Date(2013, February, 1, 00, 00, 00, 0, baghdad) + if t1 != t2 { + t.Fatalf("ParseInLocation(Feb 01 2013 AST, Baghdad) = %v, want %v", t1, t2) + } + _, offset := t1.Zone() + if offset != 3*60*60 { + t.Fatalf("ParseInLocation(Feb 01 2013 AST, Baghdad).Zone = _, %d, want _, %d", offset, 3*60*60) + } + + blancSablon, err := LoadLocation("America/Blanc-Sablon") + if err != nil { + t.Fatal(err) + } + + t1, err = ParseInLocation("Jan 02 2006 MST", "Feb 01 2013 AST", blancSablon) + if err != nil { + t.Fatal(err) + } + t2 = Date(2013, February, 1, 00, 00, 00, 0, blancSablon) + if t1 != t2 { + t.Fatalf("ParseInLocation(Feb 01 2013 AST, Blanc-Sablon) = %v, want %v", t1, t2) + } + _, offset = t1.Zone() + if offset != -4*60*60 { + t.Fatalf("ParseInLocation(Feb 01 2013 AST, Blanc-Sablon).Zone = _, %d, want _, %d", offset, -4*60*60) + } +} + +func TestLoadLocationZipFile(t *testing.T) { + t.Skip("gccgo does not use the zip file") + + ForceZipFileForTesting(true) + defer ForceZipFileForTesting(false) + + _, err := LoadLocation("Australia/Sydney") + if err != nil { + t.Fatal(err) + } +} + +var rubyTests = []ParseTest{ + {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, + // Ignore the time zone in the test. If it parses, it'll be OK. + {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0000 2010", false, true, 1, 0}, + {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +0000 2010", false, true, 1, 0}, + {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +1130 2010", false, true, 1, 0}, +} + +// Problematic time zone format needs special tests. +func TestRubyParse(t *testing.T) { + for _, test := range rubyTests { + time, err := Parse(test.format, test.value) + if err != nil { + t.Errorf("%s error: %v", test.name, err) + } else { + checkTime(time, &test, t) + } + } +} + +func checkTime(time Time, test *ParseTest, t *testing.T) { + // The time should be Thu Feb 4 21:00:57 PST 2010 + if test.yearSign >= 0 && test.yearSign*time.Year() != 2010 { + t.Errorf("%s: bad year: %d not %d", test.name, time.Year(), 2010) + } + if time.Month() != February { + t.Errorf("%s: bad month: %s not %s", test.name, time.Month(), February) + } + if time.Day() != 4 { + t.Errorf("%s: bad day: %d not %d", test.name, time.Day(), 4) + } + if time.Hour() != 21 { + t.Errorf("%s: bad hour: %d not %d", test.name, time.Hour(), 21) + } + if time.Minute() != 0 { + t.Errorf("%s: bad minute: %d not %d", test.name, time.Minute(), 0) + } + if time.Second() != 57 { + t.Errorf("%s: bad second: %d not %d", test.name, time.Second(), 57) + } + // Nanoseconds must be checked against the precision of the input. + nanosec, err := strconv.ParseUint("012345678"[:test.fracDigits]+"000000000"[:9-test.fracDigits], 10, 0) + if err != nil { + panic(err) + } + if time.Nanosecond() != int(nanosec) { + t.Errorf("%s: bad nanosecond: %d not %d", test.name, time.Nanosecond(), nanosec) + } + name, offset := time.Zone() + if test.hasTZ && offset != -28800 { + t.Errorf("%s: bad tz offset: %s %d not %d", test.name, name, offset, -28800) + } + if test.hasWD && time.Weekday() != Thursday { + t.Errorf("%s: bad weekday: %s not %s", test.name, time.Weekday(), Thursday) + } +} + +func TestFormatAndParse(t *testing.T) { + const fmt = "Mon MST " + RFC3339 // all fields + f := func(sec int64) bool { + t1 := Unix(sec, 0) + if t1.Year() < 1000 || t1.Year() > 9999 { + // not required to work + return true + } + t2, err := Parse(fmt, t1.Format(fmt)) + if err != nil { + t.Errorf("error: %s", err) + return false + } + if t1.Unix() != t2.Unix() || t1.Nanosecond() != t2.Nanosecond() { + t.Errorf("FormatAndParse %d: %q(%d) %q(%d)", sec, t1, t1.Unix(), t2, t2.Unix()) + return false + } + return true + } + f32 := func(sec int32) bool { return f(int64(sec)) } + cfg := &quick.Config{MaxCount: 10000} + + // Try a reasonable date first, then the huge ones. + if err := quick.Check(f32, cfg); err != nil { + t.Fatal(err) + } + if err := quick.Check(f, cfg); err != nil { + t.Fatal(err) + } +} + +type ParseTimeZoneTest struct { + value string + length int + ok bool +} + +var parseTimeZoneTests = []ParseTimeZoneTest{ + {"gmt hi there", 0, false}, + {"GMT hi there", 3, true}, + {"GMT+12 hi there", 6, true}, + {"GMT+00 hi there", 3, true}, // 0 or 00 is not a legal offset. + {"GMT-5 hi there", 5, true}, + {"GMT-51 hi there", 3, true}, + {"ChST hi there", 4, true}, + {"MeST hi there", 4, true}, + {"MSDx", 3, true}, + {"MSDY", 0, false}, // four letters must end in T. + {"ESAST hi", 5, true}, + {"ESASTT hi", 0, false}, // run of upper-case letters too long. + {"ESATY hi", 0, false}, // five letters must end in T. +} + +func TestParseTimeZone(t *testing.T) { + for _, test := range parseTimeZoneTests { + length, ok := ParseTimeZone(test.value) + if ok != test.ok { + t.Errorf("expected %t for %q got %t", test.ok, test.value, ok) + } else if length != test.length { + t.Errorf("expected %d for %q got %d", test.length, test.value, length) + } + } +} + +type ParseErrorTest struct { + format string + value string + expect string // must appear within the error +} + +var parseErrorTests = []ParseErrorTest{ + {ANSIC, "Feb 4 21:00:60 2010", "cannot parse"}, // cannot parse Feb as Mon + {ANSIC, "Thu Feb 4 21:00:57 @2010", "cannot parse"}, + {ANSIC, "Thu Feb 4 21:00:60 2010", "second out of range"}, + {ANSIC, "Thu Feb 4 21:61:57 2010", "minute out of range"}, + {ANSIC, "Thu Feb 4 24:00:60 2010", "hour out of range"}, + {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59x01 2010", "cannot parse"}, + {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.xxx 2010", "cannot parse"}, + {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.-123 2010", "fractional second out of range"}, + // issue 4502. StampNano requires exactly 9 digits of precision. + {StampNano, "Dec 7 11:22:01.000000", `cannot parse ".000000" as ".000000000"`}, + {StampNano, "Dec 7 11:22:01.0000000000", "extra text: 0"}, + // issue 4493. Helpful errors. + {RFC3339, "2006-01-02T15:04:05Z07:00", `parsing time "2006-01-02T15:04:05Z07:00": extra text: 07:00`}, + {RFC3339, "2006-01-02T15:04_abc", `parsing time "2006-01-02T15:04_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as ":"`}, + {RFC3339, "2006-01-02T15:04:05_abc", `parsing time "2006-01-02T15:04:05_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as "Z07:00"`}, + {RFC3339, "2006-01-02T15:04:05Z_abc", `parsing time "2006-01-02T15:04:05Z_abc": extra text: _abc`}, +} + +func TestParseErrors(t *testing.T) { + for _, test := range parseErrorTests { + _, err := Parse(test.format, test.value) + if err == nil { + t.Errorf("expected error for %q %q", test.format, test.value) + } else if strings.Index(err.Error(), test.expect) < 0 { + t.Errorf("expected error with %q for %q %q; got %s", test.expect, test.format, test.value, err) + } + } +} + +func TestNoonIs12PM(t *testing.T) { + noon := Date(0, January, 1, 12, 0, 0, 0, UTC) + const expect = "12:00PM" + got := noon.Format("3:04PM") + if got != expect { + t.Errorf("got %q; expect %q", got, expect) + } + got = noon.Format("03:04PM") + if got != expect { + t.Errorf("got %q; expect %q", got, expect) + } +} + +func TestMidnightIs12AM(t *testing.T) { + midnight := Date(0, January, 1, 0, 0, 0, 0, UTC) + expect := "12:00AM" + got := midnight.Format("3:04PM") + if got != expect { + t.Errorf("got %q; expect %q", got, expect) + } + got = midnight.Format("03:04PM") + if got != expect { + t.Errorf("got %q; expect %q", got, expect) + } +} + +func Test12PMIsNoon(t *testing.T) { + noon, err := Parse("3:04PM", "12:00PM") + if err != nil { + t.Fatal("error parsing date:", err) + } + if noon.Hour() != 12 { + t.Errorf("got %d; expect 12", noon.Hour()) + } + noon, err = Parse("03:04PM", "12:00PM") + if err != nil { + t.Fatal("error parsing date:", err) + } + if noon.Hour() != 12 { + t.Errorf("got %d; expect 12", noon.Hour()) + } +} + +func Test12AMIsMidnight(t *testing.T) { + midnight, err := Parse("3:04PM", "12:00AM") + if err != nil { + t.Fatal("error parsing date:", err) + } + if midnight.Hour() != 0 { + t.Errorf("got %d; expect 0", midnight.Hour()) + } + midnight, err = Parse("03:04PM", "12:00AM") + if err != nil { + t.Fatal("error parsing date:", err) + } + if midnight.Hour() != 0 { + t.Errorf("got %d; expect 0", midnight.Hour()) + } +} + +// Check that a time without a Zone still produces a (numeric) time zone +// when formatted with MST as a requested zone. +func TestMissingZone(t *testing.T) { + time, err := Parse(RubyDate, "Thu Feb 02 16:10:03 -0500 2006") + if err != nil { + t.Fatal("error parsing date:", err) + } + expect := "Thu Feb 2 16:10:03 -0500 2006" // -0500 not EST + str := time.Format(UnixDate) // uses MST as its time zone + if str != expect { + t.Errorf("got %s; expect %s", str, expect) + } +} + +func TestMinutesInTimeZone(t *testing.T) { + time, err := Parse(RubyDate, "Mon Jan 02 15:04:05 +0123 2006") + if err != nil { + t.Fatal("error parsing date:", err) + } + expected := (1*60 + 23) * 60 + _, offset := time.Zone() + if offset != expected { + t.Errorf("ZoneOffset = %d, want %d", offset, expected) + } +} + +type SecondsTimeZoneOffsetTest struct { + format string + value string + expectedoffset int +} + +var secondsTimeZoneOffsetTests = []SecondsTimeZoneOffsetTest{ + {"2006-01-02T15:04:05-070000", "1871-01-01T05:33:02-003408", -(34*60 + 8)}, + {"2006-01-02T15:04:05-07:00:00", "1871-01-01T05:33:02-00:34:08", -(34*60 + 8)}, + {"2006-01-02T15:04:05-070000", "1871-01-01T05:33:02+003408", 34*60 + 8}, + {"2006-01-02T15:04:05-07:00:00", "1871-01-01T05:33:02+00:34:08", 34*60 + 8}, + {"2006-01-02T15:04:05Z070000", "1871-01-01T05:33:02-003408", -(34*60 + 8)}, + {"2006-01-02T15:04:05Z07:00:00", "1871-01-01T05:33:02+00:34:08", 34*60 + 8}, +} + +func TestParseSecondsInTimeZone(t *testing.T) { + // should accept timezone offsets with seconds like: Zone America/New_York -4:56:02 - LMT 1883 Nov 18 12:03:58 + for _, test := range secondsTimeZoneOffsetTests { + time, err := Parse(test.format, test.value) + if err != nil { + t.Fatal("error parsing date:", err) + } + _, offset := time.Zone() + if offset != test.expectedoffset { + t.Errorf("ZoneOffset = %d, want %d", offset, test.expectedoffset) + } + } +} + +func TestFormatSecondsInTimeZone(t *testing.T) { + for _, test := range secondsTimeZoneOffsetTests { + d := Date(1871, 1, 1, 5, 33, 2, 0, FixedZone("LMT", test.expectedoffset)) + timestr := d.Format(test.format) + if timestr != test.value { + t.Errorf("Format = %s, want %s", timestr, test.value) + } + } +} diff --git a/libgo/go/time/genzabbrs.go b/libgo/go/time/genzabbrs.go index 7c637cb43a7..9eb0728a42e 100644 --- a/libgo/go/time/genzabbrs.go +++ b/libgo/go/time/genzabbrs.go @@ -7,22 +7,26 @@ // // usage: // -// go run genzabbrs.go | gofmt > $GOROOT/src/pkg/time/zoneinfo_abbrs_windows.go +// go run genzabbrs.go -output zoneinfo_abbrs_windows.go // package main import ( + "bytes" "encoding/xml" + "flag" + "go/format" "io/ioutil" "log" "net/http" - "os" "sort" "text/template" "time" ) +var filename = flag.String("output", "zoneinfo_abbrs_windows.go", "output file name") + // getAbbrs finds timezone abbreviations (standard and daylight saving time) // for location l. func getAbbrs(l *time.Location) (st, dt string) { @@ -105,6 +109,7 @@ func readWindowsZones() (zones, error) { } func main() { + flag.Parse() zs, err := readWindowsZones() if err != nil { log.Fatal(err) @@ -117,7 +122,16 @@ func main() { wzURL, zs, } - err = template.Must(template.New("prog").Parse(prog)).Execute(os.Stdout, v) + var buf bytes.Buffer + err = template.Must(template.New("prog").Parse(prog)).Execute(&buf, v) + if err != nil { + log.Fatal(err) + } + data, err := format.Source(buf.Bytes()) + if err != nil { + log.Fatal(err) + } + err = ioutil.WriteFile(*filename, data, 0644) if err != nil { log.Fatal(err) } diff --git a/libgo/go/time/internal_test.go b/libgo/go/time/internal_test.go index 87fdd3216fa..edd523bc80c 100644 --- a/libgo/go/time/internal_test.go +++ b/libgo/go/time/internal_test.go @@ -4,11 +4,6 @@ package time -import ( - "errors" - "runtime" -) - func init() { // force US/Pacific for time zone tests ForceUSPacificForTesting() @@ -17,31 +12,25 @@ func init() { var Interrupt = interrupt var DaysIn = daysIn -func empty(now int64, arg interface{}) {} +func empty(arg interface{}, seq uintptr) {} // Test that a runtimeTimer with a duration so large it overflows // does not cause other timers to hang. // // This test has to be in internal_test.go since it fiddles with // unexported data structures. -func CheckRuntimeTimerOverflow() error { +func CheckRuntimeTimerOverflow() { // We manually create a runtimeTimer to bypass the overflow // detection logic in NewTimer: we're testing the underlying // runtime.addtimer function. r := &runtimeTimer{ - when: nano() + (1<<63 - 1), + when: runtimeNano() + (1<<63 - 1), f: empty, arg: nil, } startTimer(r) - timeout := 100 * Millisecond - if runtime.GOOS == "windows" { - // Allow more time for gobuilder to succeed. - timeout = Second - } - - // Start a goroutine that should send on t.C before the timeout. + // Start a goroutine that should send on t.C right away. t := NewTimer(1) defer func() { @@ -60,21 +49,11 @@ func CheckRuntimeTimerOverflow() error { startTimer(r) }() - // Try to receive from t.C before the timeout. It will succeed - // iff the previous sleep was able to finish. We're forced to - // spin and yield after trying to receive since we can't start - // any more timers (they might hang due to the same bug we're - // now testing). - stop := Now().Add(timeout) - for { - select { - case <-t.C: - return nil // It worked! - default: - if Now().After(stop) { - return errors.New("runtime timer stuck: overflow in addtimer") - } - runtime.Gosched() - } - } + // If the test fails, we will hang here until the timeout in the testing package + // fires, which is 10 minutes. It would be nice to catch the problem sooner, + // but there is no reliable way to guarantee that timerproc schedules without + // doing something involving timerproc itself. Previous failed attempts have + // tried calling runtime.Gosched and runtime.GC, but neither is reliable. + // So we fall back to hope: We hope we don't hang here. + <-t.C } diff --git a/libgo/go/time/sleep.go b/libgo/go/time/sleep.go index 4f55bebe62a..e7a2ee20598 100644 --- a/libgo/go/time/sleep.go +++ b/libgo/go/time/sleep.go @@ -8,19 +8,18 @@ package time // A negative or zero duration causes Sleep to return immediately. func Sleep(d Duration) -func nano() int64 { - sec, nsec := now() - return sec*1e9 + int64(nsec) -} +// runtimeNano returns the current value of the runtime clock in nanoseconds. +func runtimeNano() int64 // Interface to timers implemented in package runtime. // Must be in sync with ../runtime/runtime.h:/^struct.Timer$ type runtimeTimer struct { - i int32 + i int when int64 period int64 - f func(int64, interface{}) // NOTE: must not be closure + f func(interface{}, uintptr) // NOTE: must not be closure arg interface{} + seq uintptr } // when is a helper function for setting the 'when' field of a runtimeTimer. @@ -29,9 +28,9 @@ type runtimeTimer struct { // zero because of an overflow, MaxInt64 is returned. func when(d Duration) int64 { if d <= 0 { - return nano() + return runtimeNano() } - t := nano() + int64(d) + t := runtimeNano() + int64(d) if t < 0 { t = 1<<63 - 1 // math.MaxInt64 } @@ -44,6 +43,7 @@ func stopTimer(*runtimeTimer) bool // The Timer type represents a single event. // When the Timer expires, the current time will be sent on C, // unless the Timer was created by AfterFunc. +// A Timer must be created with NewTimer or AfterFunc. type Timer struct { C <-chan Time r runtimeTimer @@ -55,6 +55,9 @@ type Timer struct { // Stop does not close the channel, to prevent a read from the channel succeeding // incorrectly. func (t *Timer) Stop() bool { + if t.r.f == nil { + panic("time: Stop called on uninitialized Timer") + } return stopTimer(&t.r) } @@ -78,6 +81,9 @@ func NewTimer(d Duration) *Timer { // It returns true if the timer had been active, false if the timer had // expired or been stopped. func (t *Timer) Reset(d Duration) bool { + if t.r.f == nil { + panic("time: Reset called on uninitialized Timer") + } w := when(d) active := stopTimer(&t.r) t.r.when = w @@ -85,14 +91,14 @@ func (t *Timer) Reset(d Duration) bool { return active } -func sendTime(now int64, c interface{}) { +func sendTime(c interface{}, seq uintptr) { // Non-blocking send of time on c. // Used in NewTimer, it cannot block anyway (buffer). // Used in NewTicker, dropping sends on the floor is // the desired behavior when the reader gets behind, // because the sends are periodic. select { - case c.(chan Time) <- Unix(0, now): + case c.(chan Time) <- Now(): default: } } @@ -119,6 +125,6 @@ func AfterFunc(d Duration, f func()) *Timer { return t } -func goFunc(now int64, arg interface{}) { +func goFunc(arg interface{}, seq uintptr) { go arg.(func())() } diff --git a/libgo/go/time/sleep_test.go b/libgo/go/time/sleep_test.go index cb09a84469e..c21eb997dc4 100644 --- a/libgo/go/time/sleep_test.go +++ b/libgo/go/time/sleep_test.go @@ -9,12 +9,21 @@ import ( "fmt" "runtime" "sort" + "strings" "sync" "sync/atomic" "testing" . "time" ) +// Go runtime uses different Windows timers for time.Now and sleeping. +// These can tick at different frequencies and can arrive out of sync. +// The effect can be seen, for example, as time.Sleep(100ms) is actually +// shorter then 100ms when measured as difference between time.Now before and +// after time.Sleep call. This was observed on Windows XP SP3 (windows/386). +// windowsInaccuracy is to ignore such errors. +const windowsInaccuracy = 17 * Millisecond + func TestSleep(t *testing.T) { const delay = 100 * Millisecond go func() { @@ -23,8 +32,12 @@ func TestSleep(t *testing.T) { }() start := Now() Sleep(delay) + delayadj := delay + if runtime.GOOS == "windows" { + delayadj -= windowsInaccuracy + } duration := Now().Sub(start) - if duration < delay { + if duration < delayadj { t.Fatalf("Sleep(%s) slept for only %s", delay, duration) } } @@ -74,26 +87,13 @@ func benchmark(b *testing.B, bench func(n int)) { for i := 0; i < len(garbage); i++ { garbage[i] = AfterFunc(Hour, nil) } - - const batch = 1000 - P := runtime.GOMAXPROCS(-1) - N := int32(b.N / batch) - b.ResetTimer() - var wg sync.WaitGroup - wg.Add(P) - - for p := 0; p < P; p++ { - go func() { - for atomic.AddInt32(&N, -1) >= 0 { - bench(batch) - } - wg.Done() - }() - } - - wg.Wait() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + bench(1000) + } + }) b.StopTimer() for i := 0; i < len(garbage); i++ { @@ -163,10 +163,14 @@ func TestAfter(t *testing.T) { const delay = 100 * Millisecond start := Now() end := <-After(delay) - if duration := Now().Sub(start); duration < delay { + delayadj := delay + if runtime.GOOS == "windows" { + delayadj -= windowsInaccuracy + } + if duration := Now().Sub(start); duration < delayadj { t.Fatalf("After(%s) slept for only %d ns", delay, duration) } - if min := start.Add(delay); end.Before(min) { + if min := start.Add(delayadj); end.Before(min) { t.Fatalf("After(%s) expect >= %s, got %s", delay, min, end) } } @@ -361,19 +365,18 @@ func TestReset(t *testing.T) { // Test that sleeping for an interval so large it overflows does not // result in a short sleep duration. func TestOverflowSleep(t *testing.T) { - const timeout = 25 * Millisecond const big = Duration(int64(1<<63 - 1)) select { case <-After(big): t.Fatalf("big timeout fired") - case <-After(timeout): + case <-After(25 * Millisecond): // OK } const neg = Duration(-1 << 63) select { case <-After(neg): // OK - case <-After(timeout): + case <-After(1 * Second): t.Fatalf("negative timeout didn't fire") } } @@ -399,7 +402,30 @@ func TestIssue5745(t *testing.T) { } func TestOverflowRuntimeTimer(t *testing.T) { - if err := CheckRuntimeTimerOverflow(); err != nil { - t.Fatalf(err.Error()) + if testing.Short() { + t.Skip("skipping in short mode, see issue 6874") + } + // This may hang forever if timers are broken. See comment near + // the end of CheckRuntimeTimerOverflow in internal_test.go. + CheckRuntimeTimerOverflow() +} + +func checkZeroPanicString(t *testing.T) { + e := recover() + s, _ := e.(string) + if want := "called on uninitialized Timer"; !strings.Contains(s, want) { + t.Errorf("panic = %v; want substring %q", e, want) } } + +func TestZeroTimerResetPanics(t *testing.T) { + defer checkZeroPanicString(t) + var tr Timer + tr.Reset(1) +} + +func TestZeroTimerStopPanics(t *testing.T) { + defer checkZeroPanicString(t) + var tr Timer + tr.Stop() +} diff --git a/libgo/go/time/sys_unix.go b/libgo/go/time/sys_unix.go index 60a3ce08f90..379e13d6a53 100644 --- a/libgo/go/time/sys_unix.go +++ b/libgo/go/time/sys_unix.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build darwin dragonfly freebsd linux netbsd openbsd +// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris package time diff --git a/libgo/go/time/tick.go b/libgo/go/time/tick.go index b92c339c02a..19007841e1a 100644 --- a/libgo/go/time/tick.go +++ b/libgo/go/time/tick.go @@ -17,6 +17,7 @@ type Ticker struct { // time with a period specified by the duration argument. // It adjusts the intervals or drops ticks to make up for slow receivers. // The duration d must be greater than zero; if not, NewTicker will panic. +// Stop the ticker to release associated resources. func NewTicker(d Duration) *Ticker { if d <= 0 { panic(errors.New("non-positive interval for NewTicker")) @@ -28,7 +29,7 @@ func NewTicker(d Duration) *Ticker { t := &Ticker{ C: c, r: runtimeTimer{ - when: nano() + int64(d), + when: when(d), period: int64(d), f: sendTime, arg: c, diff --git a/libgo/go/time/tick_test.go b/libgo/go/time/tick_test.go index d8a086ceb25..32f4740ad93 100644 --- a/libgo/go/time/tick_test.go +++ b/libgo/go/time/tick_test.go @@ -48,6 +48,24 @@ func TestTeardown(t *testing.T) { } } +// Test the Tick convenience wrapper. +func TestTick(t *testing.T) { + // Test that giving a negative duration returns nil. + if got := Tick(-1); got != nil { + t.Errorf("Tick(-1) = %v; want nil", got) + } +} + +// Test that NewTicker panics when given a duration less than zero. +func TestNewTickerLtZeroDuration(t *testing.T) { + defer func() { + if err := recover(); err == nil { + t.Errorf("NewTicker(-1) should have panicked") + } + }() + NewTicker(-1) +} + func BenchmarkTicker(b *testing.B) { ticker := NewTicker(1) b.ResetTimer() diff --git a/libgo/go/time/time.go b/libgo/go/time/time.go index c504df74013..0300e846a4b 100644 --- a/libgo/go/time/time.go +++ b/libgo/go/time/time.go @@ -31,6 +31,11 @@ import "errors" // change the instant in time being denoted and therefore does not affect the // computations described in earlier paragraphs. // +// Note that the Go == operator compares not just the time instant but also the +// Location. Therefore, Time values should not be used as map or database keys +// without first guaranteeing that the identical Location has been set for all +// values, which can be achieved through use of the UTC or Local method. +// type Time struct { // sec gives the number of seconds elapsed since // January 1, year 1 00:00:00 UTC. @@ -39,14 +44,7 @@ type Time struct { // nsec specifies a non-negative nanosecond // offset within the second named by Seconds. // It must be in the range [0, 999999999]. - // - // It is declared as uintptr instead of int32 or uint32 - // to avoid garbage collector aliasing in the case where - // on a 64-bit system the int32 or uint32 field is written - // over the low half of a pointer, creating another pointer. - // TODO(rsc): When the garbage collector is completely - // precise, change back to int32. - nsec uintptr + nsec int32 // loc specifies the Location that should be used to // determine the minute, hour, month, day, and year @@ -475,29 +473,28 @@ func (d Duration) String() string { if u < uint64(Second) { // Special case: if duration is smaller than a second, // use smaller units, like 1.2ms - var ( - prec int - unit byte - ) + var prec int + w-- + buf[w] = 's' + w-- switch { case u == 0: return "0" case u < uint64(Microsecond): // print nanoseconds prec = 0 - unit = 'n' + buf[w] = 'n' case u < uint64(Millisecond): // print microseconds prec = 3 - unit = 'u' + // U+00B5 'µ' micro sign == 0xC2 0xB5 + w-- // Need room for two bytes. + copy(buf[w:], "µ") default: // print milliseconds prec = 6 - unit = 'm' + buf[w] = 'm' } - w -= 2 - buf[w] = unit - buf[w+1] = 's' w, u = fmtFrac(buf[:w], u, prec) w = fmtInt(buf[:w], u) } else { @@ -620,7 +617,7 @@ func (t Time) Add(d Duration) Time { t.sec-- nsec += 1e9 } - t.nsec = uintptr(nsec) + t.nsec = nsec return t } @@ -783,7 +780,7 @@ func now() (sec int64, nsec int32) // Now returns the current local time. func Now() Time { sec, nsec := now() - return Time{sec + unixToInternal, uintptr(nsec), Local} + return Time{sec + unixToInternal, nsec, Local} } // UTC returns t with the location set to UTC. @@ -900,7 +897,7 @@ func (t *Time) UnmarshalBinary(data []byte) error { int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56 buf = buf[8:] - t.nsec = uintptr(int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24) + t.nsec = int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24 buf = buf[4:] offset := int(int16(buf[1])|int16(buf[0])<<8) * 60 @@ -934,6 +931,8 @@ func (t *Time) GobDecode(data []byte) error { // The time is a quoted string in RFC 3339 format, with sub-second precision added if present. func (t Time) MarshalJSON() ([]byte, error) { if y := t.Year(); y < 0 || y >= 10000 { + // RFC 3339 is clear that years are 4 digits exactly. + // See golang.org/issue/4556#c15 for more discussion. return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") } return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil @@ -977,7 +976,7 @@ func Unix(sec int64, nsec int64) Time { sec-- } } - return Time{sec + unixToInternal, uintptr(nsec), Local} + return Time{sec + unixToInternal, int32(nsec), Local} } func isLeap(year int) bool { @@ -1086,7 +1085,7 @@ func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) T unix -= int64(offset) } - return Time{unix + unixToInternal, uintptr(nsec), loc} + return Time{unix + unixToInternal, int32(nsec), loc} } // Truncate returns the result of rounding t down to a multiple of d (since the zero time). diff --git a/libgo/go/time/time_test.go b/libgo/go/time/time_test.go index 53ae97ea0af..7e31dd78a92 100644 --- a/libgo/go/time/time_test.go +++ b/libgo/go/time/time_test.go @@ -12,8 +12,6 @@ import ( "math/big" "math/rand" "runtime" - "strconv" - "strings" "testing" "testing/quick" . "time" @@ -372,504 +370,6 @@ func TestTruncateRound(t *testing.T) { quick.Check(f4, cfg) } -type TimeFormatTest struct { - time Time - formattedValue string -} - -var rfc3339Formats = []TimeFormatTest{ - {Date(2008, 9, 17, 20, 4, 26, 0, UTC), "2008-09-17T20:04:26Z"}, - {Date(1994, 9, 17, 20, 4, 26, 0, FixedZone("EST", -18000)), "1994-09-17T20:04:26-05:00"}, - {Date(2000, 12, 26, 1, 15, 6, 0, FixedZone("OTO", 15600)), "2000-12-26T01:15:06+04:20"}, -} - -func TestRFC3339Conversion(t *testing.T) { - for _, f := range rfc3339Formats { - if f.time.Format(RFC3339) != f.formattedValue { - t.Error("RFC3339:") - t.Errorf(" want=%+v", f.formattedValue) - t.Errorf(" have=%+v", f.time.Format(RFC3339)) - } - } -} - -type FormatTest struct { - name string - format string - result string -} - -var formatTests = []FormatTest{ - {"ANSIC", ANSIC, "Wed Feb 4 21:00:57 2009"}, - {"UnixDate", UnixDate, "Wed Feb 4 21:00:57 PST 2009"}, - {"RubyDate", RubyDate, "Wed Feb 04 21:00:57 -0800 2009"}, - {"RFC822", RFC822, "04 Feb 09 21:00 PST"}, - {"RFC850", RFC850, "Wednesday, 04-Feb-09 21:00:57 PST"}, - {"RFC1123", RFC1123, "Wed, 04 Feb 2009 21:00:57 PST"}, - {"RFC1123Z", RFC1123Z, "Wed, 04 Feb 2009 21:00:57 -0800"}, - {"RFC3339", RFC3339, "2009-02-04T21:00:57-08:00"}, - {"RFC3339Nano", RFC3339Nano, "2009-02-04T21:00:57.0123456-08:00"}, - {"Kitchen", Kitchen, "9:00PM"}, - {"am/pm", "3pm", "9pm"}, - {"AM/PM", "3PM", "9PM"}, - {"two-digit year", "06 01 02", "09 02 04"}, - // Three-letter months and days must not be followed by lower-case letter. - {"Janet", "Hi Janet, the Month is January", "Hi Janet, the Month is February"}, - // Time stamps, Fractional seconds. - {"Stamp", Stamp, "Feb 4 21:00:57"}, - {"StampMilli", StampMilli, "Feb 4 21:00:57.012"}, - {"StampMicro", StampMicro, "Feb 4 21:00:57.012345"}, - {"StampNano", StampNano, "Feb 4 21:00:57.012345600"}, -} - -func TestFormat(t *testing.T) { - // The numeric time represents Thu Feb 4 21:00:57.012345600 PST 2010 - time := Unix(0, 1233810057012345600) - for _, test := range formatTests { - result := time.Format(test.format) - if result != test.result { - t.Errorf("%s expected %q got %q", test.name, test.result, result) - } - } -} - -func TestFormatShortYear(t *testing.T) { - years := []int{ - -100001, -100000, -99999, - -10001, -10000, -9999, - -1001, -1000, -999, - -101, -100, -99, - -11, -10, -9, - -1, 0, 1, - 9, 10, 11, - 99, 100, 101, - 999, 1000, 1001, - 9999, 10000, 10001, - 99999, 100000, 100001, - } - - for _, y := range years { - time := Date(y, January, 1, 0, 0, 0, 0, UTC) - result := time.Format("2006.01.02") - var want string - if y < 0 { - // The 4 in %04d counts the - sign, so print -y instead - // and introduce our own - sign. - want = fmt.Sprintf("-%04d.%02d.%02d", -y, 1, 1) - } else { - want = fmt.Sprintf("%04d.%02d.%02d", y, 1, 1) - } - if result != want { - t.Errorf("(jan 1 %d).Format(\"2006.01.02\") = %q, want %q", y, result, want) - } - } -} - -type ParseTest struct { - name string - format string - value string - hasTZ bool // contains a time zone - hasWD bool // contains a weekday - yearSign int // sign of year, -1 indicates the year is not present in the format - fracDigits int // number of digits of fractional second -} - -var parseTests = []ParseTest{ - {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, - {"UnixDate", UnixDate, "Thu Feb 4 21:00:57 PST 2010", true, true, 1, 0}, - {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, - {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57 PST", true, true, 1, 0}, - {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57 PST", true, true, 1, 0}, - {"RFC1123", RFC1123, "Thu, 04 Feb 2010 22:00:57 PDT", true, true, 1, 0}, - {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57 -0800", true, true, 1, 0}, - {"RFC3339", RFC3339, "2010-02-04T21:00:57-08:00", true, false, 1, 0}, - {"custom: \"2006-01-02 15:04:05-07\"", "2006-01-02 15:04:05-07", "2010-02-04 21:00:57-08", true, false, 1, 0}, - // Optional fractional seconds. - {"ANSIC", ANSIC, "Thu Feb 4 21:00:57.0 2010", false, true, 1, 1}, - {"UnixDate", UnixDate, "Thu Feb 4 21:00:57.01 PST 2010", true, true, 1, 2}, - {"RubyDate", RubyDate, "Thu Feb 04 21:00:57.012 -0800 2010", true, true, 1, 3}, - {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57.0123 PST", true, true, 1, 4}, - {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57.01234 PST", true, true, 1, 5}, - {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57.01234 -0800", true, true, 1, 5}, - {"RFC3339", RFC3339, "2010-02-04T21:00:57.012345678-08:00", true, false, 1, 9}, - {"custom: \"2006-01-02 15:04:05\"", "2006-01-02 15:04:05", "2010-02-04 21:00:57.0", false, false, 1, 0}, - // Amount of white space should not matter. - {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, - {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, - // Case should not matter - {"ANSIC", ANSIC, "THU FEB 4 21:00:57 2010", false, true, 1, 0}, - {"ANSIC", ANSIC, "thu feb 4 21:00:57 2010", false, true, 1, 0}, - // Fractional seconds. - {"millisecond", "Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 21:00:57.012 2010", false, true, 1, 3}, - {"microsecond", "Mon Jan _2 15:04:05.000000 2006", "Thu Feb 4 21:00:57.012345 2010", false, true, 1, 6}, - {"nanosecond", "Mon Jan _2 15:04:05.000000000 2006", "Thu Feb 4 21:00:57.012345678 2010", false, true, 1, 9}, - // Leading zeros in other places should not be taken as fractional seconds. - {"zero1", "2006.01.02.15.04.05.0", "2010.02.04.21.00.57.0", false, false, 1, 1}, - {"zero2", "2006.01.02.15.04.05.00", "2010.02.04.21.00.57.01", false, false, 1, 2}, - // Month and day names only match when not followed by a lower-case letter. - {"Janet", "Hi Janet, the Month is January: Jan _2 15:04:05 2006", "Hi Janet, the Month is February: Feb 4 21:00:57 2010", false, true, 1, 0}, - - // GMT with offset. - {"GMT-8", UnixDate, "Fri Feb 5 05:00:57 GMT-8 2010", true, true, 1, 0}, - - // Accept any number of fractional second digits (including none) for .999... - // In Go 1, .999... was completely ignored in the format, meaning the first two - // cases would succeed, but the next four would not. Go 1.1 accepts all six. - {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, - {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, - {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, - {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, - {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, - {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, - - // issue 4502. - {"", StampNano, "Feb 4 21:00:57.012345678", false, false, -1, 9}, - {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012300000", false, false, -1, 4}, - {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, - {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.0123", false, false, -1, 4}, - {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, -} - -func TestParse(t *testing.T) { - for _, test := range parseTests { - time, err := Parse(test.format, test.value) - if err != nil { - t.Errorf("%s error: %v", test.name, err) - } else { - checkTime(time, &test, t) - } - } -} - -func TestParseInSydney(t *testing.T) { - loc, err := LoadLocation("Australia/Sydney") - if err != nil { - t.Fatal(err) - } - - // Check that Parse (and ParseInLocation) understand - // that Feb EST and Aug EST are different time zones in Sydney - // even though both are called EST. - t1, err := ParseInLocation("Jan 02 2006 MST", "Feb 01 2013 EST", loc) - if err != nil { - t.Fatal(err) - } - t2 := Date(2013, February, 1, 00, 00, 00, 0, loc) - if t1 != t2 { - t.Fatalf("ParseInLocation(Feb 01 2013 EST, Sydney) = %v, want %v", t1, t2) - } - _, offset := t1.Zone() - if offset != 11*60*60 { - t.Fatalf("ParseInLocation(Feb 01 2013 EST, Sydney).Zone = _, %d, want _, %d", offset, 11*60*60) - } - - t1, err = ParseInLocation("Jan 02 2006 MST", "Aug 01 2013 EST", loc) - if err != nil { - t.Fatal(err) - } - t2 = Date(2013, August, 1, 00, 00, 00, 0, loc) - if t1 != t2 { - t.Fatalf("ParseInLocation(Aug 01 2013 EST, Sydney) = %v, want %v", t1, t2) - } - _, offset = t1.Zone() - if offset != 10*60*60 { - t.Fatalf("ParseInLocation(Aug 01 2013 EST, Sydney).Zone = _, %d, want _, %d", offset, 10*60*60) - } -} - -func TestLoadLocationZipFile(t *testing.T) { - t.Skip("gccgo does not use the zip file") - - ForceZipFileForTesting(true) - defer ForceZipFileForTesting(false) - - _, err := LoadLocation("Australia/Sydney") - if err != nil { - t.Fatal(err) - } -} - -var rubyTests = []ParseTest{ - {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, - // Ignore the time zone in the test. If it parses, it'll be OK. - {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0000 2010", false, true, 1, 0}, - {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +0000 2010", false, true, 1, 0}, - {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +1130 2010", false, true, 1, 0}, -} - -// Problematic time zone format needs special tests. -func TestRubyParse(t *testing.T) { - for _, test := range rubyTests { - time, err := Parse(test.format, test.value) - if err != nil { - t.Errorf("%s error: %v", test.name, err) - } else { - checkTime(time, &test, t) - } - } -} - -func checkTime(time Time, test *ParseTest, t *testing.T) { - // The time should be Thu Feb 4 21:00:57 PST 2010 - if test.yearSign >= 0 && test.yearSign*time.Year() != 2010 { - t.Errorf("%s: bad year: %d not %d", test.name, time.Year(), 2010) - } - if time.Month() != February { - t.Errorf("%s: bad month: %s not %s", test.name, time.Month(), February) - } - if time.Day() != 4 { - t.Errorf("%s: bad day: %d not %d", test.name, time.Day(), 4) - } - if time.Hour() != 21 { - t.Errorf("%s: bad hour: %d not %d", test.name, time.Hour(), 21) - } - if time.Minute() != 0 { - t.Errorf("%s: bad minute: %d not %d", test.name, time.Minute(), 0) - } - if time.Second() != 57 { - t.Errorf("%s: bad second: %d not %d", test.name, time.Second(), 57) - } - // Nanoseconds must be checked against the precision of the input. - nanosec, err := strconv.ParseUint("012345678"[:test.fracDigits]+"000000000"[:9-test.fracDigits], 10, 0) - if err != nil { - panic(err) - } - if time.Nanosecond() != int(nanosec) { - t.Errorf("%s: bad nanosecond: %d not %d", test.name, time.Nanosecond(), nanosec) - } - name, offset := time.Zone() - if test.hasTZ && offset != -28800 { - t.Errorf("%s: bad tz offset: %s %d not %d", test.name, name, offset, -28800) - } - if test.hasWD && time.Weekday() != Thursday { - t.Errorf("%s: bad weekday: %s not %s", test.name, time.Weekday(), Thursday) - } -} - -func TestFormatAndParse(t *testing.T) { - const fmt = "Mon MST " + RFC3339 // all fields - f := func(sec int64) bool { - t1 := Unix(sec, 0) - if t1.Year() < 1000 || t1.Year() > 9999 { - // not required to work - return true - } - t2, err := Parse(fmt, t1.Format(fmt)) - if err != nil { - t.Errorf("error: %s", err) - return false - } - if t1.Unix() != t2.Unix() || t1.Nanosecond() != t2.Nanosecond() { - t.Errorf("FormatAndParse %d: %q(%d) %q(%d)", sec, t1, t1.Unix(), t2, t2.Unix()) - return false - } - return true - } - f32 := func(sec int32) bool { return f(int64(sec)) } - cfg := &quick.Config{MaxCount: 10000} - - // Try a reasonable date first, then the huge ones. - if err := quick.Check(f32, cfg); err != nil { - t.Fatal(err) - } - if err := quick.Check(f, cfg); err != nil { - t.Fatal(err) - } -} - -type ParseTimeZoneTest struct { - value string - length int - ok bool -} - -var parseTimeZoneTests = []ParseTimeZoneTest{ - {"gmt hi there", 0, false}, - {"GMT hi there", 3, true}, - {"GMT+12 hi there", 6, true}, - {"GMT+00 hi there", 3, true}, // 0 or 00 is not a legal offset. - {"GMT-5 hi there", 5, true}, - {"GMT-51 hi there", 3, true}, - {"ChST hi there", 4, true}, - {"MSDx", 3, true}, - {"MSDY", 0, false}, // four letters must end in T. - {"ESAST hi", 5, true}, - {"ESASTT hi", 0, false}, // run of upper-case letters too long. - {"ESATY hi", 0, false}, // five letters must end in T. -} - -func TestParseTimeZone(t *testing.T) { - for _, test := range parseTimeZoneTests { - length, ok := ParseTimeZone(test.value) - if ok != test.ok { - t.Errorf("expected %t for %q got %t", test.ok, test.value, ok) - } else if length != test.length { - t.Errorf("expected %d for %q got %d", test.length, test.value, length) - } - } -} - -type ParseErrorTest struct { - format string - value string - expect string // must appear within the error -} - -var parseErrorTests = []ParseErrorTest{ - {ANSIC, "Feb 4 21:00:60 2010", "cannot parse"}, // cannot parse Feb as Mon - {ANSIC, "Thu Feb 4 21:00:57 @2010", "cannot parse"}, - {ANSIC, "Thu Feb 4 21:00:60 2010", "second out of range"}, - {ANSIC, "Thu Feb 4 21:61:57 2010", "minute out of range"}, - {ANSIC, "Thu Feb 4 24:00:60 2010", "hour out of range"}, - {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59x01 2010", "cannot parse"}, - {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.xxx 2010", "cannot parse"}, - {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.-123 2010", "fractional second out of range"}, - // issue 4502. StampNano requires exactly 9 digits of precision. - {StampNano, "Dec 7 11:22:01.000000", `cannot parse ".000000" as ".000000000"`}, - {StampNano, "Dec 7 11:22:01.0000000000", "extra text: 0"}, - // issue 4493. Helpful errors. - {RFC3339, "2006-01-02T15:04:05Z07:00", `parsing time "2006-01-02T15:04:05Z07:00": extra text: 07:00`}, - {RFC3339, "2006-01-02T15:04_abc", `parsing time "2006-01-02T15:04_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as ":"`}, - {RFC3339, "2006-01-02T15:04:05_abc", `parsing time "2006-01-02T15:04:05_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as "Z07:00"`}, - {RFC3339, "2006-01-02T15:04:05Z_abc", `parsing time "2006-01-02T15:04:05Z_abc": extra text: _abc`}, -} - -func TestParseErrors(t *testing.T) { - for _, test := range parseErrorTests { - _, err := Parse(test.format, test.value) - if err == nil { - t.Errorf("expected error for %q %q", test.format, test.value) - } else if strings.Index(err.Error(), test.expect) < 0 { - t.Errorf("expected error with %q for %q %q; got %s", test.expect, test.format, test.value, err) - } - } -} - -func TestNoonIs12PM(t *testing.T) { - noon := Date(0, January, 1, 12, 0, 0, 0, UTC) - const expect = "12:00PM" - got := noon.Format("3:04PM") - if got != expect { - t.Errorf("got %q; expect %q", got, expect) - } - got = noon.Format("03:04PM") - if got != expect { - t.Errorf("got %q; expect %q", got, expect) - } -} - -func TestMidnightIs12AM(t *testing.T) { - midnight := Date(0, January, 1, 0, 0, 0, 0, UTC) - expect := "12:00AM" - got := midnight.Format("3:04PM") - if got != expect { - t.Errorf("got %q; expect %q", got, expect) - } - got = midnight.Format("03:04PM") - if got != expect { - t.Errorf("got %q; expect %q", got, expect) - } -} - -func Test12PMIsNoon(t *testing.T) { - noon, err := Parse("3:04PM", "12:00PM") - if err != nil { - t.Fatal("error parsing date:", err) - } - if noon.Hour() != 12 { - t.Errorf("got %d; expect 12", noon.Hour()) - } - noon, err = Parse("03:04PM", "12:00PM") - if err != nil { - t.Fatal("error parsing date:", err) - } - if noon.Hour() != 12 { - t.Errorf("got %d; expect 12", noon.Hour()) - } -} - -func Test12AMIsMidnight(t *testing.T) { - midnight, err := Parse("3:04PM", "12:00AM") - if err != nil { - t.Fatal("error parsing date:", err) - } - if midnight.Hour() != 0 { - t.Errorf("got %d; expect 0", midnight.Hour()) - } - midnight, err = Parse("03:04PM", "12:00AM") - if err != nil { - t.Fatal("error parsing date:", err) - } - if midnight.Hour() != 0 { - t.Errorf("got %d; expect 0", midnight.Hour()) - } -} - -// Check that a time without a Zone still produces a (numeric) time zone -// when formatted with MST as a requested zone. -func TestMissingZone(t *testing.T) { - time, err := Parse(RubyDate, "Thu Feb 02 16:10:03 -0500 2006") - if err != nil { - t.Fatal("error parsing date:", err) - } - expect := "Thu Feb 2 16:10:03 -0500 2006" // -0500 not EST - str := time.Format(UnixDate) // uses MST as its time zone - if str != expect { - t.Errorf("got %s; expect %s", str, expect) - } -} - -func TestMinutesInTimeZone(t *testing.T) { - time, err := Parse(RubyDate, "Mon Jan 02 15:04:05 +0123 2006") - if err != nil { - t.Fatal("error parsing date:", err) - } - expected := (1*60 + 23) * 60 - _, offset := time.Zone() - if offset != expected { - t.Errorf("ZoneOffset = %d, want %d", offset, expected) - } -} - -type SecondsTimeZoneOffsetTest struct { - format string - value string - expectedoffset int -} - -var secondsTimeZoneOffsetTests = []SecondsTimeZoneOffsetTest{ - {"2006-01-02T15:04:05-070000", "1871-01-01T05:33:02-003408", -(34*60 + 8)}, - {"2006-01-02T15:04:05-07:00:00", "1871-01-01T05:33:02-00:34:08", -(34*60 + 8)}, - {"2006-01-02T15:04:05-070000", "1871-01-01T05:33:02+003408", 34*60 + 8}, - {"2006-01-02T15:04:05-07:00:00", "1871-01-01T05:33:02+00:34:08", 34*60 + 8}, - {"2006-01-02T15:04:05Z070000", "1871-01-01T05:33:02-003408", -(34*60 + 8)}, - {"2006-01-02T15:04:05Z07:00:00", "1871-01-01T05:33:02+00:34:08", 34*60 + 8}, -} - -func TestParseSecondsInTimeZone(t *testing.T) { - // should accept timezone offsets with seconds like: Zone America/New_York -4:56:02 - LMT 1883 Nov 18 12:03:58 - for _, test := range secondsTimeZoneOffsetTests { - time, err := Parse(test.format, test.value) - if err != nil { - t.Fatal("error parsing date:", err) - } - _, offset := time.Zone() - if offset != test.expectedoffset { - t.Errorf("ZoneOffset = %d, want %d", offset, test.expectedoffset) - } - } -} - -func TestFormatSecondsInTimeZone(t *testing.T) { - d := Date(1871, 9, 17, 20, 4, 26, 0, FixedZone("LMT", -(34*60+8))) - timestr := d.Format("2006-01-02T15:04:05Z070000") - expected := "1871-09-17T20:04:26-003408" - if timestr != expected { - t.Errorf("Got %s, want %s", timestr, expected) - } -} - type ISOWeekTest struct { year int // year month, day int // month and day @@ -1035,7 +535,7 @@ var durationTests = []struct { }{ {"0", 0}, {"1ns", 1 * Nanosecond}, - {"1.1us", 1100 * Nanosecond}, + {"1.1µs", 1100 * Nanosecond}, {"2.2ms", 2200 * Microsecond}, {"3.3s", 3300 * Millisecond}, {"4m5s", 4*Minute + 5*Second}, @@ -1342,6 +842,7 @@ var parseDurationTests = []struct { {"-.", false, 0}, {".s", false, 0}, {"+.s", false, 0}, + {"3000000h", false, 0}, // overflow } func TestParseDuration(t *testing.T) { @@ -1463,6 +964,60 @@ func TestSub(t *testing.T) { } } +var nsDurationTests = []struct { + d Duration + want int64 +}{ + {Duration(-1000), -1000}, + {Duration(-1), -1}, + {Duration(1), 1}, + {Duration(1000), 1000}, +} + +func TestDurationNanoseconds(t *testing.T) { + for _, tt := range nsDurationTests { + if got := tt.d.Nanoseconds(); got != tt.want { + t.Errorf("d.Nanoseconds() = %d; want: %d", got, tt.want) + } + } +} + +var minDurationTests = []struct { + d Duration + want float64 +}{ + {Duration(-60000000000), -1}, + {Duration(-1), -1 / 60e9}, + {Duration(1), 1 / 60e9}, + {Duration(60000000000), 1}, +} + +func TestDurationMinutes(t *testing.T) { + for _, tt := range minDurationTests { + if got := tt.d.Minutes(); got != tt.want { + t.Errorf("d.Minutes() = %g; want: %g", got, tt.want) + } + } +} + +var hourDurationTests = []struct { + d Duration + want float64 +}{ + {Duration(-3600000000000), -1}, + {Duration(-1), -1 / 3600e9}, + {Duration(1), 1 / 3600e9}, + {Duration(3600000000000), 1}, +} + +func TestDurationHours(t *testing.T) { + for _, tt := range hourDurationTests { + if got := tt.d.Hours(); got != tt.want { + t.Errorf("d.Hours() = %g; want: %g", got, tt.want) + } + } +} + func BenchmarkNow(b *testing.B) { for i := 0; i < b.N; i++ { t = Now() diff --git a/libgo/go/time/zoneinfo.go b/libgo/go/time/zoneinfo.go index 1c6186258f9..c8e53a27cf0 100644 --- a/libgo/go/time/zoneinfo.go +++ b/libgo/go/time/zoneinfo.go @@ -45,6 +45,13 @@ type zoneTrans struct { isstd, isutc bool // ignored - no idea what these mean } +// alpha and omega are the beginning and end of time for zone +// transitions. +const ( + alpha = -1 << 63 // math.MinInt64 + omega = 1<<63 - 1 // math.MaxInt64 +) + // UTC represents Universal Coordinated Time (UTC). var UTC *Location = &utcLoc @@ -83,9 +90,9 @@ func FixedZone(name string, offset int) *Location { l := &Location{ name: name, zone: []zone{{name, offset, false}}, - tx: []zoneTrans{{-1 << 63, 0, false, false}}, - cacheStart: -1 << 63, - cacheEnd: 1<<63 - 1, + tx: []zoneTrans{{alpha, 0, false, false}}, + cacheStart: alpha, + cacheEnd: omega, } l.cacheZone = &l.zone[0] return l @@ -101,12 +108,12 @@ func FixedZone(name string, offset int) *Location { func (l *Location) lookup(sec int64) (name string, offset int, isDST bool, start, end int64) { l = l.get() - if len(l.tx) == 0 { + if len(l.zone) == 0 { name = "UTC" offset = 0 isDST = false - start = -1 << 63 - end = 1<<63 - 1 + start = alpha + end = omega return } @@ -119,10 +126,24 @@ func (l *Location) lookup(sec int64) (name string, offset int, isDST bool, start return } + if len(l.tx) == 0 || sec < l.tx[0].when { + zone := &l.zone[l.lookupFirstZone()] + name = zone.name + offset = zone.offset + isDST = zone.isDST + start = alpha + if len(l.tx) > 0 { + end = l.tx[0].when + } else { + end = omega + } + return + } + // Binary search for entry with largest time <= sec. // Not using sort.Search to avoid dependencies. tx := l.tx - end = 1<<63 - 1 + end = omega lo := 0 hi := len(tx) for hi-lo > 1 { @@ -144,6 +165,58 @@ func (l *Location) lookup(sec int64) (name string, offset int, isDST bool, start return } +// lookupFirstZone returns the index of the time zone to use for times +// before the first transition time, or when there are no transition +// times. +// +// The reference implementation in localtime.c from +// http://www.iana.org/time-zones/repository/releases/tzcode2013g.tar.gz +// implements the following algorithm for these cases: +// 1) If the first zone is unused by the transitions, use it. +// 2) Otherwise, if there are transition times, and the first +// transition is to a zone in daylight time, find the first +// non-daylight-time zone before and closest to the first transition +// zone. +// 3) Otherwise, use the first zone that is not daylight time, if +// there is one. +// 4) Otherwise, use the first zone. +func (l *Location) lookupFirstZone() int { + // Case 1. + if !l.firstZoneUsed() { + return 0 + } + + // Case 2. + if len(l.tx) > 0 && l.zone[l.tx[0].index].isDST { + for zi := int(l.tx[0].index) - 1; zi >= 0; zi-- { + if !l.zone[zi].isDST { + return zi + } + } + } + + // Case 3. + for zi := range l.zone { + if !l.zone[zi].isDST { + return zi + } + } + + // Case 4. + return 0 +} + +// firstZoneUsed returns whether the first zone is used by some +// transition. +func (l *Location) firstZoneUsed() bool { + for _, tx := range l.tx { + if tx.index == 0 { + return true + } + } + return false +} + // lookupName returns information about the time zone with // the given name (such as "EST") at the given pseudo-Unix time // (what the given time of day would be in UTC). diff --git a/libgo/go/time/zoneinfo_abbrs_windows.go b/libgo/go/time/zoneinfo_abbrs_windows.go index 80334371fe0..51a1a2f66d8 100644 --- a/libgo/go/time/zoneinfo_abbrs_windows.go +++ b/libgo/go/time/zoneinfo_abbrs_windows.go @@ -18,6 +18,7 @@ var abbrs = map[string]abbr{ "South Africa Standard Time": {"SAST", "SAST"}, // Africa/Johannesburg "W. Central Africa Standard Time": {"WAT", "WAT"}, // Africa/Lagos "E. Africa Standard Time": {"EAT", "EAT"}, // Africa/Nairobi + "Libya Standard Time": {"EET", "EET"}, // Africa/Tripoli "Namibia Standard Time": {"WAT", "WAST"}, // Africa/Windhoek "Alaskan Standard Time": {"AKST", "AKDT"}, // America/Anchorage "Paraguay Standard Time": {"PYT", "PYST"}, // America/Asuncion @@ -63,7 +64,6 @@ var abbrs = map[string]abbr{ "Nepal Standard Time": {"NPT", "NPT"}, // Asia/Katmandu "North Asia Standard Time": {"KRAT", "KRAT"}, // Asia/Krasnoyarsk "Magadan Standard Time": {"MAGT", "MAGT"}, // Asia/Magadan - "E. Europe Standard Time": {"EET", "EEST"}, // Asia/Nicosia "N. Central Asia Standard Time": {"NOVT", "NOVT"}, // Asia/Novosibirsk "Myanmar Standard Time": {"MMT", "MMT"}, // Asia/Rangoon "Arab Standard Time": {"AST", "AST"}, // Asia/Riyadh @@ -110,6 +110,7 @@ var abbrs = map[string]abbr{ "Fiji Standard Time": {"FJT", "FJT"}, // Pacific/Fiji "Central Pacific Standard Time": {"SBT", "SBT"}, // Pacific/Guadalcanal "Hawaiian Standard Time": {"HST", "HST"}, // Pacific/Honolulu + "Line Islands Standard Time": {"LINT", "LINT"}, // Pacific/Kiritimati "West Pacific Standard Time": {"PGT", "PGT"}, // Pacific/Port_Moresby "Tonga Standard Time": {"TOT", "TOT"}, // Pacific/Tongatapu } diff --git a/libgo/go/time/zoneinfo_plan9.go b/libgo/go/time/zoneinfo_plan9.go index 0e8f3811bed..4bb0cb39096 100644 --- a/libgo/go/time/zoneinfo_plan9.go +++ b/libgo/go/time/zoneinfo_plan9.go @@ -100,7 +100,7 @@ func loadZoneDataPlan9(s string) (l *Location, err error) { for i := range tx { if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) { l.cacheStart = tx[i].when - l.cacheEnd = 1<<63 - 1 + l.cacheEnd = omega if i+1 < len(tx) { l.cacheEnd = tx[i+1].when } diff --git a/libgo/go/time/zoneinfo_read.go b/libgo/go/time/zoneinfo_read.go index 7714aa9f583..de9ebb41c82 100644 --- a/libgo/go/time/zoneinfo_read.go +++ b/libgo/go/time/zoneinfo_read.go @@ -68,7 +68,7 @@ func loadZoneData(bytes []byte) (l *Location, err error) { // 1-byte version, then 15 bytes of padding var p []byte - if p = d.read(16); len(p) != 16 || p[0] != 0 && p[0] != '2' { + if p = d.read(16); len(p) != 16 || p[0] != 0 && p[0] != '2' && p[0] != '3' { return nil, badData } @@ -123,7 +123,7 @@ func loadZoneData(bytes []byte) (l *Location, err error) { return nil, badData } - // If version == 2, the entire file repeats, this time using + // If version == 2 or 3, the entire file repeats, this time using // 8-byte ints for txtimes and leap seconds. // We won't need those until 2106. @@ -173,7 +173,7 @@ func loadZoneData(bytes []byte) (l *Location, err error) { if len(tx) == 0 { // Build fake transition to cover all time. // This happens in fixed locations like "Etc/GMT0". - tx = append(tx, zoneTrans{when: -1 << 63, index: 0}) + tx = append(tx, zoneTrans{when: alpha, index: 0}) } // Committed to succeed. @@ -185,7 +185,7 @@ func loadZoneData(bytes []byte) (l *Location, err error) { for i := range tx { if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) { l.cacheStart = tx[i].when - l.cacheEnd = 1<<63 - 1 + l.cacheEnd = omega if i+1 < len(tx) { l.cacheEnd = tx[i+1].when } diff --git a/libgo/go/time/zoneinfo_test.go b/libgo/go/time/zoneinfo_test.go new file mode 100644 index 00000000000..ede5330f5cc --- /dev/null +++ b/libgo/go/time/zoneinfo_test.go @@ -0,0 +1,66 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package time_test + +import ( + "testing" + "time" +) + +func TestVersion3(t *testing.T) { + t.Skip("gccgo does not use the zip file") + time.ForceZipFileForTesting(true) + defer time.ForceZipFileForTesting(false) + _, err := time.LoadLocation("Asia/Jerusalem") + if err != nil { + t.Fatal(err) + } +} + +// Test that we get the correct results for times before the first +// transition time. To do this we explicitly check early dates in a +// couple of specific timezones. +func TestFirstZone(t *testing.T) { + t.Skip("gccgo does not use the zip file") + + time.ForceZipFileForTesting(true) + defer time.ForceZipFileForTesting(false) + + const format = "Mon, 02 Jan 2006 15:04:05 -0700 (MST)" + var tests = []struct { + zone string + unix int64 + want1 string + want2 string + }{ + { + "PST8PDT", + -1633269601, + "Sun, 31 Mar 1918 01:59:59 -0800 (PST)", + "Sun, 31 Mar 1918 03:00:00 -0700 (PDT)", + }, + { + "Pacific/Fakaofo", + 1325242799, + "Thu, 29 Dec 2011 23:59:59 -1100 (TKT)", + "Sat, 31 Dec 2011 00:00:00 +1300 (TKT)", + }, + } + + for _, test := range tests { + z, err := time.LoadLocation(test.zone) + if err != nil { + t.Fatal(err) + } + s := time.Unix(test.unix, 0).In(z).Format(format) + if s != test.want1 { + t.Errorf("for %s %d got %q want %q", test.zone, test.unix, s, test.want1) + } + s = time.Unix(test.unix+1, 0).In(z).Format(format) + if s != test.want2 { + t.Errorf("for %s %d got %q want %q", test.zone, test.unix, s, test.want2) + } + } +} diff --git a/libgo/go/time/zoneinfo_unix.go b/libgo/go/time/zoneinfo_unix.go index 1a4d115b932..3fe8e55795c 100644 --- a/libgo/go/time/zoneinfo_unix.go +++ b/libgo/go/time/zoneinfo_unix.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build darwin dragonfly freebsd linux netbsd openbsd +// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris // Parse "zoneinfo" time zone file. // This is a fairly standard file format used on OS X, Linux, BSD, Sun, and others. diff --git a/libgo/go/time/zoneinfo_windows.go b/libgo/go/time/zoneinfo_windows.go index be4e5c13ff0..02d8e0edcc8 100644 --- a/libgo/go/time/zoneinfo_windows.go +++ b/libgo/go/time/zoneinfo_windows.go @@ -11,6 +11,8 @@ import ( "unsafe" ) +//go:generate go run genzabbrs.go -output zoneinfo_abbrs_windows.go + // TODO(rsc): Fall back to copy of zoneinfo files. // BUG(brainman,rsc): On Windows, the operating system does not provide complete @@ -54,7 +56,7 @@ func matchZoneKey(zones syscall.Handle, kname string, stdname, dstname string) ( if err != nil { return false, err } - if s != dstname { + if s != dstname && dstname != stdname { return false, nil } return true, nil @@ -90,7 +92,7 @@ func toEnglishName(stdname, dstname string) (string, error) { return "", errors.New(`English name for time zone "` + stdname + `" not found in registry`) } -// extractCAPS exracts capital letters from description desc. +// extractCAPS extracts capital letters from description desc. func extractCAPS(desc string) string { var short []rune for _, c := range desc { @@ -165,8 +167,8 @@ func initLocalFromTZI(i *syscall.Timezoneinformation) { if nzone == 1 { // No daylight savings. std.offset = -int(i.Bias) * 60 - l.cacheStart = -1 << 63 - l.cacheEnd = 1<<63 - 1 + l.cacheStart = alpha + l.cacheEnd = omega l.cacheZone = std l.tx = make([]zoneTrans, 1) l.tx[0].when = l.cacheStart |