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