diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index e8dd673cd..5381b922a 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -921,7 +921,7 @@ private struct InsertQuery: Hashable { } extension InsertQuery { - static let sqlCache = ReadWriteBox([InsertQuery: String]()) + static let sqlCache = ReadWriteBox(value: [InsertQuery: String]()) var sql: String { if let sql = InsertQuery.sqlCache.read({ $0[self] }) { return sql @@ -958,7 +958,7 @@ private struct UpdateQuery: Hashable { } extension UpdateQuery { - static let sqlCache = ReadWriteBox([UpdateQuery: String]()) + static let sqlCache = ReadWriteBox(value: [UpdateQuery: String]()) var sql: String { if let sql = UpdateQuery.sqlCache.read({ $0[self] }) { return sql diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index b4555a289..bf5894814 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -47,7 +47,7 @@ final class Pool { } private let makeElement: () throws -> T - private var items: ReadWriteBox<[Item]> = ReadWriteBox([]) + private var items: ReadWriteBox<[Item]> = ReadWriteBox(value: []) private let itemsSemaphore: DispatchSemaphore // limits the number of elements private let itemsGroup: DispatchGroup // knows when no element is used private let barrierQueue: DispatchQueue diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift index b7c0b4449..1e11f2ea7 100644 --- a/GRDB/Utils/ReadWriteBox.swift +++ b/GRDB/Utils/ReadWriteBox.swift @@ -2,12 +2,15 @@ import Dispatch /// A ReadWriteBox grants multiple readers and single-writer guarantees on a value. final class ReadWriteBox { + private var _value: T + private var queue: DispatchQueue + var value: T { get { return read { $0 } } set { write { $0 = newValue } } } - init(_ value: T) { + init(value: T) { _value = value queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent]) } @@ -23,9 +26,6 @@ final class ReadWriteBox { try block(&_value) } } - - private var _value: T - private var queue: DispatchQueue } extension ReadWriteBox where T: Numeric { @@ -36,4 +36,12 @@ extension ReadWriteBox where T: Numeric { return n } } + + @discardableResult + func decrement() -> T { + return write { n in + n -= 1 + return n + } + } } diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index 7cb9f6680..a6e8eeacd 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -8,7 +8,7 @@ import XCTest class PoolTests: XCTestCase { /// Returns a Pool whose elements are incremented integers: 1, 2, 3... private func makeCounterPool(maximumCount: Int) -> Pool { - let count = ReadWriteBox(0) + let count = ReadWriteBox(value: 0) return Pool(maximumCount: maximumCount, makeElement: count.increment) }