AnyLongObjectId.java

  1. /*
  2.  * Copyright (C) 2015, Matthias Sohn <matthias.sohn@sap.com> 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. package org.eclipse.jgit.lfs.lib;

  11. import java.io.IOException;
  12. import java.io.OutputStream;
  13. import java.io.Writer;
  14. import java.nio.ByteBuffer;

  15. import org.eclipse.jgit.lib.AnyObjectId;
  16. import org.eclipse.jgit.util.NB;
  17. import org.eclipse.jgit.util.References;

  18. /**
  19.  * A (possibly mutable) SHA-256 abstraction.
  20.  * <p>
  21.  * If this is an instance of
  22.  * {@link org.eclipse.jgit.lfs.lib.MutableLongObjectId} the concept of equality
  23.  * with this instance can alter at any time, if this instance is modified to
  24.  * represent a different object name.
  25.  *
  26.  * Ported to SHA-256 from {@link org.eclipse.jgit.lib.AnyObjectId}
  27.  *
  28.  * @since 4.3
  29.  */
  30. public abstract class AnyLongObjectId implements Comparable<AnyLongObjectId> {

  31.     /**
  32.      * Compare two object identifier byte sequences for equality.
  33.      *
  34.      * @param firstObjectId
  35.      *            the first identifier to compare. Must not be null.
  36.      * @param secondObjectId
  37.      *            the second identifier to compare. Must not be null.
  38.      * @return true if the two identifiers are the same.
  39.      * @deprecated use {@link #isEqual(AnyLongObjectId, AnyLongObjectId)}
  40.      *             instead.
  41.      */
  42.     @Deprecated
  43.     @SuppressWarnings("AmbiguousMethodReference")
  44.     public static boolean equals(final AnyLongObjectId firstObjectId,
  45.             final AnyLongObjectId secondObjectId) {
  46.         return isEqual(firstObjectId, secondObjectId);
  47.     }

  48.     /**
  49.      * Compare two object identifier byte sequences for equality.
  50.      *
  51.      * @param firstObjectId
  52.      *            the first identifier to compare. Must not be null.
  53.      * @param secondObjectId
  54.      *            the second identifier to compare. Must not be null.
  55.      * @return true if the two identifiers are the same.
  56.      * @since 5.4
  57.      */
  58.     public static boolean isEqual(final AnyLongObjectId firstObjectId,
  59.             final AnyLongObjectId secondObjectId) {
  60.         if (References.isSameObject(firstObjectId, secondObjectId)) {
  61.             return true;
  62.         }

  63.         // We test word 2 first as odds are someone already used our
  64.         // word 1 as a hash code, and applying that came up with these
  65.         // two instances we are comparing for equality. Therefore the
  66.         // first two words are very likely to be identical. We want to
  67.         // break away from collisions as quickly as possible.
  68.         //
  69.         return firstObjectId.w2 == secondObjectId.w2
  70.                 && firstObjectId.w3 == secondObjectId.w3
  71.                 && firstObjectId.w4 == secondObjectId.w4
  72.                 && firstObjectId.w1 == secondObjectId.w1;
  73.     }

  74.     long w1;

  75.     long w2;

  76.     long w3;

  77.     long w4;

  78.     /**
  79.      * Get the first 8 bits of the LongObjectId.
  80.      *
  81.      * This is a faster version of {@code getByte(0)}.
  82.      *
  83.      * @return a discriminator usable for a fan-out style map. Returned values
  84.      *         are unsigned and thus are in the range [0,255] rather than the
  85.      *         signed byte range of [-128, 127].
  86.      */
  87.     public final int getFirstByte() {
  88.         return (int) (w1 >>> 56);
  89.     }

  90.     /**
  91.      * Get the second 8 bits of the LongObjectId.
  92.      *
  93.      * @return a discriminator usable for a fan-out style map. Returned values
  94.      *         are unsigned and thus are in the range [0,255] rather than the
  95.      *         signed byte range of [-128, 127].
  96.      */
  97.     public final int getSecondByte() {
  98.         return (int) ((w1 >>> 48) & 0xff);
  99.     }

  100.     /**
  101.      * Get any byte from the LongObjectId.
  102.      *
  103.      * Callers hard-coding {@code getByte(0)} should instead use the much faster
  104.      * special case variant {@link #getFirstByte()}.
  105.      *
  106.      * @param index
  107.      *            index of the byte to obtain from the raw form of the
  108.      *            LongObjectId. Must be in range [0,
  109.      *            {@link org.eclipse.jgit.lfs.lib.Constants#LONG_OBJECT_ID_LENGTH}).
  110.      * @return the value of the requested byte at {@code index}. Returned values
  111.      *         are unsigned and thus are in the range [0,255] rather than the
  112.      *         signed byte range of [-128, 127].
  113.      * @throws java.lang.ArrayIndexOutOfBoundsException
  114.      *             {@code index} is less than 0, equal to
  115.      *             {@link org.eclipse.jgit.lfs.lib.Constants#LONG_OBJECT_ID_LENGTH},
  116.      *             or greater than
  117.      *             {@link org.eclipse.jgit.lfs.lib.Constants#LONG_OBJECT_ID_LENGTH}.
  118.      */
  119.     public final int getByte(int index) {
  120.         long w;
  121.         switch (index >> 3) {
  122.         case 0:
  123.             w = w1;
  124.             break;
  125.         case 1:
  126.             w = w2;
  127.             break;
  128.         case 2:
  129.             w = w3;
  130.             break;
  131.         case 3:
  132.             w = w4;
  133.             break;
  134.         default:
  135.             throw new ArrayIndexOutOfBoundsException(index);
  136.         }

  137.         return (int) ((w >>> (8 * (15 - (index & 15)))) & 0xff);
  138.     }

  139.     /**
  140.      * {@inheritDoc}
  141.      *
  142.      * Compare this LongObjectId to another and obtain a sort ordering.
  143.      */
  144.     @Override
  145.     public final int compareTo(AnyLongObjectId other) {
  146.         if (this == other)
  147.             return 0;

  148.         int cmp;

  149.         cmp = NB.compareUInt64(w1, other.w1);
  150.         if (cmp != 0)
  151.             return cmp;

  152.         cmp = NB.compareUInt64(w2, other.w2);
  153.         if (cmp != 0)
  154.             return cmp;

  155.         cmp = NB.compareUInt64(w3, other.w3);
  156.         if (cmp != 0)
  157.             return cmp;

  158.         return NB.compareUInt64(w4, other.w4);
  159.     }

  160.     /**
  161.      * Compare this LongObjectId to a network-byte-order LongObjectId.
  162.      *
  163.      * @param bs
  164.      *            array containing the other LongObjectId in network byte order.
  165.      * @param p
  166.      *            position within {@code bs} to start the compare at. At least
  167.      *            32 bytes, starting at this position are required.
  168.      * @return a negative integer, zero, or a positive integer as this object is
  169.      *         less than, equal to, or greater than the specified object.
  170.      */
  171.     public final int compareTo(byte[] bs, int p) {
  172.         int cmp;

  173.         cmp = NB.compareUInt64(w1, NB.decodeInt64(bs, p));
  174.         if (cmp != 0)
  175.             return cmp;

  176.         cmp = NB.compareUInt64(w2, NB.decodeInt64(bs, p + 8));
  177.         if (cmp != 0)
  178.             return cmp;

  179.         cmp = NB.compareUInt64(w3, NB.decodeInt64(bs, p + 16));
  180.         if (cmp != 0)
  181.             return cmp;

  182.         return NB.compareUInt64(w4, NB.decodeInt64(bs, p + 24));
  183.     }

  184.     /**
  185.      * Compare this LongObjectId to a network-byte-order LongObjectId.
  186.      *
  187.      * @param bs
  188.      *            array containing the other LongObjectId in network byte order.
  189.      * @param p
  190.      *            position within {@code bs} to start the compare at. At least 4
  191.      *            longs, starting at this position are required.
  192.      * @return a negative integer, zero, or a positive integer as this object is
  193.      *         less than, equal to, or greater than the specified object.
  194.      */
  195.     public final int compareTo(long[] bs, int p) {
  196.         int cmp;

  197.         cmp = NB.compareUInt64(w1, bs[p]);
  198.         if (cmp != 0)
  199.             return cmp;

  200.         cmp = NB.compareUInt64(w2, bs[p + 1]);
  201.         if (cmp != 0)
  202.             return cmp;

  203.         cmp = NB.compareUInt64(w3, bs[p + 2]);
  204.         if (cmp != 0)
  205.             return cmp;

  206.         return NB.compareUInt64(w4, bs[p + 3]);
  207.     }

  208.     /**
  209.      * Tests if this LongObjectId starts with the given abbreviation.
  210.      *
  211.      * @param abbr
  212.      *            the abbreviation.
  213.      * @return true if this LongObjectId begins with the abbreviation; else
  214.      *         false.
  215.      */
  216.     public boolean startsWith(AbbreviatedLongObjectId abbr) {
  217.         return abbr.prefixCompare(this) == 0;
  218.     }

  219.     /** {@inheritDoc} */
  220.     @Override
  221.     public final int hashCode() {
  222.         return (int) (w1 >> 32);
  223.     }

  224.     /**
  225.      * Determine if this LongObjectId has exactly the same value as another.
  226.      *
  227.      * @param other
  228.      *            the other id to compare to. May be null.
  229.      * @return true only if both LongObjectIds have identical bits.
  230.      */
  231.     @SuppressWarnings({ "NonOverridingEquals", "AmbiguousMethodReference" })
  232.     public final boolean equals(AnyLongObjectId other) {
  233.         return other != null ? equals(this, other) : false;
  234.     }

  235.     /** {@inheritDoc} */
  236.     @Override
  237.     public final boolean equals(Object o) {
  238.         if (o instanceof AnyLongObjectId) {
  239.             return equals((AnyLongObjectId) o);
  240.         }
  241.         return false;
  242.     }

  243.     /**
  244.      * Copy this LongObjectId to an output writer in raw binary.
  245.      *
  246.      * @param w
  247.      *            the buffer to copy to. Must be in big endian order.
  248.      */
  249.     public void copyRawTo(ByteBuffer w) {
  250.         w.putLong(w1);
  251.         w.putLong(w2);
  252.         w.putLong(w3);
  253.         w.putLong(w4);
  254.     }

  255.     /**
  256.      * Copy this LongObjectId to a byte array.
  257.      *
  258.      * @param b
  259.      *            the buffer to copy to.
  260.      * @param o
  261.      *            the offset within b to write at.
  262.      */
  263.     public void copyRawTo(byte[] b, int o) {
  264.         NB.encodeInt64(b, o, w1);
  265.         NB.encodeInt64(b, o + 8, w2);
  266.         NB.encodeInt64(b, o + 16, w3);
  267.         NB.encodeInt64(b, o + 24, w4);
  268.     }

  269.     /**
  270.      * Copy this LongObjectId to an long array.
  271.      *
  272.      * @param b
  273.      *            the buffer to copy to.
  274.      * @param o
  275.      *            the offset within b to write at.
  276.      */
  277.     public void copyRawTo(long[] b, int o) {
  278.         b[o] = w1;
  279.         b[o + 1] = w2;
  280.         b[o + 2] = w3;
  281.         b[o + 3] = w4;
  282.     }

  283.     /**
  284.      * Copy this LongObjectId to an output writer in raw binary.
  285.      *
  286.      * @param w
  287.      *            the stream to write to.
  288.      * @throws java.io.IOException
  289.      *             the stream writing failed.
  290.      */
  291.     public void copyRawTo(OutputStream w) throws IOException {
  292.         writeRawLong(w, w1);
  293.         writeRawLong(w, w2);
  294.         writeRawLong(w, w3);
  295.         writeRawLong(w, w4);
  296.     }

  297.     private static void writeRawLong(OutputStream w, long v)
  298.             throws IOException {
  299.         w.write((int) (v >>> 56));
  300.         w.write((int) (v >>> 48));
  301.         w.write((int) (v >>> 40));
  302.         w.write((int) (v >>> 32));
  303.         w.write((int) (v >>> 24));
  304.         w.write((int) (v >>> 16));
  305.         w.write((int) (v >>> 8));
  306.         w.write((int) v);
  307.     }

  308.     /**
  309.      * Copy this LongObjectId to an output writer in hex format.
  310.      *
  311.      * @param w
  312.      *            the stream to copy to.
  313.      * @throws java.io.IOException
  314.      *             the stream writing failed.
  315.      */
  316.     public void copyTo(OutputStream w) throws IOException {
  317.         w.write(toHexByteArray());
  318.     }

  319.     /**
  320.      * Copy this LongObjectId to a byte array in hex format.
  321.      *
  322.      * @param b
  323.      *            the buffer to copy to.
  324.      * @param o
  325.      *            the offset within b to write at.
  326.      */
  327.     public void copyTo(byte[] b, int o) {
  328.         formatHexByte(b, o + 0, w1);
  329.         formatHexByte(b, o + 16, w2);
  330.         formatHexByte(b, o + 32, w3);
  331.         formatHexByte(b, o + 48, w4);
  332.     }

  333.     /**
  334.      * Copy this LongObjectId to a ByteBuffer in hex format.
  335.      *
  336.      * @param b
  337.      *            the buffer to copy to.
  338.      */
  339.     public void copyTo(ByteBuffer b) {
  340.         b.put(toHexByteArray());
  341.     }

  342.     private byte[] toHexByteArray() {
  343.         final byte[] dst = new byte[Constants.LONG_OBJECT_ID_STRING_LENGTH];
  344.         formatHexByte(dst, 0, w1);
  345.         formatHexByte(dst, 16, w2);
  346.         formatHexByte(dst, 32, w3);
  347.         formatHexByte(dst, 48, w4);
  348.         return dst;
  349.     }

  350.     private static final byte[] hexbyte = { '0', '1', '2', '3', '4', '5', '6',
  351.             '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

  352.     private static void formatHexByte(byte[] dst, int p, long w) {
  353.         int o = p + 15;
  354.         while (o >= p && w != 0) {
  355.             dst[o--] = hexbyte[(int) (w & 0xf)];
  356.             w >>>= 4;
  357.         }
  358.         while (o >= p)
  359.             dst[o--] = '0';
  360.     }

  361.     /**
  362.      * Copy this LongObjectId to an output writer in hex format.
  363.      *
  364.      * @param w
  365.      *            the stream to copy to.
  366.      * @throws java.io.IOException
  367.      *             the stream writing failed.
  368.      */
  369.     public void copyTo(Writer w) throws IOException {
  370.         w.write(toHexCharArray());
  371.     }

  372.     /**
  373.      * Copy this LongObjectId to an output writer in hex format.
  374.      *
  375.      * @param tmp
  376.      *            temporary char array to buffer construct into before writing.
  377.      *            Must be at least large enough to hold 2 digits for each byte
  378.      *            of object id (64 characters or larger).
  379.      * @param w
  380.      *            the stream to copy to.
  381.      * @throws java.io.IOException
  382.      *             the stream writing failed.
  383.      */
  384.     public void copyTo(char[] tmp, Writer w) throws IOException {
  385.         toHexCharArray(tmp);
  386.         w.write(tmp, 0, Constants.LONG_OBJECT_ID_STRING_LENGTH);
  387.     }

  388.     /**
  389.      * Copy this LongObjectId to a StringBuilder in hex format.
  390.      *
  391.      * @param tmp
  392.      *            temporary char array to buffer construct into before writing.
  393.      *            Must be at least large enough to hold 2 digits for each byte
  394.      *            of object id (64 characters or larger).
  395.      * @param w
  396.      *            the string to append onto.
  397.      */
  398.     public void copyTo(char[] tmp, StringBuilder w) {
  399.         toHexCharArray(tmp);
  400.         w.append(tmp, 0, Constants.LONG_OBJECT_ID_STRING_LENGTH);
  401.     }

  402.     char[] toHexCharArray() {
  403.         final char[] dst = new char[Constants.LONG_OBJECT_ID_STRING_LENGTH];
  404.         toHexCharArray(dst);
  405.         return dst;
  406.     }

  407.     private void toHexCharArray(char[] dst) {
  408.         formatHexChar(dst, 0, w1);
  409.         formatHexChar(dst, 16, w2);
  410.         formatHexChar(dst, 32, w3);
  411.         formatHexChar(dst, 48, w4);
  412.     }

  413.     private static final char[] hexchar = { '0', '1', '2', '3', '4', '5', '6',
  414.             '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

  415.     static void formatHexChar(char[] dst, int p, long w) {
  416.         int o = p + 15;
  417.         while (o >= p && w != 0) {
  418.             dst[o--] = hexchar[(int) (w & 0xf)];
  419.             w >>>= 4;
  420.         }
  421.         while (o >= p)
  422.             dst[o--] = '0';
  423.     }

  424.     /** {@inheritDoc} */
  425.     @SuppressWarnings("nls")
  426.     @Override
  427.     public String toString() {
  428.         return "AnyLongObjectId[" + name() + "]";
  429.     }

  430.     /**
  431.      * Get string form of the SHA-256
  432.      *
  433.      * @return string form of the SHA-256, in lower case hexadecimal.
  434.      */
  435.     public final String name() {
  436.         return new String(toHexCharArray());
  437.     }

  438.     /**
  439.      * Get string form of the SHA-256
  440.      *
  441.      * @return string form of the SHA-256, in lower case hexadecimal.
  442.      */
  443.     public final String getName() {
  444.         return name();
  445.     }

  446.     /**
  447.      * Return an abbreviation (prefix) of this object SHA-256.
  448.      * <p>
  449.      * This implementation does not guarantee uniqueness. Callers should instead
  450.      * use
  451.      * {@link org.eclipse.jgit.lib.ObjectReader#abbreviate(AnyObjectId, int)} to
  452.      * obtain a unique abbreviation within the scope of a particular object
  453.      * database.
  454.      *
  455.      * @param len
  456.      *            length of the abbreviated string.
  457.      * @return SHA-256 abbreviation.
  458.      */
  459.     public AbbreviatedLongObjectId abbreviate(int len) {
  460.         final long a = AbbreviatedLongObjectId.mask(len, 1, w1);
  461.         final long b = AbbreviatedLongObjectId.mask(len, 2, w2);
  462.         final long c = AbbreviatedLongObjectId.mask(len, 3, w3);
  463.         final long d = AbbreviatedLongObjectId.mask(len, 4, w4);
  464.         return new AbbreviatedLongObjectId(len, a, b, c, d);
  465.     }

  466.     /**
  467.      * Obtain an immutable copy of this current object.
  468.      * <p>
  469.      * Only returns <code>this</code> if this instance is an unsubclassed
  470.      * instance of {@link org.eclipse.jgit.lfs.lib.LongObjectId}; otherwise a
  471.      * new instance is returned holding the same value.
  472.      * <p>
  473.      * This method is useful to shed any additional memory that may be tied to
  474.      * the subclass, yet retain the unique identity of the object id for future
  475.      * lookups within maps and repositories.
  476.      *
  477.      * @return an immutable copy, using the smallest memory footprint possible.
  478.      */
  479.     public final LongObjectId copy() {
  480.         if (getClass() == LongObjectId.class)
  481.             return (LongObjectId) this;
  482.         return new LongObjectId(this);
  483.     }

  484.     /**
  485.      * Obtain an immutable copy of this current object.
  486.      * <p>
  487.      * See {@link #copy()} if <code>this</code> is a possibly subclassed (but
  488.      * immutable) identity and the application needs a lightweight identity
  489.      * <i>only</i> reference.
  490.      *
  491.      * @return an immutable copy. May be <code>this</code> if this is already an
  492.      *         immutable instance.
  493.      */
  494.     public abstract LongObjectId toObjectId();
  495. }