lox-d/src/clox/util.d
2025-06-07 04:09:48 +00:00

55 lines
1.4 KiB
D

module clox.util;
import core.stdc.stdio;
import core.stdc.stdlib;
import std.functional : ctEval;
enum Colour : string{
Black = "30", Red = "31", Green = "32", Yellow = "33", Blue = "34", Pink = "35", Cyan = "36",
}
string colour(string text, string num)() => ctEval!("\033[1;" ~ num ~ "m" ~ text ~ "\033[0m");
string colour(string text, string r, string g, string b)() => ctEval!("\033[38;2;" ~ r ~ ";" ~ g ~ ";" ~ b ~ "m" ~ text ~ "\033[0m");
extern(C) int isatty(int);
static char* readFile(const char* path) {
FILE* file = path.fopen("rb");
if(file == null){
stderr.fprintf("Could not open file \"%s\".\n", path);
return null;
}
scope(exit)
file.fclose();
file.fseek(0, SEEK_END);
size_t fileSize = file.ftell();
file.rewind();
char* buffer = cast(char*)malloc(fileSize + 1);
size_t bytesRead = fread(buffer, char.sizeof, fileSize, file);
buffer[bytesRead] = '\0';
return buffer;
}
char* readStdin(){
size_t bufferSize = 512;
char* buffer = cast(char*)malloc(bufferSize);
if (buffer == null) {
perror("Unable to allocate buffer");
return null;
}
size_t totalBytesRead = 0;
size_t bytesRead;
while((bytesRead = fread(buffer + totalBytesRead, 1, bufferSize - totalBytesRead, stdin)) > 0){
totalBytesRead += bytesRead;
if(totalBytesRead == bufferSize){
bufferSize *= 2;
buffer = cast(char*)realloc(buffer, bufferSize);
}
}
buffer[totalBytesRead] = '\0';
return buffer;
}