com.swirlds.common.crypto.Hashable Maven / Gradle / Ivy
Show all versions of swirlds-common Show documentation
/*
* Copyright (C) 2016-2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.swirlds.common.crypto;
import edu.umd.cs.findbugs.annotations.Nullable;
public interface Hashable {
/**
* If this object is not self hashing (i.e. {@link #isSelfHashing()} returns false) then this method returns
* an up to date hash of the contents of the object if it has been computed, or null if the hash
* has not yet been computed. The hash returned should be the last hash passed to {@link #setHash(Hash)},
* or null if that method has never been called.
*
* If this object is self hashing (i.e. {@link #isSelfHashing()} returns true) then this method must always
* return a non-null hash that is up to date with respect to the data in this object. It is ok
* if computation of the hash of such an object is delayed until this method is actually called.
*
* This method must never return a non-null hash that does not match the contents of this object.
*
* @return a valid hash or null
*/
@Nullable
Hash getHash();
/**
* If this object is not self hashing (i.e. {@link #isSelfHashing()} returns false) then this
* method is used to set the hash of this object.
*
* If this object is self hashing (i.e. {@link #isSelfHashing()} returns true) then this
* method should throw an {@link UnsupportedOperationException}.
*
* @param hash
* the hash of the object
* @throws UnsupportedOperationException
* if this object is self hashing
*/
void setHash(Hash hash);
/**
* This method must be called when an object is mutated in a way that makes the current hash no longer valid.
*
* If this object is not self hashing (i.e. {@link #isSelfHashing()} returns false) then this method should
* cause {@link #getHash()} to return null if it is called afterwards.
*
* If this object is self hashing (i.e. {@link #isSelfHashing()} returns true) then it should either be a
* no-op, or it can be used to force the object to recompute its hash (at the implementer's discretion).
*/
default void invalidateHash() {
if (!isSelfHashing()) {
setHash(null);
}
}
/**
* A method by which the object can indicate whether it calculates its own hash or it is hashed externally.
*
* @return true if this object calculates its own hash, false otherwise
*/
default boolean isSelfHashing() {
return false;
}
}