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
11 package org.eclipse.jgit.diff;
12
13 /**
14 * Wraps two {@link org.eclipse.jgit.diff.Sequence} instances to cache their
15 * element hash codes.
16 * <p>
17 * This pair wraps two sequences that contain cached hash codes for the input
18 * sequences.
19 *
20 * @param <S>
21 * the base sequence type.
22 */
23 public class HashedSequencePair<S extends Sequence> {
24 private final SequenceComparator<? super S> cmp;
25
26 private final S baseA;
27
28 private final S baseB;
29
30 private HashedSequence<S> cachedA;
31
32 private HashedSequence<S> cachedB;
33
34 /**
35 * Construct a pair to provide fast hash codes.
36 *
37 * @param cmp
38 * the base comparator for the sequence elements.
39 * @param a
40 * the A sequence.
41 * @param b
42 * the B sequence.
43 */
44 public HashedSequencePair(SequenceComparator<? super S> cmp, S a, S b) {
45 this.cmp = cmp;
46 this.baseA = a;
47 this.baseB = b;
48 }
49
50 /**
51 * Get comparator
52 *
53 * @return obtain a comparator that uses the cached hash codes
54 */
55 public HashedSequenceComparator<S> getComparator() {
56 return new HashedSequenceComparator<>(cmp);
57 }
58
59 /**
60 * Get A
61 *
62 * @return wrapper around A that includes cached hash codes
63 */
64 public HashedSequence<S> getA() {
65 if (cachedA == null)
66 cachedA = wrap(baseA);
67 return cachedA;
68 }
69
70 /**
71 * Get B
72 *
73 * @return wrapper around B that includes cached hash codes
74 */
75 public HashedSequence<S> getB() {
76 if (cachedB == null)
77 cachedB = wrap(baseB);
78 return cachedB;
79 }
80
81 private HashedSequence<S> wrap(S base) {
82 final int end = base.size();
83 final int[] hashes = new int[end];
84 for (int ptr = 0; ptr < end; ptr++)
85 hashes[ptr] = cmp.hash(base, ptr);
86 return new HashedSequence<>(base, hashes);
87 }
88 }