From 74cca617242eff47189e12e6654a0aafc4c23559 Mon Sep 17 00:00:00 2001 From: Hiroshi Kimura Date: Mon, 1 Jul 2024 13:44:26 +0900 Subject: [PATCH] <& (#3) --- Package.swift | 1 + Sources/Wrap/Wrap.swift | 21 +++++++++++++-------- Tests/WrapTests/File.swift | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 8 deletions(-) create mode 100644 Tests/WrapTests/File.swift diff --git a/Package.swift b/Package.swift index b0f6eb8..914a025 100644 --- a/Package.swift +++ b/Package.swift @@ -8,6 +8,7 @@ let package = Package( ], targets: [ .target(name: "Wrap", dependencies: []), + .testTarget(name: "WrapTests", dependencies: ["Wrap"]) ], swiftLanguageVersions: [.v5] ) diff --git a/Sources/Wrap/Wrap.swift b/Sources/Wrap/Wrap.swift index 24b8180..42a1e35 100644 --- a/Sources/Wrap/Wrap.swift +++ b/Sources/Wrap/Wrap.swift @@ -1,11 +1,16 @@ postfix operator &> +infix operator <& -public postfix func &> (argument: consuming T) -> Wrap { +public postfix func &> (argument: consuming T) -> _FlowDownBox { .init(consume argument) } -public struct Wrap: ~Copyable { +public func <& (argument: inout T, modifier: (inout T) throws -> Void) rethrows { + try modifier(&argument) +} + +public struct _FlowDownBox: ~Copyable { public let value: Value @@ -19,32 +24,32 @@ public func modify(_ value: inout Value, _ modifier: (inout Value) throws try modifier(&value) } -extension Wrap { +extension _FlowDownBox { - public borrowing func map(_ transform: (consuming Value) throws -> U) rethrows -> U { + public consuming func map(_ transform: (consuming Value) throws -> U) rethrows -> U { try transform(value) } @discardableResult - public borrowing func `do`(_ applier: (borrowing Value) throws -> Void) rethrows -> Value { + public consuming func `do`(_ applier: (consuming Value) throws -> Void) rethrows -> Value { try applier(value) return value } @discardableResult @_disfavoredOverload - public borrowing func `do`(_ applier: (borrowing Value) throws -> Void) rethrows -> Value? { + public consuming func `do`(_ applier: (consuming Value) throws -> Void) rethrows -> Value? { try applier(value) return value } - public borrowing func modify(_ modifier: (inout Value) throws -> Void) rethrows -> Value { + public consuming func modify(_ modifier: (inout Value) throws -> Void) rethrows -> Value { var v = value try modifier(&v) return v } - public borrowing func filter(_ filter: (borrowing Value) -> Bool) -> Value? { + public consuming func filter(_ filter: (consuming Value) -> Bool) -> Value? { guard filter(value) else { return nil } diff --git a/Tests/WrapTests/File.swift b/Tests/WrapTests/File.swift new file mode 100644 index 0000000..6ea87a2 --- /dev/null +++ b/Tests/WrapTests/File.swift @@ -0,0 +1,19 @@ + +import XCTest +import Wrap + +final class WrapTests: XCTestCase { + + func testWrap() { + let value = 42 + let wrapped = value&> + .map { $0 + 1 } + XCTAssertEqual(wrapped, 43) + } + + func testModify() { + var value = 42 + value <& { $0 += 1 } + XCTAssertEqual(value, 43) + } +}