@@ -18,13 +18,21 @@ public struct JSONParser {
1818@usableFromInline struct JSONParserImpl {
1919
2020 @usableFromInline var reader : DocumentReader
21+ @usableFromInline var depth : Int = 0
2122
2223 @inlinable init < Bytes: Collection > ( bytes: Bytes ) where Bytes. Element == UInt8 {
2324 self . reader = DocumentReader ( bytes: bytes)
2425 }
2526
2627 @usableFromInline mutating func parse( ) throws -> JSONValue {
2728 let value = try parseValue ( )
29+ #if DEBUG
30+ defer {
31+ guard self . depth == 0 else {
32+ preconditionFailure ( )
33+ }
34+ }
35+ #endif
2836
2937 // handle extra character if top level was number
3038 if case . number( _) = value {
@@ -236,13 +244,19 @@ public struct JSONParser {
236244 }
237245
238246 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 }
241253 var state = ArrayState . expectValueOrEnd
242254
243255 var array = [ JSONValue] ( )
244256 array. reserveCapacity ( 10 )
245257
258+ // parse first value or immidiate end
259+
246260 do {
247261 let value = try parseValue ( )
248262 array. append ( value)
@@ -336,6 +350,13 @@ public struct JSONParser {
336350 }
337351
338352 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+
339360 var state = ObjectState . expectKeyOrEnd
340361
341362 // parse first key or end immidiatly
0 commit comments