You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackInserter.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. /*
  2. * Copyright (C) 2017, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.file;
  44. import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
  45. import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH;
  46. import static org.eclipse.jgit.lib.Constants.OBJ_OFS_DELTA;
  47. import static org.eclipse.jgit.lib.Constants.OBJ_REF_DELTA;
  48. import java.io.BufferedInputStream;
  49. import java.io.EOFException;
  50. import java.io.File;
  51. import java.io.FileOutputStream;
  52. import java.io.FilterInputStream;
  53. import java.io.IOException;
  54. import java.io.InputStream;
  55. import java.io.OutputStream;
  56. import java.io.RandomAccessFile;
  57. import java.nio.channels.Channels;
  58. import java.text.MessageFormat;
  59. import java.util.Collection;
  60. import java.util.Collections;
  61. import java.util.HashSet;
  62. import java.util.List;
  63. import java.util.Set;
  64. import java.util.zip.CRC32;
  65. import java.util.zip.DataFormatException;
  66. import java.util.zip.Deflater;
  67. import java.util.zip.DeflaterOutputStream;
  68. import java.util.zip.Inflater;
  69. import java.util.zip.InflaterInputStream;
  70. import org.eclipse.jgit.errors.CorruptObjectException;
  71. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  72. import org.eclipse.jgit.errors.LargeObjectException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.internal.JGitText;
  75. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  76. import org.eclipse.jgit.lib.AnyObjectId;
  77. import org.eclipse.jgit.lib.Constants;
  78. import org.eclipse.jgit.lib.InflaterCache;
  79. import org.eclipse.jgit.lib.ObjectId;
  80. import org.eclipse.jgit.lib.ObjectIdOwnerMap;
  81. import org.eclipse.jgit.lib.ObjectInserter;
  82. import org.eclipse.jgit.lib.ObjectLoader;
  83. import org.eclipse.jgit.lib.ObjectReader;
  84. import org.eclipse.jgit.lib.ObjectStream;
  85. import org.eclipse.jgit.transport.PackParser;
  86. import org.eclipse.jgit.transport.PackedObjectInfo;
  87. import org.eclipse.jgit.util.BlockList;
  88. import org.eclipse.jgit.util.FileUtils;
  89. import org.eclipse.jgit.util.IO;
  90. import org.eclipse.jgit.util.NB;
  91. import org.eclipse.jgit.util.io.CountingOutputStream;
  92. import org.eclipse.jgit.util.sha1.SHA1;
  93. /**
  94. * Object inserter that inserts one pack per call to {@link #flush()}, and never
  95. * inserts loose objects.
  96. */
  97. class PackInserter extends ObjectInserter {
  98. /** Always produce version 2 indexes, to get CRC data. */
  99. private static final int INDEX_VERSION = 2;
  100. private final ObjectDirectory db;
  101. private List<PackedObjectInfo> objectList;
  102. private ObjectIdOwnerMap<PackedObjectInfo> objectMap;
  103. private boolean rollback;
  104. private boolean checkExisting = true;
  105. private int compression = Deflater.BEST_COMPRESSION;
  106. private File tmpPack;
  107. private PackStream packOut;
  108. private Inflater cachedInflater;
  109. PackInserter(ObjectDirectory db) {
  110. this.db = db;
  111. }
  112. /**
  113. * Whether to check if objects exist in the repo
  114. *
  115. * @param check
  116. * if {@code false}, will write out possibly-duplicate objects
  117. * without first checking whether they exist in the repo; default
  118. * is true.
  119. */
  120. public void checkExisting(boolean check) {
  121. checkExisting = check;
  122. }
  123. /**
  124. * Set compression level for zlib deflater.
  125. *
  126. * @param compression
  127. * compression level for zlib deflater.
  128. */
  129. public void setCompressionLevel(int compression) {
  130. this.compression = compression;
  131. }
  132. int getBufferSize() {
  133. return buffer().length;
  134. }
  135. /** {@inheritDoc} */
  136. @Override
  137. public ObjectId insert(int type, byte[] data, int off, int len)
  138. throws IOException {
  139. ObjectId id = idFor(type, data, off, len);
  140. if (objectMap != null && objectMap.contains(id)) {
  141. return id;
  142. }
  143. // Ignore loose objects, which are potentially unreachable.
  144. if (checkExisting && db.hasPackedObject(id)) {
  145. return id;
  146. }
  147. long offset = beginObject(type, len);
  148. packOut.compress.write(data, off, len);
  149. packOut.compress.finish();
  150. return endObject(id, offset);
  151. }
  152. /** {@inheritDoc} */
  153. @Override
  154. public ObjectId insert(int type, long len, InputStream in)
  155. throws IOException {
  156. byte[] buf = buffer();
  157. if (len <= buf.length) {
  158. IO.readFully(in, buf, 0, (int) len);
  159. return insert(type, buf, 0, (int) len);
  160. }
  161. long offset = beginObject(type, len);
  162. SHA1 md = digest();
  163. md.update(Constants.encodedTypeString(type));
  164. md.update((byte) ' ');
  165. md.update(Constants.encodeASCII(len));
  166. md.update((byte) 0);
  167. while (0 < len) {
  168. int n = in.read(buf, 0, (int) Math.min(buf.length, len));
  169. if (n <= 0) {
  170. throw new EOFException();
  171. }
  172. md.update(buf, 0, n);
  173. packOut.compress.write(buf, 0, n);
  174. len -= n;
  175. }
  176. packOut.compress.finish();
  177. return endObject(md.toObjectId(), offset);
  178. }
  179. private long beginObject(int type, long len) throws IOException {
  180. if (packOut == null) {
  181. beginPack();
  182. }
  183. long offset = packOut.getOffset();
  184. packOut.beginObject(type, len);
  185. return offset;
  186. }
  187. private ObjectId endObject(ObjectId id, long offset) {
  188. PackedObjectInfo obj = new PackedObjectInfo(id);
  189. obj.setOffset(offset);
  190. obj.setCRC((int) packOut.crc32.getValue());
  191. objectList.add(obj);
  192. objectMap.addIfAbsent(obj);
  193. return id;
  194. }
  195. private static File idxFor(File packFile) {
  196. String p = packFile.getName();
  197. return new File(
  198. packFile.getParentFile(),
  199. p.substring(0, p.lastIndexOf('.')) + ".idx"); //$NON-NLS-1$
  200. }
  201. private void beginPack() throws IOException {
  202. objectList = new BlockList<>();
  203. objectMap = new ObjectIdOwnerMap<>();
  204. rollback = true;
  205. tmpPack = File.createTempFile("insert_", ".pack", db.getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
  206. packOut = new PackStream(tmpPack);
  207. // Write the header as though it were a single object pack.
  208. packOut.write(packOut.hdrBuf, 0, writePackHeader(packOut.hdrBuf, 1));
  209. }
  210. private static int writePackHeader(byte[] buf, int objectCount) {
  211. System.arraycopy(Constants.PACK_SIGNATURE, 0, buf, 0, 4);
  212. NB.encodeInt32(buf, 4, 2); // Always use pack version 2.
  213. NB.encodeInt32(buf, 8, objectCount);
  214. return 12;
  215. }
  216. /** {@inheritDoc} */
  217. @Override
  218. public PackParser newPackParser(InputStream in) {
  219. throw new UnsupportedOperationException();
  220. }
  221. /** {@inheritDoc} */
  222. @Override
  223. public ObjectReader newReader() {
  224. return new Reader();
  225. }
  226. /** {@inheritDoc} */
  227. @Override
  228. public void flush() throws IOException {
  229. if (tmpPack == null) {
  230. return;
  231. }
  232. if (packOut == null) {
  233. throw new IOException();
  234. }
  235. byte[] packHash;
  236. try {
  237. packHash = packOut.finishPack();
  238. } finally {
  239. packOut = null;
  240. }
  241. Collections.sort(objectList);
  242. File tmpIdx = idxFor(tmpPack);
  243. writePackIndex(tmpIdx, packHash, objectList);
  244. File realPack = new File(db.getPackDirectory(),
  245. "pack-" + computeName(objectList).name() + ".pack"); //$NON-NLS-1$ //$NON-NLS-2$
  246. db.closeAllPackHandles(realPack);
  247. tmpPack.setReadOnly();
  248. FileUtils.rename(tmpPack, realPack, ATOMIC_MOVE);
  249. File realIdx = idxFor(realPack);
  250. tmpIdx.setReadOnly();
  251. try {
  252. FileUtils.rename(tmpIdx, realIdx, ATOMIC_MOVE);
  253. } catch (IOException e) {
  254. File newIdx = new File(
  255. realIdx.getParentFile(), realIdx.getName() + ".new"); //$NON-NLS-1$
  256. try {
  257. FileUtils.rename(tmpIdx, newIdx, ATOMIC_MOVE);
  258. } catch (IOException e2) {
  259. newIdx = tmpIdx;
  260. e = e2;
  261. }
  262. throw new IOException(MessageFormat.format(
  263. JGitText.get().panicCantRenameIndexFile, newIdx,
  264. realIdx), e);
  265. }
  266. db.openPack(realPack);
  267. rollback = false;
  268. clear();
  269. }
  270. private static void writePackIndex(File idx, byte[] packHash,
  271. List<PackedObjectInfo> list) throws IOException {
  272. try (OutputStream os = new FileOutputStream(idx)) {
  273. PackIndexWriter w = PackIndexWriter.createVersion(os, INDEX_VERSION);
  274. w.write(list, packHash);
  275. }
  276. }
  277. private ObjectId computeName(List<PackedObjectInfo> list) {
  278. SHA1 md = digest().reset();
  279. byte[] buf = buffer();
  280. for (PackedObjectInfo otp : list) {
  281. otp.copyRawTo(buf, 0);
  282. md.update(buf, 0, OBJECT_ID_LENGTH);
  283. }
  284. return ObjectId.fromRaw(md.digest());
  285. }
  286. /** {@inheritDoc} */
  287. @Override
  288. public void close() {
  289. try {
  290. if (packOut != null) {
  291. try {
  292. packOut.close();
  293. } catch (IOException err) {
  294. // Ignore a close failure, the pack should be removed.
  295. }
  296. }
  297. if (rollback && tmpPack != null) {
  298. try {
  299. FileUtils.delete(tmpPack);
  300. } catch (IOException e) {
  301. // Still delete idx.
  302. }
  303. try {
  304. FileUtils.delete(idxFor(tmpPack));
  305. } catch (IOException e) {
  306. // Ignore error deleting temp idx.
  307. }
  308. rollback = false;
  309. }
  310. } finally {
  311. clear();
  312. try {
  313. InflaterCache.release(cachedInflater);
  314. } finally {
  315. cachedInflater = null;
  316. }
  317. }
  318. }
  319. private void clear() {
  320. objectList = null;
  321. objectMap = null;
  322. tmpPack = null;
  323. packOut = null;
  324. }
  325. private Inflater inflater() {
  326. if (cachedInflater == null) {
  327. cachedInflater = InflaterCache.get();
  328. } else {
  329. cachedInflater.reset();
  330. }
  331. return cachedInflater;
  332. }
  333. /**
  334. * Stream that writes to a pack file.
  335. * <p>
  336. * Backed by two views of the same open file descriptor: a random-access file,
  337. * and an output stream. Seeking in the file causes subsequent writes to the
  338. * output stream to occur wherever the file pointer is pointing, so we need to
  339. * take care to always seek to the end of the file before writing a new
  340. * object.
  341. * <p>
  342. * Callers should always use {@link #seek(long)} to seek, rather than reaching
  343. * into the file member. As long as this contract is followed, calls to {@link
  344. * #write(byte[], int, int)} are guaranteed to write at the end of the file,
  345. * even if there have been intermediate seeks.
  346. */
  347. private class PackStream extends OutputStream {
  348. final byte[] hdrBuf;
  349. final CRC32 crc32;
  350. final DeflaterOutputStream compress;
  351. private final RandomAccessFile file;
  352. private final CountingOutputStream out;
  353. private final Deflater deflater;
  354. private boolean atEnd;
  355. PackStream(File pack) throws IOException {
  356. file = new RandomAccessFile(pack, "rw"); //$NON-NLS-1$
  357. out = new CountingOutputStream(new FileOutputStream(file.getFD()));
  358. deflater = new Deflater(compression);
  359. compress = new DeflaterOutputStream(this, deflater, 8192);
  360. hdrBuf = new byte[32];
  361. crc32 = new CRC32();
  362. atEnd = true;
  363. }
  364. long getOffset() {
  365. // This value is accurate as long as we only ever write to the end of the
  366. // file, and don't seek back to overwrite any previous segments. Although
  367. // this is subtle, storing the stream counter this way is still preferable
  368. // to returning file.length() here, as it avoids a syscall and possible
  369. // IOException.
  370. return out.getCount();
  371. }
  372. void seek(long offset) throws IOException {
  373. file.seek(offset);
  374. atEnd = false;
  375. }
  376. void beginObject(int objectType, long length) throws IOException {
  377. crc32.reset();
  378. deflater.reset();
  379. write(hdrBuf, 0, encodeTypeSize(objectType, length));
  380. }
  381. private int encodeTypeSize(int type, long rawLength) {
  382. long nextLength = rawLength >>> 4;
  383. hdrBuf[0] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (type << 4) | (rawLength & 0x0F));
  384. rawLength = nextLength;
  385. int n = 1;
  386. while (rawLength > 0) {
  387. nextLength >>>= 7;
  388. hdrBuf[n++] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (rawLength & 0x7F));
  389. rawLength = nextLength;
  390. }
  391. return n;
  392. }
  393. @Override
  394. public void write(final int b) throws IOException {
  395. hdrBuf[0] = (byte) b;
  396. write(hdrBuf, 0, 1);
  397. }
  398. @Override
  399. public void write(byte[] data, int off, int len) throws IOException {
  400. crc32.update(data, off, len);
  401. if (!atEnd) {
  402. file.seek(file.length());
  403. atEnd = true;
  404. }
  405. out.write(data, off, len);
  406. }
  407. byte[] finishPack() throws IOException {
  408. // Overwrite placeholder header with actual object count, then hash. This
  409. // method intentionally uses direct seek/write calls rather than the
  410. // wrappers which keep track of atEnd. This leaves atEnd, the file
  411. // pointer, and out's counter in an inconsistent state; that's ok, since
  412. // this method closes the file anyway.
  413. try {
  414. file.seek(0);
  415. out.write(hdrBuf, 0, writePackHeader(hdrBuf, objectList.size()));
  416. byte[] buf = buffer();
  417. SHA1 md = digest().reset();
  418. file.seek(0);
  419. while (true) {
  420. int r = file.read(buf);
  421. if (r < 0) {
  422. break;
  423. }
  424. md.update(buf, 0, r);
  425. }
  426. byte[] packHash = md.digest();
  427. out.write(packHash, 0, packHash.length);
  428. return packHash;
  429. } finally {
  430. close();
  431. }
  432. }
  433. @Override
  434. public void close() throws IOException {
  435. deflater.end();
  436. try {
  437. out.close();
  438. } finally {
  439. file.close();
  440. }
  441. }
  442. byte[] inflate(long filePos, int len) throws IOException, DataFormatException {
  443. byte[] dstbuf;
  444. try {
  445. dstbuf = new byte[len];
  446. } catch (OutOfMemoryError noMemory) {
  447. return null; // Caller will switch to large object streaming.
  448. }
  449. byte[] srcbuf = buffer();
  450. Inflater inf = inflater();
  451. filePos += setInput(filePos, inf, srcbuf);
  452. for (int dstoff = 0;;) {
  453. int n = inf.inflate(dstbuf, dstoff, dstbuf.length - dstoff);
  454. dstoff += n;
  455. if (inf.finished()) {
  456. return dstbuf;
  457. }
  458. if (inf.needsInput()) {
  459. filePos += setInput(filePos, inf, srcbuf);
  460. } else if (n == 0) {
  461. throw new DataFormatException();
  462. }
  463. }
  464. }
  465. private int setInput(long filePos, Inflater inf, byte[] buf)
  466. throws IOException {
  467. if (file.getFilePointer() != filePos) {
  468. seek(filePos);
  469. }
  470. int n = file.read(buf);
  471. if (n < 0) {
  472. throw new EOFException(JGitText.get().unexpectedEofInPack);
  473. }
  474. inf.setInput(buf, 0, n);
  475. return n;
  476. }
  477. }
  478. private class Reader extends ObjectReader {
  479. private final ObjectReader ctx;
  480. private Reader() {
  481. ctx = db.newReader();
  482. setStreamFileThreshold(ctx.getStreamFileThreshold());
  483. }
  484. @Override
  485. public ObjectReader newReader() {
  486. return db.newReader();
  487. }
  488. @Override
  489. public ObjectInserter getCreatedFromInserter() {
  490. return PackInserter.this;
  491. }
  492. @Override
  493. public Collection<ObjectId> resolve(AbbreviatedObjectId id)
  494. throws IOException {
  495. Collection<ObjectId> stored = ctx.resolve(id);
  496. if (objectList == null) {
  497. return stored;
  498. }
  499. Set<ObjectId> r = new HashSet<>(stored.size() + 2);
  500. r.addAll(stored);
  501. for (PackedObjectInfo obj : objectList) {
  502. if (id.prefixCompare(obj) == 0) {
  503. r.add(obj.copy());
  504. }
  505. }
  506. return r;
  507. }
  508. @Override
  509. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  510. throws MissingObjectException, IncorrectObjectTypeException,
  511. IOException {
  512. if (objectMap == null) {
  513. return ctx.open(objectId, typeHint);
  514. }
  515. PackedObjectInfo obj = objectMap.get(objectId);
  516. if (obj == null) {
  517. return ctx.open(objectId, typeHint);
  518. }
  519. byte[] buf = buffer();
  520. packOut.seek(obj.getOffset());
  521. int cnt = packOut.file.read(buf, 0, 20);
  522. if (cnt <= 0) {
  523. throw new EOFException(JGitText.get().unexpectedEofInPack);
  524. }
  525. int c = buf[0] & 0xff;
  526. int type = (c >> 4) & 7;
  527. if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
  528. throw new IOException(MessageFormat.format(
  529. JGitText.get().cannotReadBackDelta, Integer.toString(type)));
  530. }
  531. if (typeHint != OBJ_ANY && type != typeHint) {
  532. throw new IncorrectObjectTypeException(objectId.copy(), typeHint);
  533. }
  534. long sz = c & 0x0f;
  535. int ptr = 1;
  536. int shift = 4;
  537. while ((c & 0x80) != 0) {
  538. if (ptr >= cnt) {
  539. throw new EOFException(JGitText.get().unexpectedEofInPack);
  540. }
  541. c = buf[ptr++] & 0xff;
  542. sz += ((long) (c & 0x7f)) << shift;
  543. shift += 7;
  544. }
  545. long zpos = obj.getOffset() + ptr;
  546. if (sz < getStreamFileThreshold()) {
  547. byte[] data = inflate(obj, zpos, (int) sz);
  548. if (data != null) {
  549. return new ObjectLoader.SmallObject(type, data);
  550. }
  551. }
  552. return new StreamLoader(type, sz, zpos);
  553. }
  554. private byte[] inflate(PackedObjectInfo obj, long zpos, int sz)
  555. throws IOException, CorruptObjectException {
  556. try {
  557. return packOut.inflate(zpos, sz);
  558. } catch (DataFormatException dfe) {
  559. throw new CorruptObjectException(
  560. MessageFormat.format(
  561. JGitText.get().objectAtHasBadZlibStream,
  562. Long.valueOf(obj.getOffset()),
  563. tmpPack.getAbsolutePath()),
  564. dfe);
  565. }
  566. }
  567. @Override
  568. public Set<ObjectId> getShallowCommits() throws IOException {
  569. return ctx.getShallowCommits();
  570. }
  571. @Override
  572. public void close() {
  573. ctx.close();
  574. }
  575. private class StreamLoader extends ObjectLoader {
  576. private final int type;
  577. private final long size;
  578. private final long pos;
  579. StreamLoader(int type, long size, long pos) {
  580. this.type = type;
  581. this.size = size;
  582. this.pos = pos;
  583. }
  584. @Override
  585. public ObjectStream openStream()
  586. throws MissingObjectException, IOException {
  587. int bufsz = buffer().length;
  588. packOut.seek(pos);
  589. InputStream fileStream = new FilterInputStream(
  590. Channels.newInputStream(packOut.file.getChannel())) {
  591. // atEnd was already set to false by the previous seek, but it's
  592. // technically possible for a caller to call insert on the
  593. // inserter in the middle of reading from this stream. Behavior is
  594. // undefined in this case, so it would arguably be ok to ignore,
  595. // but it's not hard to at least make an attempt to not corrupt
  596. // the data.
  597. @Override
  598. public int read() throws IOException {
  599. packOut.atEnd = false;
  600. return super.read();
  601. }
  602. @Override
  603. public int read(byte[] b) throws IOException {
  604. packOut.atEnd = false;
  605. return super.read(b);
  606. }
  607. @Override
  608. public int read(byte[] b, int off, int len) throws IOException {
  609. packOut.atEnd = false;
  610. return super.read(b,off,len);
  611. }
  612. @Override
  613. public void close() {
  614. // Never close underlying RandomAccessFile, which lasts the
  615. // lifetime of the enclosing PackStream.
  616. }
  617. };
  618. return new ObjectStream.Filter(
  619. type, size,
  620. new BufferedInputStream(
  621. new InflaterInputStream(fileStream, inflater(), bufsz), bufsz));
  622. }
  623. @Override
  624. public int getType() {
  625. return type;
  626. }
  627. @Override
  628. public long getSize() {
  629. return size;
  630. }
  631. @Override
  632. public byte[] getCachedBytes() throws LargeObjectException {
  633. throw new LargeObjectException.ExceedsLimit(
  634. getStreamFileThreshold(), size);
  635. }
  636. }
  637. }
  638. }