1
0
Fork 0

pdu_stream can read/write fixed length strings

This commit is contained in:
Kevin Matz 2021-08-17 12:24:19 -04:00
parent 1d5e36ae10
commit 112326b695
2 changed files with 35 additions and 0 deletions

View File

@ -40,6 +40,37 @@ pdu_stream::pdu_stream(uint8_t * p, std::streamsize l)
}
/**
* @brief pdu_stream::readString
* @param str std::string to which the read string will be appended.
* @param length this many bytes will be read from the stream.
*/
void pdu_stream::readString(std::string &str, const int length)
{
uint8_t buffer[length];
read(buffer, sizeof(buffer));
if (gcount() != length)
return setstate(std::ios_base::failbit);
str += std::string(reinterpret_cast<char*>(buffer));
}
/**
* @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.
*/
void pdu_stream::writeString(const std::string &str, const int fixed_length)
{
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);
}
/**
* @brief pdu_stream::operator >>
* @param val

View File

@ -50,6 +50,7 @@ public:
pdu_stream& operator>> (uint64_t& val);
pdu_stream& operator>> (UUID::uuid& uuid);
void readString(std::string& str, const int length);
template<typename T> T readType()
{
@ -74,6 +75,9 @@ public:
pdu_stream& operator<< (const uint32_t& val);
pdu_stream& operator<< (const uint64_t& val);
pdu_stream& operator<< (const UUID::uuid& uuid);
void writeString(const std::string& str, const int fixed_length = 0);
template<typename T> void writeType (const T& val)
{
auto data = reinterpret_cast<const uint8_t*>(&val);