RuneHive-Tarnish
Neural OSRS Enhancement Framework
Loading...
Searching...
No Matches
Cache.java
1package com.osroyale.fs.cache;
2
3import com.google.common.base.Preconditions;
4
5import java.io.IOException;
6import java.nio.ByteBuffer;
7import java.nio.channels.SeekableByteChannel;
8
41
42public final class Cache {
43
48 public static final int INDEX_SIZE = 6;
49
54 public static final int SECTOR_HEADER_SIZE = 8;
55
60 public static final int SECTOR_SIZE = 520;
61
69 private final ByteBuffer buffer = ByteBuffer.allocate(SECTOR_SIZE);
70
75 private final SeekableByteChannel sectorChannel;
76
81 private final SeekableByteChannel indexChannel;
82
86 private final int id;
87
95 protected Cache(SeekableByteChannel sectorChannel, SeekableByteChannel indexChannel, int id) {
96 this.sectorChannel = sectorChannel;
97 this.indexChannel = indexChannel;
98 this.id = ++id;
99 }
100
109 public ByteBuffer get(final int indexId) throws IOException {
110 final Index index = readIndex(indexId);
111 if (!index.check()) {
112 return null;
113 }
114
115 long position = (long) index.getId() * SECTOR_HEADER_SIZE;
116
117 Preconditions.checkArgument(sectorChannel.size() >= position + SECTOR_SIZE);
118
119 byte[] data = new byte[index.getLength()];
120 int next = index.getId();
121 int offset = 0;
122
123 for (int chunk = 0; offset < index.getLength(); chunk++) {
124 int read = Math.min(index.getLength() - offset, 512);
125
126 Sector sector = readSector(next, data, offset, read);
127 sector.check(id, indexId, chunk);
128
129 next = sector.getNextIndexId();
130 offset += read;
131 }
132
133 return ByteBuffer.wrap(data);
134 }
135
143 private Index readIndex(int indexId) throws IOException {
144 long position = (long) indexId * INDEX_SIZE;
145
146 buffer.clear().limit(INDEX_SIZE);
147 indexChannel.position(position);
148 indexChannel.read(buffer);
149 buffer.flip();
150
151 return Index.decode(buffer);
152 }
153
164 private Sector readSector(int sectorId, byte[] data, int offset, int length) throws IOException {
165 long position = (long) sectorId * SECTOR_SIZE;
166
167 buffer.clear().limit(length + SECTOR_HEADER_SIZE);
168 sectorChannel.position(position);
169 sectorChannel.read(buffer);
170 buffer.flip();
171
172 return Sector.decode(buffer, data, offset, length);
173 }
174
175}
static final int SECTOR_HEADER_SIZE
Definition Cache.java:54
Cache(SeekableByteChannel sectorChannel, SeekableByteChannel indexChannel, int id)
Definition Cache.java:95
static final int SECTOR_SIZE
Definition Cache.java:60
static final int INDEX_SIZE
Definition Cache.java:48
static Index decode(ByteBuffer buffer)
Definition Index.java:71
void check(int cacheId, int indexId, int chunk)
Definition Sector.java:103