Skip to content

Commit

Permalink
Merge pull request #8 from magodo/period_ensure_consumption
Browse files Browse the repository at this point in the history
Period parsing ensure consumption of all components.
  • Loading branch information
rickb777 authored Apr 22, 2020
2 parents 2248ec4 + 31e2dc8 commit 6300e54
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion period/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions period/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,21 @@ 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]
}

result.years, st = parseField(st, 'Y')
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)
Expand All @@ -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)

Expand Down
3 changes: 3 additions & 0 deletions period/period_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 6300e54

Please sign in to comment.