Skip to content

Commit fd83a95

Browse files
committed
Add stream-style logging macros
1 parent 5705473 commit fd83a95

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: src/include/common/macros.h

+34
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,46 @@
1414

1515
#include <cassert>
1616
#include <exception>
17+
#include <sstream>
1718
#include <stdexcept>
1819

1920
namespace bustub {
2021

2122
#define BUSTUB_ASSERT(expr, message) assert((expr) && (message))
2223

24+
namespace internal {
25+
26+
// An internal stream, used to take C++ stream-style parameters for display, and exit the program with `std::abort`.
27+
class LogFatalStream {
28+
public:
29+
LogFatalStream(const char *file, int line) : file_(file), line_(line) {}
30+
31+
~LogFatalStream() {
32+
std::cerr << file_ << ":" << line_ << ": " << log_stream_.str() << std::endl;
33+
std::abort();
34+
}
35+
36+
template <typename T>
37+
LogFatalStream &operator<<(const T &val) {
38+
log_stream_ << val;
39+
return *this;
40+
}
41+
42+
private:
43+
const char *file_;
44+
int line_;
45+
std::ostringstream log_stream_;
46+
};
47+
48+
} // namespace internal
49+
50+
// A macro which checks `expr` value and performs assert.
51+
// Different from `BUSTUB_ASSERT`, it takes stream-style parameters.
52+
#define BUSTUB_ASSERT_AND_LOG(expr) \
53+
if (bool val = (expr); !val) LogFatalStream { \
54+
__FILE__, __LINE__ \
55+
}
56+
2357
#define UNIMPLEMENTED(message) throw std::logic_error(message)
2458

2559
#define BUSTUB_ENSURE(expr, message) \

0 commit comments

Comments
 (0)