add changelog
[platform/upstream/gdbm.git] / src / gdbmfetch.c
1 /* gdbmfetch.c - Find a key and return the associated data.  */
2
3 /* This file is part of GDBM, the GNU data base manager.
4    Copyright (C) 1990, 1991, 1993, 2007, 2011, 2013 Free Software Foundation,
5    Inc.
6
7    GDBM is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11
12    GDBM is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GDBM. If not, see <http://www.gnu.org/licenses/>.   */
19
20 /* Include system configuration before all else. */
21 #include "autoconf.h"
22
23 #include "gdbmdefs.h"
24
25 /* Look up a given KEY and return the information associated with that KEY.
26    The pointer in the structure that is  returned is a pointer to dynamically
27    allocated memory block.  */
28
29 datum
30 gdbm_fetch (GDBM_FILE dbf, datum key)
31 {
32   datum  return_val;            /* The return value. */
33   int    elem_loc;              /* The location in the bucket. */
34   char  *find_data;             /* Returned from find_key. */
35   int    hash_val;              /* Returned from find_key. */
36
37   /* Set the default return value. */
38   return_val.dptr  = NULL;
39   return_val.dsize = 0;
40
41   /* Initialize the gdbm_errno variable. */
42   gdbm_errno = GDBM_NO_ERROR;
43
44   /* Find the key and return a pointer to the data. */
45   elem_loc = _gdbm_findkey (dbf, key, &find_data, &hash_val);
46
47   /* Copy the data if the key was found.  */
48   if (elem_loc >= 0)
49     {
50       /* This is the item.  Return the associated data. */
51       return_val.dsize = dbf->bucket->h_table[elem_loc].data_size;
52       if (return_val.dsize == 0)
53         return_val.dptr = (char *) malloc (1);
54       else
55         return_val.dptr = (char *) malloc (return_val.dsize);
56       if (return_val.dptr == NULL) _gdbm_fatal (dbf, _("malloc error"));
57       memcpy (return_val.dptr, find_data, return_val.dsize);
58     }
59
60   /* Check for an error and return. */
61   if (return_val.dptr == NULL) gdbm_errno = GDBM_ITEM_NOT_FOUND;
62   return return_val;
63 }