Skip to content

Commit 9df2fa0

Browse files
committed
Fix a crash
1 parent f0d2b05 commit 9df2fa0

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

Sources/StreamReader/Implementations/GenericStreamReader.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ public final class GenericStreamReader : StreamReader {
175175
var unmatchedDelimiters = Array(delimiters.filter{ !$0.isEmpty }.enumerated())
176176
let (minDelimiterLength, maxDelimiterLength) = (unmatchedDelimiters.map(\.element.count).min() ?? 0, unmatchedDelimiters.map(\.element.count).max() ?? 0)
177177

178-
let allowedToBeRead = readSizeLimit.flatMap{ $0 - currentReadPosition } ?? .max
178+
let allowedToBeRead = readSizeLimit.flatMap{ max(0, $0 - currentReadPosition) } ?? .max
179179

180180
var searchOffset = 0
181181
repeat {
@@ -258,7 +258,7 @@ public final class GenericStreamReader : StreamReader {
258258
/* 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. */
259259
guard size > 0 else {return UnsafeRawBufferPointer(start: nil, count: 0)}
260260
/* We check reading the given size is allowed. */
261-
let allowedToBeRead = readSizeLimit.flatMap{ $0 - currentReadPosition }
261+
let allowedToBeRead = readSizeLimit.flatMap{ max(0, $0 - currentReadPosition) }
262262
if let allowedToBeRead = allowedToBeRead, allowedToBeRead < size {
263263
guard readContraints.allowReadingLess else {
264264
throw Err.notEnoughData(wouldReachReadSizeLimit: true)
@@ -360,8 +360,8 @@ public final class GenericStreamReader : StreamReader {
360360
let unconstrainedSizeToRead = bufferSize - (bufferStartPos + bufferValidLength)
361361
/* But we have to constrain to the size allowed to be read */
362362
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}
365365
/* And to the underlying stream read size limit */
366366
let sizeToRead: Int
367367
if let readLimit = underlyingStreamReadSizeLimit {sizeToRead = min(readLimit, sizeAllowedToBeRead)}

0 commit comments

Comments
 (0)