Function to read a number of bytes from an input stream.

This commit is contained in:
chriseth 2021-12-01 12:31:21 +01:00
parent 829fe6615b
commit d9a4020a92
3 changed files with 24 additions and 0 deletions

View File

@ -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
{

View File

@ -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();

View File

@ -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