Skip to content

Commit

Permalink
<& (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
muukii authored Jul 1, 2024
1 parent 4b5c07a commit 74cca61
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
1 change: 1 addition & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ let package = Package(
],
targets: [
.target(name: "Wrap", dependencies: []),
.testTarget(name: "WrapTests", dependencies: ["Wrap"])
],
swiftLanguageVersions: [.v5]
)
21 changes: 13 additions & 8 deletions Sources/Wrap/Wrap.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@

postfix operator &>
infix operator <&

public postfix func &> <T>(argument: consuming T) -> Wrap<T> {
public postfix func &> <T>(argument: consuming T) -> _FlowDownBox<T> {
.init(consume argument)
}

public struct Wrap<Value>: ~Copyable {
public func <& <T>(argument: inout T, modifier: (inout T) throws -> Void) rethrows {
try modifier(&argument)
}

public struct _FlowDownBox<Value>: ~Copyable {

public let value: Value

Expand All @@ -19,32 +24,32 @@ public func modify<Value>(_ value: inout Value, _ modifier: (inout Value) throws
try modifier(&value)
}

extension Wrap {
extension _FlowDownBox {

public borrowing func map<U>(_ transform: (consuming Value) throws -> U) rethrows -> U {
public consuming func map<U>(_ 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
}
Expand Down
19 changes: 19 additions & 0 deletions Tests/WrapTests/File.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 74cca61

Please sign in to comment.