// PresetFilename.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation /// Sanitises a user-supplied name so it is safe as a file-system component on HFS+ and APFS. /// /// Shared by the preset stores (`BoardVersionStore`, `RigLibraryStore`) so every on-disk preset /// filename follows one scheme: `-.json`. /// /// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace with underscores. /// - Replaces a leading `.` (which would produce a hidden file or `.`/`..`) with an underscore. /// - Trims leading and trailing underscores that resulted from the substitutions (cosmetic). /// - Caps the UTF-8 byte length of the result at `maxLength` so the full filename /// (`-.json`, 54 extra bytes) stays within the 255-byte component limit. /// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely to /// separator characters after substitution. /// /// - Parameters: /// - name: The raw, user-supplied name. /// - maxLength: Maximum UTF-8 byte length of the sanitised prefix. Defaults to `200`. /// - Returns: A file-system-safe name, never empty. func sanitizePresetFilename( _ name: String, maxLength: Int = 200 ) -> String { let replacementCharacter: Character = "_" let forbiddenCharacters: Set = ["/", "\\", ":", "\0"] var sanitized: String = name.map { character -> Character in if character.isWhitespace || forbiddenCharacters.contains(character) { return replacementCharacter } return character }.reduce(into: "") { $0.append($1) } // Replace a leading dot so the filename is never `.`, `..`, or a hidden file. if sanitized.first == "." { sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_") } // Trim whitespace-replacement underscores at both ends (cosmetic). sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_")) // Treat all-empty or all-separator results as unnamed. guard !sanitized.isEmpty else { return "unnamed" } // Cap to maxLength UTF-8 bytes so the full filename stays within 255 bytes. if sanitized.utf8.count > maxLength { var truncated: String = "" var byteCount: Int = 0 for scalar: Unicode.Scalar in sanitized.unicodeScalars { let encodedLength: Int = UTF8.width(scalar) guard byteCount + encodedLength <= maxLength else { break } truncated.unicodeScalars.append(scalar) byteCount += encodedLength } sanitized = truncated } return sanitized.isEmpty ? "unnamed" : sanitized }