aboutsummaryrefslogtreecommitdiff
path: root/std/std.zig
blob: d628692ae0cdbab3aeda77e0be2e4ec0b5c06951 (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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import "syscall.zig";
import "errno.zig";
import "math.zig";

pub const stdin_fileno = 0;
pub const stdout_fileno = 1;
pub const stderr_fileno = 2;

pub var stdin = InStream {
    .fd = stdin_fileno,
};

pub var stdout = OutStream {
    .fd = stdout_fileno,
    .buffer = undefined,
    .index = 0,
    .buffered = true,
};

pub var stderr = OutStream {
    .fd = stderr_fileno,
    .buffer = undefined,
    .index = 0,
    .buffered = false,
};

/// The function received invalid input at runtime. An Invalid error means a
/// bug in the program that called the function.
pub error Invalid;

/// When an Unexpected error occurs, code that emitted the error likely needs
/// a patch to recognize the unexpected case so that it can handle it and emit
/// a more specific error.
pub error Unexpected;

pub error DiskQuota;
pub error FileTooBig;
pub error SigInterrupt;
pub error Io;
pub error NoSpaceLeft;
pub error BadPerm;
pub error PipeFail;
pub error BadFd;

const buffer_size = 4 * 1024;
const max_u64_base10_digits = 20;
const max_f64_digits = 65;

pub struct OutStream {
    fd: isize,
    buffer: [buffer_size]u8,
    index: isize,
    buffered: bool,

    pub fn print_str(os: &OutStream, str: []const u8) -> %isize {
        var src_bytes_left = str.len;
        var src_index: @typeof(str.len) = 0;
        const dest_space_left = os.buffer.len - os.index;

        while (src_bytes_left > 0) {
            const copy_amt = min_isize(dest_space_left, src_bytes_left);
            @memcpy(&os.buffer[os.index], &str[src_index], copy_amt);
            os.index += copy_amt;
            if (os.index == os.buffer.len) {
                %return os.flush();
            }
            src_bytes_left -= copy_amt;
        }
        if (!os.buffered) {
            %return os.flush();
        }
        return str.len;
    }

    /// Prints a byte buffer, flushes the buffer, then returns the number of
    /// bytes printed. The "f" is for "flush".
    pub fn printf(os: &OutStream, str: []const u8) -> %isize {
        const byte_count = %return os.print_str(str);
        %return os.flush();
        return byte_count;
    }

    pub fn print_u64(os: &OutStream, x: u64) -> %isize {
        if (os.index + max_u64_base10_digits >= os.buffer.len) {
            %return os.flush();
        }
        const amt_printed = buf_print_u64(os.buffer[os.index...], x);
        os.index += amt_printed;

        if (!os.buffered) {
            %return os.flush();
        }

        return amt_printed;
    }

    pub fn print_i64(os: &OutStream, x: i64) -> %isize {
        if (os.index + max_u64_base10_digits >= os.buffer.len) {
            %return os.flush();
        }
        const amt_printed = buf_print_i64(os.buffer[os.index...], x);
        os.index += amt_printed;

        if (!os.buffered) {
            %return os.flush();
        }

        return amt_printed;
    }

    pub fn print_f64(os: &OutStream, x: f64) -> %isize {
        if (os.index + max_f64_digits >= os.buffer.len) {
            %return os.flush();
        }
        const amt_printed = buf_print_f64(os.buffer[os.index...], x, 4);
        os.index += amt_printed;

        if (!os.buffered) {
            %return os.flush();
        }

        return amt_printed;
    }

    pub fn flush(os: &OutStream) -> %void {
        const amt_written = write(os.fd, os.buffer.ptr, os.index);
        os.index = 0;
        if (amt_written < 0) {
            return switch (-amt_written) {
                EINVAL => unreachable{},
                EDQUOT => error.DiskQuota,
                EFBIG  => error.FileTooBig,
                EINTR  => error.SigInterrupt,
                EIO    => error.Io,
                ENOSPC => error.NoSpaceLeft,
                EPERM  => error.BadPerm,
                EPIPE  => error.PipeFail,
                else   => error.Unexpected,
            }
        }
    }
}

pub struct InStream {
    fd: isize,

    pub fn read(is: &InStream, buf: []u8) -> %isize {
        const amt_read = read(is.fd, buf.ptr, buf.len);
        if (amt_read < 0) {
            return switch (-amt_read) {
                EINVAL => unreachable{},
                EFAULT => unreachable{},
                EBADF  => error.BadFd,
                EINTR  => error.SigInterrupt,
                EIO    => error.Io,
                else   => error.Unexpected,
            }
        }
        return amt_read;
    }
}

pub fn os_get_random_bytes(buf: []u8) -> %void {
    const amt_got = getrandom(buf.ptr, buf.len, 0);
    if (amt_got < 0) {
        return switch (-amt_got) {
            EINVAL => unreachable{},
            EFAULT => unreachable{},
            EINTR  => error.SigInterrupt,
            else   => error.Unexpected,
        }
    }
}

#attribute("cold")
pub fn abort() -> unreachable {
    raise(SIGABRT);
    raise(SIGKILL);
    while (true) {}
}

pub error InvalidChar;
pub error Overflow;

pub fn parse_u64(buf: []u8, radix: u8) -> %u64 {
    var x : u64 = 0;

    for (c, buf) {
        const digit = char_to_digit(c);

        if (digit > radix) {
            return error.InvalidChar;
        }

        // x *= radix
        if (@mul_with_overflow(u64, x, radix, &x)) {
            return error.Overflow;
        }

        // x += digit
        if (@add_with_overflow(u64, x, digit, &x)) {
            return error.Overflow;
        }
    }

    return x;
}

fn char_to_digit(c: u8) -> u8 {
    // TODO use switch with range
    if ('0' <= c && c <= '9') {
        c - '0'
    } else if ('A' <= c && c <= 'Z') {
        c - 'A' + 10
    } else if ('a' <= c && c <= 'z') {
        c - 'a' + 10
    } else {
        @max_value(u8)
    }
}

pub fn buf_print_i64(out_buf: []u8, x: i64) -> isize {
    if (x < 0) {
        out_buf[0] = '-';
        return 1 + buf_print_u64(out_buf[1...], u64(-(x + 1)) + 1);
    } else {
        return buf_print_u64(out_buf, u64(x));
    }
}

pub fn buf_print_u64(out_buf: []u8, x: u64) -> isize {
    var buf: [max_u64_base10_digits]u8 = undefined;
    var a = x;
    var index = buf.len;

    while (true) {
        const digit = a % 10;
        index -= 1;
        buf[index] = '0' + u8(digit);
        a /= 10;
        if (a == 0)
            break;
    }

    const len = buf.len - index;

    @memcpy(&out_buf[0], &buf[index], len);

    return len;
}

pub fn buf_print_f64(out_buf: []u8, x: f64, decimals: isize) -> isize {
    const numExpBits = 11;
    const numRawSigBits = 52; // not including implicit 1 bit
    const expBias = 1023;

    var decs = decimals;
    if (decs >= max_u64_base10_digits) {
        decs = max_u64_base10_digits - 1;
    }

    if (x == f64_get_pos_inf()) {
        const buf2 = "+Inf";
        @memcpy(&out_buf[0], &buf2[0], buf2.len);
        return 4;
    } else if (x == f64_get_neg_inf()) {
        const buf2 = "-Inf";
        @memcpy(&out_buf[0], &buf2[0], buf2.len);
        return 4;
    } else if (f64_is_nan(x)) {
        const buf2 = "NaN";
        @memcpy(&out_buf[0], &buf2[0], buf2.len);
        return 3;
    }

    var buf: [max_f64_digits]u8 = undefined;

    var len: isize = 0;

    // 1 sign bit
    // 11 exponent bits
    // 52 significand bits (+ 1 implicit always non-zero bit)

    const bits = f64_to_bits(x);
    if (bits & (1 << 63) != 0) {
        buf[0] = '-';
        len += 1;
    }

    const rexponent: i64 = i64((bits >> numRawSigBits) & ((1 << numExpBits) - 1));
    const exponent = rexponent - expBias - numRawSigBits;

    if (rexponent == 0) {
        buf[len] = '0';
        len += 1;
        @memcpy(&out_buf[0], &buf[0], len);
        return len;
    }

    const sig = (bits & ((1 << numRawSigBits) - 1)) | (1 << numRawSigBits);

    if (exponent >= 0) {
        // number is an integer

        if (exponent >= 64 - 53) {
            // use XeX form

            // TODO support printing large floats
            //len += buf_print_u64(buf[len...], sig << 10);
            const str = "LARGEF64";
            @memcpy(&buf[len], &str[0], str.len);
            len += str.len;
        } else {
            // use typical form

            len += buf_print_u64(buf[len...], sig << u64(exponent));
            buf[len] = '.';
            len += 1;

            var i: isize = 0;
            while (i < decs) {
                buf[len] = '0';
                len += 1;
                i += 1;
            }
        }
    } else {
        // number is not an integer

        // print out whole part
        len += buf_print_u64(buf[len...], sig >> u64(-exponent));
        buf[len] = '.';
        len += 1;

        // print out fractional part
        // dec_num holds: fractional part * 10 ^ decs
        var dec_num: u64 = 0;

        var a: isize = 1;
        var i: isize = 0;
        while (i < decs + 5) {
            a *= 10;
            i += 1;
        }

        // create a mask: 1's for the fractional part, 0's for whole part
        var masked_sig = sig & ((1 << u64(-exponent)) - 1);
        i = -1;
        while (i >= exponent) {
            var bit_set = ((1 << u64(i-exponent)) & masked_sig) != 0;

            if (bit_set) {
                dec_num += usize(a) >> usize(-i);
            }

            i -= 1;
        }

        dec_num /= 100000;

        len += decs;

        i = len - 1;
        while (i >= len - decs) {
            buf[i] = '0' + u8(dec_num % 10);
            dec_num /= 10;
            i -= 1;
        }
    }

    @memcpy(&out_buf[0], &buf[0], len);

    len
}