Re: question about Zend MM

From: Date: Thu, 01 Mar 2012 16:44:52 +0000
Subject: Re: question about Zend MM
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-58417@lists.php.net to get a copy of this message
On Thu, 01 Mar 2012 17:22:23 +0100, Adi Mutu <adi_mutu06@yahoo.com> wrote:
I want to understand how Zend MM works, so i'm looking trought the sources and i see this: #define ZEND_MM_ALIGNMENT_MASK ~(ZEND_MM_ALIGNMENT-1) #define ZEND_MM_ALIGNED_SIZE(size) (((size) + ZEND_MM_ALIGNMENT - 1) & ZEND_MM_ALIGNMENT_MASK) I understand that the first define will create something like 11111000 ( it will clear last 3 bits) but what does the 2nd define? Before clearing the last 3 bytes why does it add ZEND_MM_ALIGNMENT- 1 to size?
It basically just rounds to the next multiple of ZEND_MM_ALIGNMENT, assuming ZEND_MM_ALIGNMENT is a power of 2. ZEND_MM_ALIGNMENT is a power of 2, so it has 1 bit set. Subtracting 1 will zero that bit and and flip on all the other less significant bits. Then negating flips the bits so that now the bits less significant than the log2(ZEND_MM_ALIGNMENT)-th will be zero and the others will be one. ZEND_MM_ALIGNED_SIZE adds ZEND_MM_ALIGNMENT - 1 and applies the mask. The effect is that the result will be >= size and it will be a multiple of ZEND_MM_ALIGNMENT (in particular the smallest multiple of ZEND_MM_ALIGNMENT that's >= the argument) because the bits less significant than the log2(ZEND_MM_ALIGNMENT)-th will be zero. "a & n-1" is the same as "a mod n" with n being a power of 2. So if a & ZEND_MM_ALIGNMENT - 1 == 0 then a mod ZEND_MM_ALIGNMENT == 0 and a is a multiple of ZEND_MM_ALIGNMENT. -- Gustavo Lopes

« previous php.internals (#58417) next »