Skip to content

Commit

Permalink
Add constexpr version of ozo::detail::ltob36
Browse files Browse the repository at this point in the history
  • Loading branch information
massaraksh111 committed Jun 15, 2020
1 parent a7e1fa7 commit 742f1e0
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
19 changes: 19 additions & 0 deletions include/ozo/detail/base36.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#pragma once

#include <boost/range/algorithm/reverse.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/if.hpp>
#include <string_view>
#include <string>

Expand All @@ -10,6 +12,23 @@ inline long b36tol(std::string_view in) {
return strtol(in.data(), nullptr, 36);
}

template<unsigned long i>
constexpr auto ultob36() {
constexpr int base = 36;
constexpr int d = i % base;
if constexpr (i > 0) {
const char sym = boost::hana::if_(d < 10, '0' + d, 'A' + d - 10);
return ultob36<i / base>() + boost::hana::string_c<sym>;
} else {
return BOOST_HANA_STRING("");
}
}

template<long i>
constexpr auto ltob36() {
return ultob36<static_cast<unsigned long>(i)>();
}

inline std::string ltob36(long i) {
auto u = static_cast<unsigned long>(i);
std::string out ;
Expand Down
4 changes: 3 additions & 1 deletion include/ozo/error.h
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,9 @@ class category final : public error_category {
const char* name() const noexcept override final { return "ozo::sqlstate::category"; }

std::string message(int value) const override final {
#define OZO_SQLSTATE_NAME(value) case value: return std::string(#value) + "(" + detail::ltob36(value) + ")";
#define OZO_SQLSTATE_NAME(value) case value: return boost::hana::to<char const*>(\
BOOST_HANA_STRING(#value) + BOOST_HANA_STRING("(") +\
detail::ltob36<value>() + BOOST_HANA_STRING(")"));
switch (value) {
OZO_SQLSTATE_NAME(successful_completion)
OZO_SQLSTATE_NAME(warning)
Expand Down
3 changes: 3 additions & 0 deletions tests/detail/base36.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <ozo/detail/base36.h>
#include <boost/hana.hpp>

#include <gtest/gtest.h>

Expand All @@ -16,4 +17,6 @@ TEST(ltob36, should_with_29999809_return_HV001) {
EXPECT_EQ("HV001", ozo::detail::ltob36(29999809));
}

static_assert(BOOST_HANA_STRING("HV001") == ozo::detail::ltob36<29999809>());

} // namespace

0 comments on commit 742f1e0

Please sign in to comment.