Insert or update a key-value pair
| Type | Intent | Optional | Attributes | Name | ||
|---|---|---|---|---|---|---|
| class(json_hash_table), | intent(inout) | :: | me | |||
| character(kind=CK, len=*), | intent(in) | :: | key |
key to insert. This will be preprocessed (trimmed and/or lowercased) according to the settings of the hash table. |
||
| type(json_value), | pointer | :: | value |
value to associate with the key. This is a pointer to a JSON value. |
subroutine hash_table_insert(me, key, value) class(json_hash_table), intent(inout) :: me character(kind=CK,len=*), intent(in) :: key !! key to insert. This will be preprocessed !! (trimmed and/or lowercased) according to the !! settings of the hash table. type(json_value),pointer :: value !! value to associate with the key. !! This is a pointer to a JSON value. integer(IK) :: bucket_idx !! index of the bucket for this key real(RK) :: current_load !! current load factor of the hash table character(kind=CK,len=:), allocatable :: key_to_insert !! the key after preprocessing !! (trimming and/or lowercasing) type(hash_node_t), pointer :: current, new_node !! pointers for traversing the linked list in the !! bucket and for the new node to insert ! Check if we need to resize current_load = real(me%size, RK) / real(me%capacity, RK) if (current_load >= me%load_factor) then call me%resize(me%capacity * 2_IK) end if ! preprocess key for insertion (case-insensitive if enabled) key_to_insert = me%preprocess_key(key) bucket_idx = me%hash(key_to_insert) current => me%buckets(bucket_idx)%next ! Check if key already exists do while (associated(current)) if (me%keys_equal(current%key, key_to_insert)) then ! Update existing value current%value => value return end if current => current%next end do ! Insert new node at the beginning allocate(new_node) new_node%key = key_to_insert new_node%value => value new_node%next => me%buckets(bucket_idx)%next me%buckets(bucket_idx)%next => new_node me%size = me%size + 1 end subroutine hash_table_insert