Skip to content

Commit dc15f12

Browse files
committed
[lldb] Add indentation scope guard
Add `IndentScope Stream::MakeIndentScope()` to make managing (and restoring!) of the indentation level on `Stream` instances more ergonomic and less error prone.
1 parent 76065f0 commit dc15f12

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

lldb/include/lldb/Utility/Stream.h

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,12 @@ class Stream {
300300
/// The current indentation level.
301301
unsigned GetIndentLevel() const;
302302

303+
/// Set the current indentation level.
304+
///
305+
/// \param[in] level
306+
/// The new indentation level.
307+
void SetIndentLevel(unsigned level);
308+
303309
/// Indent the current line in the stream.
304310
///
305311
/// Indent the current line using the current indentation level and print an
@@ -315,6 +321,20 @@ class Stream {
315321
/// Increment the current indentation level.
316322
void IndentMore(unsigned amount = 2);
317323

324+
class IndentScope {
325+
Stream &m_stream;
326+
unsigned m_original_indent_level;
327+
328+
public:
329+
IndentScope(Stream &stream)
330+
: m_stream(stream), m_original_indent_level(stream.GetIndentLevel()) {}
331+
~IndentScope() { m_stream.SetIndentLevel(m_original_indent_level); }
332+
};
333+
334+
/// Create an indentation scope that restores the original indent level when
335+
/// the object goes out of scope (RAII).
336+
IndentScope MakeIndentScope(unsigned indent_amount = 2);
337+
318338
/// Output an offset value.
319339
///
320340
/// Put an offset \a uval out to the stream using the printf format in \a
@@ -364,12 +384,6 @@ class Stream {
364384
/// address and pointer values.
365385
void SetAddressByteSize(uint32_t addr_size);
366386

367-
/// Set the current indentation level.
368-
///
369-
/// \param[in] level
370-
/// The new indentation level.
371-
void SetIndentLevel(unsigned level);
372-
373387
/// Output a SLEB128 number to the stream.
374388
///
375389
/// Put an SLEB128 \a uval out to the stream using the printf format in \a

lldb/source/Utility/Stream.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,14 @@ void Stream::IndentLess(unsigned amount) {
202202
m_indent_level = 0;
203203
}
204204

205+
// Create an indentation scope that restores the original indent level when the
206+
// object goes out of scope (RAII).
207+
Stream::IndentScope Stream::MakeIndentScope(unsigned indent_amount) {
208+
IndentScope indent_scope(*this);
209+
IndentMore(indent_amount);
210+
return indent_scope;
211+
}
212+
205213
// Get the address size in bytes
206214
uint32_t Stream::GetAddressByteSize() const { return m_addr_size; }
207215

0 commit comments

Comments
 (0)