Debian Codegraph @

lib/proc/proc_cast.c

raw symbols SCIP
1 /*
2 Copyright(C) 2018 Horimoto Yasuhiro <[email protected]>
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 #include "../grn_proc.h"
20 #include "../grn_expr.h"
21
22 #include <groonga/plugin.h>
23
24 static grn_obj *
25 func_cast_loose(grn_ctx *ctx, int nargs, grn_obj **args, grn_user_data *user_data)
26 {
27 grn_obj *type;
28 grn_obj *value;
29 grn_obj *default_value;
30 grn_id type_id;
31 grn_rc rc;
32 grn_obj *casted_value = NULL;
33
34 if (nargs != 3) {
35 GRN_PLUGIN_ERROR(ctx, GRN_INVALID_ARGUMENT,
36 "cast_loose(): wrong number of arguments (%d for 3)",
37 nargs);
38 return NULL;
39 }
40
41 type = args[0];
42 if (!grn_obj_is_type(ctx, type)) {
43 grn_obj inspected;
44 GRN_TEXT_INIT(&inspected, 0);
45 grn_inspect(ctx, &inspected, type);
46 GRN_PLUGIN_ERROR(ctx, GRN_INVALID_ARGUMENT,
47 "cast_loose(): the first argument must be type: <%.*s>",
48 (int)GRN_TEXT_LEN(&inspected),
49 GRN_TEXT_VALUE(&inspected));
50 GRN_OBJ_FIN(ctx, &inspected);
51 return NULL;
52 }
53 type_id = grn_obj_id(ctx, type);
54
55 value = args[1];
56 default_value = args[2];
57
58 casted_value = grn_plugin_proc_alloc(ctx, user_data, type_id, 0);
59 if (!casted_value) {
60 return NULL;
61 }
62
63 rc = grn_obj_cast(ctx, value, casted_value, false);
64 if (rc != GRN_SUCCESS) {
65 rc = grn_obj_cast(ctx, default_value, casted_value, false);
66 if (rc != GRN_SUCCESS) {
67 char type_name[GRN_TABLE_MAX_KEY_SIZE];
68 int type_name_size;
69 grn_obj inspected;
70 type_name_size = grn_obj_name(ctx, type, type_name, sizeof(type_name));
71 GRN_TEXT_INIT(&inspected, 0);
72 grn_inspect(ctx, &inspected, default_value);
73 GRN_PLUGIN_ERROR(ctx, GRN_INVALID_ARGUMENT,
74 "cast_loose(): failed to set the default value: "
75 "<%.*s>: <%.*s>",
76 type_name_size,
77 type_name,
78 (int)GRN_TEXT_LEN(&inspected),
79 GRN_TEXT_VALUE(&inspected));
80 GRN_OBJ_FIN(ctx, &inspected);
81 }
82 }
83
84 return casted_value;
85 }
86
87 void
88 grn_proc_init_cast_loose(grn_ctx *ctx)
89 {
90 grn_proc_create(ctx, "cast_loose", -1, GRN_PROC_FUNCTION,
91 func_cast_loose, NULL, NULL, 0, NULL);
92 }