I'm working on reading fairly large data from a file. It’s compressed in the file, I need to load it from a FileDescriptor
, decompress it, and then interpret it as an array of some type, like UInt16
or Float
.
So far, I can load and decompress the data into a Data
:
let tileOffset = tileInfo.tileOffsets[inTileIdx]
let tileByteCount = tileInfo.tileByteCounts[inTileIdx]
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: Int(tileByteCount), alignment: MemoryLayout<UInt8>.alignment)
defer { buf.deallocate() }
let readCount = try self.reader.fd.read(fromAbsoluteOffset: tileOffset, into: buf)
let data = Data(bytesNoCopy: buf.baseAddress!, count: readCount, deallocator: .none)
let uncompressedData = try (data[2...] as NSData).decompressed(using: .zlib)
Using NSData
’s decompress method requires me to strip off the first two bytes of the data (which is using deflate).
I feel like there’s some cool trick with memoryReboundTo
or some such that would let me create a nice, managed array of Floats from uncompressedData
. But I’m not sure exactly how.
I also am not sure about the deferred deallocation, which I probably need to manage more explicitly (like only do it if an exception is thrown).
I'm not sure if the data[2...]
subrange creates a copy, but I don’t think so, right?
But most importantly, can I tell Swift to treat uncompressedData
as an array of Float
?