Skip to content

Commit

Permalink
DataProtocol.withDataReader { }: Can now return a value from the cl…
Browse files Browse the repository at this point in the history
…osure
  • Loading branch information
orchetect committed Aug 18, 2022
1 parent bf0eed0 commit 72660f5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
10 changes: 5 additions & 5 deletions Sources/OTCore/Abstractions/PassiveDataReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,12 @@ extension PassiveDataReader {
extension DataProtocol {
/// **OTCore:**
/// Accesses the data by providing a `PassiveDataReader` instance to a closure.
@_disfavoredOverload
public func withDataReader(
_ block: (_ dataReader: inout PassiveDataReader<Self>) throws -> Void
) rethrows {
@_disfavoredOverload @discardableResult
public func withDataReader<Result>(
_ block: (_ dataReader: inout PassiveDataReader<Self>) throws -> Result
) rethrows -> Result {
var mutableSelf = self
var reader = PassiveDataReader { $0(&mutableSelf) }
try block(&reader)
return try block(&reader)
}
}
18 changes: 18 additions & 0 deletions Tests/OTCoreTests/Abstractions/PassiveDataReader Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,24 @@ class Abstractions_PassiveDataReader_Tests: XCTestCase {
}
)
}

func testWithDataReader_ReturnsValue() throws {
let data = Data([0x01, 0x02, 0x03, 0x04])

#if swift(>=5.7)
let getByte = try data.withDataReader { dr in
_ = try dr.readByte()
return try dr.readByte()
}
#else
let getByte: UInt8 = try data.withDataReader { dr in
_ = try dr.readByte()
return try dr.readByte()
}
#endif

XCTAssertEqual(getByte, 0x02)
}
}

#endif

0 comments on commit 72660f5

Please sign in to comment.