17ef008fcbe839f3ae1f5bd6c45167acd3dcd964
[sixth-data.git] / src / main / java / eu / svjatoslav / sixth / data / store / file / EntryRecord.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
14 class EntryRecord implements Comparable<EntryRecord> {
15     public static final int ENTRY_RECORD_LENGTH = 12;
16     final int id;
17     long location = 0;
18     int length = 0;
19
20     public EntryRecord(final FileDataStore dataStore, final int id)
21             throws IOException {
22
23         this.id = id;
24
25         final long entryRecordLocation = dataStore.entryAllocationTable
26                 .getEntryRecordLocation(id);
27
28         location = dataStore.readLong(entryRecordLocation);
29
30         if (isUsed())
31             length = dataStore.readInt(entryRecordLocation + 8);
32     }
33
34     public EntryRecord(final int id, final long location, final int length) {
35         this.id = id;
36         this.location = location;
37         this.length = length;
38     }
39
40     public void clear() {
41         location = 0;
42         length = 0;
43     }
44
45     @Override
46     public boolean equals(final Object o) {
47         if (o == null) return false;
48         return o instanceof EntryRecord && compareTo((EntryRecord) o) == 0;
49     }
50
51     @Override
52     public int compareTo(final EntryRecord o) {
53         if (location < o.location)
54             return -1;
55         if (location > o.location)
56             return 1;
57
58         if (id < o.id)
59             return -1;
60         if (id > o.id)
61             return 1;
62
63         return 0;
64     }
65
66     @Override
67     public int hashCode() {
68         int result = id;
69         result = 31 * result + (int) (location ^ (location >>> 32));
70         return result;
71     }
72
73     public boolean isUsed() {
74         return location != 0;
75
76     }
77
78     public void save(final FileDataStore dataStore) throws IOException {
79
80         final long entryRecordLocation = dataStore.entryAllocationTable
81                 .getEntryRecordLocation(id);
82
83         dataStore.writeLong(entryRecordLocation, location);
84         dataStore.writeInt(entryRecordLocation + 8, length);
85     }
86 }