Source
stdlib/builtins/builtins.cpp
1
// Copyright (c) 2026 BigBrain LLC. MIT-licensed (see LICENSE).2
// Original work; see ACKNOWLEDGMENTS.md for the open-source ideas we build upon.3
#include "builtins.hpp"5
#include <algorithm>6
#include <iomanip>7
#include <sstream>9
namespace cheatah::builtins {11
std::size_t len(std::string_view s) { return s.size(); }13
int ord(std::string_view s) { return s.empty() ? 0 : static_cast<unsigned char>(s[0]); }14
std::string chr(int codepoint) {15
std::string out(1, static_cast<char>(codepoint)); // (1, c) must not become a braced list: {1, c} is two chars16
return out;17
}19
namespace {20
std::string with_base(long long value, unsigned base, const char* prefix) {21
const bool neg = value < 0;22
auto u = neg ? static_cast<unsigned long long>(-(value + 1)) + 1ULL23
: static_cast<unsigned long long>(value);24
std::string digits;25
const char* d = "0123456789abcdef";26
if (u == 0) {27
digits = "0";28
}29
while (u != 0) {30
digits.push_back(d[u % base]);31
u /= base;32
}33
std::reverse(digits.begin(), digits.end());34
return (neg ? "-" : "") + std::string(prefix) + digits;35
}36
} // namespace38
std::string hex(long long value) { return with_base(value, 16, "0x"); }39
std::string oct(long long value) { return with_base(value, 8, "0o"); }40
std::string bin(long long value) { return with_base(value, 2, "0b"); }42
std::string ascii(std::string_view s) {43
std::string r = "'";44
for (unsigned char c : s) {45
if (c == '\\') {46
r += "\\\\";47
} else if (c == '\'') {48
r += "\\'";49
} else if (c >= 32 && c < 127) {50
r += static_cast<char>(c);51
} else {52
std::ostringstream o;53
o << "\\x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(c);54
r += o.str();55
}56
}57
r += "'";58
return r;59
}61
bool to_bool(std::string_view s) { return !s.empty(); }62
long long to_int(std::string_view s) { return std::stoll(std::string(s)); }63
long long to_int(double x) { return static_cast<long long>(x); }64
double to_float(std::string_view s) { return std::stod(std::string(s)); }66
std::size_t hash(std::string_view s) { return std::hash<std::string_view>{}(s); }68
} // namespace cheatah::builtins