aboutsummaryrefslogtreecommitdiffstats
path: root/src/file.c
blob: a45d59f0061bf1cb911def259e5c5c2cc88edcef (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
/*
Copyright (c) 2021 Devine Lu Linvega
Copyright (c) 2021 Andrew Alderwick
Copyright (c) 2022 Bad Diode

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE.
*/

#include "posprintf.h"

static File f = {0};
static char *current_filename = "";

static enum {
    IDLE,
    FILE_READ,
    FILE_WRITE,
} file_state;

void
file_reset(void) {
    f = (File){0};
    file_state = IDLE;
}

u16
file_init(void *filename) {
    file_reset();
    current_filename = filename;
    return 0;
}

u16
file_read(void *dest, u16 len) {
    if(file_state != FILE_READ) {
        file_reset();
        f = fs_open_file(current_filename, FS_OPEN_READ);
        file_state = FILE_READ;
    }
    if (f.index == FS_NULL) {
        return 0;
    }
    return fs_read(dest, len, &f);
}

u16
file_write(void *src, u16 len, u8 flags) {
    if(file_state != FILE_WRITE) {
        file_reset();
        OpenMode mode = (flags & 0x01) ? FS_OPEN_APPEND : FS_OPEN_WRITE;
        f = fs_open_file(current_filename, mode);
        file_state = FILE_WRITE;
    }
    if (f.index == FS_NULL) {
        return 0;
    }
    return fs_write(src, len, &f);
}

u16
file_stat(void *dest, u16 len) {
    if(len < strlen(current_filename) + 7) {
        return 0;
    }
    if (f.index == FS_NULL) {
        posprintf(dest, "!!!! %s\n", current_filename);
    } else {
        u16 file_size = fs_file_size(&f);
        posprintf(dest, "%04x %s\n", (unsigned int)file_size, current_filename);
    }
    return 0;
}

// static u16
// file_delete(void)
// {
// 	return unlink(current_filename);
// }