-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebug.h
79 lines (61 loc) · 1.75 KB
/
debug.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
#pragma once
#ifndef NDEBUG
#include <iostream>
#include <cassert>
#include <memory>
#include <mutex>
struct safe_ostream {
struct guarded_impl {
guarded_impl() = delete;
guarded_impl(const guarded_impl &) = delete;
void operator=(const guarded_impl &) = delete;
guarded_impl(std::ostream &ostream, std::mutex &mutex) : ostream_(ostream), guard_(mutex) {
}
~guarded_impl() {
ostream_.flush();
}
template<typename T>
void write(const T &x) {
ostream_ << x;
}
std::ostream &ostream_;
std::lock_guard<std::mutex> guard_;
};
struct impl {
impl() = delete;
void operator=(const impl &) = delete;
impl(std::ostream &ostream, std::mutex &mutex) : unique_impl_(new guarded_impl(ostream, mutex)) {
}
impl(const impl &rhs) {
assert(rhs.unique_impl_.get());
unique_impl_.swap(rhs.unique_impl_);
}
template<typename T>
impl &operator<<(const T &x) {
guarded_impl *p = unique_impl_.get();
assert(p);
p->write(x);
return *this;
}
mutable std::unique_ptr<guarded_impl> unique_impl_;
};
explicit safe_ostream(std::ostream &ostream) : ostream_(ostream) {
}
template<typename T>
impl operator<<(const T &x) {
return impl(ostream_, mutex_) << x;
}
std::ostream &ostream_;
std::mutex mutex_;
};
static safe_ostream safe_cout(std::cout);
static safe_ostream safe_cerr(std::cerr);
#define dout(obj) do { \
safe_cerr << "" << __FILE__ << ":" << __LINE__ << ": " << obj; \
} while(false)
#else
/**
* for debug statements
*/
#define dout(obj) do {} while(false)
#endif