User Guide

Basic usage

The package provides a fhash_tbl_t type with set and get methods for storing and retrieving key-value pairs.

e.g. Declare a table instance

use fhash
...
type(fhash_tbl_t) :: tbl

The fhash_key interface

A extensible interface for generating an instance of fhash_key_t needed to set and get key-value pairs.

The library provides generic support for generating keys from scalar or 1D arrays of integers (integer(int32), integer(int64)) or from scalar character(*)

e.g. Create a key from a string

use fhash, only: key=>fhash_key
...
key('key_string')

For how to extend the fhash_key_t interface to other types, see the custom key demo

The set method

Stores (or overwrites) a key-value pair into the hash table.

Will accept any scalar variable as a value, including (scalar) derived types.

e.g. Set key value pair

use fhash, only: fhash_tbl_t, key=>fhash_key
...
type(fhash_tbl_t) :: tbl

tbl%set(key('key'),value=1)

To store a pointer instead of copying the value, use set_ptr.

The get method

A generic interface for retrieving intrinsic scalar values from the table.

The library provides generic support for retrieving scalar values of the following types:

  • integer(int32), integer(int64)
  • real(real32), real(real64)
  • character(*)
  • logical

e.g. Get integer value for a key

use fhash, only: fhash_tbl_t, key=>fhash_key
...
type(fhash_tbl_t) :: tbl
integer :: v

tbl%get(key('key'),value=v)

An optional integer stat argument may be passed which is non-zero on exit if the retrieval was unsuccessful. Non-zero return values may be one of: FHASH_KEY_NOT_FOUND, FHASH_FOUND_WRONG_TYPE, or FHASH_EMPTY_TABLE.

For how to retrieve derived types see the derived type demo.

To retrieve a pointer instead of copying the value, use get_ptr.

A simple example program

!> Example program demonstrating basic set/get usage
!>  for different key/value types
program fhash_demo
  use fhash, only: fhash_tbl_t, key=>fhash_key
  implicit none

  type(fhash_tbl_t) :: tbl
  integer :: i
  real :: r
  character(:), allocatable :: char
  logical :: bool

  print *, '# fhash demo program: simple-demo'

  call tbl%set(key('my_key_1'), value=10)
  call tbl%set(key('my_key_2'), value=1.0)
  call tbl%set(key(123456), value='a string value')
  call tbl%set(key([1,2,3,4,5]), value=.false.)

  call tbl%get(key('my_key_1'),i)
  call tbl%get(key('my_key_2'),r)
  call tbl%get(key(123456),char)
  call tbl%get(key([1,2,3,4,5]),bool)

  print *, 'Key = "my_key_1"     Value = ',i
  print *, 'Key = "my_key_2"     Value = ',r
  print *, 'Key = 123456         Value = "',char,'"'
  print *, 'Key = [1,2,3,4,5]    Value = ', bool
  print *

end program fhash_demo