summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/kbackupfabric/backup/incremental/identifier/SingleHashIdentifier.java
blob: 9fd61c834ef8d45ea49a610af363ecfea723ff25 (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
package com.keuin.kbackupfabric.backup.incremental.identifier;

import com.keuin.kbackupfabric.util.BytesUtil;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * A simple identifier based on a single hash function.
 * Immutable.
 */
public abstract class SingleHashIdentifier implements ObjectIdentifier {

    private final byte[] hash;
    private final String type;

    protected SingleHashIdentifier(byte[] hash, String type) {
        Objects.requireNonNull(hash);
        Objects.requireNonNull(type);
        this.hash = Arrays.copyOf(hash, hash.length);
        this.type = type;
    }

    /**
     * The hash function.
     *
     * @param file the file to be hashed.
     * @return the hash bytes.
     */
    protected abstract byte[] hash(File file) throws IOException;

    @Override
    public String getIdentification() {
        return type + "-" + BytesUtil.bytesToHex(hash);
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof SingleHashIdentifier)) {
            return false;
        }
        return Arrays.equals(hash, ((SingleHashIdentifier) obj).hash);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(type);
        result = 31 * result + Arrays.hashCode(hash);
        return result;
    }
}