Skip to content

Commit

Permalink
Revise Boxes 📦
Browse files Browse the repository at this point in the history
We have had two `Box` variants for a very long time: `Box` and `VarBox`,
containing an immutable and mutable value respectively.

However, from our experience the immutable variant is not used often if
at all, which means its immutability guarantee is not something that
people want or need.

Furthermore, following the latest language developments a `Box` is a
very good candidate for a property wrapper, and more so now that they
can be defined as local properties.

## Changes

- Deprecate `VarBox` in favor of `Box`, making it wrap a mutable value.

- Make `Box` a `@propertyWrapper`, and `@dynamicMemberLookup`. The
latter is useful if we use `Box<T>` as a regular type (i.e. not a PW).
  • Loading branch information
p4checo committed Jan 17, 2022
1 parent a1b58a2 commit 538c294
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 40 deletions.
8 changes: 4 additions & 4 deletions Sources/Network/Network+URLSessionNetworkStack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,20 +114,20 @@ extension Network {
fatalError("🔥 `session` is `nil`! Forgot to 💉?")
}

let taskIdentifierBox = VarBox<Int>(.max)
@Box var taskIdentifierBox = Int.max
let cancelableBag = CancelableBag()

let completionHandler = makeTaskCompletionHandler(
request: request,
resource: resource,
taskIdentifierBox: taskIdentifierBox,
taskIdentifierBox: _taskIdentifierBox,
cancelableBag: cancelableBag,
completion: completion
)

let task = session.dataTask(with: request, completionHandler: completionHandler)

taskIdentifierBox.value = task.taskIdentifier
taskIdentifierBox = task.taskIdentifier
cancelableBag.add(cancelable: WeakCancelable(task))

