Skip to content

Commit 1c4f441

Browse files
kwvgknst
andcommitted
util: implement string padding function
Co-authored-by: Konstantin Akimov <knstqq@gmail.com>
1 parent 5bfc4bc commit 1c4f441

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/test/util_tests.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1828,4 +1828,26 @@ BOOST_AUTO_TEST_CASE(clearshrink_test)
18281828
}
18291829
}
18301830

1831+
BOOST_AUTO_TEST_CASE(padding_test)
1832+
{
1833+
/* By default strings will be padded to the left */
1834+
BOOST_CHECK_EQUAL(PadString("example", 8), " example");
1835+
1836+
/* Check padding works on the correct side */
1837+
BOOST_CHECK_EQUAL(PadString("example", 8, /*left=*/true), " example");
1838+
BOOST_CHECK_EQUAL(PadString("example", 8, /*left=*/false), "example ");
1839+
1840+
/* Padding lesser than the string size should return the string */
1841+
BOOST_CHECK_EQUAL(PadString("example", 6), "example");
1842+
1843+
/* Padding equal to the string size should return the string */
1844+
BOOST_CHECK_EQUAL(PadString("example", 7), "example");
1845+
1846+
/* Padding an empty string with zero length should return an empty string */
1847+
BOOST_CHECK(PadString("", 0).empty());
1848+
1849+
/* An empty string should be padded if non-zero length specified */
1850+
BOOST_CHECK_EQUAL(PadString("", 1), " ");
1851+
}
1852+
18311853
BOOST_AUTO_TEST_SUITE_END()

src/util/string.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ void ReplaceAll(std::string& in_out, const std::string& search, const std::strin
5757
return std::string(RemovePrefixView(str, prefix));
5858
}
5959

60+
[[nodiscard]] inline std::string PadString(std::string str, std::string::size_type size, bool left = true)
61+
{
62+
if (size <= str.size()) return str;
63+
return left ? std::string(size - str.size(), ' ').append(str) : str.append(std::string(size - str.size(), ' '));
64+
}
65+
6066
/**
6167
* Join all container items. Typically used to concatenate strings but accepts
6268
* containers with elements of any type.

0 commit comments

Comments
 (0)