Imported Upstream version 0.19.7
[platform/upstream/gettext.git] / gettext-runtime / libasprintf / autosprintf.cc
1 /* Class autosprintf - formatted output to an ostream.
2    Copyright (C) 2002, 2013, 2015 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2002.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU Lesser General Public License as published by
7    the Free Software Foundation; either version 2.1 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Tell glibc's <stdio.h> to provide a prototype for vasprintf().
19    This must come before <config.h> because <config.h> may include
20    <features.h>, and once <features.h> has been included, it's too late.  */
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE    1
23 #endif
24
25 /* Specification.  */
26 #include "autosprintf.h"
27
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include "lib-asprintf.h"
32
33 /* std::swap() is in <utility> since C++11.  */
34 #if __cplusplus >= 201103L
35 # include <utility>
36 #else
37 # include <algorithm>
38 #endif
39
40 namespace gnu
41 {
42
43   /* Constructor: takes a format string and the printf arguments.  */
44   autosprintf::autosprintf (const char *format, ...)
45   {
46     va_list args;
47     va_start (args, format);
48     if (vasprintf (&str, format, args) < 0)
49       str = NULL;
50     va_end (args);
51   }
52
53   /* Copy constructor.  Necessary because the destructor is nontrivial.  */
54   autosprintf::autosprintf (const autosprintf& src)
55   {
56     str = (src.str != NULL ? strdup (src.str) : NULL);
57   }
58
59   /* Copy constructor.  Necessary because the destructor is nontrivial.  */
60   autosprintf& autosprintf::operator = (autosprintf copy)
61   {
62     std::swap (copy.str, this->str);
63     return *this;
64   }
65
66   /* Destructor: frees the temporarily allocated string.  */
67   autosprintf::~autosprintf ()
68   {
69     free (str);
70   }
71
72   /* Conversion to string.  */
73   autosprintf::operator char * () const
74   {
75     if (str != NULL)
76       {
77         size_t length = strlen (str) + 1;
78         char *copy = new char[length];
79         memcpy (copy, str, length);
80         return copy;
81       }
82     else
83       return NULL;
84   }
85   autosprintf::operator std::string () const
86   {
87     return std::string (str ? str : "(error in autosprintf)");
88   }
89 }