Debian Codegraph @

deps/winpty/src/shared/StringUtil.h

raw
1 // Copyright (c) 2015 Ryan Prichard
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to
5 // deal in the Software without restriction, including without limitation the
6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 // sell copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 // IN THE SOFTWARE.
20
21 #ifndef WINPTY_SHARED_STRING_UTIL_H
22 #define WINPTY_SHARED_STRING_UTIL_H
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <wchar.h>
27
28 #include <algorithm>
29 #include <string>
30 #include <vector>
31
32 #include "WinptyAssert.h"
33
34 size_t winpty_wcsnlen(const wchar_t *s, size_t maxlen);
35 std::string utf8FromWide(const std::wstring &input);
36
37 // Return a vector containing each character in the string.
38 template <typename T>
39 std::vector<T> vectorFromString(const std::basic_string<T> &str) {
40 return std::vector<T>(str.begin(), str.end());
41 }
42
43 // Return a vector containing each character in the string, followed by a
44 // NUL terminator.
45 template <typename T>
46 std::vector<T> vectorWithNulFromString(const std::basic_string<T> &str) {
47 std::vector<T> ret;
48 ret.reserve(str.size() + 1);
49 ret.insert(ret.begin(), str.begin(), str.end());
50 ret.push_back('\0');
51 return ret;
52 }
53
54 // A safer(?) version of wcsncpy that is accepted by MSVC's /SDL mode.
55 template <size_t N>
56 wchar_t *winpty_wcsncpy(wchar_t (&d)[N], const wchar_t *s) {
57 ASSERT(s != nullptr);
58 size_t i = 0;
59 for (; i < N; ++i) {
60 if (s[i] == L'\0') {
61 break;
62 }
63 d[i] = s[i];
64 }
65 for (; i < N; ++i) {
66 d[i] = L'\0';
67 }
68 return d;
69 }
70
71 // Like wcsncpy, but ensure that the destination buffer is NUL-terminated.
72 template <size_t N>
73 wchar_t *winpty_wcsncpy_nul(wchar_t (&d)[N], const wchar_t *s) {
74 static_assert(N > 0, "array cannot be 0-size");
75 winpty_wcsncpy(d, s);
76 d[N - 1] = L'\0';
77 return d;
78 }
79
80 #endif // WINPTY_SHARED_STRING_UTIL_H