Upstream | cc2ee17 | 1970-01-12 13:46:40 +0000 | [diff] [blame^] | 1 | /** |
| 2 | * @file db_insert.c |
| 3 | * Inserting a key-value pair into a DB |
| 4 | * |
| 5 | * @remark Copyright 2002 OProfile authors |
| 6 | * @remark Read the file COPYING |
| 7 | * |
| 8 | * @author Philippe Elie |
| 9 | */ |
| 10 | |
| 11 | #define _GNU_SOURCE |
| 12 | |
| 13 | #include <stdio.h> |
| 14 | #include <stdlib.h> |
| 15 | #include <string.h> |
| 16 | #include <errno.h> |
| 17 | |
| 18 | #include "odb.h" |
| 19 | |
| 20 | int odb_insert(odb_t * odb, odb_key_t key, odb_value_t value) |
| 21 | { |
| 22 | odb_index_t index; |
| 23 | odb_index_t new_node; |
| 24 | odb_node_t * node; |
| 25 | odb_data_t * data; |
| 26 | |
| 27 | data = odb->data; |
| 28 | index = data->hash_base[odb_do_hash(data, key)]; |
| 29 | while (index) { |
| 30 | if (index <= 0 || index >= data->descr->current_size) { |
| 31 | return EINVAL; |
| 32 | } |
| 33 | node = &data->node_base[index]; |
| 34 | if (node->key == key) { |
| 35 | if (node->value + value >= node->value) { |
| 36 | node->value += value; |
| 37 | } else { |
| 38 | /* post profile tools must handle overflow */ |
| 39 | node->value = ~(odb_value_t)0; |
| 40 | } |
| 41 | return 0; |
| 42 | } |
| 43 | |
| 44 | index = node->next; |
| 45 | } |
| 46 | |
| 47 | /* no locking is necessary: iteration interface retrieve data through |
| 48 | * the node_base array, odb_hash_add_node() increase current_size but |
| 49 | * odb_travel just ignore node with a zero key so on setting the key |
| 50 | * atomically update the node */ |
| 51 | new_node = odb_hash_add_node(odb); |
| 52 | if (new_node == ODB_NODE_NR_INVALID) { |
| 53 | return EINVAL; |
| 54 | } |
| 55 | |
| 56 | node = &data->node_base[new_node]; |
| 57 | node->value = value; |
| 58 | node->key = key; |
| 59 | |
| 60 | /* we need to recalculate hash code, hash table has perhaps grown */ |
| 61 | index = odb_do_hash(data, key); |
| 62 | node->next = data->hash_base[index]; |
| 63 | data->hash_base[index] = new_node; |
| 64 | |
| 65 | return 0; |
| 66 | } |