@@ -41,10 +41,47 @@ class ChunkedFile {
4141 func readNextChunk( ) -> Result < FileChunk , Error > {
4242 SDKLogger . logger? . info ( " --readNextChunk(): called " )
4343 do {
44- guard fileHandle != nil else {
44+ guard let fileHandle else {
4545 return Result . failure ( ChunkedFileError . invalidState ( " readNextChunk() called but the file was not open " ) )
4646 }
47- return try Result . success ( doReadNextChunk ( ) )
47+
48+ guard let fileURL = fileURL else {
49+ throw ChunkedFileError . invalidState ( " Missing file url. " )
50+ }
51+ var data : Data ?
52+ try autoreleasepool {
53+ data = try fileHandle. read ( upToCount: chunkSize)
54+ }
55+
56+ let fileSize = try fileManager. fileSizeOfItem (
57+ atPath: fileURL. path
58+ )
59+
60+ guard let data = data else {
61+ // Called while already at the end of the file. We read zero bytes, "ending" at the end of the file
62+ return . success(
63+ FileChunk (
64+ startByte: fileSize,
65+ endByte: fileSize,
66+ totalFileSize: fileSize,
67+ chunkData: Data ( capacity: 0 )
68+ )
69+ )
70+ }
71+
72+ let chunkLength = data. count
73+ let updatedFilePosition = filePos + UInt64( chunkLength)
74+
75+ let chunk = FileChunk (
76+ startByte: self . filePos,
77+ endByte: updatedFilePosition,
78+ totalFileSize: fileSize,
79+ chunkData: data
80+ )
81+
82+ state? . filePosition = updatedFilePosition
83+
84+ return . success( chunk)
4885 } catch {
4986 return Result . failure ( ChunkedFileError . fileHandle ( error) )
5087 }
@@ -86,40 +123,6 @@ class ChunkedFile {
86123 state? . filePosition = byte
87124 }
88125
89- private func doReadNextChunk( ) throws -> FileChunk {
90- SDKLogger . logger? . info ( " --doReadNextChunk " )
91- guard let fileHandle = fileHandle, let fileURL = fileURL else {
92- throw ChunkedFileError . invalidState ( " doReadNextChunk called without file handle. Did you call open()? " )
93- }
94- var data : Data ?
95- try autoreleasepool {
96- data = try fileHandle. read ( upToCount: chunkSize)
97- }
98-
99- let fileSize = try fileManager. fileSizeOfItem (
100- atPath: fileURL. path
101- )
102-
103- guard let data = data else {
104- // Called while already at the end of the file. We read zero bytes, "ending" at the end of the file
105- return FileChunk ( startByte: fileSize, endByte: fileSize, totalFileSize: fileSize, chunkData: Data ( capacity: 0 ) )
106- }
107-
108- let nsData = NSData ( data: data)
109- let readLen = nsData. length
110- let newFilePos = filePos + UInt64( readLen)
111- let chunk = FileChunk (
112- startByte: self . filePos,
113- endByte: newFilePos,
114- totalFileSize: fileSize,
115- chunkData: data
116- )
117-
118- state? . filePosition = newFilePos
119-
120- return chunk
121- }
122-
123126 /// Creates a ``ChunkedFile`` that wraps the file given by the URL. The file will be opened after calling ``openFile()``
124127 init ( chunkSize: Int ) {
125128 self . chunkSize = chunkSize
0 commit comments