|
34 | 34 | #import "NSTimeZoneShims.h"
|
35 | 35 | #import "NSUndoManagerShims.h"
|
36 | 36 |
|
| 37 | +typedef struct { |
| 38 | + void *_Nonnull memory; |
| 39 | + size_t capacity; |
| 40 | + _Bool onStack; |
| 41 | +} _ConditionalAllocationBuffer; |
| 42 | + |
| 43 | +static inline _Bool _resizeConditionalAllocationBuffer(_ConditionalAllocationBuffer *_Nonnull buffer, size_t amt) { |
| 44 | + size_t amount = malloc_good_size(amt); |
| 45 | + if (amount <= buffer->capacity) { return true; } |
| 46 | + void *newMemory; |
| 47 | + if (buffer->onStack) { |
| 48 | + newMemory = malloc(amount); |
| 49 | + if (newMemory == NULL) { return false; } |
| 50 | + memcpy(newMemory, buffer->memory, buffer->capacity); |
| 51 | + buffer->onStack = false; |
| 52 | + } else { |
| 53 | + newMemory = realloc(buffer->memory, amount); |
| 54 | + if (newMemory == NULL) { return false; } |
| 55 | + } |
| 56 | + if (newMemory == NULL) { return false; } |
| 57 | + buffer->memory = newMemory; |
| 58 | + buffer->capacity = amount; |
| 59 | + return true; |
| 60 | +} |
| 61 | + |
| 62 | +static inline _Bool _withStackOrHeapBuffer(size_t amount, void (__attribute__((noescape)) ^ _Nonnull applier)(_ConditionalAllocationBuffer *_Nonnull)) { |
| 63 | + _ConditionalAllocationBuffer buffer; |
| 64 | + buffer.capacity = malloc_good_size(amount); |
| 65 | + buffer.onStack = (pthread_main_np() != 0 ? buffer.capacity < 2048 : buffer.capacity < 512); |
| 66 | + buffer.memory = buffer.onStack ? alloca(buffer.capacity) : malloc(buffer.capacity); |
| 67 | + if (buffer.memory == NULL) { return false; } |
| 68 | + applier(&buffer); |
| 69 | + if (!buffer.onStack) { |
| 70 | + free(buffer.memory); |
| 71 | + } |
| 72 | + return true; |
| 73 | +} |
| 74 | + |
37 | 75 | @protocol _NSKVOCompatibilityShim <NSObject>
|
38 | 76 | + (void)_noteProcessHasUsedKVOSwiftOverlay;
|
39 | 77 | @end
|
0 commit comments