/* test for alignword() calls in APC */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define max(a, b) ((a) > (b) ? (a) : (b))

typedef struct block_t block_t;
struct block_t {
    size_t size;       /* size of this block */
    size_t next;       /* offset in segment of next free block */
};

/* {{{ alignword: returns x, aligned to the system's word boundary */
static int alignword(int x)
{
    typedef union { void* p; int i; long l; double d; void (*f)(); } word_t;
    return sizeof(word_t) * (1 + ((x-1)/sizeof(word_t)));
}
/* }}} */

static int realsizenew(int size)
{
    return alignword(size + alignword(sizeof(struct block_t)));
}

static int realsizeold(int size)
{
	return alignword(max(size + alignword(sizeof(int)), sizeof(block_t)));
}

int main()
{
	int i;
	for(i = 0; i < 8192; i++)
	{
		int s1 = realsizeold(i);
		int s2 = realsizenew(i);
		if(s1 < i + sizeof(block_t))
		{
			printf("Old algorithm fails for size=%d (%d < %d)\n", i, s1, i+sizeof(block_t)); 
		}
		if(s2 < i + sizeof(block_t))
		{
			printf("New algorithm fails for size=%d (%d < %d)\n", i, s1, i+sizeof(block_t)); 
		}
		
		//printf("%d, %d : %d\n", s1, s2, i + sizeof(block_t));
	}
}