resource.interceptScheduledTask(withIdentifier: task.taskIdentifier, request: request)
Expand All @@ -141,7 +141,7 @@ extension Network {
private func makeTaskCompletionHandler(
request: URLRequest,
resource: Resource,
taskIdentifierBox: VarBox<Int>,
taskIdentifierBox: Box<Int>,
cancelableBag: CancelableBag,
completion: @escaping FetchCompletionClosure
) -> URLSessionDataTaskClosure {
Expand Down
42 changes: 24 additions & 18 deletions Sources/Utils/Box.swift
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
/// An arbitrary container which stores a **constant** value of type `T`.
/// An arbitrary container (and property wrapper) which stores a **mutable** value of type `T`.
///
/// This main purpose of this object is to encapsulate value types so that they can be used like a reference type
/// (e.g. pass value types around without copying them, "share" value types between closures, etc)
/// The main purpose of this object is to encapsulate value types so that they can be used like a reference type
/// (e.g. pass value types around without copying them, memoize value types inside closures via capture list, etc)
@propertyWrapper
@dynamicMemberLookup
public final class Box<T> {

/// The encapsulated value.
public let value: T
/// The wrapped value.
public var wrappedValue: T

/// Instantiate a new constant value box with the given value.
/// Instantiate a new mutable value box with the given value.
///
/// - parameter value: the value to encapsulate.
/// - parameter wrappedValue: the value to encapsulate.
///
/// - returns: a newly instantiated box with the encapsulated value.
public init(_ value: T) { self.value = value }
public init(wrappedValue: T) { self.wrappedValue = wrappedValue }

public subscript<U>(dynamicMember keyPath: KeyPath<T, U>) -> U { wrappedValue[keyPath: keyPath] }
}

/// An arbitrary container which stores a **variable** value of type `T`.
///
/// This main purpose of this object is to encapsulate value types so that they can be used like a reference type
/// (e.g. pass value types around without copying them, "share" value types between closures, etc)
public final class VarBox<T> {
extension Box {

/// The encapsulated value.
public var value: T
/// The wrapped value (compact).
public var value: T {
get { wrappedValue }
set { wrappedValue = newValue }
}

/// Instantiate a new variable value box with the given value.
/// Instantiate a new mutable value box with the given value (compact).
///
/// - parameter value: the value to encapsulate.
/// - parameter wrappedValue: the value to encapsulate.
///
/// - returns: a newly instantiated box with the encapsulated value.
public init(_ value: T) { self.value = value }
public convenience init(_ value: T) { self.init(wrappedValue: value) }
}

@available(*, unavailable, renamed: "Box")
public typealias VarBox<T> = Box<T>
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ final class DiskMemoryPersistenceTestCase: XCTestCase {
let measureExpectation = expectation(description: "measure")
measureExpectation.expectedFulfillmentCount = 2

performanceMetrics.measureInvokedClosure = { [count = VarBox(0)] identifier, metadata in
performanceMetrics.measureInvokedClosure = { [count = Box(0)] identifier, metadata in
if count.value == 0 {
XCTAssertEqual(identifier, performanceMetrics.memoryWriteIdentifier)
XCTAssertDumpsEqual(metadata, [performanceMetrics.blobSizeMetadataKey : mrMinderSize,
Expand Down Expand Up @@ -313,7 +313,7 @@ final class DiskMemoryPersistenceTestCase: XCTestCase {
let measure = self.expectation(description: "measure")
measure.expectedFulfillmentCount = 2

performanceMetrics.measureInvokedClosure = { [count = VarBox(0)] identifier, metadata in
performanceMetrics.measureInvokedClosure = { [count = Box(0)] identifier, metadata in
if count.value == 0 {
XCTAssertEqual(identifier, performanceMetrics.memoryWriteIdentifier)
XCTAssertDumpsEqual(metadata, [performanceMetrics.blobSizeMetadataKey : mrMinderSize,
Expand Down Expand Up @@ -371,7 +371,7 @@ final class DiskMemoryPersistenceTestCase: XCTestCase {
let measureExpectation = expectation(description: "measure")
measureExpectation.expectedFulfillmentCount = 2

performanceMetrics.measureInvokedClosure = { [count = VarBox(0)] identifier, metadata in
performanceMetrics.measureInvokedClosure = { [count = Box(0)] identifier, metadata in
if count.value == 0 {
XCTAssertEqual(identifier, performanceMetrics.memoryWriteIdentifier)
XCTAssertDumpsEqual(metadata, [performanceMetrics.blobSizeMetadataKey : mrMinderSize,
Expand Down Expand Up @@ -437,7 +437,7 @@ final class DiskMemoryPersistenceTestCase: XCTestCase {
let measureExpectation = expectation(description: "measure")
measureExpectation.expectedFulfillmentCount = 2

performanceMetrics.measureInvokedClosure = { [count = VarBox(0)] identifier, metadata in
performanceMetrics.measureInvokedClosure = { [count = Box(0)] identifier, metadata in
if count.value == 0 {
XCTAssertEqual(identifier, performanceMetrics.memoryWriteIdentifier)
XCTAssertDumpsEqual(metadata, [performanceMetrics.blobSizeMetadataKey : mrMinderSize,
Expand Down Expand Up @@ -477,7 +477,7 @@ final class DiskMemoryPersistenceTestCase: XCTestCase {
let measureExpectation2 = expectation(description: "measure")
measureExpectation2.expectedFulfillmentCount = 3

performanceMetrics.measureInvokedClosure = { [count = VarBox(0)] identifier, metadata in
performanceMetrics.measureInvokedClosure = { [count = Box(0)] identifier, metadata in
if count.value == 0 {
XCTAssertEqual(identifier, performanceMetrics.memoryReadIdentifier)
// cache miss
Expand Down Expand Up @@ -522,7 +522,7 @@ final class DiskMemoryPersistenceTestCase: XCTestCase {
let measureExpectation = expectation(description: "measure")
measureExpectation.expectedFulfillmentCount = 2

performanceMetrics.measureInvokedClosure = { [count = VarBox(0)] identifier, metadata in
performanceMetrics.measureInvokedClosure = { [count = Box(0)] identifier, metadata in
if count.value == 0 {
XCTAssertEqual(identifier, performanceMetrics.memoryReadIdentifier)
XCTAssertDumpsEqual(metadata, [performanceMetrics.blobSizeMetadataKey : 0,
Expand Down
31 changes: 25 additions & 6 deletions Tests/AlicerceTests/Utils/BoxTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,43 @@ import XCTest

class BoxTestCase: XCTestCase {

func testBox_ShouldWrapValue() {
func test_init_ShouldWrapValueAndAllowMutation() {

let value = 1337
let box = Box<Int>(value)

XCTAssertEqual(value, box.value)

let newValue = 7331
box.value = newValue

XCTAssertEqual(newValue, box.value)
}

func testVarBox_ShouldWrapValueAndAllowModifying() {
func test_propertyWrapper_ShouldWrapValueAndAllowMutation() {

let value = 1337
let varBox = VarBox<Int>(value)
@Box var box = value

XCTAssertEqual(value, varBox.value)
XCTAssertEqual(value, box)

let newValue = 7331
varBox.value = newValue
box = newValue

XCTAssertEqual(newValue, box)
}

func test_dynamicMember_ShouldExposePropertiesInWrappedValue() {

struct Foo {

var foo: Int = 1337
}

let box = Box<Foo>(.init())
XCTAssertEqual(box.foo, 1337)

XCTAssertEqual(newValue, varBox.value)
@Box var box2 = Foo()
XCTAssertEqual(_box2.foo, 1337)
}
}
6 changes: 3 additions & 3 deletions Tests/AlicerceTests/Utils/PthreadLockTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,13 @@ class PthreadLockTestCase: XCTestCase {
return q
}

let box = VarBox(0)
@Box var box = 0

for _ in 1...numWrites {
queues.forEach {
$0.addOperation {
self.lock.lock()
box.value += 1
box += 1
self.lock.unlock()
writeExpectation.fulfill()
}
Expand All @@ -130,6 +130,6 @@ class PthreadLockTestCase: XCTestCase {

waitForExpectations(timeout: 1)

XCTAssertEqual(box.value, numWrites * numQueues)
XCTAssertEqual(box, numWrites * numQueues)
}
}
6 changes: 3 additions & 3 deletions Tests/AlicerceTests/Utils/UnfairLockTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,13 @@ class UnfairLockTestCase: XCTestCase {
return q
}

let box = VarBox(0)
@Box var box = 0

for _ in 1...numWrites {
queues.forEach {
$0.addOperation {
self.lock.lock()
box.value += 1
box += 1
self.lock.unlock()
writeExpectation.fulfill()
}
Expand All @@ -130,7 +130,7 @@ class UnfairLockTestCase: XCTestCase {

waitForExpectations(timeout: 1)

XCTAssertEqual(box.value, numWrites * numQueues)
XCTAssertEqual(box, numWrites * numQueues)
}
}

0 comments on commit 538c294

Please sign in to comment.