Skip to content

Instantly share code, notes, and snippets.

@MrSmith33
Last active July 13, 2021 22:49
Show Gist options
  • Save MrSmith33/9645d9552b567fdbdc1a4d8822b4f1f7 to your computer and use it in GitHub Desktop.
Save MrSmith33/9645d9552b567fdbdc1a4d8822b4f1f7 to your computer and use it in GitHub Desktop.
Vox fibonacci
// Windows> vox fib.vx C:\Windows\System32\kernel32.dll
// Linux> vox fib.vx
i64 fibR(i64 n)
{
if (n < 2) return n;
return (fibR(n-2) + fibR(n-1));
}
void main()
{
print("fib: ");
printInt(fibR(40));
println;
#version(windows) ExitProcess(0);
#version(linux) exit(0);
}
void println(u8[] str = null) {
print(str);
u8 endl = '\n';
print((&endl)[0..1]);
}
#version(windows) {
noreturn ExitProcess(u32 uExitCode);
u8 WriteConsoleA(
void* hConsoleOutput,
u8* lpBuffer,
u32 nNumberOfCharsToWrite,
u32* lpNumberOfCharsWritten,
void* lpReserved
);
void* GetStdHandle(u32 nStdHandle);
enum : u32 {
STD_INPUT_HANDLE = 0xFFFFFFF6,
STD_OUTPUT_HANDLE = 0xFFFFFFF5,
STD_ERROR_HANDLE = 0xFFFFFFF4
}
void print(u8[] str) {
void* handle = GetStdHandle(STD_OUTPUT_HANDLE);
u32 numWritten;
WriteConsoleA(
handle,
str.ptr,
cast(u32)str.length,
&numWritten,
null);
}
}
#version(linux) {
enum u32 stdout = 1;
enum u32 stderr = 2;
@extern(syscall, 60)
noreturn exit(i32 error_code);
@extern(syscall, 1)
void sys_write(u32 fd, u8* buf, u64 count);
void print(u8[] str) {
sys_write(stdout, str.ptr, str.length);
}
}
void setRangeu8(u8[] slice, u8 value) {
for (u64 i = 0; i < slice.length; ++i) {
slice[i] = value;
}
}
void printInt(i64 i)
{
u8[21] buf;
u8[] res = formatInt(i, &buf, 1);
print(res);
}
u8[] formatInt(i64 i, u8[21]* output, u32 minSize)
{
u32 numDigits = 0;
if (i == 0)
{
if (minSize == 0)
minSize = 1;
setRangeu8((*output)[21 - minSize..21], ' ');
(*output)[20] = '0';
numDigits = minSize;
}
else
{
bool neg = i < 0;
if (neg) {
i = -i;
}
bool overflow = i < 0;
if (overflow)
i = i64.max;
while (i)
{
u8 c = cast(u8)('0' + i % 10);
(*output)[21 - ++numDigits] = c;
i /= 10;
}
while (numDigits < minSize) {
(*output)[21 - ++numDigits] = ' ';
}
if (neg) {
(*output)[21 - ++numDigits] = '-';
}
if (overflow) {
++(*output)[20];
}
}
return (*output)[21 - numDigits..21];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment