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