Cotton code
20 lines · 895 B · SwiftRaw
// A SIDECAR'S TEXT, READ ONLY WHILE IT IS A SIDECAR'S SIZE: a film's NFO or a// song's LRC beside it is a few kilobytes, but the name alone says nothing// of what the file holds. One byte past the most is read to know the file is// longer, and then it is none — never a whole body in memory// (`WholeBodySweepTests`).import Foundationenum BoundedText {    /// The file's text (read as UTF-8) when it holds at most `most` bytes;    /// nil when it is longer or cannot be read.    static func read(_ url: URL, most: Int) -> String? {        guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }        defer { try? handle.close() }        let data: Data        do { data = try handle.read(upToCount: most + 1) ?? Data() } catch { return nil }        guard data.count <= most else { return nil }        return String(decoding: data, as: UTF8.self)    }}