]> Dogcows Code - chaz/yoink/blob - src/stlplus/portability/dprintf.cpp
import stlplus 3.7
[chaz/yoink] / src / stlplus / portability / dprintf.cpp
1 ////////////////////////////////////////////////////////////////////////////////
2
3 // Author: Andy Rushton
4 // Copyright: (c) Southampton University 1999-2004
5 // (c) Andy Rushton 2004 onwards
6 // License: BSD License, see ../docs/license.html
7
8 // Notes:
9
10 // Feb 2007: Rewritten in terms of platform-specific fixes to the
11 // buffer-overflow problem. Using native functions for this has the added
12 // benefit of giving access to other features of the C-runtime such as Unicode
13 // support.
14
15 ////////////////////////////////////////////////////////////////////////////////
16
17 #include "dprintf.hpp"
18 #include <stdio.h>
19 #include <limits.h>
20 #include <float.h>
21 #include <ctype.h>
22 #include <stdlib.h>
23
24 ////////////////////////////////////////////////////////////////////////////////
25
26 namespace stlplus
27 {
28
29 ////////////////////////////////////////////////////////////////////////////////
30
31 int vdprintf(std::string& formatted, const char* format, va_list args)
32 {
33 #ifdef MSWINDOWS
34 int length = 0;
35 char* buffer = 0;
36 for(int buffer_length = 256; ; buffer_length*=2)
37 {
38 buffer = (char*)malloc(buffer_length);
39 if (!buffer) return -1;
40 length = _vsnprintf(buffer, buffer_length-1, format, args);
41 if (length >= 0)
42 {
43 buffer[length] = 0;
44 formatted += std::string(buffer);
45 free(buffer);
46 break;
47 }
48 free(buffer);
49 }
50 return length;
51 #else
52 char* buffer = 0;
53 int length = vasprintf(&buffer, format, args);
54 if (!buffer) return -1;
55 if (length >= 0)
56 formatted += std::string(buffer);
57 free(buffer);
58 return length;
59 #endif
60 }
61
62 int dprintf(std::string& formatted, const char* format, ...)
63 {
64 va_list args;
65 va_start(args, format);
66 int result = vdprintf(formatted, format, args);
67 va_end(args);
68 return result;
69 }
70
71 std::string vdformat(const char* format, va_list args) throw(std::invalid_argument)
72 {
73 std::string formatted;
74 int length = vdprintf(formatted, format, args);
75 if (length < 0) throw std::invalid_argument("dprintf");
76 return formatted;
77 }
78
79 std::string dformat(const char* format, ...) throw(std::invalid_argument)
80 {
81 std::string formatted;
82 va_list args;
83 va_start(args, format);
84 int length = vdprintf(formatted, format, args);
85 va_end(args);
86 if (length < 0) throw std::invalid_argument("dprintf");
87 return formatted;
88 }
89
90 ////////////////////////////////////////////////////////////////////////////////
91
92 } // end namespace stlplus
This page took 0.03534 seconds and 4 git commands to generate.