1 /*
2  * Copyright 2003-2021 The Music Player Daemon Project
3  * http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 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 General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #include "FormatString.hxx"
21 #include "AllocatedString.hxx"
22 
23 #include <stdio.h>
24 #include <stdlib.h>
25 
26 AllocatedString
FormatStringV(const char * fmt,std::va_list args)27 FormatStringV(const char *fmt, std::va_list args) noexcept
28 {
29 	std::va_list tmp;
30 	va_copy(tmp, args);
31 	const int length = vsnprintf(nullptr, 0, fmt, tmp);
32 	va_end(tmp);
33 
34 	if (length <= 0)
35 		/* wtf.. */
36 		abort();
37 
38 	char *buffer = new char[length + 1];
39 	vsnprintf(buffer, length + 1, fmt, args);
40 	return AllocatedString::Donate(buffer);
41 }
42 
43 AllocatedString
FormatString(const char * fmt,...)44 FormatString(const char *fmt, ...) noexcept
45 {
46 	std::va_list args;
47 	va_start(args, fmt);
48 	auto p = FormatStringV(fmt, args);
49 	va_end(args);
50 	return p;
51 }
52