]> pd.if.org Git - pdclib/blob - platform/example/functions/_PDCLIB/_PDCLIB_allocpages.c
_PDCLIB_* prefixing of filenames.
[pdclib] / platform / example / functions / _PDCLIB / _PDCLIB_allocpages.c
1 /* _PDCLIB_allocpages( int const )
2
3    This file is part of the Public Domain C Library (PDCLib).
4    Permission is granted to use, modify, and / or redistribute at will.
5 */
6
7 /* This is an example implementation of _PDCLIB_allocpages() (declared in
8    _PDCLIB_config.h), fit for use with POSIX kernels.
9 */
10
11 #include <stdint.h>
12 #include <stddef.h>
13
14 #ifndef REGTEST
15
16 int brk( void * );
17 void * sbrk( intptr_t );
18
19 #include "_PDCLIB_glue.h"
20
21 static void * membreak = NULL;
22
23 void * _PDCLIB_allocpages( int const n )
24 {
25     if ( membreak == NULL )
26     {
27         /* first call, make sure end-of-heap is page-aligned */
28         intptr_t unaligned = 0;
29         membreak = sbrk( 0 );
30         unaligned = _PDCLIB_PAGESIZE - (intptr_t)membreak % _PDCLIB_PAGESIZE;
31         if ( unaligned < _PDCLIB_PAGESIZE )
32         {
33             /* end-of-heap not page-aligned - adjust */
34             if ( sbrk( unaligned ) != membreak )
35             {
36                 /* error */
37                 return NULL;
38             }
39             membreak = (char *)membreak + unaligned;
40         }
41     }
42     /* increasing or decreasing heap - standard operation */
43     void * oldbreak = membreak;
44     membreak = (void *)( (char *)membreak + ( n * _PDCLIB_PAGESIZE ) );
45     if ( brk( membreak ) == 0 )
46     {
47         /* successful */
48         return oldbreak;
49     }
50     else
51     {
52         /* out of memory */
53         membreak = oldbreak;
54         return NULL;
55     }
56 }
57
58 #endif
59
60 #ifdef TEST
61
62 #include "_PDCLIB_test.h"
63
64 int main( void )
65 {
66 #ifndef REGTEST
67     char * startbreak = sbrk( 0 );
68     TESTCASE( _PDCLIB_allocpages( 0 ) );
69     TESTCASE( ( (char *)sbrk( 0 ) - startbreak ) <= _PDCLIB_PAGESIZE );
70     startbreak = sbrk( 0 );
71     TESTCASE( _PDCLIB_allocpages( 1 ) );
72     TESTCASE( sbrk( 0 ) == startbreak + ( 1 * _PDCLIB_PAGESIZE ) );
73     TESTCASE( _PDCLIB_allocpages( 5 ) );
74     TESTCASE( sbrk( 0 ) == startbreak + ( 6 * _PDCLIB_PAGESIZE ) );
75     TESTCASE( _PDCLIB_allocpages( -3 ) );
76     TESTCASE( sbrk( 0 ) == startbreak + ( 3 * _PDCLIB_PAGESIZE ) );
77 #endif
78     return TEST_RESULTS;
79 }
80
81 #endif