Branch data Line data Source code
1 : : /* cdb_make_add.c: basic cdb_make_add routine
2 : : *
3 : : * This file is a part of tinycdb package.
4 : : * Copyright (C) 2001-2023 Michael Tokarev <mjt+cdb@corpit.ru>
5 : : *
6 : : * Permission is hereby granted, free of charge, to any person obtaining a
7 : : * copy of this software and associated documentation files (the "Software"),
8 : : * to deal in the Software without restriction, including without limitation
9 : : * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 : : * and/or sell copies of the Software, and to permit persons to whom the
11 : : * Software is furnished to do so, subject to the following conditions:
12 : : *
13 : : * The above copyright notice and this permission notice shall be included
14 : : * in all copies or substantial portions of the Software.
15 : : *
16 : : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : : * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : : * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 : : * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : : * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 : : * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 : : * DEALINGS IN THE SOFTWARE.
23 : : */
24 : :
25 : : #include <stdlib.h> /* for malloc */
26 : : #include "cdb_int.h"
27 : :
28 : : int internal_function
29 : 8 : _cdb_make_add(struct cdb_make *cdbmp, unsigned hval,
30 : : const void *key, unsigned klen,
31 : : const void *val, unsigned vlen)
32 : : {
33 : : unsigned char rlen[8];
34 : : struct cdb_rl *rl;
35 : : unsigned i;
36 [ + - ]: 8 : if (klen > 0xffffffff - (cdbmp->cdb_dpos + 8) ||
37 [ - + ]: 8 : vlen > 0xffffffff - (cdbmp->cdb_dpos + klen + 8))
38 : 0 : return errno = ENOMEM, -1;
39 : 8 : i = hval & 255;
40 : 8 : rl = cdbmp->cdb_rec[i];
41 [ - + - - ]: 8 : if (!rl || rl->cnt >= sizeof(rl->rec)/sizeof(rl->rec[0])) {
42 : 8 : rl = (struct cdb_rl*)malloc(sizeof(struct cdb_rl));
43 [ - + ]: 8 : if (!rl)
44 : 0 : return errno = ENOMEM, -1;
45 : 8 : rl->cnt = 0;
46 : 8 : rl->next = cdbmp->cdb_rec[i];
47 : 8 : cdbmp->cdb_rec[i] = rl;
48 : : }
49 : 8 : i = rl->cnt++;
50 : 8 : rl->rec[i].hval = hval;
51 : 8 : rl->rec[i].rpos = cdbmp->cdb_dpos;
52 : 8 : ++cdbmp->cdb_rcnt;
53 : 8 : cdb_pack(klen, rlen);
54 : 8 : cdb_pack(vlen, rlen + 4);
55 [ + - + - ]: 16 : if (_cdb_make_write(cdbmp, rlen, 8) < 0 ||
56 [ - + ]: 16 : _cdb_make_write(cdbmp, key, klen) < 0 ||
57 : 8 : _cdb_make_write(cdbmp, val, vlen) < 0)
58 : 0 : return -1;
59 : 8 : return 0;
60 : : }
61 : :
62 : : int
63 : 0 : cdb_make_add(struct cdb_make *cdbmp,
64 : : const void *key, unsigned klen,
65 : : const void *val, unsigned vlen) {
66 : 0 : return _cdb_make_add(cdbmp, cdb_hash(key, klen), key, klen, val, vlen);
67 : : }
|