aboutsummaryrefslogtreecommitdiffstats
path: root/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsStreamKey.java
blob: 8983c2d2ebf8de593d4e765a61ed8013e1c77cfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 * Copyright (C) 2011, Google Inc. and others
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Distribution License v. 1.0 which is available at
 * https://www.eclipse.org/org/documents/edl-v10.php.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

package org.eclipse.jgit.internal.storage.dfs;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.util.Arrays;

import org.eclipse.jgit.annotations.Nullable;
import org.eclipse.jgit.internal.storage.pack.PackExt;

/**
 * Key used by {@link org.eclipse.jgit.internal.storage.dfs.DfsBlockCache} to disambiguate streams.
 */
public abstract class DfsStreamKey {
	/**
	 * Create a {@code DfsStreamKey}
	 *
	 * @param repo
	 *            description of the containing repository.
	 * @param name
	 *            compute the key from a string name.
	 * @param ext
	 *            pack file extension, or {@code null}.
	 * @return key for {@code name}
	 */
	public static DfsStreamKey of(DfsRepositoryDescription repo, String name,
			@Nullable PackExt ext) {
		return new ByteArrayDfsStreamKey(repo, name.getBytes(UTF_8), ext);
	}

	final int hash;

	final int packExtPos;

	/**
	 * Constructor for DfsStreamKey.
	 *
	 * @param hash
	 *            hash of the other identifying components of the key.
	 * @param ext
	 *            pack file extension, or {@code null}.
	 */
	protected DfsStreamKey(int hash, @Nullable PackExt ext) {
		// Multiply by 31 here so we can more directly combine with another
		// value without doing the multiply there.
		this.hash = hash * 31;
		this.packExtPos = ext == null ? 0 : ext.getPosition();
	}

	@Override
	public int hashCode() {
		return hash;
	}

	@Override
	public abstract boolean equals(Object o);

	@SuppressWarnings("boxing")
	@Override
	public String toString() {
		return String.format("DfsStreamKey[hash=%08x]", hash); //$NON-NLS-1$
	}

	private static final class ByteArrayDfsStreamKey extends DfsStreamKey {
		private final DfsRepositoryDescription repo;

		private final byte[] name;

		ByteArrayDfsStreamKey(DfsRepositoryDescription repo, byte[] name,
				@Nullable PackExt ext) {
			super(repo.hashCode() * 31 + Arrays.hashCode(name), ext);
			this.repo = repo;
			this.name = name;
		}

		@Override
		public boolean equals(Object o) {
			if (o instanceof ByteArrayDfsStreamKey) {
				ByteArrayDfsStreamKey k = (ByteArrayDfsStreamKey) o;
				return hash == k.hash && repo.equals(k.repo)
						&& Arrays.equals(name, k.name);
			}
			return false;
		}
	}
}