View Javadoc
1   /*
2    * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
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.IOException;
47  import java.io.OutputStream;
48  import java.io.Writer;
49  import java.nio.ByteBuffer;
50  
51  import org.eclipse.jgit.util.NB;
52  
53  /**
54   * A (possibly mutable) SHA-1 abstraction.
55   * <p>
56   * If this is an instance of {@link MutableObjectId} the concept of equality
57   * with this instance can alter at any time, if this instance is modified to
58   * represent a different object name.
59   */
60  public abstract class AnyObjectId implements Comparable<AnyObjectId> {
61  
62  	/**
63  	 * Compare to object identifier byte sequences for equality.
64  	 *
65  	 * @param firstObjectId
66  	 *            the first identifier to compare. Must not be null.
67  	 * @param secondObjectId
68  	 *            the second identifier to compare. Must not be null.
69  	 * @return true if the two identifiers are the same.
70  	 */
71  	public static boolean equals(final AnyObjectId firstObjectId,
72  			final AnyObjectId secondObjectId) {
73  		if (firstObjectId == secondObjectId)
74  			return true;
75  
76  		// We test word 2 first as odds are someone already used our
77  		// word 1 as a hash code, and applying that came up with these
78  		// two instances we are comparing for equality. Therefore the
79  		// first two words are very likely to be identical. We want to
80  		// break away from collisions as quickly as possible.
81  		//
82  		return firstObjectId.w2 == secondObjectId.w2
83  				&& firstObjectId.w3 == secondObjectId.w3
84  				&& firstObjectId.w4 == secondObjectId.w4
85  				&& firstObjectId.w5 == secondObjectId.w5
86  				&& firstObjectId.w1 == secondObjectId.w1;
87  	}
88  
89  	int w1;
90  
91  	int w2;
92  
93  	int w3;
94  
95  	int w4;
96  
97  	int w5;
98  
99  	/**
100 	 * Get the first 8 bits of the ObjectId.
101 	 *
102 	 * This is a faster version of {@code getByte(0)}.
103 	 *
104 	 * @return a discriminator usable for a fan-out style map. Returned values
105 	 *         are unsigned and thus are in the range [0,255] rather than the
106 	 *         signed byte range of [-128, 127].
107 	 */
108 	public final int getFirstByte() {
109 		return w1 >>> 24;
110 	}
111 
112 	/**
113 	 * Get any byte from the ObjectId.
114 	 *
115 	 * Callers hard-coding {@code getByte(0)} should instead use the much faster
116 	 * special case variant {@link #getFirstByte()}.
117 	 *
118 	 * @param index
119 	 *            index of the byte to obtain from the raw form of the ObjectId.
120 	 *            Must be in range [0, {@link Constants#OBJECT_ID_LENGTH}).
121 	 * @return the value of the requested byte at {@code index}. Returned values
122 	 *         are unsigned and thus are in the range [0,255] rather than the
123 	 *         signed byte range of [-128, 127].
124 	 * @throws ArrayIndexOutOfBoundsException
125 	 *             {@code index} is less than 0, equal to
126 	 *             {@link Constants#OBJECT_ID_LENGTH}, or greater than
127 	 *             {@link Constants#OBJECT_ID_LENGTH}.
128 	 */
129 	public final int getByte(int index) {
130 		int w;
131 		switch (index >> 2) {
132 		case 0:
133 			w = w1;
134 			break;
135 		case 1:
136 			w = w2;
137 			break;
138 		case 2:
139 			w = w3;
140 			break;
141 		case 3:
142 			w = w4;
143 			break;
144 		case 4:
145 			w = w5;
146 			break;
147 		default:
148 			throw new ArrayIndexOutOfBoundsException(index);
149 		}
150 
151 		return (w >>> (8 * (3 - (index & 3)))) & 0xff;
152 	}
153 
154 	/**
155 	 * Compare this ObjectId to another and obtain a sort ordering.
156 	 *
157 	 * @param other
158 	 *            the other id to compare to. Must not be null.
159 	 * @return &lt; 0 if this id comes before other; 0 if this id is equal to
160 	 *         other; &gt; 0 if this id comes after other.
161 	 */
162 	public final int compareTo(final AnyObjectId other) {
163 		if (this == other)
164 			return 0;
165 
166 		int cmp;
167 
168 		cmp = NB.compareUInt32(w1, other.w1);
169 		if (cmp != 0)
170 			return cmp;
171 
172 		cmp = NB.compareUInt32(w2, other.w2);
173 		if (cmp != 0)
174 			return cmp;
175 
176 		cmp = NB.compareUInt32(w3, other.w3);
177 		if (cmp != 0)
178 			return cmp;
179 
180 		cmp = NB.compareUInt32(w4, other.w4);
181 		if (cmp != 0)
182 			return cmp;
183 
184 		return NB.compareUInt32(w5, other.w5);
185 	}
186 
187 	/**
188 	 * Compare this ObjectId to a network-byte-order ObjectId.
189 	 *
190 	 * @param bs
191 	 *            array containing the other ObjectId in network byte order.
192 	 * @param p
193 	 *            position within {@code bs} to start the compare at. At least
194 	 *            20 bytes, starting at this position are required.
195 	 * @return a negative integer, zero, or a positive integer as this object is
196 	 *         less than, equal to, or greater than the specified object.
197 	 */
198 	public final int compareTo(final byte[] bs, final int p) {
199 		int cmp;
200 
201 		cmp = NB.compareUInt32(w1, NB.decodeInt32(bs, p));
202 		if (cmp != 0)
203 			return cmp;
204 
205 		cmp = NB.compareUInt32(w2, NB.decodeInt32(bs, p + 4));
206 		if (cmp != 0)
207 			return cmp;
208 
209 		cmp = NB.compareUInt32(w3, NB.decodeInt32(bs, p + 8));
210 		if (cmp != 0)
211 			return cmp;
212 
213 		cmp = NB.compareUInt32(w4, NB.decodeInt32(bs, p + 12));
214 		if (cmp != 0)
215 			return cmp;
216 
217 		return NB.compareUInt32(w5, NB.decodeInt32(bs, p + 16));
218 	}
219 
220 	/**
221 	 * Compare this ObjectId to a network-byte-order ObjectId.
222 	 *
223 	 * @param bs
224 	 *            array containing the other ObjectId in network byte order.
225 	 * @param p
226 	 *            position within {@code bs} to start the compare at. At least 5
227 	 *            integers, starting at this position are required.
228 	 * @return a negative integer, zero, or a positive integer as this object is
229 	 *         less than, equal to, or greater than the specified object.
230 	 */
231 	public final int compareTo(final int[] bs, final int p) {
232 		int cmp;
233 
234 		cmp = NB.compareUInt32(w1, bs[p]);
235 		if (cmp != 0)
236 			return cmp;
237 
238 		cmp = NB.compareUInt32(w2, bs[p + 1]);
239 		if (cmp != 0)
240 			return cmp;
241 
242 		cmp = NB.compareUInt32(w3, bs[p + 2]);
243 		if (cmp != 0)
244 			return cmp;
245 
246 		cmp = NB.compareUInt32(w4, bs[p + 3]);
247 		if (cmp != 0)
248 			return cmp;
249 
250 		return NB.compareUInt32(w5, bs[p + 4]);
251 	}
252 
253 	/**
254 	 * Tests if this ObjectId starts with the given abbreviation.
255 	 *
256 	 * @param abbr
257 	 *            the abbreviation.
258 	 * @return true if this ObjectId begins with the abbreviation; else false.
259 	 */
260 	public boolean startsWith(final AbbreviatedObjectId abbr) {
261 		return abbr.prefixCompare(this) == 0;
262 	}
263 
264 	public final int hashCode() {
265 		return w2;
266 	}
267 
268 	/**
269 	 * Determine if this ObjectId has exactly the same value as another.
270 	 *
271 	 * @param other
272 	 *            the other id to compare to. May be null.
273 	 * @return true only if both ObjectIds have identical bits.
274 	 */
275 	public final boolean equals(final AnyObjectId other) {
276 		return other != null ? equals(this, other) : false;
277 	}
278 
279 	public final boolean equals(final Object o) {
280 		if (o instanceof AnyObjectId)
281 			return equals((AnyObjectId) o);
282 		else
283 			return false;
284 	}
285 
286 	/**
287 	 * Copy this ObjectId to an output writer in raw binary.
288 	 *
289 	 * @param w
290 	 *            the buffer to copy to. Must be in big endian order.
291 	 */
292 	public void copyRawTo(final ByteBuffer w) {
293 		w.putInt(w1);
294 		w.putInt(w2);
295 		w.putInt(w3);
296 		w.putInt(w4);
297 		w.putInt(w5);
298 	}
299 
300 	/**
301 	 * Copy this ObjectId to a byte array.
302 	 *
303 	 * @param b
304 	 *            the buffer to copy to.
305 	 * @param o
306 	 *            the offset within b to write at.
307 	 */
308 	public void copyRawTo(final byte[] b, final int o) {
309 		NB.encodeInt32(b, o, w1);
310 		NB.encodeInt32(b, o + 4, w2);
311 		NB.encodeInt32(b, o + 8, w3);
312 		NB.encodeInt32(b, o + 12, w4);
313 		NB.encodeInt32(b, o + 16, w5);
314 	}
315 
316 	/**
317 	 * Copy this ObjectId to an int array.
318 	 *
319 	 * @param b
320 	 *            the buffer to copy to.
321 	 * @param o
322 	 *            the offset within b to write at.
323 	 */
324 	public void copyRawTo(final int[] b, final int o) {
325 		b[o] = w1;
326 		b[o + 1] = w2;
327 		b[o + 2] = w3;
328 		b[o + 3] = w4;
329 		b[o + 4] = w5;
330 	}
331 
332 	/**
333 	 * Copy this ObjectId to an output writer in raw binary.
334 	 *
335 	 * @param w
336 	 *            the stream to write to.
337 	 * @throws IOException
338 	 *             the stream writing failed.
339 	 */
340 	public void copyRawTo(final OutputStream w) throws IOException {
341 		writeRawInt(w, w1);
342 		writeRawInt(w, w2);
343 		writeRawInt(w, w3);
344 		writeRawInt(w, w4);
345 		writeRawInt(w, w5);
346 	}
347 
348 	private static void writeRawInt(final OutputStream w, int v)
349 			throws IOException {
350 		w.write(v >>> 24);
351 		w.write(v >>> 16);
352 		w.write(v >>> 8);
353 		w.write(v);
354 	}
355 
356 	/**
357 	 * Copy this ObjectId to an output writer in hex format.
358 	 *
359 	 * @param w
360 	 *            the stream to copy to.
361 	 * @throws IOException
362 	 *             the stream writing failed.
363 	 */
364 	public void copyTo(final OutputStream w) throws IOException {
365 		w.write(toHexByteArray());
366 	}
367 
368 	/**
369 	 * Copy this ObjectId to a byte array in hex format.
370 	 *
371 	 * @param b
372 	 *            the buffer to copy to.
373 	 * @param o
374 	 *            the offset within b to write at.
375 	 */
376 	public void copyTo(byte[] b, int o) {
377 		formatHexByte(b, o + 0, w1);
378 		formatHexByte(b, o + 8, w2);
379 		formatHexByte(b, o + 16, w3);
380 		formatHexByte(b, o + 24, w4);
381 		formatHexByte(b, o + 32, w5);
382 	}
383 
384 	/**
385 	 * Copy this ObjectId to a ByteBuffer in hex format.
386 	 *
387 	 * @param b
388 	 *            the buffer to copy to.
389 	 */
390 	public void copyTo(ByteBuffer b) {
391 		b.put(toHexByteArray());
392 	}
393 
394 	private byte[] toHexByteArray() {
395 		final byte[] dst = new byte[Constants.OBJECT_ID_STRING_LENGTH];
396 		formatHexByte(dst, 0, w1);
397 		formatHexByte(dst, 8, w2);
398 		formatHexByte(dst, 16, w3);
399 		formatHexByte(dst, 24, w4);
400 		formatHexByte(dst, 32, w5);
401 		return dst;
402 	}
403 
404 	private static final byte[] hexbyte = { '0', '1', '2', '3', '4', '5', '6',
405 			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
406 
407 	private static void formatHexByte(final byte[] dst, final int p, int w) {
408 		int o = p + 7;
409 		while (o >= p && w != 0) {
410 			dst[o--] = hexbyte[w & 0xf];
411 			w >>>= 4;
412 		}
413 		while (o >= p)
414 			dst[o--] = '0';
415 	}
416 
417 	/**
418 	 * Copy this ObjectId to an output writer in hex format.
419 	 *
420 	 * @param w
421 	 *            the stream to copy to.
422 	 * @throws IOException
423 	 *             the stream writing failed.
424 	 */
425 	public void copyTo(final Writer w) throws IOException {
426 		w.write(toHexCharArray());
427 	}
428 
429 	/**
430 	 * Copy this ObjectId to an output writer in hex format.
431 	 *
432 	 * @param tmp
433 	 *            temporary char array to buffer construct into before writing.
434 	 *            Must be at least large enough to hold 2 digits for each byte
435 	 *            of object id (40 characters or larger).
436 	 * @param w
437 	 *            the stream to copy to.
438 	 * @throws IOException
439 	 *             the stream writing failed.
440 	 */
441 	public void copyTo(final char[] tmp, final Writer w) throws IOException {
442 		toHexCharArray(tmp);
443 		w.write(tmp, 0, Constants.OBJECT_ID_STRING_LENGTH);
444 	}
445 
446 	/**
447 	 * Copy this ObjectId to a StringBuilder in hex format.
448 	 *
449 	 * @param tmp
450 	 *            temporary char array to buffer construct into before writing.
451 	 *            Must be at least large enough to hold 2 digits for each byte
452 	 *            of object id (40 characters or larger).
453 	 * @param w
454 	 *            the string to append onto.
455 	 */
456 	public void copyTo(final char[] tmp, final StringBuilder w) {
457 		toHexCharArray(tmp);
458 		w.append(tmp, 0, Constants.OBJECT_ID_STRING_LENGTH);
459 	}
460 
461 	private char[] toHexCharArray() {
462 		final char[] dst = new char[Constants.OBJECT_ID_STRING_LENGTH];
463 		toHexCharArray(dst);
464 		return dst;
465 	}
466 
467 	private void toHexCharArray(final char[] dst) {
468 		formatHexChar(dst, 0, w1);
469 		formatHexChar(dst, 8, w2);
470 		formatHexChar(dst, 16, w3);
471 		formatHexChar(dst, 24, w4);
472 		formatHexChar(dst, 32, w5);
473 	}
474 
475 	private static final char[] hexchar = { '0', '1', '2', '3', '4', '5', '6',
476 			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
477 
478 	static void formatHexChar(final char[] dst, final int p, int w) {
479 		int o = p + 7;
480 		while (o >= p && w != 0) {
481 			dst[o--] = hexchar[w & 0xf];
482 			w >>>= 4;
483 		}
484 		while (o >= p)
485 			dst[o--] = '0';
486 	}
487 
488 	@SuppressWarnings("nls")
489 	@Override
490 	public String toString() {
491 		return "AnyObjectId[" + name() + "]";
492 	}
493 
494 	/**
495 	 * @return string form of the SHA-1, in lower case hexadecimal.
496 	 */
497 	public final String name() {
498 		return new String(toHexCharArray());
499 	}
500 
501 	/**
502 	 * @return string form of the SHA-1, in lower case hexadecimal.
503 	 */
504 	public final String getName() {
505 		return name();
506 	}
507 
508 	/**
509 	 * Return an abbreviation (prefix) of this object SHA-1.
510 	 * <p>
511 	 * This implementation does not guarantee uniqueness. Callers should
512 	 * instead use {@link ObjectReader#abbreviate(AnyObjectId, int)} to obtain a
513 	 * unique abbreviation within the scope of a particular object database.
514 	 *
515 	 * @param len
516 	 *            length of the abbreviated string.
517 	 * @return SHA-1 abbreviation.
518 	 */
519 	public AbbreviatedObjectId abbreviate(final int len) {
520 		final int a = AbbreviatedObjectId.mask(len, 1, w1);
521 		final int b = AbbreviatedObjectId.mask(len, 2, w2);
522 		final int c = AbbreviatedObjectId.mask(len, 3, w3);
523 		final int d = AbbreviatedObjectId.mask(len, 4, w4);
524 		final int e = AbbreviatedObjectId.mask(len, 5, w5);
525 		return new AbbreviatedObjectId(len, a, b, c, d, e);
526 	}
527 
528 	/**
529 	 * Obtain an immutable copy of this current object name value.
530 	 * <p>
531 	 * Only returns <code>this</code> if this instance is an unsubclassed
532 	 * instance of {@link ObjectId}; otherwise a new instance is returned
533 	 * holding the same value.
534 	 * <p>
535 	 * This method is useful to shed any additional memory that may be tied to
536 	 * the subclass, yet retain the unique identity of the object id for future
537 	 * lookups within maps and repositories.
538 	 *
539 	 * @return an immutable copy, using the smallest memory footprint possible.
540 	 */
541 	public final ObjectId copy() {
542 		if (getClass() == ObjectId.class)
543 			return (ObjectId) this;
544 		return new ObjectId(this);
545 	}
546 
547 	/**
548 	 * Obtain an immutable copy of this current object name value.
549 	 * <p>
550 	 * See {@link #copy()} if <code>this</code> is a possibly subclassed (but
551 	 * immutable) identity and the application needs a lightweight identity
552 	 * <i>only</i> reference.
553 	 *
554 	 * @return an immutable copy. May be <code>this</code> if this is already
555 	 *         an immutable instance.
556 	 */
557 	public abstract ObjectId toObjectId();
558 }