1 /* -*- Mode: C; indent-tabs-mode: t; tab-width: 4 -*-
2 // ---------------------------------------------------------------------------
4 // Copyright (C) Stephanie Gawroriski <xer@multiphasicapps.net>
5 // ---------------------------------------------------------------------------
6 // SquirrelJME is under the Mozilla Public License Version 2.0.
7 // See license.mkd for licensing and copyright information.
8 // -------------------------------------------------------------------------*/
13 #include "sjme/alloc.h"
14 #include "sjme/util.h"
18 /** The number of random allocations to make. */
19 #define NUM_RANDOM 512
21 /** Basic allocation link. */
22 typedef struct testLink testLink
;
26 /** The previous link. */
34 * Tests random allocations and frees.
38 SJME_TEST_DECLARE(testAllocRandom
)
41 sjme_jint chunkLen
, i
, linkLen
, desire
;
42 sjme_alloc_pool
* pool
;
49 /* Allocate data on the stack so it gets cleared. */
51 chunk
= alloca(chunkLen
);
53 return sjme_unitSkip(test
, "Could not alloca(%d).",
56 /* Initialize the pool. */
58 if (SJME_IS_ERROR(sjme_alloc_poolStatic(&pool
, chunk
,
59 chunkLen
)) || pool
== NULL
)
60 return sjme_unitFail(test
, "Could not initialize static pool?");
62 /* Initialize the PRNG. */
63 memset(&random
, 0, sizeof(random
));
64 if (!sjme_randomInit(&random
, 12345, 67890))
65 return sjme_unitFail(test
, "Could not initialize PRNG?");
67 /* Perform many small allocations. */
69 for (i
= 0; i
< NUM_RANDOM
; i
++)
71 /* Determine size to allocate. */
73 if (!sjme_randomNextIntMax(&random
, &linkLen
, 32))
74 return sjme_unitFail(test
, "Could not random size %d %d.",
75 (int)i
, (int)linkLen
);
76 linkLen
+= sizeof(linkLen
);
80 if (SJME_IS_ERROR(sjme_alloc(pool
, linkLen
, &link
)))
81 return sjme_unitFail(test
, "Could not allocate link %d %d.",
82 (int)i
, (int)linkLen
);
89 /* Connect the two. */
90 link
->prev
= lastLink
;
91 lastLink
->next
= link
;
93 /* Replace the old link. */
98 /* Reallocate all links randomly. */
99 for (i
= 1; i
< NUM_RANDOM
; i
++)
101 /* Which link do we want to clear? */
103 if (!sjme_randomNextIntMax(&random
, &desire
,
105 return sjme_unitFail(test
, "Could not desire %d.",
108 /* Always bump up by one to skip the last link. */
111 /* Find the target link to free. */
115 /* Always pivot onto the last link. */
117 link
= lastLink
->prev
;
122 /* Reduce count one. */
124 } while (desire
> 0);
126 /* Always pivot onto the last link, again... */
128 link
= lastLink
->prev
;
131 oldPrev
= link
->prev
;
132 oldNext
= link
->next
;
134 /* Determine size to allocate. */
136 if (!sjme_randomNextIntMax(&random
, &linkLen
, 32))
137 return sjme_unitFail(test
, "Could not random size %d %d.",
138 (int)i
, (int)linkLen
);
139 linkLen
+= sizeof(linkLen
);
142 if (SJME_IS_ERROR(sjme_allocRealloc((void**)&link
,
144 return sjme_unitFail(test
, "Could not realloc link %d at %p.",
149 oldPrev
->next
= link
;
151 oldNext
->prev
= link
;
155 return SJME_TEST_RESULT_PASS
;