tdb_wrap: Move to specific directory.
[samba.git] / source3 / lib / string_init.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
5    Copyright (C) Andrew Tridgell 1992-2001
6    Copyright (C) Simo Sorce      2001-2002
7    Copyright (C) Martin Pool     2003
8    Copyright (C) James Peach     2006
9    Copyright (C) Jeremy Allison  1992-2007
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26
27 /* this is used to prevent lots of mallocs of size 1 */
28 static const char null_string[] = "";
29
30 /**
31  Set a string value, allocing the space for the string
32 **/
33
34 static bool string_init(char **dest,const char *src)
35 {
36         size_t l;
37
38         if (!src)
39                 src = "";
40
41         l = strlen(src);
42
43         if (l == 0) {
44                 *dest = discard_const_p(char, null_string);
45         } else {
46                 (*dest) = SMB_STRDUP(src);
47                 if ((*dest) == NULL) {
48                         DEBUG(0,("Out of memory in string_init\n"));
49                         return false;
50                 }
51         }
52         return(true);
53 }
54
55 /**
56  Free a string value.
57 **/
58
59 void string_free(char **s)
60 {
61         if (!s || !(*s))
62                 return;
63         if (*s == null_string)
64                 *s = NULL;
65         SAFE_FREE(*s);
66 }
67
68 /**
69  Set a string value, deallocating any existing space, and allocing the space
70  for the string
71 **/
72
73 bool string_set(char **dest,const char *src)
74 {
75         string_free(dest);
76         return(string_init(dest,src));
77 }