From 31e2dc8d51f2fdc5219300b6c150a09c269f70ae Mon Sep 17 00:00:00 2001 From: magodo Date: Wed, 22 Apr 2020 00:12:40 +0800 Subject: [PATCH] Period parsing ensure consumption of all components. --- period/marshal_test.go | 2 +- period/parse.go | 10 ++++++++-- period/period_test.go | 3 +++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/period/marshal_test.go b/period/marshal_test.go index b158723d..240719ac 100644 --- a/period/marshal_test.go +++ b/period/marshal_test.go @@ -119,7 +119,7 @@ func TestInvalidPeriodText(t *testing.T) { }{ {``, `cannot parse a blank string as a period`}, {`not-a-period`, `expected 'P' period mark at the start: not-a-period`}, - {`P000`, `expected 'Y', 'M', 'W', 'D', 'H', 'M', or 'S' marker: P000`}, + {`P000`, `unexpected remaining components 000: P000`}, } for _, c := range cases { var p Period diff --git a/period/parse.go b/period/parse.go index 30b3a693..270ae8d0 100644 --- a/period/parse.go +++ b/period/parse.go @@ -75,6 +75,10 @@ func Parse(period string) (Period, error) { return Period{}, fmt.Errorf("expected a number before the 'S' marker: %s", period) } + if len(st.pcopy) != 0 { + return Period{}, fmt.Errorf("unexpected remaining components %s: %s", st.pcopy, period) + } + st.pcopy = pcopy[:t] } @@ -82,12 +86,10 @@ func Parse(period string) (Period, error) { if st.err != nil { return Period{}, fmt.Errorf("expected a number before the 'Y' marker: %s", period) } - result.months, st = parseField(st, 'M') if st.err != nil { return Period{}, fmt.Errorf("expected a number before the 'M' marker: %s", period) } - weeks, st := parseField(st, 'W') if st.err != nil { return Period{}, fmt.Errorf("expected a number before the 'W' marker: %s", period) @@ -98,6 +100,10 @@ func Parse(period string) (Period, error) { return Period{}, fmt.Errorf("expected a number before the 'D' marker: %s", period) } + if len(st.pcopy) != 0 { + return Period{}, fmt.Errorf("unexpected remaining components %s: %s", st.pcopy, period) + } + result.days = weeks*7 + days //fmt.Printf("%#v\n", st) diff --git a/period/period_test.go b/period/period_test.go index 87d566bf..38ba9ea9 100644 --- a/period/period_test.go +++ b/period/period_test.go @@ -27,6 +27,9 @@ func TestParseErrors(t *testing.T) { {"PxD", "expected a number before the 'D' marker: PxD"}, {"PTxH", "expected a number before the 'H' marker: PTxH"}, {"PTxS", "expected a number before the 'S' marker: PTxS"}, + {"P1HT1M", "unexpected remaining components 1H: P1HT1M"}, + {"PT1Y", "unexpected remaining components 1Y: PT1Y"}, + {"P1S", "unexpected remaining components 1S: P1S"}, } for i, c := range cases { _, err := Parse(c.value)