@@ -175,7 +175,7 @@ public final class GenericStreamReader : StreamReader {
175
175
var unmatchedDelimiters = Array ( delimiters. filter { !$0. isEmpty } . enumerated ( ) )
176
176
let ( minDelimiterLength, maxDelimiterLength) = ( unmatchedDelimiters. map ( \. element. count) . min ( ) ?? 0 , unmatchedDelimiters. map ( \. element. count) . max ( ) ?? 0 )
177
177
178
- let allowedToBeRead = readSizeLimit. flatMap { $0 - currentReadPosition } ?? . max
178
+ let allowedToBeRead = readSizeLimit. flatMap { max ( 0 , $0 - currentReadPosition) } ?? . max
179
179
180
180
var searchOffset = 0
181
181
repeat {
@@ -258,7 +258,7 @@ public final class GenericStreamReader : StreamReader {
258
258
/* If we want to read 0 bytes, whether we’ve reached EOF or we are allowed to read more bytes, we can return directly an empty buffer. */
259
259
guard size > 0 else { return UnsafeRawBufferPointer ( start: nil , count: 0 ) }
260
260
/* We check reading the given size is allowed. */
261
- let allowedToBeRead = readSizeLimit. flatMap { $0 - currentReadPosition }
261
+ let allowedToBeRead = readSizeLimit. flatMap { max ( 0 , $0 - currentReadPosition) }
262
262
if let allowedToBeRead = allowedToBeRead, allowedToBeRead < size {
263
263
guard readContraints. allowReadingLess else {
264
264
throw Err . notEnoughData ( wouldReachReadSizeLimit: true )
@@ -360,8 +360,8 @@ public final class GenericStreamReader : StreamReader {
360
360
let unconstrainedSizeToRead = bufferSize - ( bufferStartPos + bufferValidLength)
361
361
/* But we have to constrain to the size allowed to be read */
362
362
let sizeAllowedToBeRead : Int
363
- if let readSizeLimit = readSizeLimit { sizeAllowedToBeRead = min ( readSizeLimit - currentStreamReadPosition, unconstrainedSizeToRead) }
364
- else { sizeAllowedToBeRead = unconstrainedSizeToRead}
363
+ if let readSizeLimit = readSizeLimit { sizeAllowedToBeRead = min ( max ( 0 , readSizeLimit - currentStreamReadPosition) , unconstrainedSizeToRead) }
364
+ else { sizeAllowedToBeRead = unconstrainedSizeToRead}
365
365
/* And to the underlying stream read size limit */
366
366
let sizeToRead : Int
367
367
if let readLimit = underlyingStreamReadSizeLimit { sizeToRead = min ( readLimit, sizeAllowedToBeRead) }
0 commit comments