Skip to content

Commit ee9c085

Browse files
committed
Function to read a number of bytes from an input stream.
1 parent d2585fd commit ee9c085

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

libsolutil/CommonIO.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,17 @@ string solidity::util::readUntilEnd(istream& _stdin)
7979
return ss.str();
8080
}
8181

82+
string solidity::util::readBytes(istream& _input, size_t _length)
83+
{
84+
string output;
85+
output.resize(_length);
86+
_input.read(output.data(), static_cast<streamsize>(_length));
87+
// If read() reads fewer bytes it sets failbit in addition to eofbit.
88+
if (_input.fail())
89+
output.resize(static_cast<size_t>(_input.gcount()));
90+
return output;
91+
}
92+
8293
#if defined(_WIN32)
8394
class DisableConsoleBuffering
8495
{

libsolutil/CommonIO.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ std::string readFileAsString(boost::filesystem::path const& _file);
5757
/// Retrieves and returns the whole content of the specified input stream (until EOF).
5858
std::string readUntilEnd(std::istream& _stdin);
5959

60+
/// Tries to read exactly @a _length bytes from @a _input.
61+
/// Returns a string containing as much data as has been read.
62+
std::string readBytes(std::istream& _input, size_t _length);
63+
6064
/// Retrieves and returns a character from standard input (without waiting for EOL).
6165
int readStandardInputChar();
6266

test/libsolutil/CommonIO.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,15 @@ BOOST_AUTO_TEST_CASE(readUntilEnd_empty)
9090
BOOST_TEST(readUntilEnd(inputStream) == "");
9191
}
9292

93+
BOOST_AUTO_TEST_CASE(readBytes_past_end)
94+
{
95+
istringstream inputStream("abc");
96+
BOOST_CHECK_EQUAL(readBytes(inputStream, 0), "");
97+
BOOST_CHECK_EQUAL(readBytes(inputStream, 1), "a");
98+
BOOST_CHECK_EQUAL(readBytes(inputStream, 20), "bc");
99+
BOOST_CHECK_EQUAL(readBytes(inputStream, 20), "");
100+
}
101+
93102
BOOST_AUTO_TEST_SUITE_END()
94103

95104
} // namespace solidity::util::test

0 commit comments

Comments
 (0)