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