Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iterator>
namespace compiletime {
template<std::size_t MaxSize = 30>
class string
{
char m_data[MaxSize] = { 0 };
std::size_t m_size;
public:
constexpr string() : m_data(), m_size(0) {}
constexpr string(const char* str) : m_data(), m_size(0) {
for(int i =0; i<MaxSize; ++i) {
m_data[m_size++] = str[i];
}
}
constexpr char const* data() const { return m_data; }
constexpr operator const char*() const { return data(); }
constexpr void push_back(char c) { m_data[m_size++] = c; }
constexpr char& operator[](std::size_t i) { return m_data[i]; }
constexpr char const& operator[](std::size_t i) const { return m_data[i]; }
constexpr size_t size() const { return m_size; }
constexpr const char* begin() const { return std::begin(m_data); }
constexpr const char* end() const { return std::begin(m_data) + m_size; }
};
}
constexpr bool is_whitespace(char c) {
return
(c == ' ') ||
(c == '\t') ||
(c == '\n') ||
(c == '\v') ||
(c == '\f') ||
(c == '\r');
}
template<std::size_t N>
constexpr auto truncateWhitespace(compiletime::string<N> str) {
compiletime::string<N> result;
bool previousIsWhitespace = false;
for(char c : str) {
if(c == '\n') {
continue;
} else if(is_whitespace(c)) {
if(previousIsWhitespace) {
continue;
}
previousIsWhitespace = true;
} else {
previousIsWhitespace = false;
}
result.push_back(c);
}
return result;
}
template<std::size_t N>
constexpr auto truncateWhitespace(const char (&str)[N])
{
compiletime::string<N> tmp(str);
return truncateWhitespace(tmp);
}
int main() {
// Old approach: Messy code
const char query1[] =
" SELECT "
" u.id, "
" u.user_name, "
" u.ref_id, "
" u.postal_code, "
" u.email, "
" o.transaction.id "
" FROM "
" users u "
" JOIN "
" orders o ON o.user_id = u.id "
" WHERE "
" u.id=? AND u.active=? ";
// Raw string literal: Lot's of whitespace chars included
const char query2[] = R"(
SELECT
u.id,
u.user_name,
u.ref_id,
u.postal_code,
u.email,
o.transaction.id
FROM
users u
JOIN
orders o ON o.user_id = u.id
WHERE
u.id=? AND u.active=?
)";
// Raw string literal slimmed at compile time
constexpr auto query3 = truncateWhitespace(R"(
SELECT
u.id,
u.user_name,
u.ref_id,
u.postal_code,
u.email,
o.transaction.id
FROM
users u
JOIN
orders o ON o.user_id = u.id
WHERE
u.id=? AND u.active=?
)");
static_assert(query3.size() == 154);
return 0;
}
@t2ym

This comment has been minimized.

Copy link

@t2ym t2ym commented Jun 15, 2021

I rearranged this program as a header file at https://gist.github.com/t2ym/b4349f1f8845e11499a39a562b1384ba
Thank you,
@t2ym

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment