|
| 1 | +/* |
| 2 | + This source file is part of the Swift.org open source project |
| 3 | + |
| 4 | + Copyright (c) 2024 Apple Inc. and the Swift project authors |
| 5 | + Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | + |
| 7 | + See https://swift.org/LICENSE.txt for license information |
| 8 | + See https://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | +*/ |
| 10 | + |
| 11 | +import Foundation |
| 12 | + |
| 13 | +extension DocumentationBundle { |
| 14 | + /// A stable and locally unique identifier for a collection of documentation inputs. |
| 15 | + public struct Identifier: RawRepresentable { |
| 16 | + public let rawValue: String |
| 17 | + |
| 18 | + public init(rawValue: String) { |
| 19 | + // To ensure that the identifier can be used as a valid "host" component of a resolved topic reference's url, |
| 20 | + // replace any consecutive sequence of unsupported characters with a "-". |
| 21 | + self.rawValue = rawValue |
| 22 | + .components(separatedBy: Self.charactersToReplace) |
| 23 | + .filter { !$0.isEmpty } |
| 24 | + .joined(separator: "-") |
| 25 | + } |
| 26 | + |
| 27 | + private static let charactersToReplace = CharacterSet.urlHostAllowed.inverted |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +extension DocumentationBundle.Identifier: Hashable {} |
| 32 | +extension DocumentationBundle.Identifier: Sendable {} |
| 33 | + |
| 34 | +// Support creating an identifier from a string literal. |
| 35 | +extension DocumentationBundle.Identifier: ExpressibleByStringLiteral { |
| 36 | + public init(stringLiteral value: StringLiteralType) { |
| 37 | + self.init(rawValue: value) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// Sort identifiers based on their raw string value. |
| 42 | +extension DocumentationBundle.Identifier: Comparable { |
| 43 | + public static func < (lhs: Self, rhs: Self) -> Bool { |
| 44 | + lhs.rawValue < rhs.rawValue |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// Print as a single string value |
| 49 | +extension DocumentationBundle.Identifier: CustomStringConvertible { |
| 50 | + public var description: String { |
| 51 | + rawValue |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// Encode and decode the identifier as a single string value. |
| 56 | +extension DocumentationBundle.Identifier: Codable { |
| 57 | + public init(from decoder: Decoder) throws { |
| 58 | + let container = try decoder.singleValueContainer() |
| 59 | + let rawValue = try container.decode(String.self) |
| 60 | + self.init(rawValue: rawValue) |
| 61 | + } |
| 62 | + |
| 63 | + public func encode(to encoder: Encoder) throws { |
| 64 | + var container = encoder.singleValueContainer() |
| 65 | + try container.encode(rawValue) |
| 66 | + } |
| 67 | +} |
0 commit comments