Skip to content

Commit

Permalink
Merge pull request ethereum#12354 from ethereum/addReadBytesFunction
Browse files Browse the repository at this point in the history
Function to read a number of bytes from an input stream.
  • Loading branch information
chriseth authored Dec 6, 2021
2 parents d8fa7ab + d9a4020 commit f985913
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
11 changes: 11 additions & 0 deletions libsolutil/CommonIO.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@ string solidity::util::readUntilEnd(istream& _stdin)
return ss.str();
}

string solidity::util::readBytes(istream& _input, size_t _length)
{
string output;
output.resize(_length);
_input.read(output.data(), static_cast<streamsize>(_length));
// If read() reads fewer bytes it sets failbit in addition to eofbit.
if (_input.fail())
output.resize(static_cast<size_t>(_input.gcount()));
return output;
}

#if defined(_WIN32)
class DisableConsoleBuffering
{
Expand Down
4 changes: 4 additions & 0 deletions libsolutil/CommonIO.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ std::string readFileAsString(boost::filesystem::path const& _file);
/// Retrieves and returns the whole content of the specified input stream (until EOF).
std::string readUntilEnd(std::istream& _stdin);

/// Tries to read exactly @a _length bytes from @a _input.
/// Returns a string containing as much data as has been read.
std::string readBytes(std::istream& _input, size_t _length);

/// Retrieves and returns a character from standard input (without waiting for EOL).
int readStandardInputChar();

Expand Down
9 changes: 9 additions & 0 deletions test/libsolutil/CommonIO.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ BOOST_AUTO_TEST_CASE(readUntilEnd_empty)
BOOST_TEST(readUntilEnd(inputStream) == "");
}

BOOST_AUTO_TEST_CASE(readBytes_past_end)
{
istringstream inputStream("abc");
BOOST_CHECK_EQUAL(readBytes(inputStream, 0), "");
BOOST_CHECK_EQUAL(readBytes(inputStream, 1), "a");
BOOST_CHECK_EQUAL(readBytes(inputStream, 20), "bc");
BOOST_CHECK_EQUAL(readBytes(inputStream, 20), "");
}

BOOST_AUTO_TEST_SUITE_END()

} // namespace solidity::util::test

0 comments on commit f985913

Please sign in to comment.