aboutsummaryrefslogtreecommitdiff
path: root/sys/libfmt/buffer.c
blob: 0099e72f4bcaaba3dcd8655094896ae81408fc4b (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
#include "internal.h"

static int
flush(fmt·State *io)
{
    int  n;
    char *s;

    void *heap = io->heap;
    mem·Reallocator mem = io->mem;

    if(!io->buffer.beg)
        return 0;

    n = 2*(uintptr)io->file;
    s = io->buffer.beg;

    io->buffer.beg = mem.realloc(heap, io->buffer.beg, n, 1);
    if(!io->buffer.beg){
        io->file = io->buffer.cur = io->buffer.end = nil;
        mem.free(heap, s);
        return 0;
    }
    io->file = (void*)(uintptr)n;
    io->buffer.cur = io->buffer.beg + (io->buffer.cur - s);
    io->buffer.end = io->buffer.beg + n - 1;

    return 1;
}

int
fmt·make(mem·Reallocator mem, void *heap, fmt·State *io)
{
    int n;

    memset(io, 0, sizeof(*io));

    n = 32;
    io->buffer.beg = io->buffer.cur = mem.alloc(heap, n, 1);
    if(!io->buffer.beg)
        return -1;
    io->buffer.end = io->buffer.beg + n - 1;

    io->flush = flush;
    io->file  = (void*)(uintptr)n;
    io->n     = 0;

    fmt·setlocale(io, nil, nil, nil);
    return 0;
}

void
fmt·free(fmt·State *io)
{
    void *heap = io->heap;
    mem·Reallocator mem = io->mem;

    mem.free(heap, io->buffer.beg);
    io->buffer.beg = io->buffer.cur = io->buffer.end = nil;
}