What is the advantage of this sizing code in C?

54 views Asked by At

Apologies for the generic question title, I wasn't sure how to phrase it properly (suggestions welcome!)

I'm trying to get my head around some of the code for the Common Mark parser and came across this:

  /* Oversize the buffer by 50% to guarantee amortized linear time
   * complexity on append operations. */
  bufsize_t new_size = target_size + target_size / 2;
  new_size += 1;
  new_size = (new_size + 7) & ~7;

So given a number, eg 32, it will add (32 / 2) [48], add 1 [49], add 7 [56], finally ANDing that with -8 [56].

Is this a common pattern? Specifically the adding of a number and then ANDing with its complement.

Is anyone able to provide any insight into what this is doing and what advantages, if any, exist?

1

There are 1 answers

0
axiac On

The (+7) & ~7 part rounds the number up to the first multiple of 8. It works only with powers of 2 (7 is 2^3-1). If you want to round to a multiple of 32 then use 31 instead of 7.

The reason to round the size to a multiple of 8 is probably specific to the algorithm.

It is also possible that the author of the code knows how the memory allocator works. If the allocator uses internally blocks of memory of multiple of 8 bytes, an allocation request of any number of bytes between 1 and 8 uses an entire block. By asking for a block having a size that is multiple of 8 one gets several extra bytes for the same price.