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

feat: Interception improvements #3742

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# master

1. Add compatibility with ReactiveSwift 7.1.1 and bump minimum deployment targets to macOS 10.13, iOS 11.0, tvOS 11.0 and watchOS 4.0.
1. Improve interception API by including intercepted function output value to interception signal

# 12.0.0

Expand Down Expand Up @@ -268,7 +269,7 @@ RAC 5.0 includes a few object interception tools from ReactiveObjC, remastered f
// Terminate the KVO observation if the lifetime of `self` ends.
let producer = object.reactive.values(forKeyPath: #keyPath(key))
.take(during: self.reactive.lifetime)

// A parameterized property that represents the supplied key path of the
// wrapped object. It holds a weak reference to the wrapped object.
let property = DynamicProperty<String>(object: person,
Expand Down Expand Up @@ -303,11 +304,11 @@ UI components now expose a collection of binding targets to which can be bound f
```swift
// Update `allowsCookies` whenever the toggle is flipped.
preferences.allowsCookies <~ toggle.reactive.isOnValues

// Compute live character counts from the continuous stream of user initiated
// changes in the text.
textField.reactive.continuousTextValues.map { $0.characters.count }

// Trigger `commit` whenever the button is pressed.
button.reactive.pressed = CocoaAction(viewModel.commit)
```
Expand Down
2 changes: 1 addition & 1 deletion ReactiveCocoa/DelegateProxy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ internal class DelegateProxy<Delegate: NSObjectProtocol>: NSObject {
return self.reactive.trigger(for: selector).take(during: lifetime)
}

func intercept(_ selector: Selector) -> Signal<[Any?], Never> {
func intercept(_ selector: Selector) -> Signal<(args: [Any?], output: Any?), Never> {
interceptedSelectors.insert(selector)
originalSetter(self)
return self.reactive.signal(for: selector).take(during: lifetime)
Expand Down
148 changes: 84 additions & 64 deletions ReactiveCocoa/NSObject+Intercepting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ extension Reactive where Base: NSObject {
/// - parameters:
/// - selector: The selector to observe.
///
/// - returns: A signal that sends an array of bridged arguments.
public func signal(for selector: Selector) -> Signal<[Any?], Never> {
/// - returns:
/// - A signal that sends a tuple of arguments and returned value
public func signal(for selector: Selector) -> Signal<(args: [Any?], output: Any?), Never> {
return base.intercept(selector).map(unpackInvocation)
}
}
Expand Down Expand Up @@ -394,78 +395,97 @@ private func checkTypeEncoding(_ types: UnsafePointer<CChar>) -> Bool {
/// - parameters:
/// - invocation: The `NSInvocation` to unpack.
///
/// - returns: An array of objects.
private func unpackInvocation(_ invocation: AnyObject) -> [Any?] {
/// - returns: A tuple of arguments and returned value
private func unpackInvocation(_ invocation: AnyObject) -> (args: [Any?], output: Any?) {
let invocation = invocation as AnyObject
let methodSignature = invocation.objcMethodSignature!
let count = methodSignature.objcNumberOfArguments!

var bridged = [Any?]()
bridged.reserveCapacity(Int(count - 2))
var args = [Any?]()
args.reserveCapacity(Int(count - 2))

// Ignore `self` and `_cmd` at index 0 and 1.
for position in 2 ..< count {
let rawEncoding = methodSignature.objcArgumentType(at: position)
let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined

func extract<U>(_ type: U.Type) -> U {
let pointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout<U>.size,
alignment: MemoryLayout<U>.alignment)
defer {
pointer.deallocate()
}
for position in 2..<count {
args.append(decodeValueFromInvocation(
rawEncoding: methodSignature.objcArgumentType(at: position),
value: { invocation.objcCopy(to: $0, forArgumentAt: Int(position)) }
))
}

invocation.objcCopy(to: pointer, forArgumentAt: Int(position))
return pointer.assumingMemoryBound(to: type).pointee
}
let output = decodeValueFromInvocation(
rawEncoding: methodSignature.objcMethodReturnType,
value: { invocation.objcCopyReturnValue(to: $0) }
)

return (args, output)
}

let value: Any?

switch encoding {
case .char:
value = NSNumber(value: extract(CChar.self))
case .int:
value = NSNumber(value: extract(CInt.self))
case .short:
value = NSNumber(value: extract(CShort.self))
case .long:
value = NSNumber(value: extract(CLong.self))
case .longLong:
value = NSNumber(value: extract(CLongLong.self))
case .unsignedChar:
value = NSNumber(value: extract(CUnsignedChar.self))
case .unsignedInt:
value = NSNumber(value: extract(CUnsignedInt.self))
case .unsignedShort:
value = NSNumber(value: extract(CUnsignedShort.self))
case .unsignedLong:
value = NSNumber(value: extract(CUnsignedLong.self))
case .unsignedLongLong:
value = NSNumber(value: extract(CUnsignedLongLong.self))
case .float:
value = NSNumber(value: extract(CFloat.self))
case .double:
value = NSNumber(value: extract(CDouble.self))
case .bool:
value = NSNumber(value: extract(CBool.self))
case .object:
value = extract((AnyObject?).self)
case .type:
value = extract((AnyClass?).self)
case .selector:
value = extract((Selector?).self)
case .undefined:
var size = 0, alignment = 0
NSGetSizeAndAlignment(rawEncoding, &size, &alignment)
let buffer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
defer { buffer.deallocate() }

invocation.objcCopy(to: buffer, forArgumentAt: Int(position))
value = NSValue(bytes: buffer, objCType: rawEncoding)
func decodeValueFromInvocation(
rawEncoding: UnsafePointer<CChar>,
value extractValueToBuffer: (UnsafeMutableRawPointer) -> Void
) -> Any? {
let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined
let value: Any?

func extract<T>(_ type: T.Type) -> T {
let pointer = UnsafeMutableRawPointer.allocate(
byteCount: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment
)

defer {
pointer.deallocate()
}

bridged.append(value)
extractValueToBuffer(pointer)
return pointer.assumingMemoryBound(to: type).pointee
}

switch encoding {
case .char:
value = NSNumber(value: extract(CChar.self))
case .int:
value = NSNumber(value: extract(CInt.self))
case .short:
value = NSNumber(value: extract(CShort.self))
case .long:
value = NSNumber(value: extract(CLong.self))
case .longLong:
value = NSNumber(value: extract(CLongLong.self))
case .unsignedChar:
value = NSNumber(value: extract(CUnsignedChar.self))
case .unsignedInt:
value = NSNumber(value: extract(CUnsignedInt.self))
case .unsignedShort:
value = NSNumber(value: extract(CUnsignedShort.self))
case .unsignedLong:
value = NSNumber(value: extract(CUnsignedLong.self))
case .unsignedLongLong:
value = NSNumber(value: extract(CUnsignedLongLong.self))
case .float:
value = NSNumber(value: extract(CFloat.self))
case .double:
value = NSNumber(value: extract(CDouble.self))
case .bool:
value = NSNumber(value: extract(CBool.self))
case .object:
value = extract((AnyObject?).self)
case .type:
value = extract((AnyClass?).self)
case .selector:
value = extract((Selector?).self)
case .void:
value = ()
case .undefined:
var size = 0
var alignment = 0
NSGetSizeAndAlignment(rawEncoding, &size, &alignment)
let buffer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
defer { buffer.deallocate() }

extractValueToBuffer(buffer)
value = NSValue(bytes: buffer, objCType: rawEncoding)
}

return bridged
return value
}
1 change: 1 addition & 0 deletions ReactiveCocoa/ObjC+Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ internal enum ObjCTypeEncoding: Int8 {
case type = 35
case selector = 58

case void = 118
case undefined = -1
}
6 changes: 6 additions & 0 deletions ReactiveCocoa/ObjC+Messages.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ internal let NSMethodSignature: AnyClass = NSClassFromString("NSMethodSignature"
@objc(invoke)
func objcInvoke()

@objc(getReturnValue:)
func objcCopyReturnValue(to buffer: UnsafeMutableRawPointer?)

@objc(invocationWithMethodSignature:)
static func objcInvocation(withMethodSignature signature: AnyObject) -> AnyObject
}
Expand All @@ -44,6 +47,9 @@ internal let NSMethodSignature: AnyClass = NSClassFromString("NSMethodSignature"
@objc(numberOfArguments)
var objcNumberOfArguments: UInt { get }

@objc(methodReturnType)
var objcMethodReturnType: UnsafePointer<CChar> { get }

@objc(getArgumentTypeAtIndex:)
func objcArgumentType(at index: UInt) -> UnsafePointer<CChar>

Expand Down
Loading