initial commit
[sixth-data.git] / src / main / java / eu / svjatoslav / sixth / data / store / file / EntryAllocationTable.java
1 /*
2  * Sixth - System for data storage, computation, exploration and interaction.
3  * Copyright ©2012-2016, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.sixth.data.store.file;
11
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.List;
16
17 public class EntryAllocationTable {
18
19     private final FileDataStore fileDataStore;
20
21     public EntryAllocationTable(final FileDataStore fileDataStore) {
22         this.fileDataStore = fileDataStore;
23     }
24
25     public void enlarge(final int newSize) throws IOException {
26         final int oldSize = fileDataStore.metaData.getEntriesTableSize();
27
28         for (int i = oldSize; i < newSize; i++) {
29             final EntryRecord entryRecord = new EntryRecord(i, 0, 0);
30             entryRecord.save(fileDataStore);
31         }
32
33         fileDataStore.metaData.setEntriesTableSize(newSize);
34     }
35
36     public long getEntryRecordLocation(final int entryId) {
37         return (entryId * EntryRecord.ENTRY_RECORD_LENGTH)
38                 + MetaData.FILE_LOCATION_ENTRY_ALLOCATION_TABLE_START;
39     }
40
41     public int getNewUnusedEntryId() throws IOException {
42         while (true) {
43
44             final int newEntryId = fileDataStore.metaData.getNewEntryId();
45
46             final EntryRecord entryRecord = new EntryRecord(fileDataStore,
47                     newEntryId);
48
49             if (!entryRecord.isUsed())
50                 return newEntryId;
51         }
52     }
53
54     public void initializeNewFile() throws IOException {
55         for (int i = 0; i < fileDataStore.metaData.getEntriesTableSize(); i++) {
56             final EntryRecord entryRecord = new EntryRecord(i, 0, 0);
57             entryRecord.save(fileDataStore);
58         }
59     }
60
61     /**
62      * Sorted list of @link {@link EntryRecord}'s.
63      */
64     public List<EntryRecord> loadAllEntryRecords() throws IOException {
65         final List<EntryRecord> entryRecords = new ArrayList<>();
66
67         for (int i = 0; i < fileDataStore.metaData.getEntriesTableSize(); i++) {
68             final EntryRecord entryRecord = new EntryRecord(fileDataStore, i);
69             if (entryRecord.isUsed())
70                 entryRecords.add(entryRecord);
71         }
72
73         Collections.sort(entryRecords);
74
75         return entryRecords;
76     }
77
78 }