Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make use of rethrows keyword to reduce read/write variations #6

Merged
merged 2 commits into from
Dec 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 5 additions & 24 deletions Sources/DBThreadSafe/DBThreadSafeContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,47 +17,28 @@ public class DBThreadSafeContainer<T> {
return value
}

public func read(_ closure: (_ value: T) -> Void) {
public func read(_ closure: (_ value: T) throws -> Void) rethrows {
pthread_rwlock_rdlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
closure(value)
}

public func read<U>(_ closure: (_ value: T) -> U) -> U {
pthread_rwlock_rdlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
return closure(value)
try closure(value)
}

public func read<U>(_ closure: (_ value: T) throws -> U) throws -> U {
public func read<U>(_ closure: (_ value: T) throws -> U) rethrows -> U {
pthread_rwlock_rdlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
return try closure(value)
}

public func read(_ closure: (_ value: T) throws -> Void) throws {
pthread_rwlock_rdlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
try closure(value)
}

/// Replaces current value with a new one
/// - Parameter newValue: The new value to be stored in the container.
public func write(_ newValue: T) {
pthread_rwlock_wrlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
value = newValue
}

/// Returns current value in a closure with possibility to make multiple modifications of any kind inside a single lock.
public func write(_ closure: (_ value: inout T) -> Void) {
pthread_rwlock_wrlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
closure(&value)
}


/// Returns current value in a closure with possibility to make multiple modifications of any kind inside a single lock.
public func write(_ closure: (_ value: inout T) throws -> Void) throws {
public func write(_ closure: (_ value: inout T) throws -> Void) rethrows {
pthread_rwlock_wrlock(&lock)
defer { pthread_rwlock_unlock(&lock) }
try closure(&value)
Expand Down