/* This file is part of the Amalthea library.
 *
 * Copyright (C) 2018-2023, 2025-2026 Eugene 'Vindex' Stulin
 *
 * Distributed under the Boost Software License 1.0 or (at your option)
 * the GNU Lesser General Public License 3.0 or later.
 */

module amalthea.libcore;

import core.stdc.string : strerror;
import std.string : fromStringz;
import std.compiler;

/// Signed size_t.
alias ssize_t = ptrdiff_t;


/*******************************************************************************
 * Template for exceptions.
 */
mixin template RealizeException() {
    this(string msg = "", string file = __FILE__, size_t line = __LINE__) {
        super(msg, file, line);
    }
}


/*******************************************************************************
 * Template for exceptions using errno.
 */
mixin template RealizeErrnoException() {
    this(
        string msg = "",
        int err = .errno,
        string file = __FILE__,
        size_t line = __LINE__
    ) {
        string strError;
        if (err == 0) {
            strError = msg;
        } else if (msg != "") {
            strError = msg ~ ": " ~ getInfoAboutError(err);
        } else {
            strError = getInfoAboutError(err);
        }
        super(strError, file, line);
    }
}


/*******************************************************************************
 * Returns string containing text view of an errno value.
 */
string getInfoAboutError(int err) {
    return strerror(err).fromStringz.idup;
}


/*******************************************************************************
 * Returns current compiler name.
 */
string getCompilerName() {
    switch (std.compiler.vendor) {
        case Vendor.digitalMars: return "dmd";
        case Vendor.gnu:         return "gdc";
        case Vendor.llvm:        return "ldc2";
        case Vendor.sdc:         return "sdc";
        default: break;
    }
    return "unknown";
}


enum amaltheaCompiler = getCompilerName();
