Changed license to Creative Commons Zero (CC0).
[sixth-data.git] / src / main / java / eu / svjatoslav / sixth / data / store / file / VacuumContext.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 public class VacuumContext {
10     private final FileDataStore vacuumContext;
11     private final int targetFragmentationPercent;
12     long analyzedBytesCount = 0;
13     long freeBytesCount = 0;
14     long lastRecordStartAddress;
15     long defragmentationStartAddress;
16
17     public VacuumContext(final FileDataStore fileDataStore,
18                          final long currentFreeAddress, final int targetFragmentationPercent) {
19
20         vacuumContext = fileDataStore;
21         lastRecordStartAddress = currentFreeAddress;
22         defragmentationStartAddress = currentFreeAddress;
23         this.targetFragmentationPercent = targetFragmentationPercent;
24     }
25
26     public void analyzeEntry(final EntryRecord record) {
27         final long bytesSinceLastEntry = lastRecordStartAddress
28                 - record.location;
29
30         final long freeSpace = bytesSinceLastEntry - record.length;
31         freeBytesCount += freeSpace;
32         analyzedBytesCount += freeSpace;
33
34         checkDefragmentationPointer(record.location + record.length);
35
36         analyzedBytesCount += record.length;
37         lastRecordStartAddress = record.location;
38     }
39
40     public void analyzeStartOfDataArea() {
41         freeBytesCount += lastRecordStartAddress
42                 - vacuumContext.metaData.getEntriesStorageAreaStart();
43
44         checkDefragmentationPointer(vacuumContext.metaData
45                 .getEntriesStorageAreaStart());
46     }
47
48     public void checkDefragmentationPointer(
49             final long defragmentationStartAddress) {
50
51         if (analyzedBytesCount == 0) {
52             this.defragmentationStartAddress = defragmentationStartAddress;
53             return;
54         }
55
56         final int fragmentationPercentage = (int) ((100L * freeBytesCount) / analyzedBytesCount);
57
58         if (fragmentationPercentage >= targetFragmentationPercent)
59             this.defragmentationStartAddress = defragmentationStartAddress;
60     }
61 }