-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.cpp
107 lines (84 loc) · 2.42 KB
/
file.cpp
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "file.h"
#include <cstdlib>
#include <cstring>
File::File() {
this->is_new = true;
this->contents = NULL;
this->file_size = 0;
}
File::File(list<unsigned int> page_nums) {
this->page_nums.clear();
list<unsigned int>::iterator it = page_nums.begin();
for(; it != page_nums.end(); ++it) {
this->page_nums.push_back(*it);
}
this->is_new = false;
this->contents = NULL;
this->file_size = 0;
}
File::~File() {
if(this->contents) {
free(this->contents);
this->contents = NULL;
this->file_size = 0;
}
}
unsigned char* File::getContents() {
if(!this->contents)
this->read();
return this->contents;
}
unsigned int File::getFileSize() {
if(!this->contents)
this->read();
return this->file_size;
}
void File::read() {
if(this->is_new) {
this->contents = NULL;
this->file_size = 0;
return;
}
Driver* drv = Driver::getInstance();
this->file_size = 0;
this->contents = (unsigned char*)malloc((PAGE_SIZE - sizeof(unsigned int)) * page_nums.size());
unsigned int tmpLen = 0;
list<unsigned int>::iterator it = page_nums.begin();
for(; it != page_nums.end(); ++it) {
if(!drv->readPage(*it, &this->contents[this->file_size], &tmpLen)) {
this->file_size = 0;
this->contents = NULL;
break;
}
this->file_size += tmpLen;
}
}
void File::write(unsigned char* data, unsigned int length) {
unsigned int actual_page_size = PAGE_SIZE - sizeof(unsigned int);
unsigned int allocated_space = this->page_nums.size() * actual_page_size;
Driver* drv = Driver::getInstance();
if(allocated_space < length) {
// Need to allocate more space!
list<unsigned int> new_pages = drv->alloc(length - allocated_space);
this->page_nums.merge(new_pages);
}
unsigned int bytes_to_go = length;
unsigned int piece_len = std::min<unsigned int>(length, actual_page_size);
list<unsigned int>::iterator it = page_nums.begin();
if(this->contents) {
free(this->contents);
}
this->contents = (unsigned char*)malloc(length * sizeof(unsigned char));
memcpy(this->contents, data, length * sizeof(unsigned char));
this->file_size = length;
while(bytes_to_go > 0) {
piece_len = std::min<unsigned int>(bytes_to_go, actual_page_size);
drv->writePage(*it, data, piece_len);
data += piece_len;
bytes_to_go -= piece_len;
++it;
}
}
list<unsigned int> File::getPageNumbers() {
return this->page_nums;
}