1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.internal.storage.dfs;
12
13 import static org.eclipse.jgit.internal.storage.pack.PackExt.REFTABLE;
14
15 import java.io.IOException;
16 import java.nio.ByteBuffer;
17
18 import org.eclipse.jgit.internal.storage.io.BlockSource;
19 import org.eclipse.jgit.internal.storage.reftable.ReftableReader;
20
21
22
23
24 public class DfsReftable extends BlockBasedFile {
25
26
27
28
29
30
31 public DfsReftable(DfsPackDescription desc) {
32 this(DfsBlockCache.getInstance(), desc);
33 }
34
35
36
37
38
39
40
41
42
43 public DfsReftable(DfsBlockCache cache, DfsPackDescription desc) {
44 super(cache, desc, REFTABLE);
45
46 int bs = desc.getBlockSize(REFTABLE);
47 if (bs > 0) {
48 setBlockSize(bs);
49 }
50
51 long sz = desc.getFileSize(REFTABLE);
52 length = sz > 0 ? sz : -1;
53 }
54
55
56
57
58
59
60 public DfsPackDescription getPackDescription() {
61 return desc;
62 }
63
64
65
66
67
68
69
70
71
72
73
74
75 public ReftableReader open(DfsReader ctx) throws IOException {
76 return new ReftableReader(new CacheSource(this, cache, ctx));
77 }
78
79 private static final class CacheSource extends BlockSource {
80 private final DfsReftable file;
81 private final DfsBlockCache cache;
82 private final DfsReader ctx;
83 private ReadableChannel ch;
84 private int readAhead;
85
86 CacheSource(DfsReftable file, DfsBlockCache cache, DfsReader ctx) {
87 this.file = file;
88 this.cache = cache;
89 this.ctx = ctx;
90 }
91
92 @Override
93 public ByteBuffer read(long pos, int cnt) throws IOException {
94 if (ch == null && readAhead > 0 && notInCache(pos)) {
95 open().setReadAheadBytes(readAhead);
96 }
97
98 DfsBlock block = cache.getOrLoad(file, pos, ctx, () -> open());
99 if (block.start == pos && block.size() >= cnt) {
100 return block.zeroCopyByteBuffer(cnt);
101 }
102
103 byte[] dst = new byte[cnt];
104 ByteBuffer buf = ByteBuffer.wrap(dst);
105 buf.position(ctx.copy(file, pos, dst, 0, cnt));
106 return buf;
107 }
108
109 private boolean notInCache(long pos) {
110 return cache.get(file.key, file.alignToBlock(pos)) == null;
111 }
112
113 @Override
114 public long size() throws IOException {
115 long n = file.length;
116 if (n < 0) {
117 n = open().size();
118 file.length = n;
119 }
120 return n;
121 }
122
123 @Override
124 public void adviseSequentialRead(long start, long end) {
125 int sz = ctx.getOptions().getStreamPackBufferSize();
126 if (sz > 0) {
127 readAhead = (int) Math.min(sz, end - start);
128 }
129 }
130
131 private ReadableChannel open() throws IOException {
132 if (ch == null) {
133 ch = ctx.db.openFile(file.desc, file.ext);
134 }
135 return ch;
136 }
137
138 @Override
139 public void close() {
140 if (ch != null) {
141 try {
142 ch.close();
143 } catch (IOException e) {
144
145 } finally {
146 ch = null;
147 }
148 }
149 }
150 }
151 }