View Javadoc
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  
13  package org.eclipse.jgit.internal.storage.file;
14  
15  import java.io.IOException;
16  import java.nio.ByteBuffer;
17  import java.util.zip.DataFormatException;
18  import java.util.zip.Inflater;
19  
20  import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
21  
22  /**
23   * A window for accessing git packs using a {@link ByteBuffer} for storage.
24   *
25   * @see ByteWindow
26   */
27  final class ByteBufferWindow extends ByteWindow {
28  	private final ByteBuffer buffer;
29  
30  	ByteBufferWindow(PackFile pack, long o, ByteBuffer b) {
31  		super(pack, o, b.capacity());
32  		buffer = b;
33  	}
34  
35  	/** {@inheritDoc} */
36  	@Override
37  	protected int copy(int p, byte[] b, int o, int n) {
38  		final ByteBuffer s = buffer.slice();
39  		s.position(p);
40  		n = Math.min(s.remaining(), n);
41  		s.get(b, o, n);
42  		return n;
43  	}
44  
45  	@Override
46  	void write(PackOutputStream out, long pos, int cnt)
47  			throws IOException {
48  		final ByteBuffer s = buffer.slice();
49  		s.position((int) (pos - start));
50  
51  		while (0 < cnt) {
52  			byte[] buf = out.getCopyBuffer();
53  			int n = Math.min(cnt, buf.length);
54  			s.get(buf, 0, n);
55  			out.write(buf, 0, n);
56  			cnt -= n;
57  		}
58  	}
59  
60  	/** {@inheritDoc} */
61  	@Override
62  	protected int setInput(int pos, Inflater inf)
63  			throws DataFormatException {
64  		final ByteBuffer s = buffer.slice();
65  		s.position(pos);
66  		final byte[] tmp = new byte[Math.min(s.remaining(), 512)];
67  		s.get(tmp, 0, tmp.length);
68  		inf.setInput(tmp, 0, tmp.length);
69  		return tmp.length;
70  	}
71  }