forked from patmorin/ods
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockStore.java
More file actions
82 lines (72 loc) · 1.46 KB
/
BlockStore.java
File metadata and controls
82 lines (72 loc) · 1.46 KB
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
package ods;
import java.util.ArrayList;
import java.util.List;
/**
* This class fakes an external memory block storage system. It's actually implemented as
* a list of blocks.
* @author morin
*
* @param <T>
*/
class BlockStore<T> {
/**
* A list of blocks
*/
List<T> blocks;
/**
* A list if available block indices (indices into the blocks list)
*/
List<Integer> free;
/**
* Initialise a BlockStore with block size b
* @param b the block size
* @param clz needed so that we can allocate arrays of type T
*/
public BlockStore() {
blocks = new ArrayList<T>();
free = new ArrayList<Integer>();
}
public void clear() {
blocks.clear();
free.clear();
}
/**
* Allocate a new block and return its index
* @return the index of the newly allocated block
*/
public int placeBlock(T block) {
int i;
if (!free.isEmpty()) {
i = free.remove(free.size());
blocks.set(i, block);
} else {
i = blocks.size();
blocks.add(i, block);
}
return i;
}
/**
* Free a block, adding its index to the free list
* @param i the block index to free
*/
public void freeBlock(int i) {
blocks.set(i, null);
free.add(i);
}
/**
* Read a block
* @param i the index of the block to read
* @return the block
*/
public T readBlock(int i) {
return blocks.get(i);
}
/**
* Write a block
* @param i the index of the block
* @param block the block
*/
public void writeBlock(int i, T block) {
blocks.set(i, block);
}
}