summaryrefslogtreecommitdiff
path: root/command_line/CmdLine/Src/CLLoadAndCache.c
blob: efc3f630cb75676bbff166b111f8717a7b9f7bff (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
#include "cmdline.h"

short FixTextHandle(Handle txt) {
    char *tptr;
    UInt32 tlen;
    char *scan;

    HLock(txt);
    tptr = *txt;
    tlen = GetHandleSize(txt);

    scan = tptr;
    while (scan < (tptr + tlen)) {
        if (scan[0] == '\r') {
            if (scan[1] == '\n')
                scan += 2;
            else
                scan += 1;
        } else if (scan[0] == '\n') {
            scan[0] = '\r';
            scan++;
        } else {
            scan++;
        }
    }

    HUnlock(txt);
    return 0;
}

int LoadAndCacheFile(OSSpec *spec, Handle *texthandle, Boolean *precomp) {
    Handle h;
    int err;
    OSType mactype;
    int refnum;
    UInt32 ltxtlen;

    if ((*texthandle = CachedIncludeFile(spec, precomp)))
        return 0;

    *precomp = !OS_GetMacFileType(spec, &mactype) && mactype != CWFOURCHAR('T','E','X','T');
    *texthandle = NULL;

    err = OS_Open(spec, OSReadOnly, &refnum);
    if (err)
        return err;
    err = OS_GetSize(refnum, &ltxtlen);
    if (err)
        return err;

    h = NewHandle(ltxtlen + 1);
    if (!h) {
        fprintf(stderr, "\n*** Out of memory\n");
        exit(-23);
    }

    HLock(h);
    err = OS_Read(refnum, *h, &ltxtlen);
    if (err) {
        DisposeHandle(h);
        OS_Close(refnum);
        return err;
    }

    OS_Close(refnum);
    (*h)[ltxtlen] = 0;
    HUnlock(h);

    if (!*precomp)
        FixTextHandle(h);

    CacheIncludeFile(spec, h, *precomp);
    *texthandle = h;
    return 0;
}

void CopyFileText(Handle src, char **text, SInt32 *textsize) {
    *textsize = GetHandleSize(src);
    *text = xmalloc(NULL, *textsize);

    HLock(src);
    memcpy(*text, *src, *textsize);
    *textsize -= 1;
    HUnlock(src);
}