Skip to content

Commit 1b180e7

Browse files
authored
Merge pull request swiftlang#1283 from phausler/swift-4.0-branch-data_sync
2 parents 14e8eba + e8854b5 commit 1b180e7

File tree

3 files changed

+447
-230
lines changed

3 files changed

+447
-230
lines changed

CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,54 @@ CF_EXPORT CFStringRef _CFXDGCreateCacheDirectoryPath(void);
343343
/// a single base directory relative to which user-specific runtime files and other file objects should be placed. This directory is defined by the environment variable $XDG_RUNTIME_DIR.
344344
CF_EXPORT CFStringRef _CFXDGCreateRuntimeDirectoryPath(void);
345345

346+
347+
typedef struct {
348+
void *_Nonnull memory;
349+
size_t capacity;
350+
_Bool onStack;
351+
} _ConditionalAllocationBuffer;
352+
353+
static inline _Bool _resizeConditionalAllocationBuffer(_ConditionalAllocationBuffer *_Nonnull buffer, size_t amt) {
354+
#if TARGET_OS_MAC
355+
size_t amount = malloc_good_size(amt);
356+
#else
357+
size_t amount = amt;
358+
#endif
359+
if (amount <= buffer->capacity) { return true; }
360+
void *newMemory;
361+
if (buffer->onStack) {
362+
newMemory = malloc(amount);
363+
if (newMemory == NULL) { return false; }
364+
memcpy(newMemory, buffer->memory, buffer->capacity);
365+
buffer->onStack = false;
366+
} else {
367+
newMemory = realloc(buffer->memory, amount);
368+
if (newMemory == NULL) { return false; }
369+
}
370+
if (newMemory == NULL) { return false; }
371+
buffer->memory = newMemory;
372+
buffer->capacity = amount;
373+
return true;
374+
}
375+
376+
static inline _Bool _withStackOrHeapBuffer(size_t amount, void (__attribute__((noescape)) ^ _Nonnull applier)(_ConditionalAllocationBuffer *_Nonnull)) {
377+
_ConditionalAllocationBuffer buffer;
378+
#if TARGET_OS_MAC
379+
buffer.capacity = malloc_good_size(amount);
380+
#else
381+
buffer.capacity = amount;
382+
#endif
383+
buffer.onStack = (_CFIsMainThread() != 0 ? buffer.capacity < 2048 : buffer.capacity < 512);
384+
buffer.memory = buffer.onStack ? alloca(buffer.capacity) : malloc(buffer.capacity);
385+
if (buffer.memory == NULL) { return false; }
386+
applier(&buffer);
387+
if (!buffer.onStack) {
388+
free(buffer.memory);
389+
}
390+
return true;
391+
}
392+
393+
346394
_CF_EXPORT_SCOPE_END
347395

348396
#endif /* __COREFOUNDATION_FORSWIFTFOUNDATIONONLY__ */

0 commit comments

Comments
 (0)