Removed format.cpp and format.h, use built-in formatting instead

Tue, 26 May 2015 18:46:24 +0300

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Tue, 26 May 2015 18:46:24 +0300
changeset 83
08bfc3d9d2ae
parent 82
895088452014
child 84
3bd32eec3d57
child 85
ed61569c501f

Removed format.cpp and format.h, use built-in formatting instead

CMakeLists.txt file | annotate | diff | comparison | revisions
sources/format.cpp file | annotate | diff | comparison | revisions
sources/format.h file | annotate | diff | comparison | revisions
sources/interface.cpp file | annotate | diff | comparison | revisions
sources/interface.h file | annotate | diff | comparison | revisions
sources/main.h file | annotate | diff | comparison | revisions
sources/mystring.cpp file | annotate | diff | comparison | revisions
sources/mystring.h file | annotate | diff | comparison | revisions
sources/network/bytestream.cpp file | annotate | diff | comparison | revisions
sources/network/rconsession.cpp file | annotate | diff | comparison | revisions
--- a/CMakeLists.txt	Tue May 26 18:19:27 2015 +0300
+++ b/CMakeLists.txt	Tue May 26 18:46:24 2015 +0300
@@ -11,7 +11,6 @@
 
 set (SOURCE_FILES
 	sources/coloredline.cpp
-	sources/format.cpp
 	sources/interface.cpp
 	sources/main.cpp
 	sources/md5.cpp
--- a/sources/format.cpp	Tue May 26 18:19:27 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-/*
-	Copyright 2014, 2015 Teemu Piippo
-	All rights reserved.
-
-	Redistribution and use in source and binary forms, with or without
-	modification, are permitted provided that the following conditions
-	are met:
-
-	1. Redistributions of source code must retain the above copyright
-	   notice, this list of conditions and the following disclaimer.
-	2. Redistributions in binary form must reproduce the above copyright
-	   notice, this list of conditions and the following disclaimer in the
-	   documentation and/or other materials provided with the distribution.
-	3. Neither the name of the copyright holder nor the names of its
-	   contributors may be used to endorse or promote products derived from
-	   this software without specific prior written permission.
-
-	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-	TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-	PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
-	OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-	PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <cstdio>
-#include "format.h"
-
-// -------------------------------------------------------------------------------------------------
-//
-// Throws an error while formatting the string
-//
-static auto format_error (String fmtstr, const String errdescribe, int pos) -> void
-{
-	fmtstr.replace ("\n", " ");
-	fmtstr.replace ("\t", " ");
-	String errmsg ("With format string:\n" + fmtstr + "\n");
-
-	for (int x = 0; x < pos; ++x)
-		errmsg += "-";
-
-	errmsg += "^\n" + errdescribe;
-	throw std::logic_error (errmsg.std_string());
-}
-
-// -------------------------------------------------------------------------------------------------
-//
-// Main formatter algorithm.
-//
-auto format_args (const String& fmtstr, const Vector<String>& args) -> String
-{
-	String fmt = fmtstr;
-	int pos = 0;
-
-	while ((pos = fmt.find ("%", pos)) != -1)
-	{
-		if (fmt[pos + 1] == '%')
-		{
-			fmt.replace (pos, 2, "%");
-			pos++;
-			continue;
-		}
-
-		int ofs = 1;
-		char mod = '\0';
-
-		// handle modifiers
-		if (fmt[pos + ofs] == 's' or fmt[pos + ofs] == 'x' or fmt[pos + ofs] == 'd')
-		{
-			mod = fmt[pos + ofs];
-			ofs++;
-		}
-
-		if (fmt[pos + ofs] < '1' or fmt[pos + ofs] > '9')
-		{
-			format_error (fmtstr, "bad format string, expected non-zero digit with "
-				"optional modifier after '%%'", pos);
-		}
-
-		int i = fmt[pos + ofs] - '0';
-
-		if (i > args.size())
-			format_error (fmtstr, String ("Format argument #") + i + " used but not defined.", pos);
-
-		String replacement = args[i - 1];
-
-		switch (mod)
-		{
-		case 's': replacement = (replacement == "1") ? "" : "s";      break;
-		case 'd': replacement.sprintf ("%d", replacement[0]);         break;
-		case 'x': replacement.sprintf ("0x%x", replacement.to_int()); break;
-		default: break;
-		}
-
-		fmt.replace (pos, 1 + ofs, replacement);
-		pos += replacement.length();
-	}
-
-	return fmt;
-}
-
--- a/sources/format.h	Tue May 26 18:19:27 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,202 +0,0 @@
-/*
-	Copyright 2014, 2015 Teemu Piippo
-	All rights reserved.
-
-	Redistribution and use in source and binary forms, with or without
-	modification, are permitted provided that the following conditions
-	are met:
-
-	1. Redistributions of source code must retain the above copyright
-	   notice, this list of conditions and the following disclaimer.
-	2. Redistributions in binary form must reproduce the above copyright
-	   notice, this list of conditions and the following disclaimer in the
-	   documentation and/or other materials provided with the distribution.
-	3. Neither the name of the copyright holder nor the names of its
-	   contributors may be used to endorse or promote products derived from
-	   this software without specific prior written permission.
-
-	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-	TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-	PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
-	OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-	PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#pragma once
-#include "mystring.h"
-#include "basics.h"
-#include "geometry.h"
-
-// -------------------------------------------------------------------------------------------------
-//
-inline String make_format_argument (String a) { return a; }
-inline String make_format_argument (char a) { return String (a); }
-inline String make_format_argument (short a) { return String::from_number (a); }
-inline String make_format_argument (int a) { return String::from_number (a); }
-inline String make_format_argument (long a) { return String::from_number (a); }
-inline String make_format_argument (double a) { return String::from_number (a); }
-inline String make_format_argument (unsigned short a) { return String::from_number (a); }
-inline String make_format_argument (unsigned int a) { return String::from_number (a); }
-inline String make_format_argument (unsigned long a) { return String::from_number (a); }
-inline String make_format_argument (const char* a) { return a; }
-inline String make_format_argument (std::nullptr_t) { return "<null pointer>"; }
-inline String make_format_argument (bool a) { return a ? "true" : "false"; }
-
-inline String make_format_argument (const void* a)
-{
-	String result;
-	result.sprintf ("%p", a);
-	return result;
-}
-
-template<typename T, typename C>
-inline String make_format_argument (const Container<T, C>& a)
-{
-	String result;
-
-	if (a.is_empty())
-		return "{}";
-
-	result = "{";
-
-	for (auto it = a.begin(); it != a.end(); ++it)
-	{
-		if (it != a.begin())
-			result += ", ";
-
-		result += make_format_argument (*it);
-	}
-
-	result += "}";
-	return result;
-}
-
-inline String make_format_argument (Color a)
-{
-	static const char* colorstrings[] =
-	{
-		"BLACK", "RED", "GREEN", "YELLOW",
-		"BLUE", "MAGENTA", "CYAN", "WHITE", "DEFAULT"
-	};
-
-	static_assert (sizeof colorstrings / sizeof *colorstrings == NUM_COLORS,
-		"colostrings[] has an incorrect amount of elements");
-
-	if (int (a) >= 0 and int (a) < NUM_COLORS)
-		return colorstrings[int (a)];
-
-	return "???";
-}
-
-inline String make_format_argument (const Position& a)
-{
-	return String ("(") + a.x + ", " + a.y + ")";
-}
-
-inline String make_format_argument (const Size& a)
-{
-	return String ("(") + a.width + "x" + a.height + ")";
-}
-
-inline String make_format_argument (const Rectangle& a)
-{
-	String result;
-	result.sprintf ("{(%d, %d), (%dx%d)}", a.x, a.y, a.width, a.height);
-	return result;
-}
-
-// -------------------------------------------------------------------------------------------------
-//
-// Formats the given string with the given args.
-//
-String format_args (const String& fmtstr, const Vector<String>& args);
-
-// -------------------------------------------------------------------------------------------------
-//
-// Expands the given arguments into a vector of strings.
-//
-template<typename T, typename... RestTypes>
-void expand_format_arguments (Vector<String>& data, const T& arg, const RestTypes& ... rest)
-{
-	data.append (make_format_argument (arg));
-	expand_format_arguments (data, rest...);
-}
-
-static void expand_format_arguments (Vector<String>&) __attribute__((unused));
-static void expand_format_arguments (Vector<String>&) {}
-
-// -------------------------------------------------------------------------------------------------
-//
-// Formats the given formatter string and args and returns the string.
-// This is essentially a modernized sprintf.
-//
-// Args in the format string take the form %n where n is a digit. The argument
-// will be expanded to the nth argument passed. This is essentially Qt's
-// QString::arg() syntax. Note: %0 is invalid.
-//
-// Arguments can be passed a modifier which takes the form of a character
-// just before the digit. Currently supported modifiers are s, d and x.
-//
-// - s: The argument will expand into "s" if it would've not expanded into "1"
-//      otherwise. If it would have expanded into "1" it will expand into an
-//      empty string.
-//
-// - d: The argument expands into the numeric form of the first character of
-//      its previous expansion. Use this to get numeric forms of @c char
-//      arguments.
-//
-// - x: The numeric argument will be represented in hexadecimal notation. This
-//      will work if the argument is a string representing a number. If the
-//      argument did not expand into a number in the first place, 0 is used
-//      and 0x0 is printed.
-//
-template<typename... argtypes>
-String format (const String& fmtstr, const argtypes&... raw_args)
-{
-	Vector<String> args;
-	expand_format_arguments (args, raw_args...);
-	return format_args (fmtstr, args);
-}
-
-// -------------------------------------------------------------------------------------------------
-//
-// This is an overload of format() where no arguments are supplied.
-// It returns the formatter string as-is.
-//
-static String format (const String& fmtstr) __attribute__ ((unused));
-static String format (const String& fmtstr) // -> String
-{
-	return fmtstr;
-}
-
-// -------------------------------------------------------------------------------------------------
-//
-// Prints the formatting result to the given file handle
-//
-template<typename... Args>
-void print_to (FILE* fp, const String& fmtstr, Args const& ...args)
-{
-	std::fprintf (fp, "%s", format (fmtstr, args...).chars());
-}
-
-// -------------------------------------------------------------------------------------------------
-//
-// Appends the formatting result to the given filename, if opening it succeeds
-//
-template<typename... argtypes>
-void print_to (const String& filename, const String& fmtstr, const argtypes&... args)
-{
-	FILE* handle;
-
-	if ((handle = fopen (filename, "a")))
-	{
-		print_to (handle, fmtstr, args...);
-		fclose (handle);
-	}
-}
--- a/sources/interface.cpp	Tue May 26 18:19:27 2015 +0300
+++ b/sources/interface.cpp	Tue May 26 18:46:24 2015 +0300
@@ -158,7 +158,7 @@
 	InputHistory << "";
 	OutputLines.clear();
 	OutputLines << ColoredLine();
-	Title = format (APPNAME " %1 (%2)", full_version_string(), changeset_date_string());
+	Title.sprintf (APPNAME " %s (%d)", full_version_string(), changeset_date_string());
 
 	if (::has_colors())
 	{
@@ -177,7 +177,7 @@
 			int bg = (j == DEFAULT) ? defaultBg : j;
 
 			if (::init_pair (pairnum, fg, bg) == ERR)
-				print ("Unable to initialize color pair %1 (%2, %3)\n", pairnum, fg, bg);
+				print ("Unable to initialize color pair %d (%d, %d)\n", pairnum, fg, bg);
 		}
 	}
 	else
@@ -514,12 +514,17 @@
 			String adminText;
 
 			if (Session.num_admins() == 0)
+			{
 				adminText = "No other admins";
+			}
 			else
-				adminText = format ("%1 other admin%s1", Session.num_admins());
+			{
+				adminText.sprintf ("%d other admin%s", Session.num_admins(),
+					Session.num_admins() != 1 ? "s" : "");
+			}
 
-			text = format ("%1 | %2 | %3", Session.address().to_string (IP_WITH_PORT),
-				Session.level(), adminText);
+			text.sprintf ("%s | %s | %s", Session.address().to_string (IP_WITH_PORT).chars(),
+				Session.level().chars(), adminText.chars());
 		}
 		break;
 	}
@@ -805,7 +810,7 @@
 			}
 			catch (std::exception& e)
 			{
-				print ("%1\n", e.what());
+				print ("%s\n", e.what());
 				return;
 			}
 
@@ -902,6 +907,49 @@
 
 // -------------------------------------------------------------------------------------------------
 //
+void Interface::vprint (const char* fmtstr, va_list args)
+{
+	String message;
+	message.vsprintf (fmtstr, args);
+	print_to_console (message);
+}
+
+// -------------------------------------------------------------------------------------------------
+//
+void __cdecl Interface::print (const char* fmtstr, ...)
+{
+	va_list args;
+	va_start (args, fmtstr);
+	vprint (fmtstr, args);
+	va_end (args);
+}
+
+// -------------------------------------------------------------------------------------------------
+//
+void __cdecl Interface::print_warning (const char* fmtstr, ...)
+{
+	va_list args;
+	va_start (args, fmtstr);
+	print_to_console (TEXTCOLOR_BrightYellow "-!- ");
+	vprint (fmtstr, args);
+	print_to_console (TEXTCOLOR_Reset);
+	va_end (args);
+}
+
+// -------------------------------------------------------------------------------------------------
+//
+void __cdecl Interface::print_error (const char* fmtstr, ...)
+{
+	va_list args;
+	va_start (args, fmtstr);
+	print_to_console (TEXTCOLOR_BrightRed "!!! ");
+	vprint (fmtstr, args);
+	print_to_console (TEXTCOLOR_Reset);
+	va_end (args);
+}
+
+// -------------------------------------------------------------------------------------------------
+//
 void Interface::print_to_console (String a)
 {
 	// Zandronum sometimes sends color codes as "\\c" and sometimes as "\x1C".
@@ -944,7 +992,7 @@
 	}
 	catch (std::exception& e)
 	{
-		print ("%1\n", e.what());
+		print ("%s\n", e.what());
 		return;
 	}
 
--- a/sources/interface.h	Tue May 26 18:19:27 2015 +0300
+++ b/sources/interface.h	Tue May 26 18:46:24 2015 +0300
@@ -57,23 +57,10 @@
 	void tab_complete (const String& part, String complete);
 	RCONSession* get_session() { return &Session; }
 
-	template<typename... argtypes>
-	void print (const String& fmtstr, const argtypes&... args)
-	{
-		print_to_console (format (fmtstr, args...));
-	}
-
-	template<typename... argtypes>
-	void print_warning (const String& fmtstr, const argtypes&... args)
-	{
-		print_to_console (TEXTCOLOR_BrightYellow "-!- " + format (fmtstr, args...) + TEXTCOLOR_Reset);
-	}
-
-	template<typename... argtypes>
-	void print_error (const String& fmtstr, const argtypes&... args)
-	{
-		print_to_console (TEXTCOLOR_BrightRed "!!! " + format (fmtstr, args...) + TEXTCOLOR_Reset);
-	}
+	void vprint (const char* fmtstr, va_list args);
+	void __cdecl print (const char* fmtstr, ...);
+	void __cdecl print_warning (const char* fmtstr, ...);
+	void __cdecl print_error (const char* fmtstr, ...);
 
 private:
 	StringList InputHistory;
--- a/sources/main.h	Tue May 26 18:19:27 2015 +0300
+++ b/sources/main.h	Tue May 26 18:46:24 2015 +0300
@@ -34,4 +34,3 @@
 #include "mystring.h"
 #include "geometry.h"
 #include "version.h"
-#include "format.h"
--- a/sources/mystring.cpp	Tue May 26 18:19:27 2015 +0300
+++ b/sources/mystring.cpp	Tue May 26 18:46:24 2015 +0300
@@ -31,7 +31,6 @@
 #include <cstring>
 #include "main.h"
 #include "mystring.h"
-#include "format.h"
 #include "md5.h"
 
 // -------------------------------------------------------------------------------------------------
@@ -313,21 +312,29 @@
 
 // -------------------------------------------------------------------------------------------------
 //
-void String::sprintf (const char* fmtstr, ...)
+void __cdecl String::sprintf (const char* fmtstr, ...)
+{
+	va_list args;
+	va_start (args, fmtstr);
+	this->vsprintf (fmtstr, args);
+	va_end (args);
+}
+
+// -------------------------------------------------------------------------------------------------
+//
+void String::vsprintf (const char* fmtstr, va_list args)
 {
 	char* buf = nullptr;
 	int bufsize = 256;
-	va_list va;
-	va_start (va, fmtstr);
 
 	do
 	{
+		bufsize *= 2;
 		delete[] buf;
 		buf = new char[bufsize];
 	}
-	while (vsnprintf (buf, bufsize, fmtstr, va) >= bufsize);
+	while (vsnprintf (buf, bufsize, fmtstr, args) >= bufsize);
 
-	va_end (va);
 	m_string = buf;
 	delete[] buf;
 }
--- a/sources/mystring.h	Tue May 26 18:19:27 2015 +0300
+++ b/sources/mystring.h	Tue May 26 18:46:24 2015 +0300
@@ -103,7 +103,8 @@
 	void replace (const char* a, const char* b);
 	void replace (int pos, int n, const String &a) { m_string.replace (pos, n, a.chars()); }
 	void shrink_to_fit() { m_string.shrink_to_fit(); }
-	void sprintf (const char* fmtstr, ...);
+	void __cdecl sprintf (const char* fmtstr, ...);
+	void vsprintf (const char* fmtstr, va_list args);
 	bool starts_with (const String &other);
 	String strip (char unwanted) { return strip ({unwanted}); }
 	String strip (const List<char> &unwanted);
--- a/sources/network/bytestream.cpp	Tue May 26 18:19:27 2015 +0300
+++ b/sources/network/bytestream.cpp	Tue May 26 18:46:24 2015 +0300
@@ -129,8 +129,12 @@
 {
 	if (bytes_left() < bytes)
 	{
-		throw IOError (format ("attempted to read %1 byte(s) past the end of bytestream",
-			bytes - bytes_left()));
+		int bytesPast = bytes - bytes_left();
+
+		String message;
+		message.sprintf ("attempted to read %d byte%s past the end of bytestream",
+			bytesPast, bytesPast != -1 ? "s" : "");
+		throw IOError (message);
 	}
 }
 
--- a/sources/network/rconsession.cpp	Tue May 26 18:19:27 2015 +0300
+++ b/sources/network/rconsession.cpp	Tue May 26 18:46:24 2015 +0300
@@ -42,7 +42,7 @@
 {
 	if (not m_socket.set_blocking (false))
 	{
-		print_to (stderr, "unable to set socket as non-blocking: %1\n",
+		fprintf (stderr, "unable to set socket as non-blocking: %s\n",
 			m_socket.error_string().chars());
 		exit (EXIT_FAILURE);
 	}
@@ -72,7 +72,7 @@
 		Bytestream packet;
 		packet.write_byte (CLRC_DISCONNECT);
 		this->send (packet);
-		m_interface->print ("Disconnected from %1\n", m_address.to_string (IP_WITH_PORT));
+		m_interface->print ("Disconnected from %s\n", m_address.to_string (IP_WITH_PORT).chars());
 		m_interface->update_statusbar();
 	}
 
@@ -159,7 +159,7 @@
 				{
 					String message = packet.read_string();
 					message.normalize();
-					m_interface->print ("%1\n", message);
+					m_interface->print ("%s\n", message.chars());
 				}
 				break;
 
@@ -179,7 +179,7 @@
 				{
 					String message = packet.read_string();
 					message.normalize();
-					m_interface->print ("--- %1\n", message);
+					m_interface->print ("--- %s\n", message.chars());
 				}
 
 				m_interface->print ("End of previous messages.\n");
@@ -192,8 +192,8 @@
 			case SVRC_TOOMANYTABCOMPLETES:
 				{
 					unsigned int numCompletions = packet.read_short();
-					m_interface->print ("%1 completions for '%2'.\n",
-						int (numCompletions), m_lastTabComplete);
+					m_interface->print ("%d completions for '%s'.\n",
+						int (numCompletions), m_lastTabComplete.chars());
 				}
 				break;
 
@@ -210,13 +210,13 @@
 					}
 					else if (not completes.is_empty())
 					{
-						m_interface->print ("Completions for '%1':\n", m_lastTabComplete);
+						m_interface->print ("Completions for '%s':\n", m_lastTabComplete.chars());
 
 						for (int i = 0; i < completes.size(); i += 8)
 						{
 							Range<int> spliceRange (i, min (i + 8, completes.size() - 1));
 							StringList splice (completes.splice (spliceRange));
-							m_interface->print ("- %1\n", splice.join (", "));
+							m_interface->print ("- %s\n", splice.join (", ").chars());
 						}
 					}
 				}
@@ -226,7 +226,7 @@
 	}
 	catch (std::exception& e)
 	{
-		m_interface->print_warning ("Couldn't process packet: %1\n", e.what());
+		m_interface->print_warning ("Couldn't process packet: %s\n", e.what());
 	}
 }
 
@@ -274,7 +274,7 @@
 //
 void RCONSession::send_hello()
 {
-	m_interface->print ("Connecting to %1...\n", m_address.to_string (IP_WITH_PORT));
+	m_interface->print ("Connecting to %s...\n", m_address.to_string (IP_WITH_PORT).chars());
 	Bytestream packet;
 	packet.write_byte (CLRC_BEGINCONNECTION);
 	packet.write_byte (RCON_PROTOCOL_VERSION);
@@ -375,5 +375,7 @@
 		m_lastTabComplete = part;
 	}
 	else
-		m_interface->print ("Server protocol is %1, cannot tab-complete\n", m_serverProtocol);
+	{
+		m_interface->print ("This server does not support tab-completion\n", m_serverProtocol);
+	}
 }
\ No newline at end of file

mercurial