| 
7
 | 
     1 /**
 | 
| 
 | 
     2  * utils.c:
 | 
| 
 | 
     3  *
 | 
| 
 | 
     4  * Useful utilities for general use.
 | 
| 
 | 
     5 **/
 | 
| 
10
 | 
     6 #include "utils.h"
 | 
| 
 | 
     7 
 | 
| 
 | 
     8 #include <sysinfoapi.h>
 | 
| 
11
 | 
     9 #include <windef.h>
 | 
| 
 | 
    10 #include <winbase.h>
 | 
| 
 | 
    11 #include <winuser.h>
 | 
| 
 | 
    12 #include <stringapiset.h>
 | 
| 
7
 | 
    13 #include <stdint.h>
 | 
| 
 | 
    14 
 | 
| 
11
 | 
    15 /* self explanatory. */
 | 
| 
7
 | 
    16 uint64_t get_system_time_in_milliseconds(void) {
 | 
| 
 | 
    17  	FILETIME ft;
 | 
| 
 | 
    18 	GetSystemTimeAsFileTime(&ft);
 | 
| 
 | 
    19 	uint64_t ul = (uint64_t) ft.dwHighDateTime << 32 | ft.dwLowDateTime;
 | 
| 
11
 | 
    20 	return ((ul - 116444736000000000ULL) * (1.0/10000000));
 | 
| 
7
 | 
    21 }
 | 
| 
 | 
    22 
 | 
| 
11
 | 
    23 /*
 | 
| 
 | 
    24  * appends the contents of a UTF-8 string with the content of a wide string
 | 
| 
 | 
    25  *
 | 
| 
 | 
    26  * [in] LPCWSTR wstr, the wstring to append
 | 
| 
 | 
    27  * [out] LPSTR str, the utf-8 string to append to
 | 
| 
 | 
    28  * [in] size_t offset, an offset in bytes of `str` to append at
 | 
| 
 | 
    29  * [in] size_t size, the total size of `str` in bytes
 | 
| 
 | 
    30  *
 | 
| 
 | 
    31  * if the function fails, it returns 0.
 | 
| 
 | 
    32  * if the string is empty (i.e. str[0] == '\0'), this function returns 0.
 | 
| 
 | 
    33  * if the wide string is too large to be appended within `size`, it returns 0.
 | 
| 
 | 
    34  * on success, it returns the amount of characters written ***NOT INCLUDING THE
 | 
| 
 | 
    35  * NUL BYTE***.
 | 
| 
 | 
    36 */
 | 
| 
 | 
    37 size_t append_wstr_to_utf8(LPCWSTR wstr, LPSTR str, size_t offset, size_t size) {
 | 
| 
 | 
    38 	if (!wstr || !str)
 | 
| 
 | 
    39 		return 0;
 | 
| 
7
 | 
    40 
 | 
| 
11
 | 
    41 	const int wstr_len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr, -1, NULL, 0, NULL, NULL);
 | 
| 
 | 
    42 	if (wstr_len < 0 || offset + wstr_len >= size)
 | 
| 
 | 
    43 		return 0;
 | 
| 
 | 
    44 
 | 
| 
 | 
    45 	const int actual_len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr, -1, str + offset, wstr_len, NULL, NULL);
 | 
| 
 | 
    46 	if (actual_len < 1)
 | 
| 
 | 
    47 		return 0;
 | 
| 
 | 
    48 
 | 
| 
 | 
    49 	return actual_len - 1; // remove nul byte from offset
 | 
| 
7
 | 
    50 }
 |