Skip to content

Commit

Permalink
Merge pull request #7 from tylerchr/empty-arrays
Browse files Browse the repository at this point in the history
Adopt empty array behavior in parser and validator
  • Loading branch information
tylerchr committed Jun 12, 2018
2 parents 23b72e5 + fb05782 commit 801464b
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 5 deletions.
21 changes: 16 additions & 5 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,21 @@ func (p *parser) parseArray() (Type, error) {
return Type{}, fmt.Errorf("unexpected token %s", tok.String())
}

// parse the internal type
t, err := p.parseType()
if err != nil {
return Type{}, err
// peek at the next character
tok, _ = p.scanIgnoreWhitespace(true)
p.unscan()

var childType *Type
if tok != SQUARECLOSE {

// parse the internal type
t, err := p.parseType()
if err != nil {
return Type{}, err
}

childType = &t

}

// parse the closing brace
Expand All @@ -115,7 +126,7 @@ func (p *parser) parseArray() (Type, error) {
return Type{}, fmt.Errorf("unexpected token %s", tok.String())
}

return Type{Kind: Array, Items: &t}, nil
return Type{Kind: Array, Items: childType}, nil
}

func (p *parser) parseObject() (Type, error) {
Expand Down
4 changes: 4 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ func TestParser(t *testing.T) {
Kind: Number,
}},
},
{
Schema: `[]?`,
Parsed: Type{Kind: Array, Optional: true, Items: nil},
},
{
Schema: `[number?]`,
Parsed: Type{Kind: Array, Items: &Type{
Expand Down
4 changes: 4 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,10 @@ func validArray(d *json.Decoder, t Type) bool {
defer d.Token()

for d.More() {
if t.Items == nil {
log.Println("validation failed: array: array is not empty")
return false
}
if ok := valid(d, *t.Items); !ok {
log.Println("validation failed: array: invalid sub-element")
return false
Expand Down
12 changes: 12 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ func TestValid(t *testing.T) {
Valid: true,
},

{
Type: Type{Kind: Array, Optional: false, Items: nil},
TestData: json.RawMessage(`[]`),
Valid: true,
},

{
Type: Type{Kind: Array, Optional: false, Items: nil},
TestData: json.RawMessage(`[1, 2, 3, null]`),
Valid: false,
},

{
Type: Type{Kind: Object, Optional: false, Properties: map[string]*Type{
"foo": &Type{Kind: Null},
Expand Down

0 comments on commit 801464b

Please sign in to comment.