30 lines
1.2 KiB
Swift
30 lines
1.2 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
|
|
enum TapeImage {
|
|
static let limit = 64 * 1024 * 1024
|
|
enum Failure: LocalizedError {
|
|
case notFile, tooLarge, extensionType
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .notFile: return "Choose a regular CAS or WAV tape image."
|
|
case .tooLarge: return "Tape images must be no larger than 64 MiB."
|
|
case .extensionType: return "Choose a .cas or .wav tape image."
|
|
}
|
|
}
|
|
}
|
|
static func read(_ url: URL) throws -> Data {
|
|
guard ["cas", "wav"].contains(url.pathExtension.lowercased()) else { throw Failure.extensionType }
|
|
guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile }
|
|
let file = try FileHandle(forReadingFrom: url)
|
|
defer { try? file.close() }
|
|
var bytes = Data()
|
|
while bytes.count <= limit {
|
|
guard let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - bytes.count)), !chunk.isEmpty else { break }
|
|
bytes.append(chunk)
|
|
}
|
|
guard bytes.count <= limit else { throw Failure.tooLarge }
|
|
return bytes
|
|
}
|
|
}
|