c734f85ebbe0a248bfe01bd71af26912eb671e3c
[gbajam22] / src / util.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include "util.h"
4 #include "debug.h"
5
6 extern char __iheap_start;
7 static char *top = &__iheap_start;
8
9 int iwram_brk(void *addr)
10 {
11         if((char*)addr < &__iheap_start) {
12                 addr = &__iheap_start;
13         }
14         if(addr > get_sp()) {
15                 /*return -1;*/
16                 panic(get_pc(), "iwram_brk (%p) >= sp", addr);
17         }
18         top = addr;
19         return 0;
20 }
21
22 void *iwram_sbrk(intptr_t delta)
23 {
24         void *prev = top;
25         iwram_brk(top + delta);
26         return prev;
27 }
28
29 int ispow2(unsigned int x)
30 {
31         int cnt = 0;
32         while(x) {
33                 if(x & 1) cnt++;
34                 x >>= 1;
35         }
36         return cnt == 1;
37 }
38
39
40
41 void *malloc_nf_impl(size_t sz, const char *file, int line)
42 {
43         void *p;
44         if(!(p = malloc(sz))) {
45                 panic(get_pc(), "%s:%d malloc %lu\n", file, line, (unsigned long)sz);
46         }
47         return p;
48 }
49
50 void *calloc_nf_impl(size_t num, size_t sz, const char *file, int line)
51 {
52         void *p;
53         if(!(p = calloc(num, sz))) {
54                 panic(get_pc(), "%s:%d calloc %lu\n", file, line, (unsigned long)(num * sz));
55         }
56         return p;
57 }
58
59 void *realloc_nf_impl(void *p, size_t sz, const char *file, int line)
60 {
61         if(!(p = realloc(p, sz))) {
62                 panic(get_pc(), "%s:%d realloc %lu\n", file, line, (unsigned long)sz);
63         }
64         return p;
65 }
66
67 char *strdup_nf_impl(const char *s, const char *file, int line)
68 {
69         int len;
70         char *res;
71
72         len = strlen(s);
73         if(!(res = malloc(len + 1))) {
74                 panic(get_pc(), "%s:%d strdup\n", file, line);
75         }
76         memcpy(res, s, len + 1);
77         return res;
78 }