Skip to content

Commit de65a5c

Browse files
addaleaxtargos
authored andcommitted
src: make ToLower/ToUpper input args more flexible
In particular, this enables passing `std::string_view` instead. PR-URL: #60052 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
1 parent 1d5cc5e commit de65a5c

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

src/util-inl.h

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -194,21 +194,29 @@ char ToLower(char c) {
194194
return std::tolower(c, std::locale::classic());
195195
}
196196

197-
std::string ToLower(const std::string& in) {
198-
std::string out(in.size(), 0);
199-
for (size_t i = 0; i < in.size(); ++i)
200-
out[i] = ToLower(in[i]);
197+
template <typename T>
198+
std::string ToLower(const T& in) {
199+
auto it = std::cbegin(in);
200+
auto end = std::cend(in);
201+
std::string out(std::distance(it, end), 0);
202+
size_t i;
203+
for (i = 0; it != end; ++it, ++i) out[i] = ToLower(*it);
204+
DCHECK_EQ(i, out.size());
201205
return out;
202206
}
203207

204208
char ToUpper(char c) {
205209
return std::toupper(c, std::locale::classic());
206210
}
207211

208-
std::string ToUpper(const std::string& in) {
209-
std::string out(in.size(), 0);
210-
for (size_t i = 0; i < in.size(); ++i)
211-
out[i] = ToUpper(in[i]);
212+
template <typename T>
213+
std::string ToUpper(const T& in) {
214+
auto it = std::cbegin(in);
215+
auto end = std::cend(in);
216+
std::string out(std::distance(it, end), 0);
217+
size_t i;
218+
for (i = 0; it != end; ++it, ++i) out[i] = ToUpper(*it);
219+
DCHECK_EQ(i, out.size());
212220
return out;
213221
}
214222

src/util.h

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,11 +366,13 @@ inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(v8::Isolate* isolate,
366366

367367
// tolower() is locale-sensitive. Use ToLower() instead.
368368
inline char ToLower(char c);
369-
inline std::string ToLower(const std::string& in);
369+
template <typename T>
370+
inline std::string ToLower(const T& in);
370371

371372
// toupper() is locale-sensitive. Use ToUpper() instead.
372373
inline char ToUpper(char c);
373-
inline std::string ToUpper(const std::string& in);
374+
template <typename T>
375+
inline std::string ToUpper(const T& in);
374376

375377
// strcasecmp() is locale-sensitive. Use StringEqualNoCase() instead.
376378
inline bool StringEqualNoCase(const char* a, const char* b);

0 commit comments

Comments
 (0)