X-Git-Url: https://git.dogcows.com/gitweb?a=blobdiff_plain;f=src%2Fstlplus%2Fportability%2Fdprintf.cpp;fp=src%2Fstlplus%2Fportability%2Fdprintf.cpp;h=f03217ebb26be3013bda285dcfb888ed3090a473;hb=6b0a0d0efafe34d48ab344fca3b479553bd4e62c;hp=0000000000000000000000000000000000000000;hpb=85783316365181491a3e3c0c63659972477cebba;p=chaz%2Fyoink diff --git a/src/stlplus/portability/dprintf.cpp b/src/stlplus/portability/dprintf.cpp new file mode 100644 index 0000000..f03217e --- /dev/null +++ b/src/stlplus/portability/dprintf.cpp @@ -0,0 +1,92 @@ +//////////////////////////////////////////////////////////////////////////////// + +// Author: Andy Rushton +// Copyright: (c) Southampton University 1999-2004 +// (c) Andy Rushton 2004-2009 +// License: BSD License, see ../docs/license.html + +// Notes: + +// Feb 2007: Rewritten in terms of platform-specific fixes to the +// buffer-overflow problem. Using native functions for this has the added +// benefit of giving access to other features of the C-runtime such as Unicode +// support. + +//////////////////////////////////////////////////////////////////////////////// + +#include "dprintf.hpp" +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////// + +namespace stlplus +{ + +//////////////////////////////////////////////////////////////////////////////// + + int vdprintf(std::string& formatted, const char* format, va_list args) + { +#ifdef MSWINDOWS + int length = 0; + char* buffer = 0; + for(int buffer_length = 256; ; buffer_length*=2) + { + buffer = (char*)malloc(buffer_length); + if (!buffer) return -1; + length = _vsnprintf(buffer, buffer_length-1, format, args); + if (length >= 0) + { + buffer[length] = 0; + formatted += std::string(buffer); + free(buffer); + break; + } + free(buffer); + } + return length; +#else + char* buffer = 0; + int length = vasprintf(&buffer, format, args); + if (!buffer) return -1; + if (length >= 0) + formatted += std::string(buffer); + free(buffer); + return length; +#endif + } + + int dprintf(std::string& formatted, const char* format, ...) + { + va_list args; + va_start(args, format); + int result = vdprintf(formatted, format, args); + va_end(args); + return result; + } + + std::string vdformat(const char* format, va_list args) throw(std::invalid_argument) + { + std::string formatted; + int length = vdprintf(formatted, format, args); + if (length < 0) throw std::invalid_argument("dprintf"); + return formatted; + } + + std::string dformat(const char* format, ...) throw(std::invalid_argument) + { + std::string formatted; + va_list args; + va_start(args, format); + int length = vdprintf(formatted, format, args); + va_end(args); + if (length < 0) throw std::invalid_argument("dprintf"); + return formatted; + } + +//////////////////////////////////////////////////////////////////////////////// + +} // end namespace stlplus