首页 > 解决方案 > 从类型的字符串中确定类型以快速读取二进制数据

问题描述

我有从 C++ 应用程序写入的 TB 二进制数据、带有坐标和 4 个浮点数的稀疏数据。我现在正在快速编写一个应用程序来读取该数据。二进制数据是重复的,例如UInt8, UInt8, Float32, Float32, Float32, Float32...。大约 12 个月前编写数据时,我包含了一个单独的 json 文件来描述数据。我现在需要使用 Type 的那些 String 表示来快速调用一个函数来读取二进制文件。

//A string representation of the type of binary data stored on disk
struct dimJSON{
    let diskColRowType: String = "UInt8"
    let diskQType: String = "Float32"
    var sizeColRowTypeInBytes:Int {
       if diskColRowType = "UInt8" {return 1}
    ...etc
}

//The function used to read the data
func readBinaryData<diskColRow: BinaryInteger, diskQ: BinaryFloatingPoint>(diskColRow: diskColRow.Type, diskQ: diskQ.Type) -> [[[diskQ]]]{

    var plane = [[[diskQ]]]()

    data.withUnsafeBytes{ (ptr: UnsafeRawBufferPointer) in
        for index in stride(from: 0, to: dim.binFileSizeInStructs * dim.sizeStructInBytes, by: dim.sizeStructInBytes) {


        let col = Int(ptr.load(fromByteOffset: index, as: diskColRow.self))
        let row = Int(ptr.load(fromByteOffset: index + dim.sizeColRowTypeInBytes, as: diskColRow.self))

        //Cannot ptr.load bytes offset, due to possible unaligned memory
        let q = Data(bytes: ptr.baseAddress!.advanced(by: index + dim.byteOffsetQVec), count: 4 * dim.sizeQTypeInBytes)

        plane[col][row] = q.toArray(type: diskQ.self)

        }
    }
    return plane
}


//This works, but seems dull, and I have multiple call sites for similar funcs readBinaryData.

if dim.diskColRowType == "UInt8" && dim.diskQ == "Float32"{
    let p = readBinaryData(diskColRow: UInt8.self, diskQ: Float32.self)
} else if dim.diskColRowType == "UInt16" && dim.diskQ == "Double" {
    let p = readBinaryData(diskColRow: UInt16.self, diskQ: Double.self)
}

//Something like this would be good:
extension dimJSON {
    func getType() -> ?????? {
        if diskColRowType = "UInt8" {return UInt8.self}
        else if diskColRowType = "UInt16" {return UInt16.self}
        ...
    }
}




标签: swifttypesbinaryfilesbinary-data

解决方案


推荐阅读