Skip to content

Commit

Permalink
std/encoding/json: fix DecodeJSON reserved decoder function does not …
Browse files Browse the repository at this point in the history
…supports JSON objects or arrays
  • Loading branch information
mertcandav committed Feb 7, 2025
1 parent 33162aa commit 4ebb0a4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
18 changes: 11 additions & 7 deletions std/encoding/json/decode.jule
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ impl jsonDecoder {

// Scans to the end of what was started.
// Checks syntax errors.
fn skip(self)! {
// Unlike [scanValidLit], it supports objects and arrays.
fn scanValidValue(self)!: []byte {
mut b := self.data[self.i]
if b != '[' && b != '{' { // Literal.
self.scanValidLit() else { error(error) }
ret
ret self.scanValidLit() else { error(error) }
}
i := self.i
depth := len(self.parseState)
mut colon := false
for !self.eof() {
Expand All @@ -72,7 +73,8 @@ impl jsonDecoder {
self.popParseState()
self.i++
if depth >= len(self.parseState) {
ret
// Keep immutability, it will not be mutated.
ret unsafe { (*(&self.data))[i:self.i] }
}
| ']':
if colon || self.parseState[len(self.parseState)-1] != parseState.Array {
Expand All @@ -81,7 +83,8 @@ impl jsonDecoder {
self.popParseState()
self.i++
if depth >= len(self.parseState) {
ret
// Keep immutability, it will not be mutated.
ret unsafe { (*(&self.data))[i:self.i] }
}
| ':':
if colon {
Expand Down Expand Up @@ -144,6 +147,7 @@ impl jsonDecoder {

// Scans inputs efficiently, not checks validity.
// Only checks for length.
// It only supports basic literals, not objects or arrays.
fn scanLit(self)!: []byte {
i := self.i
Match:
Expand Down Expand Up @@ -410,7 +414,7 @@ impl jsonDecoder {
}
}
// Skip JSON object field if is not decoded for struct.
self.skip() else { error(error) }
self.scanValidValue() else { error(error) }
// To avoid unused error.
// Empty or no-public field structure may cause compile error(s).
goto fieldDecoded
Expand Down Expand Up @@ -461,7 +465,7 @@ impl jsonDecoder {
m.Type().Result().Kind() == comptime::Kind.Void:
const match name {
| "DecodeJSON":
lit := self.scanValidLit() else { error(error) }
lit := self.scanValidValue() else { error(error) }
m.Unwrap()(lit) else { error(error) }
| "DecodeText":
b := self.data[self.i]
Expand Down
2 changes: 1 addition & 1 deletion std/encoding/json/validate.jule
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn Valid(data: []byte): bool {
ret false
}
for {
decoder.skip() else { ret false }
decoder.scanValidValue() else { ret false }
decoder.skipSpace()
if decoder.eof() {
break
Expand Down

0 comments on commit 4ebb0a4

Please sign in to comment.