diff options
author | beinhaerter <34543625+beinhaerter@users.noreply.github.com> | 2018-05-29 04:03:10 +0200 |
---|---|---|
committer | Anna Gringauze <annagrin@microsoft.com> | 2018-05-28 19:03:10 -0700 |
commit | 75ad0c1b40d27a2d0749861df923cb38f866a6c2 (patch) | |
tree | 0eed9664b714f03b686edb12a489504ad860448d | |
parent | 51ae678d080c4b9b97419c1ca716b2c464d72741 (diff) | |
download | Microsoft-GSL-75ad0c1b40d27a2d0749861df923cb38f866a6c2.tar.gz |
Add as_bytes for basic_string_span, fixes issue #655 (#683)
-rw-r--r-- | include/gsl/string_span | 15 | ||||
-rw-r--r-- | tests/string_span_tests.cpp | 19 |
2 files changed, 34 insertions, 0 deletions
diff --git a/include/gsl/string_span b/include/gsl/string_span index 6b4c839..c08f246 100644 --- a/include/gsl/string_span +++ b/include/gsl/string_span @@ -376,6 +376,21 @@ std::basic_string<CharT, Traits, Allocator> to_basic_string(basic_string_span<gC return {view.data(), static_cast<std::size_t>(view.length())}; } +template <class ElementType, std::ptrdiff_t Extent> +basic_string_span<const byte, details::calculate_byte_size<ElementType, Extent>::value> +as_bytes(basic_string_span<ElementType, Extent> s) noexcept +{ + return { reinterpret_cast<const byte*>(s.data()), s.size_bytes() }; +} + +template <class ElementType, std::ptrdiff_t Extent, + class = std::enable_if_t<!std::is_const<ElementType>::value>> +basic_string_span<byte, details::calculate_byte_size<ElementType, Extent>::value> +as_writeable_bytes(basic_string_span<ElementType, Extent> s) noexcept +{ + return {reinterpret_cast<byte*>(s.data()), s.size_bytes()}; +} + // zero-terminated string span, used to convert // zero-terminated spans to legacy strings template <typename CharT, std::ptrdiff_t Extent = dynamic_extent> diff --git a/tests/string_span_tests.cpp b/tests/string_span_tests.cpp index 0032b0f..c0b5b19 100644 --- a/tests/string_span_tests.cpp +++ b/tests/string_span_tests.cpp @@ -1167,3 +1167,22 @@ TEST_CASE("char32_t type") CHECK(ss8 <= ss9); CHECK(ss8 != ss9); } + +TEST_CASE("as_bytes") +{ + cwzstring_span<> v(L"qwerty"); + const auto s = v.as_string_span(); + const auto bs = as_bytes(s); + CHECK(static_cast<const void*>(bs.data()) == static_cast<const void*>(s.data())); + CHECK(bs.size() == s.size_bytes()); +} + +TEST_CASE("as_writeable_bytes") +{ + wchar_t buf[]{L"qwerty"}; + wzstring_span<> v(buf); + const auto s = v.as_string_span(); + const auto bs = as_writeable_bytes(s); + CHECK(static_cast<const void*>(bs.data()) == static_cast<const void*>(s.data())); + CHECK(bs.size() == s.size_bytes()); +} |