PackInputStream.java

  1. /*
  2.  * Copyright (C) 2010, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.internal.storage.file;

  11. import java.io.IOException;
  12. import java.io.InputStream;

  13. class PackInputStream extends InputStream {
  14.     private final WindowCursor wc;

  15.     private final Pack pack;

  16.     private long pos;

  17.     PackInputStream(Pack pack, long pos, WindowCursor wc)
  18.             throws IOException {
  19.         this.pack = pack;
  20.         this.pos = pos;
  21.         this.wc = wc;

  22.         // Pin the first window, to ensure the pack is open and valid.
  23.         //
  24.         wc.pin(pack, pos);
  25.     }

  26.     /** {@inheritDoc} */
  27.     @Override
  28.     public int read(byte[] b, int off, int len) throws IOException {
  29.         int n = wc.copy(pack, pos, b, off, len);
  30.         pos += n;
  31.         return n;
  32.     }

  33.     /** {@inheritDoc} */
  34.     @Override
  35.     public int read() throws IOException {
  36.         byte[] buf = new byte[1];
  37.         int n = read(buf, 0, 1);
  38.         return n == 1 ? buf[0] & 0xff : -1;
  39.     }

  40.     /** {@inheritDoc} */
  41.     @Override
  42.     public void close() {
  43.         wc.close();
  44.     }
  45. }