1 /*
2  * Copyright (c) 2022 Travis Geiselbrecht
3  *
4  * Use of this source code is governed by a MIT-style
5  * license that can be found in the LICENSE file or at
6  * https://opensource.org/licenses/MIT
7  */
8 #pragma once
9 
10 #include <inttypes.h>
11 #include "fat_fs.h"
12 #include "fat_priv.h"
13 
14 class fat_fs;
15 
16 class fat_file {
17 public:
18     explicit fat_file(fat_fs *f);
19     virtual ~fat_file();
20 
dir_loc()21     const dir_entry_location &dir_loc() const { return dir_loc_; }
is_dir()22     bool is_dir() const { return attributes_ == fat_attribute::directory; }
23 
24     // top level fs hooks
25     static status_t open_file(fscookie *cookie, const char *path, filecookie **fcookie);
26     static ssize_t read_file(filecookie *fcookie, void *_buf, const off_t offset, size_t len);
27     static status_t stat_file(filecookie *fcookie, struct file_stat *stat);
28     static status_t close_file(filecookie *fcookie);
29 
30     // used by fs node list maintenance
31     // node in the fs's list of open files and dirs
32     list_node node_ = LIST_INITIAL_CLEARED_VALUE;
33 
34 private:
35     // private versions of the above
36     status_t open_file_priv(const dir_entry &entry, const dir_entry_location &loc);
37     ssize_t read_file_priv(void *_buf, const off_t offset, size_t len);
38     status_t stat_file_priv(struct file_stat *stat);
39     status_t close_file_priv(bool *last_ref);
40 
41 protected:
42     // increment the ref and add/remove the file from the fs list
43     void inc_ref();
44     bool dec_ref(); // returns true when ref reaches zero
45 
46     // members
47     int ref_ = 0;
48 
49     fat_fs *fs_ = nullptr; // pointer back to the fs instance we're in
50 
51     // pointer to our dir entry, acts as our unique key
52     dir_entry_location dir_loc_ {};
53 
54     // our start cluster and length
55     uint32_t start_cluster_ = 0;
56     uint32_t length_ = 0;
57 
58     // saved attributes from our dir entry
59     fat_attribute attributes_ = fat_attribute(0);
60 };
61 
62