
public import win32.generated.*;
public import win32.constants.*;
public import win32.errorcodes.*;
public import win32.platform.*;
import win32.errornames.(errorNames);


//
// GetFileSizeEx, SetFilePointerEx
//
// redefined because LARGE_INTEGER definition is wrong
//

external (WINAPI) GetFileSizeEx(
    handle : HANDLE,
    lpFileSize : Pointer[Int64]) : BOOL;

external (WINAPI) SetFilePointerEx(
    handle : HANDLE,
    offset : Int64,
    newPosition : Pointer[Int64],
    moveMethod : DWORD) : BOOL;



//
// errorMessage
//

alias FORMAT_MESSAGE_FROM_SYSTEM = CULong(0x1000);

printErrorMessageTo(stream, errorCode) {
    var buf = Array[Byte, 1024]();
    var result = FormatMessageA(
        FORMAT_MESSAGE_FROM_SYSTEM,
        RawPointer(0),
        CULong(errorCode),
        CULong(0),
        LPSTR(begin(buf)),
        CULong(size(buf)),
        null(va_list),
    );
    if (result == 0)
        printTo(stream, "unknown error");
    else
        printTo(stream, CStringRef(begin(buf)));
}

errorCodeName(code:Int) {
    ref names = errorNames();
    var nameCodes = mapped(x => x.0, names);
    var begin, end = ..binarySearch(nameCodes, code);
    if (begin == end)
        return "";
    return mappedInnerCoordinate(begin)^.1;
}
