summaryrefslogtreecommitdiff
path: root/Sora/Data/Settings/SettingsCodec.swift
blob: 4ec361aad6627b82c54bb7f0b68eadd20f68f0d8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import Foundation
import SwiftUI

@MainActor
enum SettingsCodec {
  private static let sharedJSONEncoder = JSONEncoder()
  private static let sharedJSONDecoder = JSONDecoder()

  static func encode<T: Encodable>(_ value: T) -> Data? {
    try? sharedJSONEncoder.encode(value)
  }

  static func decode<T: Decodable>(_ type: T.Type, from data: Data) -> T? {
    try? sharedJSONDecoder.decode(type, from: data)
  }

  static func encodeOnce<T: Encodable>(_ value: T) -> (value: T, encodedData: Data)? {
    guard let encodedData = encode(value) else { return nil }

    return (value: value, encodedData: encodedData)
  }

  @discardableResult
  static func applyIfChanged(
    encodedData: Data,
    localData: Binding<Data>,
    key: String,
    enableSync: Bool
  ) -> Bool {
    guard localData.wrappedValue != encodedData else {
      return false
    }

    localData.wrappedValue = encodedData

    if enableSync {
      NSUbiquitousKeyValueStore.default.set(encodedData, forKey: key)
      NSUbiquitousKeyValueStore.default.synchronize()
    }

    return true
  }
}