[string] add String::AppendHexBytes() (#5212)

This method appends a given array of bytes in hex representation
(`%02x` style) to a `String` object. This method helps simplify the
`ToString()` methods in simpler types (e.g., `Mac::ExtAddress`).
This commit is contained in:
Abtin Keshavarzian
2020-07-08 22:36:16 -07:00
committed by GitHub
parent 4e0dc03e96
commit 9acd16a1a2
3 changed files with 38 additions and 4 deletions
+23
View File
@@ -212,6 +212,29 @@ public:
return error;
}
/**
* This method appends an array of bytes in hex representation (using "%02x" style) to the `String` object.
*
* @param[in] aBytes A pointer to buffer containing the bytes to append.
* @param[in] aLength The length of @p aBytes buffer (in bytes).
*
* @retval OT_ERROR_NONE Updated the string successfully.
* @retval OT_ERROR_NO_BUFS String could not fit in the storage.
*
*/
otError AppendHexBytes(const uint8_t *aBytes, uint16_t aLength)
{
otError error = OT_ERROR_NONE;
while (aLength--)
{
SuccessOrExit(error = Append("%02x", *aBytes++));
}
exit:
return error;
}
private:
uint16_t mLength;
char mBuffer[kSize];
+10 -2
View File
@@ -65,7 +65,11 @@ void ExtAddress::GenerateRandom(void)
ExtAddress::InfoString ExtAddress::ToString(void) const
{
return InfoString("%02x%02x%02x%02x%02x%02x%02x%02x", m8[0], m8[1], m8[2], m8[3], m8[4], m8[5], m8[6], m8[7]);
InfoString string;
IgnoreError(string.AppendHexBytes(m8, sizeof(ExtAddress)));
return string;
}
void ExtAddress::CopyAddress(uint8_t *aDst, const uint8_t *aSrc, CopyByteOrder aByteOrder)
@@ -94,7 +98,11 @@ Address::InfoString Address::ToString(void) const
ExtendedPanId::InfoString ExtendedPanId::ToString(void) const
{
return InfoString("%02x%02x%02x%02x%02x%02x%02x%02x", m8[0], m8[1], m8[2], m8[3], m8[4], m8[5], m8[6], m8[7]);
InfoString string;
IgnoreError(string.AppendHexBytes(m8, sizeof(ExtendedPanId)));
return string;
}
uint8_t NameData::CopyTo(char *aBuffer, uint8_t aMaxSize) const
+5 -2
View File
@@ -148,8 +148,11 @@ bool InterfaceIdentifier::IsAnycastServiceLocator(void) const
InterfaceIdentifier::InfoString InterfaceIdentifier::ToString(void) const
{
return InfoString("%02x%02x%02x%02x%02x%02x%02x%02x", mFields.m8[0], mFields.m8[1], mFields.m8[2], mFields.m8[3],
mFields.m8[4], mFields.m8[5], mFields.m8[6], mFields.m8[7]);
InfoString string;
IgnoreError(string.AppendHexBytes(mFields.m8, kSize));
return string;
}
//---------------------------------------------------------------------------------------------------------------------