81 lines
1.7 KiB
C++
81 lines
1.7 KiB
C++
#ifndef DLANG_LIBS_OS_HPP
|
|
#define DLANG_LIBS_OS_HPP
|
|
|
|
#include <chrono>
|
|
#include <thread>
|
|
#include <filesystem>
|
|
#include "../vm.hpp"
|
|
#include "../helpers.hpp"
|
|
|
|
static void NativeOsTime(DlangVM* vm)
|
|
{
|
|
auto now = std::chrono::system_clock::now();
|
|
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
|
|
|
|
dlang_pushnumber(vm, duration);
|
|
}
|
|
|
|
static void NativeSleep(DlangVM* vm) {
|
|
double ms = dlang_tonumber(vm);
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int64_t>(ms)));
|
|
}
|
|
|
|
static void NativeClock(DlangVM* vm)
|
|
{
|
|
auto now = std::chrono::steady_clock::now();
|
|
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
|
|
|
|
dlang_pushnumber(vm, duration);
|
|
}
|
|
|
|
static void NativeCreateDir(DlangVM* vm)
|
|
{
|
|
auto dir = dlang_tostring(vm);
|
|
std::filesystem::create_directories(dir);
|
|
}
|
|
|
|
static void NativeRemove(DlangVM* vm)
|
|
{
|
|
auto path = dlang_tostring(vm);
|
|
std::filesystem::remove_all(path);
|
|
}
|
|
|
|
static void NativeListDir(DlangVM* vm)
|
|
{
|
|
auto dir = dlang_tostring(vm);
|
|
|
|
dlang_newlist(vm);
|
|
|
|
for (const auto& entry : std::filesystem::directory_iterator(dir))
|
|
{
|
|
dlang_pushstring(vm, entry.path().string());
|
|
dlang_pushindex(vm);
|
|
}
|
|
}
|
|
|
|
inline void openlib_os(DlangVM* vm)
|
|
{
|
|
dlang_newtable(vm);
|
|
|
|
dlang_pushcfunction(vm, NativeOsTime);
|
|
dlang_setfield(vm, "time");
|
|
|
|
dlang_pushcfunction(vm, NativeSleep);
|
|
dlang_setfield(vm, "sleep");
|
|
|
|
dlang_pushcfunction(vm, NativeClock);
|
|
dlang_setfield(vm, "clock");
|
|
|
|
dlang_pushcfunction(vm, NativeCreateDir);
|
|
dlang_setfield(vm, "createdir");
|
|
|
|
dlang_pushcfunction(vm, NativeRemove);
|
|
dlang_setfield(vm, "remove");
|
|
|
|
dlang_pushcfunction(vm, NativeListDir);
|
|
dlang_setfield(vm, "listdir");
|
|
|
|
dlang_setglobal(vm, "os");
|
|
}
|
|
|
|
#endif |