diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/test/util_tests.cpp | 11 | ||||
-rw-r--r-- | src/util.cpp | 35 | ||||
-rw-r--r-- | src/util.h | 5 |
3 files changed, 51 insertions, 0 deletions
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 0e53a57593..0b071361d8 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -351,4 +351,15 @@ BOOST_AUTO_TEST_CASE(test_ParseInt32) BOOST_CHECK(!ParseInt32("32482348723847471234", NULL)); } +BOOST_AUTO_TEST_CASE(test_FormatParagraph) +{ + BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), ""); + BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test"); + BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), "test"); + BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test"); + BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest"); + BOOST_CHECK_EQUAL(FormatParagraph("testerde test ", 4, 0), "testerde\ntest"); + BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test"); +} + BOOST_AUTO_TEST_SUITE_END() diff --git a/src/util.cpp b/src/util.cpp index cccf2df484..3e3dabb678 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -1407,3 +1407,38 @@ std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) ss << boost::posix_time::from_time_t(nTime); return ss.str(); } + +std::string FormatParagraph(const std::string in, size_t width, size_t indent) +{ + std::stringstream out; + size_t col = 0; + size_t ptr = 0; + while(ptr < in.size()) + { + // Find beginning of next word + ptr = in.find_first_not_of(' ', ptr); + if (ptr == std::string::npos) + break; + // Find end of next word + size_t endword = in.find_first_of(' ', ptr); + if (endword == std::string::npos) + endword = in.size(); + // Add newline and indentation if this wraps over the allowed width + if (col > 0) + { + if ((col + endword - ptr) > width) + { + out << '\n'; + for(size_t i=0; i<indent; ++i) + out << ' '; + col = 0; + } else + out << ' '; + } + // Append word + out << in.substr(ptr, endword - ptr); + col += endword - ptr; + ptr = endword; + } + return out.str(); +} diff --git a/src/util.h b/src/util.h index e070365790..da1810a3d3 100644 --- a/src/util.h +++ b/src/util.h @@ -286,6 +286,11 @@ inline std::string HexStr(const T& vch, bool fSpaces=false) return HexStr(vch.begin(), vch.end(), fSpaces); } +/** Format a paragraph of text to a fixed width, adding spaces for + * indentation to any added line. + */ +std::string FormatParagraph(const std::string in, size_t width=79, size_t indent=0); + inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; |