#define __PP_INDENTED_DOCUMENT_BUILDER_H__
#include "pp/Format.h"
+#include "pp/IndentedStringBuilder.h"
namespace pp
{
class IndentedDocumentBuilder
{
public:
- IndentedDocumentBuilder(std::ostream &os) : _os(os), _level{0}
+ IndentedDocumentBuilder(std::ostream &os) : _os(os)
{
// DO NOTHING
}
std::ostream &_os;
private:
- uint32_t _level;
+ IndentedStringBuilder _builder;
};
} // namespace pp
--- /dev/null
+#ifndef __PP_INDENTED_STRING_BUILDER_H__
+#define __PP_INDENTED_STRING_BUILDER_H__
+
+#include "pp/Format.h"
+
+namespace pp
+{
+
+class IndentedStringBuilder
+{
+public:
+ IndentedStringBuilder() : _level{0}
+ {
+ // DO NOTHING
+ }
+
+public:
+ void increase(void);
+ void decrease(void);
+
+public:
+ std::string build(const std::string &content);
+
+public:
+ template <typename... Args> std::string build(const Args &... args)
+ {
+ return build(fmt(args...));
+ }
+
+private:
+ uint32_t _level;
+};
+
+} // namespace pp
+
+#endif // __PP_INDENTED_STRING_BUILDER_H__
namespace pp
{
-void IndentedDocumentBuilder::indent(void)
-{
- // TODO Check overflow
- ++_level;
-}
+void IndentedDocumentBuilder::indent(void) { _builder.increase(); }
-void IndentedDocumentBuilder::unindent(void)
-{
- assert(_level > 0);
- --_level;
-}
+void IndentedDocumentBuilder::unindent(void) { _builder.decrease(); }
void IndentedDocumentBuilder::empty(void) { _os << std::endl; }
void IndentedDocumentBuilder::line(const std::string &content)
{
- assert(std::find(content.begin(), content.end(), '\n') == content.end());
-
- const char c = ' ';
- const size_t n = 2 * _level;
-
- _os << std::string(n, c) << content << std::endl;
+ _os << _builder.build(content) << std::endl;
}
} // namespace pp
--- /dev/null
+#include "pp/IndentedStringBuilder.h"
+
+#include <algorithm>
+#include <cassert>
+
+namespace pp
+{
+
+void IndentedStringBuilder::increase(void)
+{
+ // TODO Check overflow
+ ++_level;
+}
+
+void IndentedStringBuilder::decrease(void)
+{
+ assert(_level > 0);
+ --_level;
+}
+
+std::string IndentedStringBuilder::build(const std::string &content)
+{
+ assert(std::find(content.begin(), content.end(), '\n') == content.end());
+
+ const char c = ' ';
+ const size_t space_per_indent_level = 2;
+ const size_t space_count = space_per_indent_level * _level;
+
+ return std::string(space_count, c) + content;
+}
+
+} // namespace pp
--- /dev/null
+#include "pp/IndentedStringBuilder.h"
+
+#include <gtest/gtest.h>
+
+TEST(INDENTED_STRING_BUILDER, usage)
+{
+ pp::IndentedStringBuilder builder{};
+
+ ASSERT_EQ(builder.build("A"), "A");
+ builder.increase();
+ ASSERT_EQ(builder.build("B"), " B");
+ builder.decrease();
+ ASSERT_EQ(builder.build("C"), "C");
+}