chiark / gitweb /
@@ -2,9 +2,13 @@
[chiark-tcl.git] / cdb / lookup.c
1 /*
2  * cdb, cdb-wr - Tcl bindings for tinycdb and a journalling write extension
3  * Copyright 2006 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, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18  * 02110-1301, USA.
19  */
20
21 #include "chiark_tcl_cdb.h"
22
23 int cht_cdb_donesomelookup(Tcl_Interp *ip, void *db_v,
24                            Tcl_Obj *def, Tcl_Obj **result,
25                            const Byte *data, int dlen,
26                            int (*storeanswer)(Tcl_Interp *ip, Tcl_Obj **result,
27                                               const Byte *data, int len)) {
28   if (dlen>0) return storeanswer(ip, result, data, dlen);
29   if (def) { *result= def; return TCL_OK; }
30   return cht_staticerr(ip, "cdbwr lookup key not found", "CDB NOTFOUND");
31 }
32
33 int cht_cdb_storeanswer_string(Tcl_Interp *ip, Tcl_Obj **result,
34                                const Byte *data, int len) {
35   *result= Tcl_NewStringObj(data, len);
36   if (!*result) return cht_staticerr(ip, "Tcl_NewStringObj failed for"
37        " lookup (utf-8 encoding problem?)", "CDB BADSTRING");
38   return TCL_OK;
39 }
40   
41 int cht_cdb_storeanswer_hb(Tcl_Interp *ip, Tcl_Obj **result,
42                            const Byte *data, int len) {
43   HBytes_Value val;
44   cht_hb_array(&val, data, len);
45   *result= cht_ret_hb(ip, val);
46   return TCL_OK;
47 }
48
49 int cht_cdb_lookup_cdb(Tcl_Interp *ip, struct cdb *cdb,
50                        const Byte *key, int klen,
51                        const Byte **data_r, int *len_r) {
52   int r;
53   
54   r= cdb_find(cdb, key, klen);
55   if (!r) { *data_r= 0; *len_r= -1; return TCL_OK; }
56   if (r<0) return cht_posixerr(ip, errno, "cdb_find failed");
57   assert(r==1);
58   *len_r= cdb_datalen(cdb);
59   assert(*len_r > 0);
60   *data_r= cdb_getdata(cdb);
61   if (!*data_r) return cht_posixerr(ip, errno, "cdb_getdata failed");
62   return TCL_OK;
63 }
64
65 CHT_INIT(cdb,
66          CHTI_OTHER(hbytes),
67          CHTI_COMMANDS(cht_cdbtoplevel_entries))