1 | // =============================================================== // |
---|
2 | // // |
---|
3 | // File : dupstr.h // |
---|
4 | // Purpose : C-string (heap-copies) handling // |
---|
5 | // // |
---|
6 | // Coded by Ralf Westram (coder@reallysoft.de) in January 2010 // |
---|
7 | // Institute of Microbiology (Technical University Munich) // |
---|
8 | // http://www.arb-home.de/ // |
---|
9 | // // |
---|
10 | // =============================================================== // |
---|
11 | |
---|
12 | #ifndef DUPSTR_H |
---|
13 | #define DUPSTR_H |
---|
14 | |
---|
15 | /* -------------------------------------------------------------------------------- |
---|
16 | * The following function handle char*'s, which either own a heap copy or are NULL. |
---|
17 | * |
---|
18 | * freeset: assigns a heap-copy to a variable (variable is automatically freed) |
---|
19 | * freenull: assigns NULL to a variable (variable is automatically freed) |
---|
20 | * freedup: similar to freeset, but strdup's the rhs-expression |
---|
21 | * reassign: similar to freeset, but rhs must be variable and will be set to NULL |
---|
22 | * nulldup: like strdup, but pass-through NULL |
---|
23 | * |
---|
24 | * Notes: |
---|
25 | * - freeset, freedup and reassign may safely use the changed variable in the rhs-expression! |
---|
26 | * - freeset and freenull work with any pointer-type allocated using malloc et al. |
---|
27 | */ |
---|
28 | |
---|
29 | |
---|
30 | #ifndef _GLIBCXX_CSTRING |
---|
31 | #include <cstring> |
---|
32 | #endif |
---|
33 | #ifndef _GLIBCXX_CSTDLIB |
---|
34 | #include <cstdlib> |
---|
35 | #endif |
---|
36 | |
---|
37 | #ifdef __cplusplus |
---|
38 | |
---|
39 | template<typename T> |
---|
40 | inline void freenull(T *& var) { |
---|
41 | free(var); |
---|
42 | var = NULL; |
---|
43 | } |
---|
44 | |
---|
45 | template<typename T> |
---|
46 | inline void freeset(T *& var, T *heapcopy) { |
---|
47 | free(var); |
---|
48 | var = heapcopy; |
---|
49 | } |
---|
50 | |
---|
51 | inline char *nulldup(const char *maybeStr) { |
---|
52 | return maybeStr ? strdup(maybeStr) : NULL; |
---|
53 | } |
---|
54 | inline void freedup(char *& strvar, const char *maybeStr) { |
---|
55 | freeset(strvar, nulldup(maybeStr)); |
---|
56 | } |
---|
57 | inline void reassign(char *& dstvar, char *& srcvar) { |
---|
58 | freeset(dstvar, srcvar); |
---|
59 | srcvar = NULL; |
---|
60 | } |
---|
61 | |
---|
62 | template<typename T> |
---|
63 | inline void realloc_unleaked(T*& ptr, size_t new_size) { |
---|
64 | T *new_ptr = (T*)realloc(ptr, new_size); |
---|
65 | if (!new_ptr) free(ptr); |
---|
66 | ptr = new_ptr; |
---|
67 | } |
---|
68 | |
---|
69 | #endif // __cplusplus |
---|
70 | |
---|
71 | // helper to use char as array index: |
---|
72 | inline unsigned char safeCharIndex(char c) { return static_cast<unsigned char>(c); } |
---|
73 | |
---|
74 | #else |
---|
75 | #error dupstr.h included twice |
---|
76 | #endif // DUPSTR_H |
---|