1
0
Fork 0

fixed length strings get written null-terminated by default

This commit is contained in:
Kevin Matz 2021-09-05 12:37:58 -04:00
parent 25227ff083
commit d021366fc8
2 changed files with 33 additions and 10 deletions

View File

@ -87,10 +87,14 @@ uint8_t * pdu_stream::base()
*/
void pdu_stream::readString(std::string &str, const int fixed_length)
{
if (!fixed_length) {
// if fixed_length == 0, use all available data on the stream
if (!fixed_length)
{
str += std::string(reinterpret_cast<char*>(data()), available());
return setstate(std::ios_base::eofbit);
}
// otherwise, construct a buffer and read into that.
uint8_t buffer[fixed_length];
read(buffer, fixed_length);
if (gcount() != fixed_length)
@ -102,16 +106,34 @@ void pdu_stream::readString(std::string &str, const int fixed_length)
/**
* @brief pdu_stream::writeString
* @param str
* @param fixed_length write this length to the stream, padding with null if
* str is shorter than fixed_length. If 0 will write only the contents of str.
* @param fixed_length write this length to the stream, padding with null
* if str is shorter than fixed_length. If 0, will write the unrestricted
* contents of str.
* @param terminated If true, the last byte of fixed_length is guaranteed to
* be a 0 (null) byte.
*/
void pdu_stream::writeString(const std::string &str, const int fixed_length)
void pdu_stream::writeString(const std::string &str, const size_t fixed_length,
const bool terminated)
{
for (size_t i = 0; i < (fixed_length > 0 ? fixed_length : str.size()); i++)
if (i < str.size())
writeType<char>(str.at(i));
else
writeType<uint8_t>(0);
// fixed_length == 0 means dynamic length.
bool fixed = fixed_length > 0 ? true : false;
// fixed length strings restricted to fixed_lengh characters
size_t maxlen = fixed ? fixed_length : str.size();
// write no more of the string than is available
size_t wrtlen = str.size() < maxlen ? str.size() : maxlen;
// terminated fixed-length strings get a guaranteed padding byte
if (fixed && terminated && wrtlen == maxlen)
--wrtlen;
// output the correct ammount of data from the string
write(reinterpret_cast<const uint8_t*>(str.data()), wrtlen);
// output any required padding bytes
for (size_t i = wrtlen; i < maxlen; i++)
put(0);
}

View File

@ -81,7 +81,8 @@ public:
// strings
void readString(std::string& str, const int fixed_length = 0);
void writeString(const std::string& str, const int fixed_length = 0);
void writeString(const std::string& str, const size_t fixed_length = 0,
const bool terminated = true);
// reinterpreted i/o
/**