Files
CavesOfSwift/Sources/JolkEngine/Util/FileHandle.swift
2024-05-05 17:01:56 +10:00

21 lines
717 B
Swift

import Foundation
extension FileHandle
{
// FixedWidthInteger or BinaryFloatingPoint
func read<T: FixedWidthInteger>(as: T.Type) throws -> T
{
let size = MemoryLayout<T>.size
guard let data = try self.read(upToCount: size)
else { throw NSError(domain: "FileHandle.read", code: NSFileReadUnknownError, userInfo: [
NSLocalizedFailureReasonErrorKey: "Read error",
NSLocalizedDescriptionKey: "Read error"]) }
guard data.count == size
else { throw NSError(domain: "FileHandle.read", code: NSFileReadUnknownError, userInfo: [
NSLocalizedFailureReasonErrorKey: "Value underread",
NSLocalizedDescriptionKey: "Value underread"]) }
return data.withUnsafeBytes { p -> T in p.load(as: T.self) }
}
}