NAME
djb2_hash(3f) - [M_hashkeys:bucket_hash] djb2 string hash (algorithm by Daniel J. Bernstein)
(LICENSE:PD)
SYNOPSIS
function djb2_hash_arr(anything,continue) result(hash_128)
class(*),intent(in) :: anything(:)
logical,intent(in),optional :: continue
!! use,intrinsic : ISO_FORTRAN_ENV, only : int64
integer(kind=int128) :: hash_128
DESCRIPTION
djb2_hash(3f) is based on the string hash routine commonly known as
djb2(3c). This algorithm was first described by Dan J. Bernstein many
years ago in comp.lang.c. This version returns a value calculated
using a 64-bit hash, which is returned as a 128bit value (not always
available in Fortran) to allow the value to always be a positive
value; as Fortran does not (currently) support a standard unsigned
integer. If the value is changed to be a 64-bit value on platforms
that do not support 128-bit INTEGER values the value may be negative,
but is otherwise usable.
Such non-reversible hashes may be used for data or file fingerprints,
to confirm unchanging results during regression testing, ...
More information is widely available on string hashes (including the
well-known djb2(3c) algorithm) on such sources as Wikipedia. Consult
such resources to confirm the suitability of this algorithm for your
use. This algorithm was probably first proposed as a bucket hash.
The algorithm does not consider the Endian of the programming
environment.
OPTIONS
STR May be a CHARACTER string or an array of common intrinsic
types. Currently, the types defined in the procedure
are character(len=*); complex; integer(kind=int8);
integer(kind=int16); integer(kind=int32); integer(kind=int64);
integer(kind=int128); real(kind=real32); real(kind=real64);
real(kind=real128).
CONTINUE indicate whether to continue accumulating the hash value
from the last call. This is not threadsafe. This allows
for continued hashes so that a hash can be calculated for
a series of calls.
RETURNS
djb2_hash A 128-bit INTEGER hash value for the (possibly accumulated) data.
EXAMPLE
Sample program:
program demo_djb2_hash
use M_hashkeys, only : djb2_hash, int128
implicit none
integer(kind=int128) :: hash
character(len=:),allocatable :: string
integer :: i
! string
string='test djb2_hash'
hash=djb2_hash(string)
write(*,*)'string=',string,' hash=',hash
! array of characters
hash=djb2_hash(['t','e','s','t',' ','d','j','b','2','_','h','a','s','h'])
write(*,*)'string=',string,' hash=',hash
! continued hash
hash=djb2_hash(['t','e','s','t'])
hash=djb2_hash([' ','d','j','b','2'],continue=.true.)
hash=djb2_hash(['_','h','a','s','h'],continue=.true.)
write(*,*)'string=',string,' hash=',hash
! array of integers
hash=djb2_hash([(i,i=0,100)])
write(*,*)'hash for values 0 to 100 is ',hash
!
end program demo_djb2_hash
Arguments
Type |
Intent | Optional | Attributes |
|
Name |
|
class(*),
|
intent(in) |
|
|
:: |
anything(:) |
|
logical,
|
intent(in), |
optional |
|
:: |
continue |
|
Return Value
integer(kind=int128)