Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce str_lower_case() and str_upper_case() helpers #3008

Merged
merged 1 commit into from Jan 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions esphome/core/helpers.cpp
Expand Up @@ -2,6 +2,7 @@
#include "esphome/core/defines.h"
#include <cstdio>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>

Expand Down Expand Up @@ -361,6 +362,16 @@ std::string str_until(const char *str, char ch) {
return pos == nullptr ? std::string(str) : std::string(str, pos - str);
}
std::string str_until(const std::string &str, char ch) { return str.substr(0, str.find(ch)); }
// wrapper around std::transform to run safely on functions from the ctype.h header
// see https://en.cppreference.com/w/cpp/string/byte/toupper#Notes
template<int (*fn)(int)> std::string str_ctype_transform(const std::string &str) {
std::string result;
result.resize(str.length());
std::transform(str.begin(), str.end(), result.begin(), [](unsigned char ch) { return fn(ch); });
return result;
}
std::string str_lower_case(const std::string &str) { return str_ctype_transform<std::toupper>(str); }
std::string str_upper_case(const std::string &str) { return str_ctype_transform<std::tolower>(str); }
std::string str_snake_case(const std::string &str) {
std::string result;
result.resize(str.length());
Expand Down
4 changes: 4 additions & 0 deletions esphome/core/helpers.h
Expand Up @@ -369,6 +369,10 @@ std::string str_until(const char *str, char ch);
/// Extract the part of the string until either the first occurence of the specified character, or the end.
std::string str_until(const std::string &str, char ch);

/// Convert the string to lower case.
std::string str_lower_case(const std::string &str);
/// Convert the string to upper case.
std::string str_upper_case(const std::string &str);
/// Convert the string to snake case (lowercase with underscores).
std::string str_snake_case(const std::string &str);

Expand Down