source: tags/ms_r18q1/TEMPLATES/dupstr.h

Last change on this file was 16763, checked in by westram, 6 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 NULp.
17 *
18 * freeset:  assigns a heap-copy to a variable (variable is automatically freed)
19 * freenull: assigns NULp 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 NULp
22 * nulldup:  like strdup, but pass-through NULp
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#ifndef CXXFORWARD_H
36#include "cxxforward.h"
37#endif
38
39#ifdef __cplusplus
40
41template<typename T>
42inline void freenull(T *& var) {
43    free(var);
44    var = NULp;
45}
46
47template<typename T>
48inline void freeset(T *& var, T *heapcopy) {
49    free(var);
50    var = heapcopy;
51}
52
53inline char *nulldup(const char *maybeStr) {
54    return maybeStr ? strdup(maybeStr) : NULp; // @@@ how can ARB_strdup be used in nulldup/freedup? using it causes link problems
55}
56inline void freedup(char *& strvar, const char *maybeStr) {
57    freeset(strvar, nulldup(maybeStr));
58}
59inline void reassign(char *& dstvar, char *& srcvar) {
60    freeset(dstvar, srcvar);
61    srcvar = NULp;
62}
63
64#endif // __cplusplus
65
66// helper to use char as array index:
67CONSTEXPR_INLINE unsigned char safeCharIndex(char c) { return static_cast<unsigned char>(c); }
68
69struct charpLess { // sort type for set<char*> / map<char*, ...>
70    bool operator()(const char *n1, const char *n2) const {
71        return strcmp(n1, n2)<0;
72    }
73};
74
75#else
76#error dupstr.h included twice
77#endif // DUPSTR_H
Note: See TracBrowser for help on using the repository browser.