This:
the need to allocate a block of memory (and then memory manage it!) to pass closure to a pointer sized quantity; and this quote from a different thread:
Makes me wonder if the following can happen:
- a closure functionPointer can be odd †
- a closure functionPointer can point to some illegal instruction (unless of course you badly want the closure to die in a specific way)
If either of these can not (realistically) happen this could open up an opportunity to use a single word closures:
struct NewClosure {
var pointer: UnsafeRawPointer
}
The benefits would be a better interop between closures <-> blocks and closures <-> C API's that accept function pointer + userData pointers.
- Option 1 ("closure function pointers must be even"):
pointer is odd †, ††:
yes? then pointer - 1 actually points to a heap allocated object with:
var function pointer
var closure captured variables
...
no? then it points to a function code directly and there is no captured state
† - a variation to this method could be using some unusual / unmapped memory address. As an example, imagine that all valid function and heap addresses must not have their most significant bit "on". If so happens we know that this is not a normal function address, so we invert the bits to get the heap allocated object address.
†† - a second variation would be to invert the cases: make function pointer odd-ball case (and adjust the pointer accordingly before calling through it) - if this plays better with ARC rules or some such.
- Option 2 ("a specific illegal instruction must not happen as the very beginning of the closure function"):
pointer points to the chosen illegal instruction?
yes? then it is actually pointing to a heap allocated object with:
var illegalInstruction: UInt64
var functionPointer: UnsafeRawPointer
var closure captured variables
...
no? then it points to a function code directly and there is no captured state
- Option 3 ("magic spell"):
pointer points to a specific sequence of magic words?
yes? then it is actually pointing at a heap allocated object with:
var magicSpell: (UInt64, UInt64) // like deadbeef feedface etc
var functionPointer: UnsafeRawPointer
var closure captured variables
...
no? then it points to a function code directly and there is no captured state
Could this fly?