-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreeList.cpp
106 lines (88 loc) · 2.55 KB
/
freeList.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
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <array>
#include <bitset>
#include "freeList.h"
using namespace FileSys;
using std::cerr; using std::endl; using std::cout;
using std::ios_base;
using std::string;
using std::array;
using std::bitset;
// Pre: ::fFileName exists and is of correct size
// Called by: FileMan()
FreeList::FreeList(string ffn): frs(ffn, ios_base::in | ios_base::out
| ios_base::binary)
{
assert(frs);
loadLst();
}
// Called by: ~FileMan()
FreeList::~FreeList()
{
storeLst();
if (frs.is_open())
frs.close();
}
// Get free block numbers as bits from free file.
// Store them in bitsFrm and bitsTo.
// Called by: FreeList()
void FreeList::loadLst()
{
frs.seekg(0, ios_base::beg);
frs.read(reinterpret_cast<char *>(&bitsFrm), sizeof(bitsFrm));
frs.read(reinterpret_cast<char *>(&bitsTo), sizeof(bitsTo));
frs.read(reinterpret_cast<char *>(&fromPosn), sizeof(bNum_t));
}
// Called by: ~FreeList()
void FreeList::storeLst()
{
frs.seekp(0, ios_base::beg);
frs.write(reinterpret_cast<char *>(&bitsFrm), sizeof(bitsFrm));
frs.write(reinterpret_cast<char *>(&bitsTo), sizeof(bitsTo));
frs.write(reinterpret_cast<char *>(&fromPosn), sizeof(bNum_t));
std::clog << '\n' << tabs(1) << "Free list stored.\n";
}
// Gets the next available block and returns its number or SENTINEL_BNUM
// Called by: FileMan::addBlock()
bNum_t FreeList::getBlk()
{
if (fromPosn == NUM_DISK_BLOCKS) { // if all blocks have been used
if (bitsTo.any()) // if any blocks have been returned
refresh();
}
bool found = false;
if (fromPosn < NUM_DISK_BLOCKS) {
bitsFrm.reset(fromPosn);
found = true;
}
return (found ? fromPosn++ : SENTINEL_BNUM);
}
// Copy any available block numbers from bitsTo to bitsFrm
// Reset bitsTo
// Reset the block selector 'fromPosn'
// Post: if there is an available block:
// fromPosn holds its number
// else:
// fromPosn == NUM_DISK_BLOCKS
// Called by: getBlk()
void FreeList::refresh()
{
bitsFrm |= bitsTo;
bitsTo.reset();
fromPosn = 0U;
for (bNum_t i = 0U; fromPosn < NUM_DISK_BLOCKS; ++i)
if (!bitsFrm.test(i))
++fromPosn;
else
break;
}
// Put a block back on the free list when it is no longer in use.
// Called by: FileMan::remvBlock(), FileMan::deleteFile()
void FreeList::putBlk(bNum_t bN)
{
assert(bN < NUM_DISK_BLOCKS);
bitsTo.set(bN);
}