Compare commits

...

2 Commits

Author SHA1 Message Date
Muhammad
cb2ae14bdf
Make isBase64() and isInteger() take string_view (#1662) 2023-07-05 17:47:49 +08:00
Muhammad
34a5c37974
constexpr base64 length calculators (#1652) 2023-07-05 15:25:33 +08:00
2 changed files with 28 additions and 17 deletions

View File

@ -59,9 +59,13 @@ namespace utils
{
/// Determine if the string is an integer
DROGON_EXPORT bool isInteger(const std::string &str);
/// Determine if the string is an integer
DROGON_EXPORT bool isInteger(string_view str);
/// Determine if the string is base64 encoded
DROGON_EXPORT bool isBase64(const std::string &str);
/// Determine if the string is base64 encoded
DROGON_EXPORT bool isBase64(string_view str);
/// Generate random a string
/**
@ -102,8 +106,10 @@ DROGON_EXPORT std::set<std::string> splitStringToSet(
DROGON_EXPORT std::string getUuid();
/// Get the encoded length of base64.
DROGON_EXPORT size_t base64EncodedLength(unsigned int in_len,
bool padded = true);
constexpr size_t base64EncodedLength(unsigned int in_len, bool padded = true)
{
return padded ? ((in_len + 3 - 1) / 3) * 4 : (in_len * 8 + 6 - 1) / 6;
}
/// Encode the string to base64 format.
DROGON_EXPORT std::string base64Encode(const unsigned char *bytes_to_encode,
@ -135,7 +141,10 @@ inline std::string base64EncodeUnpadded(string_view data, bool url_safe = false)
}
/// Get the decoded length of base64.
DROGON_EXPORT size_t base64DecodedLength(unsigned int in_len);
constexpr size_t base64DecodedLength(unsigned int in_len)
{
return (in_len * 3) / 4;
}
/// Decode the base64 format string.
DROGON_EXPORT std::string base64Decode(string_view encoded_string);

View File

@ -141,11 +141,16 @@ static inline bool isBase64(unsigned char c)
bool isInteger(const std::string &str)
{
for (auto const &c : str)
{
if (c > '9' || c < '0')
for (auto c : str)
if (c < '0' || c > '9')
return false;
return true;
}
bool isInteger(string_view str)
{
for (auto c : str)
if (c < '0' || c > '9')
return false;
}
return true;
}
@ -156,6 +161,13 @@ bool isBase64(const std::string &str)
return false;
return true;
}
bool isBase64(string_view str)
{
for (auto c : str)
if (!isBase64(c))
return false;
return true;
}
std::string genRandomString(int length)
{
@ -395,11 +407,6 @@ std::string getUuid()
#endif
}
size_t base64EncodedLength(unsigned int in_len, bool padded)
{
return padded ? ((in_len + 3 - 1) / 3) * 4 : (in_len * 8 + 6 - 1) / 6;
}
std::string base64Encode(const unsigned char *bytes_to_encode,
unsigned int in_len,
bool url_safe,
@ -460,11 +467,6 @@ std::string base64EncodeUnpadded(const unsigned char *bytes_to_encode,
return base64Encode(bytes_to_encode, in_len, url_safe, false);
}
size_t base64DecodedLength(unsigned int in_len)
{
return (in_len * 3) / 4;
}
std::vector<char> base64DecodeToVector(string_view encoded_string)
{
auto in_len = encoded_string.size();