in include/wil/resource.h [3271:3318]
template<typename string_type> string_type make_unique_string_nothrow(
_When_((source != nullptr) && length != static_cast<size_t>(-1), _In_reads_(length))
_When_((source != nullptr) && length == static_cast<size_t>(-1), _In_z_)
const wchar_t* source, size_t length = static_cast<size_t>(-1)) WI_NOEXCEPT
{
// guard against invalid parameters (null source with -1 length)
FAIL_FAST_IF(!source && (length == static_cast<size_t>(-1)));
// When the source string exists, calculate the number of characters to copy up to either
// 1) the length that is given
// 2) the length of the source string. When the source does not exist, use the given length
// for calculating both the size of allocated buffer and the number of characters to copy.
size_t lengthToCopy = length;
if (source)
{
size_t maxLength = length < MAKE_UNIQUE_STRING_MAX_CCH ? length : MAKE_UNIQUE_STRING_MAX_CCH;
PCWSTR endOfSource = source;
while (maxLength && (*endOfSource != L'\0'))
{
endOfSource++;
maxLength--;
}
lengthToCopy = endOfSource - source;
}
if (length == static_cast<size_t>(-1))
{
length = lengthToCopy;
}
const size_t allocatedBytes = (length + 1) * sizeof(*source);
auto result = static_cast<PWSTR>(details::string_allocator<string_type>::allocate(allocatedBytes));
if (result)
{
if (source)
{
const size_t bytesToCopy = lengthToCopy * sizeof(*source);
memcpy_s(result, allocatedBytes, source, bytesToCopy);
result[lengthToCopy] = L'\0'; // ensure the copied string is zero terminated
}
else
{
*result = L'\0'; // ensure null terminated in the "reserve space" use case.
}
result[length] = L'\0'; // ensure the final char of the buffer is zero terminated
}
return string_type(result);
}