common/string_util: Move TextFromBuffer to string_util

This commit is contained in:
zhupengfei 2019-04-08 22:34:21 +08:00
parent 25be09c7a3
commit d7fbc1ca2c
No known key found for this signature in database
GPG key ID: DD129E108BD09378
4 changed files with 22 additions and 48 deletions

View file

@ -4,10 +4,12 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
#include "common/common_types.h"
#include "common/swap.h"
namespace Common {
@ -58,6 +60,20 @@ bool ComparePartialString(InIt begin, InIt end, const char* other) {
return (begin == end) == (*other == '\0');
}
/**
* Converts a UTF-16 text in a container to a UTF-8 std::string.
*/
template <typename T>
std::string UTF16BufferToUTF8(const T& text) {
const auto text_end = std::find(text.begin(), text.end(), u'\0');
const std::size_t text_size = std::distance(text.begin(), text_end);
std::u16string buffer(text_size, 0);
std::transform(text.begin(), text_end, buffer.begin(), [](u16_le character) {
return static_cast<char16_t>(static_cast<u16>(character));
});
return UTF16ToUTF8(buffer);
}
/**
* 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.