Skip to content

Instantly share code, notes, and snippets.

@yujincheng08
Last active October 17, 2023 13:58
Show Gist options
  • Save yujincheng08/06b4c03fc33508262f45936db69bd1aa to your computer and use it in GitHub Desktop.
Save yujincheng08/06b4c03fc33508262f45936db69bd1aa to your computer and use it in GitHub Desktop.
Compile time encrypt string
#include "enc_str.h"
#include <cstdio>
static_assert(next_prime<next_prime<4>> == next_prime<4> && next_prime<4> == 5, "??");
static constexpr auto j = "I love vvb2060 and she's my wife."_senc;
static constexpr auto k = ".."_senc;
static constexpr auto l = j + k;
int main() {
auto i = "I love rikka and she's my wife"_ienc;
auto ll = l.obtain();
std::printf("%s\n", i.c_str());
std::printf("%s\n", ll.c_str());
return 0;
}
#include <utility>
#if __cplusplus >= 202002L
#define CONSTEVAL consteval
#else
#define CONSTEVAL constexpr
#endif
CONSTEVAL bool isPrime(std::size_t x) {
if (x == 2 || x == 3)
return true;
if (x % 2 == 0 || x % 3 == 0)
return false;
int divisor = 6;
while (divisor * divisor - 2 * divisor + 1 <= x) {
if (x % (divisor - 1) == 0)
return false;
if (x % (divisor + 1) == 0)
return false;
divisor += 6;
}
return true;
}
CONSTEVAL std::size_t nextPrime(std::size_t x) {
while(!isPrime(x)) ++x;
return x;
}
template <std::size_t x> constexpr auto next_prime = nextPrime(x);
template <char... cs> class InlineEnc {
private:
char inner[sizeof...(cs) + 1];
public:
CONSTEVAL InlineEnc() : inner{cs..., '\0'} {
for (std::size_t i = 0; i < sizeof...(cs); ++i) {
inner[i] ^= (i + sizeof...(cs)) % next_prime<sizeof...(cs)>;
}
}
constexpr const char *c_str() const { return inner; }
};
template <char... is, std::size_t... I>
CONSTEVAL auto MakeInlineEnc(std::index_sequence<I...>) {
return InlineEnc<(is ^ ((I + sizeof...(is)) % next_prime<sizeof...(is)>))...>();
}
template <char... cs> class StaticEnc {
public:
CONSTEVAL StaticEnc() = default;
CONSTEVAL auto obtain() const {
return MakeInlineEnc<cs...>(std::make_index_sequence<sizeof...(cs)>());
}
};
template <typename T, T... cs> CONSTEVAL auto operator""_ienc() {
return MakeInlineEnc<cs...>(std::make_index_sequence<sizeof...(cs)>());
}
template <typename T, T... cs> CONSTEVAL auto operator""_senc() {
return StaticEnc<cs...>{};
}
template <char... as, char... bs>
CONSTEVAL auto operator+(const StaticEnc<as...> &, const StaticEnc<bs...> &) {
return StaticEnc<as..., bs...>{};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment