xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / Model / Entitlements / Entitlements.swift
Entitlements.swift71 lines · 2.2 KiBRaw
| 1 | // |
| 2 | // EntitlementContainer.swift |
| 3 | // Supercharge |
| 4 | // |
| 5 | // Created by Kabir Oberai on 19/09/19. |
| 6 | // Copyright © 2019 Kabir Oberai. All rights reserved. |
| 7 | // |
| 8 | |
| 9 | import Foundation |
| 10 | import ProtoCodable |
| 11 | import Superutils |
| 12 | |
| 13 | public struct EntitlementContainer: ProtoCodableContainer, Sendable { |
| 14 | public var value: Entitlement |
| 15 | public init(value: Entitlement) { self.value = value } |
| 16 | } |
| 17 | |
| 18 | // allows access to a parsable entitlements list while not losing unparsed entitlements when it's modified |
| 19 | public struct Entitlements: Sendable { |
| 20 | |
| 21 | private static let decoder = PropertyListDecoder() |
| 22 | private static let encoder = PropertyListEncoder() |
| 23 | |
| 24 | private var dict: [String: AnyEncodable] |
| 25 | |
| 26 | public init(entitlements: [Entitlement]) throws { |
| 27 | dict = [:] |
| 28 | try setEntitlements(entitlements) |
| 29 | } |
| 30 | |
| 31 | public func entitlements() throws -> [Entitlement] { |
| 32 | try Self.decoder.decode( |
| 33 | ProtoCodableKeyValueContainer<EntitlementContainer>.self, from: Self.encoder.encode(dict) |
| 34 | ).values |
| 35 | } |
| 36 | |
| 37 | // if `entitlements` and `setEntitlements` were the primitives, this function would end up performing |
| 38 | // two entitlements() calls. This way we can optimize the number of calls. |
| 39 | public mutating func updateEntitlements(_ block: (inout [Entitlement]) throws -> Void) throws { |
| 40 | let old = try self.entitlements() |
| 41 | |
| 42 | var new = old |
| 43 | try block(&new) |
| 44 | |
| 45 | let oldEnts = Dictionary(uniqueKeysWithValues: old.map { (type(of: $0).identifier, $0) }) |
| 46 | let newEnts = Dictionary(uniqueKeysWithValues: new.map { (type(of: $0).identifier, $0) }) |
| 47 | |
| 48 | oldEnts.keys.filter { newEnts[$0] == nil }.forEach { dict[$0] = nil } |
| 49 | newEnts.forEach { dict[$0] = AnyEncodable($1) } |
| 50 | } |
| 51 | |
| 52 | public mutating func setEntitlements(_ new: [Entitlement]) throws { |
| 53 | try updateEntitlements { $0 = new } |
| 54 | } |
| 55 | |
| 56 | } |
| 57 | |
| 58 | extension Entitlements: Codable { |
| 59 | |
| 60 | public init(from decoder: Decoder) throws { |
| 61 | self.dict = try decoder.singleValueContainer() |
| 62 | .decode([String: CodableElement].self) |
| 63 | .mapValues(AnyEncodable.init) |
| 64 | } |
| 65 | |
| 66 | public func encode(to encoder: Encoder) throws { |
| 67 | var container = encoder.singleValueContainer() |
| 68 | try container.encode(dict) |
| 69 | } |
| 70 | |
| 71 | } |