Repository navigation
Expand file tree
/
Copy pathVolume.java
More file actions
1301 lines (1060 loc) · 40.3 KB
/
Copy pathVolume.java
File metadata and controls
1301 lines (1060 loc) · 40.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapdb;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;
/**
* MapDB abstraction over raw storage (file, disk partition, memory etc...).
* <p/>
* Implementations needs to be thread safe (especially
'ensureAvailable') operation.
* However updates do not have to be atomic, it is clients responsibility
* to ensure two threads are not writing/reading into the same location.
*
* @author Jan Kotek
*/
public abstract class Volume implements Closeable{
/**
* Check space allocated by Volume is bigger or equal to given offset.
* So it is safe to write into smaller offsets.
*
* @throws IOError if Volume can not be expanded beyond given offset
* @param offset
*/
public void ensureAvailable(final long offset){
if(!tryAvailable(offset))
throw new IOError(new IOException("no free space to expand Volume"));
}
abstract public boolean tryAvailable(final long offset);
public abstract void truncate(long size);
abstract public void putLong(final long offset, final long value);
abstract public void putInt(long offset, int value);
abstract public void putByte(final long offset, final byte value);
abstract public void putData(final long offset, final byte[] src, int srcPos, int srcSize);
abstract public void putData(final long offset, final ByteBuffer buf);
abstract public long getLong(final long offset);
abstract public int getInt(long offset);
abstract public byte getByte(final long offset);
abstract public DataInput getDataInput(final long offset, final int size);
abstract public void close();
abstract public void sync();
/**
*
* @return slice size or `-1` if not sliced
*/
abstract public int sliceSize();
public abstract boolean isEmpty();
public abstract void deleteFile();
public abstract boolean isSliced();
public void putUnsignedShort(final long offset, final int value){
putByte(offset, (byte) (value>>8));
putByte(offset+1, (byte) (value));
}
public int getUnsignedShort(long offset) {
return (( (getByte(offset) & 0xff) << 8) |
( (getByte(offset+1) & 0xff)));
}
public int getUnsignedByte(long offset) {
return getByte(offset) & 0xff;
}
public void putUnsignedByte(long offset, int b) {
putByte(offset, (byte)(b & 0xff));
}
/**
* Reads a long from the indicated position
*/
public long getSixLong(long pos) {
return
((long) (getByte(pos + 0) & 0xff) << 40) |
((long) (getByte(pos + 1) & 0xff) << 32) |
((long) (getByte(pos + 2) & 0xff) << 24) |
((long) (getByte(pos + 3) & 0xff) << 16) |
((long) (getByte(pos + 4) & 0xff) << 8) |
((long) (getByte(pos + 5) & 0xff) << 0);
}
/**
* Writes a long to the indicated position
*/
public void putSixLong(long pos, long value) {
assert(value>=0 && (value>>>6*8)==0): "value does not fit";
//TODO read/write as integer+short, might be faster
putByte(pos + 0, (byte) (0xff & (value >> 40)));
putByte(pos + 1, (byte) (0xff & (value >> 32)));
putByte(pos + 2, (byte) (0xff & (value >> 24)));
putByte(pos + 3, (byte) (0xff & (value >> 16)));
putByte(pos + 4, (byte) (0xff & (value >> 8)));
putByte(pos + 5, (byte) (0xff & (value >> 0)));
}
/**
* Writes packed long at given position and returns number of bytes used.
*/
public int putPackedLong(long pos, long value) {
assert(value>=0):"negative value";
int ret = 0;
while ((value & ~0x7FL) != 0) {
putUnsignedByte(pos+(ret++), (((int) value & 0x7F) | 0x80));
value >>>= 7;
}
putUnsignedByte(pos + (ret++), (byte) value);
return ret;
}
/** returns underlying file if it exists */
abstract public File getFile();
public long getPackedLong(long pos){
//TODO unrolled version?
long result = 0;
for (int offset = 0; offset < 64; offset += 7) {
long b = getUnsignedByte(pos++);
result |= (b & 0x7F) << offset;
if ((b & 0x80) == 0) {
return result;
}
}
throw new AssertionError("Malformed long.");
}
/**
* Transfers data from this Volume into target volume.
* If its possible, the implementation should override this method to enable direct memory transfer.
*
* Caller must respect slice boundaries. ie it is not possible to transfer data which cross slice boundaries.
*
* @param inputOffset offset inside this Volume, ie data will be read from this offset
* @param target Volume to copy data into
* @param targetOffset position in target volume where data will be copied into
* @param size size of data to copy
*/
public void transferInto(long inputOffset, Volume target, long targetOffset, int size) {
byte[] data = new byte[size];
try {
getDataInput(inputOffset, size).readFully(data);
}catch(IOException e){
throw new IOError(e);
}
target.putData(targetOffset,data,0,size);
}
/**
* Factory which creates two/three volumes used by each MapDB Storage Engine
*/
public static interface Factory {
Volume createIndexVolume();
Volume createPhysVolume();
Volume createTransLogVolume();
}
public static Volume volumeForFile(File f, boolean useRandomAccessFile, boolean readOnly, long sizeLimit, int sliceShift, int sizeIncrement) {
return useRandomAccessFile ?
new FileChannelVol(f, readOnly,sizeLimit, sliceShift, sizeIncrement):
new MappedFileVol(f, readOnly,sizeLimit,sliceShift, sizeIncrement);
}
public static Factory fileFactory(final File indexFile, final int rafMode, final boolean readOnly, final long sizeLimit,
final int sliceShift, final int sizeIncrement){
return fileFactory(
indexFile,
rafMode, readOnly, sizeLimit, sliceShift, sizeIncrement,
new File(indexFile.getPath() + StoreDirect.DATA_FILE_EXT),
new File(indexFile.getPath() + StoreWAL.TRANS_LOG_FILE_EXT));
}
public static Factory fileFactory(final File indexFile,
final int rafMode,
final boolean readOnly,
final long sizeLimit,
final int sliceShift,
final int sizeIncrement,
final File physFile,
final File transLogFile) {
return new Factory() {
@Override
public Volume createIndexVolume() {
return volumeForFile(indexFile, rafMode>1, readOnly, sizeLimit, sliceShift, sizeIncrement);
}
@Override
public Volume createPhysVolume() {
return volumeForFile(physFile, rafMode>0, readOnly, sizeLimit, sliceShift, sizeIncrement);
}
@Override
public Volume createTransLogVolume() {
return volumeForFile(transLogFile, rafMode>0, readOnly, sizeLimit,sliceShift, sizeIncrement);
}
};
}
public static Factory memoryFactory(final boolean useDirectBuffer, final long sizeLimit, final int sliceShift) {
return new Factory() {
@Override public synchronized Volume createIndexVolume() {
return useDirectBuffer?
new MemoryVol(useDirectBuffer, sizeLimit, sliceShift):
new ByteArrayVol(sizeLimit, sliceShift);
}
@Override public synchronized Volume createPhysVolume() {
return useDirectBuffer?
new MemoryVol(useDirectBuffer, sizeLimit, sliceShift):
new ByteArrayVol(sizeLimit, sliceShift); }
@Override public synchronized Volume createTransLogVolume() {
return useDirectBuffer?
new MemoryVol(useDirectBuffer, sizeLimit, sliceShift):
new ByteArrayVol(sizeLimit, sliceShift);
}
};
}
/**
* Abstract Volume over bunch of ByteBuffers
* It leaves ByteBufferVol details (allocation, disposal) on subclasses.
* Most methods are final for better performance (JIT compiler can inline those).
*/
abstract static public class ByteBufferVol extends Volume{
protected final ReentrantLock growLock = new ReentrantLock(CC.FAIR_LOCKS);
protected final long sizeLimit;
protected final boolean hasLimit;
protected final int sliceShift;
protected final int sliceSizeModMask;
protected final int sliceSize;
protected volatile ByteBuffer[] slices = new ByteBuffer[0];
protected final boolean readOnly;
protected ByteBufferVol(boolean readOnly, long sizeLimit, int sliceShift) {
this.readOnly = readOnly;
this.sizeLimit = sizeLimit;
this.sliceShift = sliceShift;
this.sliceSize = 1<< sliceShift;
this.sliceSizeModMask = sliceSize -1;
this.hasLimit = sizeLimit>0;
}
@Override
public final boolean tryAvailable(long offset) {
if (hasLimit && offset > sizeLimit) return false;
int slicePos = (int) (offset >>> sliceShift);
//check for most common case, this is already mapped
if (slicePos < slices.length){
return true;
}
growLock.lock();
try{
//check second time
if(slicePos< slices.length)
return true;
int oldSize = slices.length;
ByteBuffer[] slices2 = slices;
slices2 = Arrays.copyOf(slices2, Math.max(slicePos+1, slices2.length + slices2.length/1000));
for(int pos=oldSize;pos<slices2.length;pos++) {
slices2[pos]=makeNewBuffer(1L* sliceSize *pos);
}
slices = slices2;
}finally{
growLock.unlock();
}
return true;
}
protected abstract ByteBuffer makeNewBuffer(long offset);
@Override public final void putLong(final long offset, final long value) {
slices[(int)(offset >>> sliceShift)].putLong((int) (offset & sliceSizeModMask), value);
}
@Override public final void putInt(final long offset, final int value) {
slices[(int)(offset >>> sliceShift)].putInt((int) (offset & sliceSizeModMask), value);
}
@Override public final void putByte(final long offset, final byte value) {
slices[(int)(offset >>> sliceShift)].put((int) (offset & sliceSizeModMask), value);
}
@Override public void putData(final long offset, final byte[] src, int srcPos, int srcSize){
final ByteBuffer b1 = slices[(int)(offset >>> sliceShift)].duplicate();
final int bufPos = (int) (offset& sliceSizeModMask);
b1.position(bufPos);
b1.put(src, srcPos, srcSize);
}
@Override public final void putData(final long offset, final ByteBuffer buf) {
final ByteBuffer b1 = slices[(int)(offset >>> sliceShift)].duplicate();
final int bufPos = (int) (offset& sliceSizeModMask);
//no overlap, so just write the value
b1.position(bufPos);
b1.put(buf);
}
@Override
public void transferInto(long inputOffset, Volume target, long targetOffset, int size) {
final ByteBuffer b1 = slices[(int)(inputOffset >>> sliceShift)].duplicate();
final int bufPos = (int) (inputOffset& sliceSizeModMask);
b1.position(bufPos);
b1.limit(bufPos+size);
target.putData(targetOffset,b1);
}
@Override final public long getLong(long offset) {
return slices[(int)(offset >>> sliceShift)].getLong((int) (offset& sliceSizeModMask));
}
@Override final public int getInt(long offset) {
return slices[(int)(offset >>> sliceShift)].getInt((int) (offset& sliceSizeModMask));
}
@Override public final byte getByte(long offset) {
return slices[(int)(offset >>> sliceShift)].get((int) (offset& sliceSizeModMask));
}
@Override
public final DataInput2 getDataInput(long offset, int size) {
return new DataInput2(slices[(int)(offset >>> sliceShift)], (int) (offset& sliceSizeModMask));
}
@Override
public boolean isEmpty() {
return slices.length==0;
}
@Override
public boolean isSliced(){
return true;
}
@Override
public int sliceSize() {
return sliceSize;
}
/**
* Hack to unmap MappedByteBuffer.
* Unmap is necessary on Windows, otherwise file is locked until JVM exits or BB is GCed.
* There is no public JVM API to unmap buffer, so this tries to use SUN proprietary API for unmap.
* Any error is silently ignored (for example SUN API does not exist on Android).
*/
protected void unmap(MappedByteBuffer b){
try{
if(unmapHackSupported){
// need to dispose old direct buffer, see bug
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038
Method cleanerMethod = b.getClass().getMethod("cleaner", new Class[0]);
if(cleanerMethod!=null){
cleanerMethod.setAccessible(true);
Object cleaner = cleanerMethod.invoke(b);
if(cleaner!=null){
Method clearMethod = cleaner.getClass().getMethod("clean", new Class[0]);
if(clearMethod!=null)
clearMethod.invoke(cleaner);
}
}
}
}catch(Exception e){
unmapHackSupported = false;
//TODO exception handling
//Utils.LOG.log(Level.WARNING, "ByteBufferVol Unmap failed", e);
}
}
private static boolean unmapHackSupported = true;
static{
try{
unmapHackSupported =
SerializerPojo.classForName("sun.nio.ch.DirectBuffer")!=null;
}catch(Exception e){
unmapHackSupported = false;
}
}
// Workaround for https://github.com/jankotek/MapDB/issues/326
// File locking after .close() on Windows.
private static boolean windowsWorkaround = System.getProperty("os.name").toLowerCase().startsWith("win");
}
public static final class MappedFileVol extends ByteBufferVol {
protected final File file;
protected final FileChannel fileChannel;
protected final FileChannel.MapMode mapMode;
protected final java.io.RandomAccessFile raf;
public MappedFileVol(File file, boolean readOnly, long sizeLimit, int sliceShift, int sizeIncrement) {
super(readOnly, sizeLimit, sliceShift);
this.file = file;
this.mapMode = readOnly? FileChannel.MapMode.READ_ONLY: FileChannel.MapMode.READ_WRITE;
try {
FileChannelVol.checkFolder(file,readOnly);
this.raf = new java.io.RandomAccessFile(file, readOnly?"r":"rw");
this.fileChannel = raf.getChannel();
final long fileSize = fileChannel.size();
if(fileSize>0){
//map existing data
slices = new ByteBuffer[(int) ((fileSize>>> sliceShift))];
for(int i=0;i< slices.length;i++){
slices[i] = makeNewBuffer(1L*i* sliceSize);
}
}else{
slices = new ByteBuffer[0];
}
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void close() {
growLock.lock();
try{
fileChannel.close();
raf.close();
//TODO not sure if no sync causes problems while unlocking files
//however if it is here, it causes slow commits, sync is called on write-ahead-log just before it is deleted and closed
// if(!readOnly)
// sync();
for(ByteBuffer b: slices){
if(b!=null && (b instanceof MappedByteBuffer)){
unmap((MappedByteBuffer) b);
}
}
slices = null;
} catch (IOException e) {
throw new IOError(e);
}finally{
growLock.unlock();
}
}
@Override
public void sync() {
if(readOnly) return;
growLock.lock();
try{
for(ByteBuffer b: slices){
if(b!=null && (b instanceof MappedByteBuffer)){
MappedByteBuffer bb = ((MappedByteBuffer) b);
bb.force();
}
}
}finally{
growLock.unlock();
}
}
@Override
public int sliceSize() {
return sliceSize;
}
@Override
protected ByteBuffer makeNewBuffer(long offset) {
try {
assert((offset& sliceSizeModMask)==0);
assert(offset>=0);
ByteBuffer ret = fileChannel.map(mapMode,offset, sliceSize);
if(mapMode == FileChannel.MapMode.READ_ONLY) {
ret = ret.asReadOnlyBuffer();
}
return ret;
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void deleteFile() {
file.delete();
}
@Override
public File getFile() {
return file;
}
@Override
public void truncate(long size) {
final int maxSize = 1+(int) (size >>> sliceShift);
if(maxSize== slices.length)
return;
if(maxSize> slices.length) {
ensureAvailable(size);
return;
}
growLock.lock();
try{
if(maxSize>= slices.length)
return;
ByteBuffer[] old = slices;
slices = Arrays.copyOf(slices,maxSize);
//unmap remaining buffers
for(int i=maxSize;i<old.length;i++){
unmap((MappedByteBuffer) old[i]);
old[i] = null;
}
if (ByteBufferVol.windowsWorkaround) {
for(int i=0;i<maxSize;i++){
unmap((MappedByteBuffer) old[i]);
old[i] = null;
}
}
try {
fileChannel.truncate(1L * sliceSize *maxSize);
} catch (IOException e) {
throw new IOError(e);
}
if (ByteBufferVol.windowsWorkaround) {
for(int pos=0;pos<maxSize;pos++) {
slices[pos]=makeNewBuffer(1L* sliceSize *pos);
}
}
}finally {
growLock.unlock();
}
}
}
public static final class MemoryVol extends ByteBufferVol {
protected final boolean useDirectBuffer;
@Override
public String toString() {
return super.toString()+",direct="+useDirectBuffer;
}
public MemoryVol(final boolean useDirectBuffer, final long sizeLimit, final int sliceShift) {
super(false,sizeLimit, sliceShift);
this.useDirectBuffer = useDirectBuffer;
}
@Override
protected ByteBuffer makeNewBuffer(long offset) {
return useDirectBuffer?
ByteBuffer.allocateDirect(sliceSize):
ByteBuffer.allocate(sliceSize);
}
@Override
public void truncate(long size) {
final int maxSize = 1+(int) (size >>> sliceShift);
if(maxSize== slices.length)
return;
if(maxSize> slices.length) {
ensureAvailable(size);
return;
}
growLock.lock();
try{
if(maxSize>= slices.length)
return;
ByteBuffer[] old = slices;
slices = Arrays.copyOf(slices,maxSize);
//unmap remaining buffers
for(int i=maxSize;i<old.length;i++){
if(old[i] instanceof MappedByteBuffer)
unmap((MappedByteBuffer) old[i]);
old[i] = null;
}
}finally {
growLock.unlock();
}
}
@Override public void close() {
growLock.lock();
try{
for(ByteBuffer b: slices){
if(b!=null && (b instanceof MappedByteBuffer)){
unmap((MappedByteBuffer)b);
}
}
slices = null;
}finally{
growLock.unlock();
}
}
@Override public void sync() {}
@Override public void deleteFile() {}
@Override
public File getFile() {
return null;
}
}
/**
* Volume which uses FileChannel.
* Uses global lock and does not use mapped memory.
*/
public static final class FileChannelVol extends Volume {
protected final File file;
protected final int sliceSize;
protected RandomAccessFile raf;
protected FileChannel channel;
protected final boolean readOnly;
protected final long sizeLimit;
protected final boolean hasLimit;
protected volatile long size;
protected final Object growLock = new Object();
public FileChannelVol(File file, boolean readOnly, long sizeLimit, int sliceShift, int sizeIncrement){
this.file = file;
this.readOnly = readOnly;
this.sizeLimit = sizeLimit;
this.hasLimit = sizeLimit>0;
this.sliceSize = 1<<sliceShift;
try {
checkFolder(file,readOnly);
if(readOnly && !file.exists()){
raf = null;
channel = null;
size = 0;
}else {
raf = new RandomAccessFile(file, readOnly ? "r" : "rw");
channel = raf.getChannel();
size = channel.size();
}
} catch (IOException e) {
throw new IOError(e);
}
}
protected static void checkFolder(File file, boolean readOnly) throws IOException {
File parent = file.getParentFile();
if(parent == null) {
parent = file.getCanonicalFile().getParentFile();
}
if (parent == null) {
throw new IOException("Parent folder could not be determined for: "+file);
}
if(!parent.exists() || !parent.isDirectory())
throw new IOException("Parent folder does not exist: "+file);
if(!parent.canRead())
throw new IOException("Parent folder is not readable: "+file);
if(!readOnly && !parent.canWrite())
throw new IOException("Parent folder is not writable: "+file);
}
@Override
public boolean tryAvailable(long offset) {
if(hasLimit && offset>sizeLimit) return false;
if(offset% sliceSize !=0)
offset += sliceSize - offset% sliceSize; //round up to multiply of slice size
if(offset>size)synchronized (growLock){
try {
channel.truncate(offset);
size = offset;
} catch (IOException e) {
throw new IOError(e);
}
}
return true;
}
@Override
public void truncate(long size) {
synchronized (growLock){
try {
this.size = size;
channel.truncate(size);
} catch (IOException e) {
throw new IOError(e);
}
}
}
protected void writeFully(long offset, ByteBuffer buf) throws IOException {
int remaining = buf.limit()-buf.position();
while(remaining>0){
int write = channel.write(buf, offset);
if(write<0) throw new EOFException();
remaining-=write;
}
}
@Override
public final void putSixLong(long offset, long value) {
assert(value>=0 && (value>>>6*8)==0): "value does not fit";
try{
ByteBuffer buf = ByteBuffer.allocate(6);
buf.put(0, (byte) (0xff & (value >> 40)));
buf.put(1, (byte) (0xff & (value >> 32)));
buf.put(2, (byte) (0xff & (value >> 24)));
buf.put(3, (byte) (0xff & (value >> 16)));
buf.put(4, (byte) (0xff & (value >> 8)));
buf.put(5, (byte) (0xff & (value >> 0)));
writeFully(offset, buf);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void putLong(long offset, long value) {
try{
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putLong(0, value);
writeFully(offset, buf);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void putInt(long offset, int value) {
try{
ByteBuffer buf = ByteBuffer.allocate(4);
buf.putInt(0, value);
writeFully(offset, buf);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void putByte(long offset, byte value) {
try{
ByteBuffer buf = ByteBuffer.allocate(1);
buf.put(0, value);
writeFully(offset, buf);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void putData(long offset, byte[] src, int srcPos, int srcSize) {
try{
ByteBuffer buf = ByteBuffer.wrap(src,srcPos, srcSize);
writeFully(offset, buf);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void putData(long offset, ByteBuffer buf) {
try{
writeFully(offset,buf);
}catch(IOException e){
throw new IOError(e);
}
}
protected void readFully(long offset, ByteBuffer buf) throws IOException {
int remaining = buf.limit()-buf.position();
while(remaining>0){
int read = channel.read(buf, offset);
if(read<0) throw new EOFException();
remaining-=read;
}
}
@Override
public final long getSixLong(long offset) {
try{
ByteBuffer buf = ByteBuffer.allocate(6);
readFully(offset,buf);
return ((long) (buf.get(0) & 0xff) << 40) |
((long) (buf.get(1) & 0xff) << 32) |
((long) (buf.get(2) & 0xff) << 24) |
((long) (buf.get(3) & 0xff) << 16) |
((long) (buf.get(4) & 0xff) << 8) |
((long) (buf.get(5) & 0xff) << 0);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public long getLong(long offset) {
try{
ByteBuffer buf = ByteBuffer.allocate(8);
readFully(offset,buf);
return buf.getLong(0);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public int getInt(long offset) {
try{
ByteBuffer buf = ByteBuffer.allocate(4);
readFully(offset,buf);
return buf.getInt(0);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public byte getByte(long offset) {
try{
ByteBuffer buf = ByteBuffer.allocate(1);
readFully(offset,buf);
return buf.get(0);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public DataInput2 getDataInput(long offset, int size) {
try{
ByteBuffer buf = ByteBuffer.allocate(size);
readFully(offset,buf);
return new DataInput2(buf,0);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void close() {
try{
if(channel!=null)
channel.close();
channel = null;
if (raf != null)
raf.close();
raf = null;
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public void sync() {
try{
channel.force(true);
}catch(IOException e){
throw new IOError(e);
}
}
@Override
public boolean isEmpty() {
try {
return channel==null || channel.size()==0;
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void deleteFile() {
file.delete();
}
@Override
public int sliceSize() {
return -1;
}
@Override
public boolean isSliced() {
return false;
}
@Override
public File getFile() {
return file;
}
}
/** transfer data from one volume to second. Second volume will be expanded if needed*/
public static void volumeTransfer(long size, Volume from, Volume to){
int bufSize = Math.min(from.sliceSize(),to.sliceSize());
if(bufSize<0 || bufSize>1024*1024*128){
bufSize = 64 * 1024; //something strange, set safe limit
}
to.ensureAvailable(size);
for(long offset=0;offset<size;offset+=bufSize){
int bb = (int) Math.min(bufSize, size-offset);
from.transferInto(offset,to,offset,bb);
}
}
public static final class ByteArrayVol extends Volume{
protected final ReentrantLock growLock = new ReentrantLock(CC.FAIR_LOCKS);
protected final long sizeLimit;
protected final boolean hasLimit;
protected final int sliceShift;