69 private final ByteBuffer buffer = ByteBuffer.allocate(
SECTOR_SIZE);
75 private final SeekableByteChannel sectorChannel;
81 private final SeekableByteChannel indexChannel;
95 protected Cache(SeekableByteChannel sectorChannel, SeekableByteChannel indexChannel,
int id) {
96 this.sectorChannel = sectorChannel;
97 this.indexChannel = indexChannel;
109 public ByteBuffer
get(
final int indexId)
throws IOException {
110 final Index index = readIndex(indexId);
111 if (!index.
check()) {
117 Preconditions.checkArgument(sectorChannel.size() >= position +
SECTOR_SIZE);
119 byte[] data =
new byte[index.
getLength()];
120 int next = index.
getId();
123 for (
int chunk = 0; offset < index.
getLength(); chunk++) {
124 int read = Math.min(index.
getLength() - offset, 512);
126 Sector sector = readSector(next, data, offset, read);
127 sector.
check(
id, indexId, chunk);
133 return ByteBuffer.wrap(data);
143 private Index readIndex(
int indexId)
throws IOException {
147 indexChannel.position(position);
148 indexChannel.read(buffer);
164 private Sector readSector(
int sectorId,
byte[] data,
int offset,
int length)
throws IOException {
168 sectorChannel.position(position);
169 sectorChannel.read(buffer);
172 return Sector.decode(buffer, data, offset, length);