Skip to content

Commit

Permalink
Remove the need for a semaphore in ResourceResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
mickael-menu committed Jul 12, 2024
1 parent 548b29c commit be843c6
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions Sources/Adapters/GCDWebServer/ResourceResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,26 +98,19 @@ class ResourceResponse: ReadiumGCDWebServerFileResponse, Loggable {
}

/// Read a new chunk of data.
override open func readData() throws -> Data {
let semaphore = DispatchSemaphore(value: 0)
Task {
let len = min(bufferSize, range.count - Int(totalNumberOfBytesRead))
// If nothing to read, return
guard len > 0, offset < length else {
lastReadData = .success(Data())
return
}
// Read
lastReadData = await resource.read(range: offset ..< (offset + UInt64(len)))
if case let .success(data) = lastReadData {
totalNumberOfBytesRead += UInt64(data.count)
offset += UInt64(data.count)
}

semaphore.signal()
override func asyncReadData() async throws -> Data {
let len = min(bufferSize, range.count - Int(totalNumberOfBytesRead))
// If nothing to read, return
guard len > 0, offset < length else {
lastReadData = .success(Data())
return Data()
}
// Read
lastReadData = await resource.read(range: offset ..< (offset + UInt64(len)))
if case let .success(data) = lastReadData {
totalNumberOfBytesRead += UInt64(data.count)
offset += UInt64(data.count)
}

_ = semaphore.wait(timeout: .distantFuture)

return (try? lastReadData?.get()) ?? Data()
}
Expand Down

0 comments on commit be843c6

Please sign in to comment.