chiark / gitweb /
remove fsf street address
[chiark-tcl.git] / cdb / lookup.c
1 /*
2  * cdb, cdb-wr - Tcl bindings for tinycdb and a journalling write extension
3  * Copyright 2006-2012 Ian Jackson
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this library; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "chiark_tcl_cdb.h"
20
21 int cht_cdb_donesomelookup(Tcl_Interp *ip, void *db_v,
22                            Tcl_Obj *def, Tcl_Obj **result,
23                            const Byte *data, int dlen,
24                            int (*storeanswer)(Tcl_Interp *ip, Tcl_Obj **result,
25                                               const Byte *data, int len)) {
26   if (dlen>0) return storeanswer(ip, result, data, dlen);
27   if (def) { *result= def; return TCL_OK; }
28   return cht_staticerr(ip, "cdbwr lookup key not found", "CDB NOTFOUND");
29 }
30
31 int cht_cdb_storeanswer_string(Tcl_Interp *ip, Tcl_Obj **result,
32                                const Byte *data, int len) {
33   *result= Tcl_NewStringObj(data, len);
34   if (!*result) return cht_staticerr(ip, "Tcl_NewStringObj failed for"
35        " lookup (utf-8 encoding problem?)", "CDB BADSTRING");
36   return TCL_OK;
37 }
38   
39 int cht_cdb_storeanswer_hb(Tcl_Interp *ip, Tcl_Obj **result,
40                            const Byte *data, int len) {
41   HBytes_Value val;
42   cht_hb_array(&val, data, len);
43   *result= cht_ret_hb(ip, val);
44   return TCL_OK;
45 }
46
47 int cht_cdb_lookup_cdb(Tcl_Interp *ip, struct cdb *cdb,
48                        const Byte *key, int klen,
49                        const Byte **data_r, int *len_r) {
50   int r;
51   
52   r= cdb_find(cdb, key, klen);
53   if (!r) { *data_r= 0; *len_r= -1; return TCL_OK; }
54   if (r<0) return cht_posixerr(ip, errno, "cdb_find failed");
55   assert(r==1);
56   *len_r= cdb_datalen(cdb);
57   assert(*len_r > 0);
58   *data_r= cdb_getdata(cdb);
59   if (!*data_r) return cht_posixerr(ip, errno, "cdb_getdata failed");
60   return TCL_OK;
61 }
62
63 CHT_INIT(cdb,
64          CHTI_OTHER(hbytes),
65          CHTI_COMMANDS(cht_cdbtoplevel_entries))