source: tags/ms_r16q3/TEMPLATES/dupstr.h

Last change on this file was 15176, checked in by westram, 8 years ago
File size: 2.5 KB
Line 
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#ifndef _GLIBCXX_CSTRING
30#include <cstring>
31#endif
32#ifndef _GLIBCXX_CSTDLIB
33#include <cstdlib>
34#endif
35
36#ifdef __cplusplus
37
38template<typename T>
39inline void freenull(T *& var) {
40    free(var);
41    var = NULL;
42}
43
44template<typename T>
45inline void freeset(T *& var, T *heapcopy) {
46    free(var);
47    var = heapcopy;
48}
49
50inline char *nulldup(const char *maybeStr) {
51    return maybeStr ? strdup(maybeStr) : NULL; // @@@ how can ARB_strdup be used in nulldup/freedup? using it causes link problems
52}
53inline void freedup(char *& strvar, const char *maybeStr) {
54    freeset(strvar, nulldup(maybeStr));
55}
56inline void reassign(char *& dstvar, char *& srcvar) {
57    freeset(dstvar, srcvar);
58    srcvar = NULL;
59}
60
61#endif // __cplusplus
62
63// helper to use char as array index:
64inline unsigned char safeCharIndex(char c) { return static_cast<unsigned char>(c); }
65
66struct charpLess { // sort type for set<char*> / map<char*, ...>
67    bool operator()(const char *n1, const char *n2) const {
68        return strcmp(n1, n2)<0;
69    }
70};
71
72#else
73#error dupstr.h included twice
74#endif // DUPSTR_H
Note: See TracBrowser for help on using the repository browser.