@@ -18,13 +18,21 @@ public struct JSONParser {
18
18
@usableFromInline struct JSONParserImpl {
19
19
20
20
@usableFromInline var reader : DocumentReader
21
+ @usableFromInline var depth : Int = 0
21
22
22
23
@inlinable init < Bytes: Collection > ( bytes: Bytes ) where Bytes. Element == UInt8 {
23
24
self . reader = DocumentReader ( bytes: bytes)
24
25
}
25
26
26
27
@usableFromInline mutating func parse( ) throws -> JSONValue {
27
28
let value = try parseValue ( )
29
+ #if DEBUG
30
+ defer {
31
+ guard self . depth == 0 else {
32
+ preconditionFailure ( )
33
+ }
34
+ }
35
+ #endif
28
36
29
37
// handle extra character if top level was number
30
38
if case . number( _) = value {
@@ -236,13 +244,19 @@ public struct JSONParser {
236
244
}
237
245
238
246
mutating func parseArray( ) throws -> [ JSONValue ] {
239
- // parse first value or immidiate end
240
- precondition ( reader. value == UInt8 ( ascii: " [ " ) )
247
+ assert ( reader. value == UInt8 ( ascii: " [ " ) )
248
+ guard depth < 512 else {
249
+ throw JSONError . tooManyNestedArraysOrDictionaries ( characterIndex: reader. index)
250
+ }
251
+ depth += 1
252
+ defer { depth -= 1 }
241
253
var state = ArrayState . expectValueOrEnd
242
254
243
255
var array = [ JSONValue] ( )
244
256
array. reserveCapacity ( 10 )
245
257
258
+ // parse first value or immidiate end
259
+
246
260
do {
247
261
let value = try parseValue ( )
248
262
array. append ( value)
@@ -336,6 +350,13 @@ public struct JSONParser {
336
350
}
337
351
338
352
mutating func parseObject( ) throws -> [ String : JSONValue ] {
353
+ assert ( reader. value == UInt8 ( ascii: " { " ) )
354
+ guard depth < 512 else {
355
+ throw JSONError . tooManyNestedArraysOrDictionaries ( characterIndex: reader. index)
356
+ }
357
+ depth += 1
358
+ defer { depth -= 1 }
359
+
339
360
var state = ObjectState . expectKeyOrEnd
340
361
341
362
// parse first key or end immidiatly
0 commit comments