Browse Source

string_util: Make use of std::string_view and add bounds checking

Makes use of std::string_view in StringFromFixedZeroTerminatedBuffer and add bounds checking
pull/15/merge
Morph 4 years ago
parent
commit
0d6057b2fa
  1. 8
      src/common/string_util.cpp
  2. 2
      src/common/string_util.h

8
src/common/string_util.cpp

@ -180,12 +180,12 @@ std::wstring UTF8ToUTF16W(const std::string& input) {
#endif #endif
std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, std::size_t max_len) {
std::string StringFromFixedZeroTerminatedBuffer(std::string_view buffer, std::size_t max_len) {
std::size_t len = 0; std::size_t len = 0;
while (len < max_len && buffer[len] != '\0')
while (len < buffer.length() && len < max_len && buffer[len] != '\0') {
++len; ++len;
return std::string(buffer, len);
}
return std::string(buffer.begin(), buffer.begin() + len);
} }
std::u16string UTF16StringFromFixedZeroTerminatedBuffer(std::u16string_view buffer, std::u16string UTF16StringFromFixedZeroTerminatedBuffer(std::u16string_view buffer,

2
src/common/string_util.h

@ -63,7 +63,7 @@ template <typename InIt>
* Creates a std::string from a fixed-size NUL-terminated char buffer. If the buffer isn't * Creates a std::string from a fixed-size NUL-terminated char buffer. If the buffer isn't
* NUL-terminated then the string ends at max_len characters. * NUL-terminated then the string ends at max_len characters.
*/ */
[[nodiscard]] std::string StringFromFixedZeroTerminatedBuffer(const char* buffer,
[[nodiscard]] std::string StringFromFixedZeroTerminatedBuffer(std::string_view buffer,
std::size_t max_len); std::size_t max_len);
/** /**

Loading…
Cancel
Save