source: tags/svn.1.5.4/TEMPLATES/dupstr.h

Last change on this file was 8253, checked in by westram, 12 years ago
  • fixed some global shadow warnings
File size: 2.2 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
30#ifndef _GLIBCXX_CSTRING
31#include <cstring>
32#endif
33#ifndef _GLIBCXX_CSTDLIB
34#include <cstdlib>
35#endif
36
37#ifdef __cplusplus
38
39template<typename T>
40inline void freenull(T *& var) {
41    free(var);
42    var = NULL;
43}
44
45template<typename T>
46inline void freeset(T *& var, T *heapcopy) {
47    free(var);
48    var = heapcopy;
49}
50
51inline char *nulldup(const char *maybeStr) {
52    return maybeStr ? strdup(maybeStr) : NULL;
53}
54inline void freedup(char *& strvar, const char *maybeStr) {
55    freeset(strvar, nulldup(maybeStr));
56}
57inline void reassign(char *& dstvar, char *& srcvar) {
58    freeset(dstvar, srcvar);
59    srcvar = NULL;
60}
61
62#endif // __cplusplus
63
64// helper to use char as array index:
65inline unsigned char safeCharIndex(char c) { return static_cast<unsigned char>(c); }
66
67#else
68#error dupstr.h included twice
69#endif // DUPSTR_H
Note: See TracBrowser for help on using the repository browser.