File: OstringStream.cpp

package info (click to toggle)
log4cpp 0.2.5-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,436 kB
  • ctags: 524
  • sloc: sh: 6,657; cpp: 1,960; ansic: 421; makefile: 334
file content (103 lines) | stat: -rw-r--r-- 2,091 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
 * OstringStream.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "log4cpp/Portability.hh"
#include <stdio.h>
#include "log4cpp/OstringStream.hh"

#if defined(_MSC_VER)
    #define VSNPRINTF _vsnprintf
#else
    #define VSNPRINTF vsnprintf
#endif // _MSC_VER

namespace {

#ifndef LOG4CPP_HAVE_SNPRINTF

    int vsnprintf(char* s, size_t maxlen, const char* fmt, va_list args)
    {
	int  len;
	FILE f;

	if (maxlen == 0)
	    return 0;

	memset(&f, 0, sizeof(f));

	f._flag    = _IOWRT + _IOSTRG;

	f._bufsiz  = f._cnt = maxlen - 1;
	f._base    = f._ptr = (unsigned char*) s;
	f._bufendp = f._base + f._bufsiz;

	len = vfprintf(&f, fmt, args);
	*f._ptr = '\0';

	return len;
    }

    int snprintf(char* s, size_t maxlen, const char* fmt, ...)
    {
	int         len;
	va_list	args;

	va_start(args, fmt);
	len = vsnprintf(s, maxlen, fmt, args);
	va_end(args);

	return len;
    }

#endif // !LOG4CPP_HAVE_SNPRINTF

    std::string vstrprintf(const char* format, va_list args)
    {
	int         size   = 1024;
	char*       buffer = new char[size];
            
	while (1) {
	    int n = VSNPRINTF(buffer, size, format, args);
                
	    // If that worked, return a string.
	    if (n > -1 && n < size) {
		std::string s(buffer);
		delete [] buffer;
		return s;
	    }
                
	    // Else try again with more space.
	    if (n > -1)     size  = n+1;    // ISO/IEC 9899:1999
	    else            size *= 2;      // twice the old size
                
	    delete [] buffer;
	    buffer = new char[size];
	}
    }

}

namespace log4cpp {

#ifndef LOG4CPP_HAVE_SSTREAM
    std::string OstringStream::str() { 
        (*this) << '\0'; 
        std::string msg(ostrstream::str()); 
        ostrstream::freeze(false); //unfreeze stream 
        return msg; 
        
    } 
#endif

    void OstringStream::vform(const char* format, va_list args) {
	*this << vstrprintf(format, args);
    }

}