Skip to content

Commit

Permalink
warn on default access
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeredpath committed Mar 30, 2024
1 parent 2364741 commit 3870645
Showing 1 changed file with 25 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,40 @@
///
/// - Parameter key: A string key identifying a value to share in memory.
/// - Returns: An in-memory persistence key.
public static func inMemory<Value>(_ key: String, defaultValue: Value) -> Self
public static func inMemory<Value>(
_ key: String,
defaultValue: Value,
warnOnDefaultValueAccess: Bool = false
) -> Self
where Self == DefaultProvidingKey<InMemoryKey<Value>> {
DefaultProvidingKey(.init(key), defaultValue: defaultValue)
DefaultProvidingKey(
.init(key),
defaultValue: defaultValue,
warnOnDefaultValueAccess: warnOnDefaultValueAccess
)
}
}

/// A decorator around an in-memory persistence strategy that provides a built-in default value.
///
/// See ``PersistenceKey/inMemory(_:)`` to create values of this type.
public struct DefaultProvidingKey<UnderlyingKey: PersistenceKey>: Hashable, PersistenceKey, Sendable
where UnderlyingKey: Hashable & Sendable, UnderlyingKey.Value: Hashable & Sendable {
public struct DefaultProvidingKey<UnderlyingKey: PersistenceKey>: Hashable, PersistenceKey, Sendable
where UnderlyingKey: Hashable & Sendable, UnderlyingKey.Value: Hashable & Sendable {
let key: UnderlyingKey
let defaultValue: UnderlyingKey.Value
init(_ key: UnderlyingKey, defaultValue: UnderlyingKey.Value) {
let _defaultValue: UnderlyingKey.Value
let warnOnDefaultValueAccess: Bool
var defaultValue: UnderlyingKey.Value {
get {
if warnOnDefaultValueAccess {
runtimeWarn("Accessed default value for shared state using key: \(key)")
}
return _defaultValue
}
}
init(_ key: UnderlyingKey, defaultValue: UnderlyingKey.Value, warnOnDefaultValueAccess: Bool) {
self.key = key
self.defaultValue = defaultValue
self._defaultValue = defaultValue
self.warnOnDefaultValueAccess = warnOnDefaultValueAccess
}
public func load(initialValue: UnderlyingKey.Value?) -> UnderlyingKey.Value? {
self.key.load(initialValue: initialValue)
Expand Down

0 comments on commit 3870645

Please sign in to comment.