View Javadoc
1   /*
2    * Copyright (C) 2008-2011, 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.dfs;
14  
15  import java.io.IOException;
16  import java.nio.ByteBuffer;
17  import java.util.zip.CRC32;
18  import java.util.zip.DataFormatException;
19  import java.util.zip.Inflater;
20  
21  import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
22  
23  /** A cached slice of a {@link BlockBasedFile}. */
24  final class DfsBlock {
25  	final DfsStreamKey stream;
26  	final long start;
27  	final long end;
28  	private final byte[] block;
29  
30  	DfsBlock(DfsStreamKey p, long pos, byte[] buf) {
31  		stream = p;
32  		start = pos;
33  		end = pos + buf.length;
34  		block = buf;
35  	}
36  
37  	int size() {
38  		return block.length;
39  	}
40  
41  	ByteBuffer zeroCopyByteBuffer(int n) {
42  		ByteBuffer b = ByteBuffer.wrap(block);
43  		b.position(n);
44  		return b;
45  	}
46  
47  	boolean contains(DfsStreamKey want, long pos) {
48  		return stream.equals(want) && start <= pos && pos < end;
49  	}
50  
51  	int copy(long pos, byte[] dstbuf, int dstoff, int cnt) {
52  		int ptr = (int) (pos - start);
53  		return copy(ptr, dstbuf, dstoff, cnt);
54  	}
55  
56  	int copy(int p, byte[] b, int o, int n) {
57  		n = Math.min(block.length - p, n);
58  		System.arraycopy(block, p, b, o, n);
59  		return n;
60  	}
61  
62  	int setInput(long pos, Inflater inf) throws DataFormatException {
63  		int ptr = (int) (pos - start);
64  		int cnt = block.length - ptr;
65  		if (cnt <= 0) {
66  			throw new DataFormatException(cnt + " bytes to inflate:" //$NON-NLS-1$
67  					+ " at pos=" + pos //$NON-NLS-1$
68  					+ "; block.start=" + start //$NON-NLS-1$
69  					+ "; ptr=" + ptr //$NON-NLS-1$
70  					+ "; block.length=" + block.length); //$NON-NLS-1$
71  		}
72  		inf.setInput(block, ptr, cnt);
73  		return cnt;
74  	}
75  
76  	void crc32(CRC32 out, long pos, int cnt) {
77  		int ptr = (int) (pos - start);
78  		out.update(block, ptr, cnt);
79  	}
80  
81  	void write(PackOutputStream out, long pos, int cnt)
82  			throws IOException {
83  		out.write(block, (int) (pos - start), cnt);
84  	}
85  
86  	void check(Inflater inf, byte[] tmp, long pos, int cnt)
87  			throws DataFormatException {
88  		// Unlike inflate() above the exact byte count is known by the caller.
89  		// Push all of it in a single invocation to avoid unnecessary loops.
90  		//
91  		inf.setInput(block, (int) (pos - start), cnt);
92  		while (inf.inflate(tmp, 0, tmp.length) > 0)
93  			continue;
94  	}
95  }