summaryrefslogtreecommitdiff
path: root/src/cache/backings/file_common.h
blob: 6dd4e968eff24cafa16b9a9ce69c33a67794fe40 (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
#pragma once

#include "../backing.h"
#include "../range.h"

#include "file.h"

AL_IGNORE_WARNING("-Wunused-function")

static off_t file_backing_get_size_if_known(struct cch_backing *backing)
{
    struct cch_backing_file *file = (struct cch_backing_file *)backing;
    nn_mutex_lock(&file->mutex);
    off_t size = file->backing.size;
    nn_mutex_unlock(&file->mutex);
    return size;
}

static void file_backing_finalize(struct cch_backing *backing)
{
    struct cch_backing_file *file = (struct cch_backing_file *)backing;
    nn_mutex_lock(&file->mutex);
    file->backing.size = file->file.size;
    nn_mutex_unlock(&file->mutex);
}

static bool file_open_internal(struct cch_backing_file *file, str *path, size_t size)
{
    s32 flags = (size != 0) ? NNWT_FILE_CREATE : NNWT_FILE_READONLY;
    if (al_str_cmp(path, &al_str_c("fd://"), 0, 5) == 0) {
        str fd_str = al_str_substr(path, 5, path->length);
        bool error;
        s32 fd = (s32)al_str_to_long(&fd_str, 10, &error);
        if (error) return false;
        if (!nn_file_wrap_fd(&file->file, fd)) {
            return false;
        }
    } else {
        if (!nn_file_open(&file->file, path, flags)) {
            return false;
        }
    }
    size_t filesize = file->file.size;
    if (!size) {
        file->backing.size = filesize;
        cch_backing_fill_range(&file->backing, 0, filesize);
    } else if (filesize < size) {
        nn_file_truncate(&file->file, size);
    }
    return true;
}

AL_IGNORE_WARNING_END