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) }
	}
}
