-
Notifications
You must be signed in to change notification settings - Fork 2
/
LogStream.h
139 lines (109 loc) · 3 KB
/
LogStream.h
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
//@author Jingyu Tong
//@email: jingyutong0806@gmail.com
#ifndef LOGSTREAM_H_
#define LOGSTREAM_H_
#include "base/noncopyable.h"
#include <string>
#include <string.h>
const int kSmallBuffer = 4000;
const int kLargeBuffer = 4000 * 1000;
template<int SIZE>
class FixedBuffer : noncopyable {
public:
FixedBuffer()
: cur_(data_)
{
}
~FixedBuffer() {
}
void append(const char* buf, size_t len) {
if(avail() > static_cast<int>(len)) {
memcpy(cur_, buf, len);
cur_ += len;
}
}
const char* data() const {
return data_;
}
int length() const {
return static_cast<int>(cur_ - data_);
}
char* current() {
return cur_;
}
int avail() const {
return static_cast<int>(end() - cur_);
}
void add(size_t len) {
cur_ += len;
}
void reset() {
cur_ = data_;
}
void bzero() {
memset(data_, 0, sizeof data_);
}
private:
const char* end() const {
return data_ + sizeof data_;
}
char data_[SIZE];
char* cur_;
};
class LogStream : noncopyable {
public:
typedef FixedBuffer<kSmallBuffer> Buffer;
LogStream& operator<<(bool v)
{
buffer_.append(v ? "1" : "0", 1);
return *this;
}
LogStream& operator<<(short);
LogStream& operator<<(unsigned short);
LogStream& operator<<(int);
LogStream& operator<<(unsigned int);
LogStream& operator<<(long);
LogStream& operator<<(unsigned long);
LogStream& operator<<(long long);
LogStream& operator<<(unsigned long long);
LogStream& operator<<(const void*);
LogStream& operator<<(float v)
{
*this << static_cast<double>(v);
return *this;
}
LogStream& operator<<(double);
LogStream& operator<<(long double);
LogStream& operator<<(char v)
{
buffer_.append(&v, 1);
return *this;
}
LogStream& operator<<(const char* str)
{
if (str)
buffer_.append(str, strlen(str));
else
buffer_.append("(null)", 6);
return *this;
}
LogStream& operator<<(const unsigned char* str)
{
return operator<<(reinterpret_cast<const char*>(str));
}
LogStream& operator<<(const std::string& v)
{
buffer_.append(v.c_str(), v.size());
return *this;
}
void append(const char* data, int len) { buffer_.append(data, len); }
const Buffer& buffer() const { return buffer_; }
void resetBuffer() { buffer_.reset(); }
private:
void staticCheck();
template<typename T>
void formatInteger(T);
Buffer buffer_;
static const int kMaxNumericSize = 32;
};
#endif