SPB Git

Repository Public License

Hashing.swift 2.1 KB 49 lines swift

1import CryptoKit2import Foundation34public enum ContentHash {5    /// Lowercase hex SHA-256.6    public static func sha256(_ data: Data) -> String {7        SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()8    }910    public static func sha256(_ value: JSONValue) -> String { sha256(value.canonicalData()) }11}1213public enum PrismID {14    /// A stable, readable identifier: `prefix_` + 10 lowercase base-32 characters.15    public static func make(_ prefix: String) -> String {16        let alphabet = Array("abcdefghijklmnopqrstuvwxyz234567")17        var g = SystemRandomNumberGenerator()18        return prefix + "_" + String((0..<10).map { _ in alphabet[Int(g.next() % 32)] })19    }2021    /// Lowercase letters, digits and underscores; never empty; never starts with a digit.22    public static func slug(_ text: String, fallback: String = "item") -> String {23        var out = ""24        for u in text.lowercased().unicodeScalars {25            if ("a"..."z").contains(u) || ("0"..."9").contains(u) { out.unicodeScalars.append(u) }26            else if !out.hasSuffix("_") && !out.isEmpty { out += "_" }27        }28        while out.hasSuffix("_") { out.removeLast() }29        if out.isEmpty { return fallback }30        if out.first!.isNumber { out = "n" + out }31        return String(out.prefix(48))32    }3334    public static func isValid(_ id: String) -> Bool {35        guard let first = id.unicodeScalars.first, id.count <= 80 else { return false }36        let letter: (Unicode.Scalar) -> Bool = { ("a"..."z").contains($0) || ("A"..."Z").contains($0) }37        guard letter(first) else { return false }38        return id.unicodeScalars.allSatisfy { letter($0) || ("0"..."9").contains($0) || $0 == "_" || $0 == "-" }39    }40}4142public enum AtomicFile {43    /// Write to a temporary sibling then rename, so a crash never leaves a half-written file.44    public static func write(_ data: Data, to url: URL) throws {45        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)46        try data.write(to: url, options: [.atomic])47    }48}49
Files main
Menu

Theme