Skip to content

Commit 1c22ad1

Browse files
committed
Clarify max size calculaton comment
1 parent 43814e2 commit 1c22ad1

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

libc/src/__support/block.h

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -268,20 +268,28 @@ class Block {
268268
if (alignment == alignof(max_align_t))
269269
return size;
270270

271-
// We must create a padding block to align the usable space of the next
272-
// block. The next block's usable space can be found by advancing by
273-
// sizeof(Block) then aligning up. The amount advanced is the amount of
274-
// additional inner size required.
275-
//
276-
// The minimum advancment is sizeof(Block), since the resulting position may
277-
// happen to be aligned. What is the maximum? Advancing by sizeof(Block)
278-
// leaves the result still aligned to alignof(Block). So the most additional
279-
// advancement required would be if the point is exactly alignof(Block) past
280-
// alignment. The remaining size to the next alignment would then be
281-
// alignment - alignof(Block). So the total maximum advancement required is
282-
// sizeof(Block) + alignment - alignof(Block).
271+
// We must create a new block inside this one (splitting). This requires a
272+
// block header in addition to the requested size.
283273
if (add_overflow(size, sizeof(Block), size))
284274
return 0;
275+
276+
// Beyond that, padding space may need to remain in this block to ensure
277+
// that the usable space of the next block is aligned.
278+
//
279+
// Consider a position P of some lesser alignment, L, with maximal distance
280+
// to the next position of some greater alignment, G, where G is a multiple
281+
// of L. P must be one L unit past a G-aligned point. If it were one L-unit
282+
// earlier, its distance would be zero. If it were one L-unit later, its
283+
// distance would not be maximal. If it were not some integral number of L
284+
// units away, it would not be L-aligned.
285+
//
286+
// So the maximum distance would be G - L. As a special case, if L is 1
287+
// (unaligned), the max distance is G - 1.
288+
//
289+
// This block's usable space is aligned to max_align_t >= Block. With zero
290+
// padding, the next block's usable space is sizeof(Block) past it, which is
291+
// a point aligned to Block. Thus the max padding needed is alignment -
292+
// alignof(Block).
285293
if (add_overflow(size, alignment - alignof(Block), size))
286294
return 0;
287295
return size;

0 commit comments

Comments
 (0)