Skip to content

Commit 49667c9

Browse files
authored
Merge pull request #111 from microsoft/align
Small refactoring of code for finding a sizeclass for an alignment
2 parents e8e0f60 + 5786ecc commit 49667c9

File tree

1 file changed

+33
-21
lines changed

1 file changed

+33
-21
lines changed

src/override/malloc.cc

+33-21
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,32 @@ extern "C"
104104
}
105105
#endif
106106

107-
SNMALLOC_EXPORT void*
108-
SNMALLOC_NAME_MANGLE(aligned_alloc)(size_t alignment, size_t size)
107+
inline size_t aligned_size(size_t alignment, size_t size)
109108
{
110-
assert((size % alignment) == 0);
111-
(void)alignment;
112-
return SNMALLOC_NAME_MANGLE(malloc)(size);
109+
// Client responsible for checking alignment is not zero
110+
assert(alignment != 0);
111+
// Client responsible for checking alignment is not above SUPERSLAB_SIZE
112+
assert(alignment <= SUPERSLAB_SIZE);
113+
// Client responsible for checking alignment is a power of two
114+
assert(bits::next_pow2(alignment) == alignment);
115+
116+
size = bits::max(size, alignment);
117+
snmalloc::sizeclass_t sc = size_to_sizeclass(size);
118+
if (sc >= NUM_SIZECLASSES)
119+
{
120+
// large allocs are 16M aligned, which is maximum we guarantee
121+
return size;
122+
}
123+
for (; sc < NUM_SIZECLASSES; sc++)
124+
{
125+
size = sizeclass_to_size(sc);
126+
if ((size & (~size + 1)) >= alignment)
127+
{
128+
return size;
129+
}
130+
}
131+
// Give max alignment.
132+
return SUPERSLAB_SIZE;
113133
}
114134

115135
SNMALLOC_EXPORT void*
@@ -128,22 +148,14 @@ extern "C"
128148
return nullptr;
129149
}
130150

131-
size = bits::max(size, alignment);
132-
snmalloc::sizeclass_t sc = size_to_sizeclass(size);
133-
if (sc >= NUM_SIZECLASSES)
134-
{
135-
// large allocs are 16M aligned.
136-
return SNMALLOC_NAME_MANGLE(malloc)(size);
137-
}
138-
for (; sc < NUM_SIZECLASSES; sc++)
139-
{
140-
size = sizeclass_to_size(sc);
141-
if ((size & (~size + 1)) >= alignment)
142-
{
143-
return SNMALLOC_NAME_MANGLE(aligned_alloc)(alignment, size);
144-
}
145-
}
146-
return SNMALLOC_NAME_MANGLE(malloc)(SUPERSLAB_SIZE);
151+
return SNMALLOC_NAME_MANGLE(malloc)(aligned_size(alignment, size));
152+
}
153+
154+
SNMALLOC_EXPORT void*
155+
SNMALLOC_NAME_MANGLE(aligned_alloc)(size_t alignment, size_t size)
156+
{
157+
assert((size % alignment) == 0);
158+
return SNMALLOC_NAME_MANGLE(memalign)(alignment, size);
147159
}
148160

149161
SNMALLOC_EXPORT int SNMALLOC_NAME_MANGLE(posix_memalign)(

0 commit comments

Comments
 (0)