Skip to content

Commit

Permalink
Stricter parsing (#8)
Browse files Browse the repository at this point in the history
Closes issue #4 

* check for leading P, allow for negative
* use switch, add more invalid period string tests, increase parser strictness again
* simplify negative parsing
  • Loading branch information
sosodev authored May 7, 2024
1 parent 58dbc8d commit 5b2735a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
19 changes: 12 additions & 7 deletions duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,26 @@ var (
// Parse attempts to parse the given duration string into a *Duration,
// if parsing fails an error is returned instead.
func Parse(d string) (*Duration, error) {
if !strings.Contains(d, "P") {
return nil, ErrUnexpectedInput
}

state := parsingPeriod
duration := &Duration{}
num := ""
var err error

switch {
case strings.HasPrefix(d, "P"): // standard duration
case strings.HasPrefix(d, "-P"): // negative duration
duration.Negative = true
d = strings.TrimPrefix(d, "-") // remove the negative sign
default:
return nil, ErrUnexpectedInput
}

for _, char := range d {
switch char {
case '-':
duration.Negative = true
case 'P':
state = parsingPeriod
if state != parsingPeriod {
return nil, ErrUnexpectedInput
}
case 'T':
state = parsingTime
case 'Y':
Expand Down
12 changes: 12 additions & 0 deletions duration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ func TestParse(t *testing.T) {
want: nil,
wantErr: true,
},
{
name: "invalid-duration-2",
args: args{d: "P-T0S"},
want: nil,
wantErr: true,
},
{
name: "invalid-duration-3",
args: args{d: "PT0SP0D"},
want: nil,
wantErr: true,
},
{
name: "period-only",
args: args{d: "P4Y"},
Expand Down

0 comments on commit 5b2735a

Please sign in to comment.