Skip to content

Commit

Permalink
clean-up
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewjl-mux committed Mar 6, 2024
1 parent b194a5b commit e6f39f8
Showing 1 changed file with 39 additions and 35 deletions.
74 changes: 39 additions & 35 deletions Sources/MuxUploadSDK/InternalUtilities/ChunkedFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,45 @@ class ChunkedFile {
guard fileHandle != nil else {
return Result.failure(ChunkedFileError.invalidState("readNextChunk() called but the file was not open"))
}
return try Result.success(doReadNextChunk())

SDKLogger.logger?.info("--doReadNextChunk")
guard let fileHandle = fileHandle, let fileURL = fileURL else {
throw ChunkedFileError.invalidState("doReadNextChunk called without file handle. Did you call open()?")
}
var data : Data?
try autoreleasepool {
data = try fileHandle.read(upToCount: chunkSize)
}

let fileSize = try fileManager.fileSizeOfItem(
atPath: fileURL.path
)

guard let data = data else {
// Called while already at the end of the file. We read zero bytes, "ending" at the end of the file
return .success(
FileChunk(
startByte: fileSize,
endByte: fileSize,
totalFileSize: fileSize,
chunkData: Data(capacity: 0)
)
)
}

let chunkLength = data.count
let updatedFilePosition = filePos + UInt64(chunkLength)

let chunk = FileChunk(
startByte: self.filePos,
endByte: updatedFilePosition,
totalFileSize: fileSize,
chunkData: data
)

state?.filePosition = updatedFilePosition

return .success(chunk)
} catch {
return Result.failure(ChunkedFileError.fileHandle(error))
}
Expand Down Expand Up @@ -86,40 +124,6 @@ class ChunkedFile {
state?.filePosition = byte
}

private func doReadNextChunk() throws -> FileChunk {
SDKLogger.logger?.info("--doReadNextChunk")
guard let fileHandle = fileHandle, let fileURL = fileURL else {
throw ChunkedFileError.invalidState("doReadNextChunk called without file handle. Did you call open()?")
}
var data : Data?
try autoreleasepool {
data = try fileHandle.read(upToCount: chunkSize)
}

let fileSize = try fileManager.fileSizeOfItem(
atPath: fileURL.path
)

guard let data = data else {
// Called while already at the end of the file. We read zero bytes, "ending" at the end of the file
return FileChunk(startByte: fileSize, endByte: fileSize, totalFileSize: fileSize, chunkData: Data(capacity: 0))
}

let nsData = NSData(data: data)
let readLen = nsData.length
let newFilePos = filePos + UInt64(readLen)
let chunk = FileChunk(
startByte: self.filePos,
endByte: newFilePos,
totalFileSize: fileSize,
chunkData: data
)

state?.filePosition = newFilePos

return chunk
}

/// Creates a ``ChunkedFile`` that wraps the file given by the URL. The file will be opened after calling ``openFile()``
init(chunkSize: Int) {
self.chunkSize = chunkSize
Expand Down

0 comments on commit e6f39f8

Please sign in to comment.