Remove support for outdated libGrammar, replaced by Grammar2
[SXSI/xpathcomp.git] / src / common_stub.cpp
1 #include <unordered_map>
2 #include <string>
3
4 #include "common_stub.hpp"
5
6 extern "C" {
7 #include <sys/time.h>
8 #include <sys/resource.h>
9 }
10
11 using std::string;
12 using std::pair;
13 using std::unordered_map;
14 using std::make_pair;
15
16 typedef unordered_map<string, pair<struct custom_operations*, size_t>> type_map_t;
17 static type_map_t * type_map = 0;
18 static value * cpp_exception = 0;
19
20 static void init_error()
21 {
22   caml_failwith("C++: initialization error");
23 }
24
25 static void init_exception()
26 {
27   cpp_exception = caml_named_value("CPlusPlusError");
28   if (cpp_exception == 0)
29     init_error();
30 }
31
32 static void init_type_map()
33 {
34   if (type_map == 0)
35     type_map = new type_map_t();
36   if (type_map == 0)
37     init_error();
38 }
39
40 void register_custom_(char* name,
41                       size_t size,
42                       void (*finalize)(value v))
43 {
44   if (type_map == 0) init_error();
45   struct custom_operations * ops =
46     (struct custom_operations*) calloc(1, sizeof(struct custom_operations));
47   ops->identifier = name;
48   ops->finalize = finalize;
49   ops->compare = custom_compare_default;
50   ops->hash = custom_hash_default;
51   ops->serialize = custom_serialize_default;
52   ops->deserialize = custom_deserialize_default;
53   type_map->insert(make_pair(string(name), make_pair(ops, size)));
54 }
55
56 value alloc_custom_(char* name)
57 {
58   CAMLparam0();
59   CAMLlocal1(result);
60   if (type_map == 0) init_error();
61   string key = string(name);
62   type_map_t::iterator it = type_map->find(key);
63   if (it == type_map->end())
64     result = Val_unit;
65   else
66     result = caml_alloc_custom(it->second.first, it->second.second, 1, 1);
67
68   CAMLreturn(result);
69 }
70
71
72 extern "C" value sxsi_cpp_init(value unit)
73 {
74   struct rlimit rlim;
75   init_exception();
76   init_type_map();
77
78   /* Set the stack space to unlimited */
79   getrlimit(RLIMIT_STACK, &rlim);
80   if (rlim.rlim_max == RLIM_INFINITY && rlim.rlim_cur != RLIM_INFINITY) {
81     rlim.rlim_cur = RLIM_INFINITY;
82     setrlimit(RLIMIT_STACK, &rlim);
83   };
84
85   return Val_unit;
86 }
87
88 void sxsi_raise_msg(char * msg)
89 {
90   if (cpp_exception == 0) init_error();
91   caml_raise_with_string(*cpp_exception, msg);
92 }