Files
R8VeritasCC/include/r8veritas.hh
T
2026-07-23 12:40:40 +08:00

97 lines
2.6 KiB
C++

#ifndef R8VERITAS
#define R8VERITAS
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <utility>
#define CELL_SIZE 5
#define CELL_SIZE_BITWIDTH std::bit_width(unsigned(CELL_SIZE))
#define INS_SIZE (1 + CELL_SIZE)
#define INS_BYTECODE_SIZE (1 + CELL_SIZE + CELL_SIZE_BITWIDTH)
namespace r8veritas {
// using cell = std::bitset<CELL_SIZE>;
using cell = uint16_t;
using stat = std::array<r8veritas::cell, 1 << CELL_SIZE>;
using truthtable = std::pair<r8veritas::stat, r8veritas::stat>;
using op = std::function<r8veritas::cell(r8veritas::cell)>;
using index = size_t;
enum ins_opcode {
SET1 = 0,
FLIP = 1,
};
/*
using ins_body = std::bitset<INS_SIZE>;
using ins_bytecode = std::bitset<INS_BYTECODE_SIZE>;
*/
using ins_body = uint16_t;
using ins_bytecode = uint16_t;
using ins = struct ins {
r8veritas::ins_body bc;
r8veritas::index sacrifice;
operator const ins_bytecode() const {
return (bc << CELL_SIZE_BITWIDTH) | sacrifice;
}
};
} // namespace r8veritas
inline r8veritas::stat generate_empty_stat() {
r8veritas::stat arr;
for (r8veritas::index i = 0; i < (1 << CELL_SIZE); i++) {
arr[i] = 0;
}
return (arr);
}
namespace std {
// Overload hash to make some unordered_maps work.
template <> struct hash<r8veritas::stat> {
// Magic,from Boost's hash_combine.
// An explanation from MCMC here: https://zhuanlan.zhihu.com/p/574573421
size_t operator()(const r8veritas::stat &p) const {
size_t h = 0;
for (auto iter : p) {
h ^= hash<r8veritas::cell>{}(iter) + 0x9e3779b9 + (h << 6) + (h >> 2);
}
return (h);
}
};
template <> struct hash<pair<r8veritas::stat, r8veritas::ins_bytecode>> {
// Yep,magic again.
size_t
operator()(const pair<r8veritas::stat, r8veritas::ins_bytecode> &p) const {
size_t h =
hash<r8veritas::stat>{}(p.first) + 0x9e3779b9 + (h << 6) + (h >> 2);
h ^= hash<r8veritas::ins_bytecode>{}(p.second) + 0x9e3779b9 + (h << 6) +
(h >> 2);
return h;
}
};
} // namespace std
#define OPCODE_SET1 (static_cast<int>(r8veritas::ins_opcode::SET1))
#define OPCODE_FLIP (static_cast<int>(r8veritas::ins_opcode::FLIP))
r8veritas::truthtable generate_truthtable(const r8veritas::op &operation);
r8veritas::stat operate_ins(const r8veritas::stat &last_stat,
const r8veritas::ins &ins);
static std::unordered_map<std::pair<r8veritas::stat, r8veritas::ins_bytecode>,
r8veritas::stat>
visited_stat;
static std::unordered_map<r8veritas::stat,
std::pair<r8veritas::stat, r8veritas::ins_bytecode>>
visited_op;
#endif