fixed maven repository URL
[sixth-data.git] / src / main / java / eu / svjatoslav / sixth / data / store / file / EntryAllocationTable.java
1 /*
2  * Sixth Data. Author: Svjatoslav Agejenko. 
3  * This project is released under Creative Commons Zero (CC0) license.
4  *
5 */
6
7 package eu.svjatoslav.sixth.data.store.file;
8
9 import java.io.IOException;
10 import java.util.ArrayList;
11 import java.util.Collections;
12 import java.util.List;
13
14 public class EntryAllocationTable {
15
16     private final FileDataStore fileDataStore;
17
18     public EntryAllocationTable(final FileDataStore fileDataStore) {
19         this.fileDataStore = fileDataStore;
20     }
21
22     public void enlarge(final int newSize) throws IOException {
23         final int oldSize = fileDataStore.metaData.getEntriesTableSize();
24
25         for (int i = oldSize; i < newSize; i++) {
26             final EntryRecord entryRecord = new EntryRecord(i, 0, 0);
27             entryRecord.save(fileDataStore);
28         }
29
30         fileDataStore.metaData.setEntriesTableSize(newSize);
31     }
32
33     public long getEntryRecordLocation(final int entryId) {
34         return (entryId * EntryRecord.ENTRY_RECORD_LENGTH)
35                 + MetaData.FILE_LOCATION_ENTRY_ALLOCATION_TABLE_START;
36     }
37
38     public int getNewUnusedEntryId() throws IOException {
39         while (true) {
40
41             final int newEntryId = fileDataStore.metaData.getNewEntryId();
42
43             final EntryRecord entryRecord = new EntryRecord(fileDataStore,
44                     newEntryId);
45
46             if (!entryRecord.isUsed())
47                 return newEntryId;
48         }
49     }
50
51     public void initializeNewFile() throws IOException {
52         for (int i = 0; i < fileDataStore.metaData.getEntriesTableSize(); i++) {
53             final EntryRecord entryRecord = new EntryRecord(i, 0, 0);
54             entryRecord.save(fileDataStore);
55         }
56     }
57
58     /**
59      * Sorted list of @link {@link EntryRecord}'s.
60      */
61     public List<EntryRecord> loadAllEntryRecords() throws IOException {
62         final List<EntryRecord> entryRecords = new ArrayList<>();
63
64         for (int i = 0; i < fileDataStore.metaData.getEntriesTableSize(); i++) {
65             final EntryRecord entryRecord = new EntryRecord(fileDataStore, i);
66             if (entryRecord.isUsed())
67                 entryRecords.add(entryRecord);
68         }
69
70         Collections.sort(entryRecords);
71
72         return entryRecords;
73     }
74
75 }