ByteBufferWindow.java

  1. /*
  2.  * Copyright (C) 2008-2009, Google Inc.
  3.  * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
  4.  * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org> and others
  5.  *
  6.  * This program and the accompanying materials are made available under the
  7.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  8.  * https://www.eclipse.org/org/documents/edl-v10.php.
  9.  *
  10.  * SPDX-License-Identifier: BSD-3-Clause
  11.  */

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

  13. import java.io.IOException;
  14. import java.nio.ByteBuffer;
  15. import java.util.zip.DataFormatException;
  16. import java.util.zip.Inflater;

  17. import org.eclipse.jgit.internal.storage.pack.PackOutputStream;

  18. /**
  19.  * A window for accessing git packs using a {@link ByteBuffer} for storage.
  20.  *
  21.  * @see ByteWindow
  22.  */
  23. final class ByteBufferWindow extends ByteWindow {
  24.     private final ByteBuffer buffer;

  25.     ByteBufferWindow(Pack pack, long o, ByteBuffer b) {
  26.         super(pack, o, b.capacity());
  27.         buffer = b;
  28.     }

  29.     /** {@inheritDoc} */
  30.     @Override
  31.     protected int copy(int p, byte[] b, int o, int n) {
  32.         final ByteBuffer s = buffer.slice();
  33.         s.position(p);
  34.         n = Math.min(s.remaining(), n);
  35.         s.get(b, o, n);
  36.         return n;
  37.     }

  38.     @Override
  39.     void write(PackOutputStream out, long pos, int cnt)
  40.             throws IOException {
  41.         final ByteBuffer s = buffer.slice();
  42.         s.position((int) (pos - start));

  43.         while (0 < cnt) {
  44.             byte[] buf = out.getCopyBuffer();
  45.             int n = Math.min(cnt, buf.length);
  46.             s.get(buf, 0, n);
  47.             out.write(buf, 0, n);
  48.             cnt -= n;
  49.         }
  50.     }

  51.     /** {@inheritDoc} */
  52.     @Override
  53.     protected int setInput(int pos, Inflater inf)
  54.             throws DataFormatException {
  55.         final ByteBuffer s = buffer.slice();
  56.         s.position(pos);
  57.         final byte[] tmp = new byte[Math.min(s.remaining(), 512)];
  58.         s.get(tmp, 0, tmp.length);
  59.         inf.setInput(tmp, 0, tmp.length);
  60.         return tmp.length;
  61.     }
  62. }