summaryrefslogtreecommitdiff
path: root/source/base/base_os.h
blob: 2e192c596f45741f57ca7d6438c850ec893a6050 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#ifndef BASE_OS_H
#define BASE_OS_H

#define STDIN_FD  0
#define STDOUT_FD 1
#define STDERR_FD 2

#endif /* BASE_OS_H */

#ifdef BASE_IMPLEMENTATION

internal string8
load_file(mem_arena *arena, const char *path)
{
    string8 result = {0};
    struct stat sbuf = {0};

    s32 file = open(path, O_RDONLY);
    if(file == -1)
    {
        return (string8){0};
    }

    if(fstat(file, &sbuf) == -1)
    {
        close(file);
        return (string8){0};
    }

    result = PushString8(arena, sbuf.st_size);
    result.size = (u64)sbuf.st_size;
    if(result.size != 0)
    {
        result.data = (u8 *)mmap(0, result.size, PROT_READ, MAP_PRIVATE, file, 0);
    }

    close(file);
    return result;
}

internal string8
write_file(const char *path, string8 data)
{
    string8 result = {0};
    s32 file = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if(file == -1)
    {
        return (string8){0};
    }

    u64 written = 0;
    while(written < data.size)
    {
        s64 err = write(file, data.data + written, data.size - written);
        if(err == -1)
        {
            close(file);
            return (string8){0};
        }
        written += err;
    }

    close(file);
    result = data;
    return result;
}

#if 0
#define os_write(buf, count) _os_write(STDOUT_FD, buf, count)
#define os_read(buf, count) _os_read(STDIN_FD, buf, count)

internal s64
_os_write(s32 fd, void const *buf, u64 count)
{
    return syscall(SYS_write, fd, buf, count);
}

internal s64
_os_read(s32 fd, void *buf, u64 count)
{
    return syscall(SYS_read, fd, buf, count);
}


internal void
log_s8(string8 s)
{
    os_write(s.data, s.size);
}

#if 1
internal void
_log(const char *str)
{
#ifdef BASE_LOGGING
    s32 len = 0;
    while (str[len]) len++;
    os_write(str, len);
#else
    unused(str);
#endif
}
#endif


internal void
write_string(const char *str)
{
    s32 len = 0;
    while (str[len]) len++;
    os_write(str, len);
}

#endif

internal void
write_int(s32 num)
{
    if (num < 0)
    {
        write(STDERR_FILENO, "-", 1);
        num = -num;
    }
    if (num >= 10) write_int(num / 10);

    char digit = '0' + (num % 10);
    write(STDERR_FILENO, &digit, 1);
}

#endif /* BASE_IMPLEMENTATION */