View Javadoc
1   /*
2    * Copyright (C) 2008-2009, 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  
11  package org.eclipse.jgit.lib;
12  
13  import java.io.Serializable;
14  import java.text.MessageFormat;
15  
16  import org.eclipse.jgit.errors.InvalidObjectIdException;
17  import org.eclipse.jgit.internal.JGitText;
18  import org.eclipse.jgit.util.NB;
19  import org.eclipse.jgit.util.RawParseUtils;
20  
21  /**
22   * A prefix abbreviation of an {@link org.eclipse.jgit.lib.ObjectId}.
23   * <p>
24   * Sometimes Git produces abbreviated SHA-1 strings, using sufficient leading
25   * digits from the ObjectId name to still be unique within the repository the
26   * string was generated from. These ids are likely to be unique for a useful
27   * period of time, especially if they contain at least 6-10 hex digits.
28   * <p>
29   * This class converts the hex string into a binary form, to make it more
30   * efficient for matching against an object.
31   */
32  public final class AbbreviatedObjectId implements Serializable {
33  	private static final long serialVersionUID = 1L;
34  
35  	/**
36  	 * Test a string of characters to verify it is a hex format.
37  	 * <p>
38  	 * If true the string can be parsed with {@link #fromString(String)}.
39  	 *
40  	 * @param id
41  	 *            the string to test.
42  	 * @return true if the string can converted into an AbbreviatedObjectId.
43  	 */
44  	public static final boolean isId(String id) {
45  		if (id.length() < 2 || Constants.OBJECT_ID_STRING_LENGTH < id.length())
46  			return false;
47  		try {
48  			for (int i = 0; i < id.length(); i++)
49  				RawParseUtils.parseHexInt4((byte) id.charAt(i));
50  			return true;
51  		} catch (ArrayIndexOutOfBoundsException e) {
52  			return false;
53  		}
54  	}
55  
56  	/**
57  	 * Convert an AbbreviatedObjectId from hex characters (US-ASCII).
58  	 *
59  	 * @param buf
60  	 *            the US-ASCII buffer to read from.
61  	 * @param offset
62  	 *            position to read the first character from.
63  	 * @param end
64  	 *            one past the last position to read (<code>end-offset</code> is
65  	 *            the length of the string).
66  	 * @return the converted object id.
67  	 */
68  	public static final AbbreviatedObjectId fromString(final byte[] buf,
69  			final int offset, final int end) {
70  		if (end - offset > Constants.OBJECT_ID_STRING_LENGTH)
71  			throw new IllegalArgumentException(MessageFormat.format(
72  					JGitText.get().invalidIdLength,
73  					Integer.valueOf(end - offset),
74  					Integer.valueOf(Constants.OBJECT_ID_STRING_LENGTH)));
75  		return fromHexString(buf, offset, end);
76  	}
77  
78  	/**
79  	 * Convert an AbbreviatedObjectId from an
80  	 * {@link org.eclipse.jgit.lib.AnyObjectId}.
81  	 * <p>
82  	 * This method copies over all bits of the Id, and is therefore complete
83  	 * (see {@link #isComplete()}).
84  	 *
85  	 * @param id
86  	 *            the {@link org.eclipse.jgit.lib.ObjectId} to convert from.
87  	 * @return the converted object id.
88  	 */
89  	public static final AbbreviatedObjectId fromObjectId(AnyObjectId id) {
90  		return new AbbreviatedObjectId(Constants.OBJECT_ID_STRING_LENGTH,
91  				id.w1, id.w2, id.w3, id.w4, id.w5);
92  	}
93  
94  	/**
95  	 * Convert an AbbreviatedObjectId from hex characters.
96  	 *
97  	 * @param str
98  	 *            the string to read from. Must be &lt;= 40 characters.
99  	 * @return the converted object id.
100 	 */
101 	public static final AbbreviatedObjectId fromString(String str) {
102 		if (str.length() > Constants.OBJECT_ID_STRING_LENGTH)
103 			throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidId, str));
104 		final byte[] b = Constants.encodeASCII(str);
105 		return fromHexString(b, 0, b.length);
106 	}
107 
108 	private static final AbbreviatedObjectId fromHexString(final byte[] bs,
109 			int ptr, final int end) {
110 		try {
111 			final int a = hexUInt32(bs, ptr, end);
112 			final int b = hexUInt32(bs, ptr + 8, end);
113 			final int c = hexUInt32(bs, ptr + 16, end);
114 			final int d = hexUInt32(bs, ptr + 24, end);
115 			final int e = hexUInt32(bs, ptr + 32, end);
116 			return new AbbreviatedObjectId(end - ptr, a, b, c, d, e);
117 		} catch (ArrayIndexOutOfBoundsException e) {
118 			InvalidObjectIdException e1 = new InvalidObjectIdException(bs, ptr,
119 					end - ptr);
120 			e1.initCause(e);
121 			throw e1;
122 		}
123 	}
124 
125 	private static final int hexUInt32(final byte[] bs, int p, final int end) {
126 		if (8 <= end - p)
127 			return RawParseUtils.parseHexInt32(bs, p);
128 
129 		int r = 0, n = 0;
130 		while (n < 8 && p < end) {
131 			r <<= 4;
132 			r |= RawParseUtils.parseHexInt4(bs[p++]);
133 			n++;
134 		}
135 		return r << ((8 - n) * 4);
136 	}
137 
138 	static int mask(int nibbles, int word, int v) {
139 		final int b = (word - 1) * 8;
140 		if (b + 8 <= nibbles) {
141 			// We have all of the bits required for this word.
142 			//
143 			return v;
144 		}
145 
146 		if (nibbles <= b) {
147 			// We have none of the bits required for this word.
148 			//
149 			return 0;
150 		}
151 
152 		final int s = 32 - (nibbles - b) * 4;
153 		return (v >>> s) << s;
154 	}
155 
156 	/** Number of half-bytes used by this id. */
157 	final int nibbles;
158 
159 	final int w1;
160 
161 	final int w2;
162 
163 	final int w3;
164 
165 	final int w4;
166 
167 	final int w5;
168 
169 	AbbreviatedObjectId(final int n, final int new_1, final int new_2,
170 			final int new_3, final int new_4, final int new_5) {
171 		nibbles = n;
172 		w1 = new_1;
173 		w2 = new_2;
174 		w3 = new_3;
175 		w4 = new_4;
176 		w5 = new_5;
177 	}
178 
179 	/**
180 	 * Get number of hex digits appearing in this id.
181 	 *
182 	 * @return number of hex digits appearing in this id.
183 	 */
184 	public int length() {
185 		return nibbles;
186 	}
187 
188 	/**
189 	 * Whether this ObjectId is actually a complete id.
190 	 *
191 	 * @return true if this ObjectId is actually a complete id.
192 	 */
193 	public boolean isComplete() {
194 		return length() == Constants.OBJECT_ID_STRING_LENGTH;
195 	}
196 
197 	/**
198 	 * A complete ObjectId; null if {@link #isComplete()} is false
199 	 *
200 	 * @return a complete ObjectId; null if {@link #isComplete()} is false
201 	 */
202 	public ObjectId toObjectId() {
203 		return isComplete() ? new ObjectId(w1, w2, w3, w4, w5) : null;
204 	}
205 
206 	/**
207 	 * Compares this abbreviation to a full object id.
208 	 *
209 	 * @param other
210 	 *            the other object id.
211 	 * @return &lt;0 if this abbreviation names an object that is less than
212 	 *         <code>other</code>; 0 if this abbreviation exactly matches the
213 	 *         first {@link #length()} digits of <code>other.name()</code>;
214 	 *         &gt;0 if this abbreviation names an object that is after
215 	 *         <code>other</code>.
216 	 */
217 	public final int prefixCompare(AnyObjectId other) {
218 		int cmp;
219 
220 		cmp = NB.compareUInt32(w1, mask(1, other.w1));
221 		if (cmp != 0)
222 			return cmp;
223 
224 		cmp = NB.compareUInt32(w2, mask(2, other.w2));
225 		if (cmp != 0)
226 			return cmp;
227 
228 		cmp = NB.compareUInt32(w3, mask(3, other.w3));
229 		if (cmp != 0)
230 			return cmp;
231 
232 		cmp = NB.compareUInt32(w4, mask(4, other.w4));
233 		if (cmp != 0)
234 			return cmp;
235 
236 		return NB.compareUInt32(w5, mask(5, other.w5));
237 	}
238 
239 	/**
240 	 * Compare this abbreviation to a network-byte-order ObjectId.
241 	 *
242 	 * @param bs
243 	 *            array containing the other ObjectId in network byte order.
244 	 * @param p
245 	 *            position within {@code bs} to start the compare at. At least
246 	 *            20 bytes, starting at this position are required.
247 	 * @return &lt;0 if this abbreviation names an object that is less than
248 	 *         <code>other</code>; 0 if this abbreviation exactly matches the
249 	 *         first {@link #length()} digits of <code>other.name()</code>;
250 	 *         &gt;0 if this abbreviation names an object that is after
251 	 *         <code>other</code>.
252 	 */
253 	public final int prefixCompare(byte[] bs, int p) {
254 		int cmp;
255 
256 		cmp = NB.compareUInt32(w1, mask(1, NB.decodeInt32(bs, p)));
257 		if (cmp != 0)
258 			return cmp;
259 
260 		cmp = NB.compareUInt32(w2, mask(2, NB.decodeInt32(bs, p + 4)));
261 		if (cmp != 0)
262 			return cmp;
263 
264 		cmp = NB.compareUInt32(w3, mask(3, NB.decodeInt32(bs, p + 8)));
265 		if (cmp != 0)
266 			return cmp;
267 
268 		cmp = NB.compareUInt32(w4, mask(4, NB.decodeInt32(bs, p + 12)));
269 		if (cmp != 0)
270 			return cmp;
271 
272 		return NB.compareUInt32(w5, mask(5, NB.decodeInt32(bs, p + 16)));
273 	}
274 
275 	/**
276 	 * Compare this abbreviation to a network-byte-order ObjectId.
277 	 *
278 	 * @param bs
279 	 *            array containing the other ObjectId in network byte order.
280 	 * @param p
281 	 *            position within {@code bs} to start the compare at. At least 5
282 	 *            ints, starting at this position are required.
283 	 * @return &lt;0 if this abbreviation names an object that is less than
284 	 *         <code>other</code>; 0 if this abbreviation exactly matches the
285 	 *         first {@link #length()} digits of <code>other.name()</code>;
286 	 *         &gt;0 if this abbreviation names an object that is after
287 	 *         <code>other</code>.
288 	 */
289 	public final int prefixCompare(int[] bs, int p) {
290 		int cmp;
291 
292 		cmp = NB.compareUInt32(w1, mask(1, bs[p]));
293 		if (cmp != 0)
294 			return cmp;
295 
296 		cmp = NB.compareUInt32(w2, mask(2, bs[p + 1]));
297 		if (cmp != 0)
298 			return cmp;
299 
300 		cmp = NB.compareUInt32(w3, mask(3, bs[p + 2]));
301 		if (cmp != 0)
302 			return cmp;
303 
304 		cmp = NB.compareUInt32(w4, mask(4, bs[p + 3]));
305 		if (cmp != 0)
306 			return cmp;
307 
308 		return NB.compareUInt32(w5, mask(5, bs[p + 4]));
309 	}
310 
311 	/**
312 	 * Get value for a fan-out style map, only valid of length &gt;= 2.
313 	 *
314 	 * @return value for a fan-out style map, only valid of length &gt;= 2.
315 	 */
316 	public final int getFirstByte() {
317 		return w1 >>> 24;
318 	}
319 
320 	private int mask(int word, int v) {
321 		return mask(nibbles, word, v);
322 	}
323 
324 	/** {@inheritDoc} */
325 	@Override
326 	public int hashCode() {
327 		return w1;
328 	}
329 
330 	/** {@inheritDoc} */
331 	@Override
332 	public boolean equals(Object o) {
333 		if (o instanceof AbbreviatedObjectId) {
334 			final AbbreviatedObjectId/../org/eclipse/jgit/lib/AbbreviatedObjectId.html#AbbreviatedObjectId">AbbreviatedObjectId b = (AbbreviatedObjectId) o;
335 			return nibbles == b.nibbles && w1 == b.w1 && w2 == b.w2
336 					&& w3 == b.w3 && w4 == b.w4 && w5 == b.w5;
337 		}
338 		return false;
339 	}
340 
341 	/**
342 	 * Get string form of the abbreviation, in lower case hexadecimal.
343 	 *
344 	 * @return string form of the abbreviation, in lower case hexadecimal.
345 	 */
346 	public final String name() {
347 		final char[] b = new char[Constants.OBJECT_ID_STRING_LENGTH];
348 
349 		AnyObjectId.formatHexChar(b, 0, w1);
350 		if (nibbles <= 8)
351 			return new String(b, 0, nibbles);
352 
353 		AnyObjectId.formatHexChar(b, 8, w2);
354 		if (nibbles <= 16)
355 			return new String(b, 0, nibbles);
356 
357 		AnyObjectId.formatHexChar(b, 16, w3);
358 		if (nibbles <= 24)
359 			return new String(b, 0, nibbles);
360 
361 		AnyObjectId.formatHexChar(b, 24, w4);
362 		if (nibbles <= 32)
363 			return new String(b, 0, nibbles);
364 
365 		AnyObjectId.formatHexChar(b, 32, w5);
366 		return new String(b, 0, nibbles);
367 	}
368 
369 	/** {@inheritDoc} */
370 	@SuppressWarnings("nls")
371 	@Override
372 	public String toString() {
373 		return "AbbreviatedObjectId[" + name() + "]"; //$NON-NLS-1$
374 	}
375 }