HashedSequencePair.java

  1. /*
  2.  * Copyright (C) 2010, 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. package org.eclipse.jgit.diff;

  11. /**
  12.  * Wraps two {@link org.eclipse.jgit.diff.Sequence} instances to cache their
  13.  * element hash codes.
  14.  * <p>
  15.  * This pair wraps two sequences that contain cached hash codes for the input
  16.  * sequences.
  17.  *
  18.  * @param <S>
  19.  *            the base sequence type.
  20.  */
  21. public class HashedSequencePair<S extends Sequence> {
  22.     private final SequenceComparator<? super S> cmp;

  23.     private final S baseA;

  24.     private final S baseB;

  25.     private HashedSequence<S> cachedA;

  26.     private HashedSequence<S> cachedB;

  27.     /**
  28.      * Construct a pair to provide fast hash codes.
  29.      *
  30.      * @param cmp
  31.      *            the base comparator for the sequence elements.
  32.      * @param a
  33.      *            the A sequence.
  34.      * @param b
  35.      *            the B sequence.
  36.      */
  37.     public HashedSequencePair(SequenceComparator<? super S> cmp, S a, S b) {
  38.         this.cmp = cmp;
  39.         this.baseA = a;
  40.         this.baseB = b;
  41.     }

  42.     /**
  43.      * Get comparator
  44.      *
  45.      * @return obtain a comparator that uses the cached hash codes
  46.      */
  47.     public HashedSequenceComparator<S> getComparator() {
  48.         return new HashedSequenceComparator<>(cmp);
  49.     }

  50.     /**
  51.      * Get A
  52.      *
  53.      * @return wrapper around A that includes cached hash codes
  54.      */
  55.     public HashedSequence<S> getA() {
  56.         if (cachedA == null)
  57.             cachedA = wrap(baseA);
  58.         return cachedA;
  59.     }

  60.     /**
  61.      * Get B
  62.      *
  63.      * @return wrapper around B that includes cached hash codes
  64.      */
  65.     public HashedSequence<S> getB() {
  66.         if (cachedB == null)
  67.             cachedB = wrap(baseB);
  68.         return cachedB;
  69.     }

  70.     private HashedSequence<S> wrap(S base) {
  71.         final int end = base.size();
  72.         final int[] hashes = new int[end];
  73.         for (int ptr = 0; ptr < end; ptr++)
  74.             hashes[ptr] = cmp.hash(base, ptr);
  75.         return new HashedSequence<>(base, hashes);
  76.     }
  77. }