Merge branch 'master' of git@git.opensuse.org:projects/zypp/sat-solver
[platform/upstream/libsolv.git] / src / util.h
1 /*
2  * Copyright (c) 2007, Novell Inc.
3  *
4  * This program is licensed under the BSD license, read LICENSE.BSD
5  * for further information
6  */
7
8 /*
9  * util.h
10  *
11  */
12
13 #ifndef SATSOLVER_UTIL_H
14 #define SATSOLVER_UTIL_H
15
16 #include <stddef.h>
17 #include <string.h>
18
19 /**
20  * malloc
21  * exits with error message on error
22  */
23 extern void *sat_malloc(size_t);
24 extern void *sat_malloc2(size_t, size_t);
25 extern void *sat_calloc(size_t, size_t);
26 extern void *sat_realloc(void *, size_t);
27 extern void *sat_realloc2(void *, size_t, size_t);
28 extern void *sat_free(void *);
29 extern void sat_oom(size_t, size_t);
30 extern unsigned int sat_timems(unsigned int subtract);
31 extern void sat_sort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *, void *), void *compard);
32
33 static inline void *sat_extend(void *buf, size_t len, size_t nmemb, size_t size, size_t block)
34 {
35   if (nmemb == 1)
36     {
37       if ((len & block) == 0)
38         buf = sat_realloc2(buf, len + (1 + block), size);
39     }
40   else
41     {
42       if (((len - 1) | block) != ((len + nmemb - 1) | block))
43         buf = sat_realloc2(buf, (len + (nmemb + block)) & ~block, size);
44     }
45   return buf;
46 }
47
48 /**
49  * extend an array by reallocation and zero's the new section
50  * buf old pointer
51  * len current size
52  * nmbemb number of elements to add
53  * size size of each element
54  * block block size used to allocate the elements
55  */
56 static inline void *sat_zextend(void *buf, size_t len, size_t nmemb, size_t size, size_t block)
57 {
58   buf = sat_extend(buf, len, nmemb, size, block);
59   memset((char *)buf + len * size, 0, nmemb * size);
60   return buf;
61 }
62
63 static inline void *sat_extend_resize(void *buf, size_t len, size_t size, size_t block)
64 {
65   if (len)
66     buf = sat_realloc2(buf, (len + block) & ~block, size);
67   return buf;
68 }
69
70 static inline void *sat_calloc_block(size_t len, size_t size, size_t block)
71 {
72   void *buf;
73   if (!len)
74     return 0;
75   buf = sat_malloc2((len + block) & ~block, size);
76   memset(buf, 0, ((len + block) & ~block) * size);
77   return buf;
78 }
79 #endif /* SATSOLVER_UTIL_H */