26 lines
1.0 KiB
Swift
26 lines
1.0 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
|
|
enum BinaryFile {
|
|
static let limit = 1024 * 1024 // Matches BinaryImage::maxBytes; structural parsing belongs to the core.
|
|
enum Failure: LocalizedError {
|
|
case notFile, size
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .notFile: return "Choose a regular CoCo .bin file."
|
|
case .size: return "Choose a nonempty CoCo .bin file, up to 1 MiB."
|
|
}
|
|
}
|
|
}
|
|
static func read(_ url: URL) throws -> Data {
|
|
let resolved = url.resolvingSymlinksInPath()
|
|
guard url.pathExtension.lowercased() == "bin",
|
|
try resolved.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile }
|
|
let file = try FileHandle(forReadingFrom: resolved)
|
|
defer { try? file.close() }
|
|
let data = try file.read(upToCount: limit + 1) ?? Data()
|
|
guard !data.isEmpty, data.count <= limit else { throw Failure.size }
|
|
return data
|
|
}
|
|
}
|