mongory 0.8.2-aarch64-linux → 0.9.0-aarch64-linux

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -0
  3. data/docs/advanced_usage.md +7 -0
  4. data/docs/clang_bridge.md +6 -0
  5. data/ext/mongory_ext/extconf.rb +6 -1
  6. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/config.h +25 -0
  7. data/ext/mongory_ext/mongory-core/src/foundations/config.c +64 -27
  8. data/ext/mongory_ext/mongory-core/src/foundations/config_private.h +1 -0
  9. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool.c +49 -0
  10. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool_private.h +45 -0
  11. data/ext/mongory_ext/mongory-core/src/foundations/utils.c +2 -5
  12. data/ext/mongory_ext/mongory-core/src/foundations/value.c +44 -7
  13. data/ext/mongory_ext/mongory-core/src/matchers/array_record_matcher.c +31 -10
  14. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.c +2 -0
  15. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.c +32 -13
  16. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.c +34 -13
  17. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.c +76 -15
  18. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.h +12 -0
  19. data/ext/mongory_ext/mongory-core/src/matchers/literal_matcher.c +55 -17
  20. data/ext/mongory_ext/mongory_ext.c +35 -724
  21. data/ext/mongory_ext/mongory_ext_internal.h +75 -0
  22. data/ext/mongory_ext/rb_mongory_adapters.c +140 -0
  23. data/ext/mongory_ext/rb_mongory_cmatcher.c +386 -0
  24. data/ext/mongory_ext/rb_mongory_value.c +260 -0
  25. data/lib/core/2.6/mongory_ext.so +0 -0
  26. data/lib/core/2.7/mongory_ext.so +0 -0
  27. data/lib/core/3.0/mongory_ext.so +0 -0
  28. data/lib/core/3.1/mongory_ext.so +0 -0
  29. data/lib/core/3.2/mongory_ext.so +0 -0
  30. data/lib/core/3.3/mongory_ext.so +0 -0
  31. data/lib/core/3.4/mongory_ext.so +0 -0
  32. data/lib/core/4.0/mongory_ext.so +0 -0
  33. data/lib/generators/mongory/install/templates/initializer.rb.erb +5 -0
  34. data/lib/mongory/converters/abstract_converter.rb +6 -5
  35. data/lib/mongory/converters/condition_converter.rb +2 -2
  36. data/lib/mongory/matchers/abstract_matcher.rb +1 -1
  37. data/lib/mongory/matchers/abstract_multi_matcher.rb +2 -2
  38. data/lib/mongory/matchers/array_record_matcher.rb +23 -11
  39. data/lib/mongory/matchers/elem_match_matcher.rb +2 -0
  40. data/lib/mongory/matchers/eq_matcher.rb +4 -2
  41. data/lib/mongory/matchers/hash_condition_matcher.rb +23 -6
  42. data/lib/mongory/matchers/in_matcher.rb +17 -1
  43. data/lib/mongory/matchers/ne_matcher.rb +7 -6
  44. data/lib/mongory/matchers/nin_matcher.rb +2 -6
  45. data/lib/mongory/matchers/regex_matcher.rb +29 -0
  46. data/lib/mongory/matchers.rb +7 -4
  47. data/lib/mongory/version.rb +1 -1
  48. data/lib/mongory.rb +57 -5
  49. metadata +7 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 806ee035e2422ad023a16fb1acdf04b8f4709a4c3c74c7377e7e0a7c71f0daf1
4
- data.tar.gz: edffc93ca014408eeb8d478f8dc0d696bb22c8ee363005b114500f9675b9c53c
3
+ metadata.gz: 2144ae1fbdc5a722e784cc0510d1c8a9c0c6fb8dd20105a59fc56ced9defa0e7
4
+ data.tar.gz: 3615514859a9f09c2dc047d1e7e131022d6eed5d787176ecf16f6c398500d6af
5
5
  SHA512:
6
- metadata.gz: 21e989778eed8a24839f879fb78839940f32f4159c97eb0fd64263013d3b344875d6a21d1769eaf54ecb1adc796a7598a30bdbf185cd1a434b28452d736f3b72
7
- data.tar.gz: 662e7dfe7805775f82e94e6add5219cd952ade8103dd3d23fb5eabec85a614acc398e199678f9f8708b4e1b2781abf2bb81125863d488136e77f02ea5ad9c58f
6
+ metadata.gz: 7b636f0b7a96e631dcb0438287546a0ee513ff39f5275b795799fcbf2a70ffd4964fa31af1180858bbec153716dc85d87c33dabab05b10565a18eac89f605ba8
7
+ data.tar.gz: ebb6ea699893f18d00e68a9b5026d776c6975cf65aa2c73e2706b2ee74eb96b9b99671b71a29e62710c4db9cf8a6bb82856381f74157d98bfcae44403920e273
data/CHANGELOG.md CHANGED
@@ -1,7 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.9.0] - 2026-11-17
4
+
5
+ Aligns with mongory-spec `0.2.0` and `mongory-core` `v0.2.0`.
6
+
7
+ ### Breaking Changes
8
+ - **Unknown operators raise `Mongory::TypeError`**: a condition key that starts with `$` and is not a registered operator (e.g. `{ age: { '$foo' => 1 } }`) is now rejected, as MongoDB does. It was previously matched as a field named `$foo`, which silently never matched.
9
+
10
+ ### Features
11
+ - **`$options` for `$regex`**: `{ '$regex' => '^ab', '$options' => 'i' }` accepts the MongoDB flags `i`, `m` and `s`. Other flags, a non-string value, `$options` without `$regex`, or `$options` with a `Regexp` pattern raise `Mongory::TypeError`. On array fields, `$options` follows `$regex` into the implicit `$elemMatch`.
12
+ - **C Extension (`CMatcher`) `$options` Adapter**: registers a `$options` regex adapter with `mongory-core` so `QueryMatcher` and `CMatcher` enforce identical regex option rules.
13
+ - **Configuration & Helpers**:
14
+ - Add `Mongory.enable_c_extension_by_default!` configuration option and Rails initializer template update.
15
+ - Add `Mongory.build_matcher` helper returning `CMatcher` or `QueryMatcher` according to `c_extension_by_default?`.
16
+ - **MongoDB Array & Equality Alignment**:
17
+ - Route element-level comparison operators (`$gt`, `$gte`, `$lt`, `$lte`, `$regex`, scalar `$eq`) on array records into implicit `$elemMatch`.
18
+ - Support array element inclusion semantics in `$eq` / `$ne`, and enforce non-Hash `$elemMatch` validation.
19
+
20
+ ### Fixes
21
+ - **`QueryMatcher` & Config**:
22
+ - Expand integer/whole-float numeric equivalents in `$in` / `$nin` and guard `$elemMatch` against non-`Array` records.
23
+ - Unify freeze behavior across converters and matchers in `Mongory.configure`.
24
+ - **C Extension (`mongory_ext`)**:
25
+ - Refactor `mongory_ext.c` into focused modules (`rb_mongory_cmatcher.c`, `rb_mongory_value.c`, `rb_mongory_adapters.c`), switch `CMatcher` to standard `TypedData` `alloc_func` / `initialize`, forbid `initialize_copy`, and handle single bare keyword-style hash arguments on Ruby 3.0+.
26
+ - Make per-matcher scratch pools re-entrant, thread-safe, and exception-safe using `scratch_free_list` and `rb_ensure` in `CMatcher#match?` and `CMatcher#explain`, and preserve `pattern->pool` in `rb_mongory_regex_cache`.
27
+ - Link `-lpthread` directly in `extconf.rb` without the `mkmf` executable link probe to avoid prebuilt Linux Ruby 3.2 build failures.
28
+ - Switch `mongory-core` submodule URL in `.gitmodules` to HTTPS and update `mongory-core` to `v0.2.0` (thread safety, `mongory_table` equality, LLP64 `ERANGE` check, and empty `$elemMatch`/`$every` array handling).
29
+
3
30
  ## [0.8.2] - 2026-11-14
4
31
 
32
+ ### Features & Platform Support
33
+ - **Ruby 3.4 & 4.0 Support**: Added precompiled native gems and CI test coverage for Ruby `3.4` and `4.0` across Linux (`x86_64-linux`, `aarch64-linux`, `x86_64-linux-musl`, `aarch64-linux-musl`), macOS (`x86_64-darwin`, `arm64-darwin`), and Windows (`x64-mingw32`, `x64-mingw-ucrt`).
34
+
5
35
  ### Fixes
6
36
  - **Key & Array Index Matching (`QueryMatcher` & `CMatcher`)**:
7
37
  - Normalize `Integer` condition keys to `String` in `KeyConverter` (consistent with `Symbol` keys), preventing `TypeError` in `CMatcher` and `NoMethodError` in `FieldMatcher`.
@@ -13,6 +43,7 @@
13
43
  - Fix memory pool type mismatch and out-of-bounds `owner` read in `CMatcher#trace` and uninitialized `owner` pointer in `CMatcher#enable_trace`.
14
44
  - Prevent memory leaks when `CMatcher.new`, `trace`, `enable_trace`, or `disable_trace` raises `Mongory::TypeError`.
15
45
  - Coerce non-string/non-symbol hash keys in `DataConverter`-converted condition values and register them in `mark_list`.
46
+ - Undefine default allocator (`rb_undef_alloc_func`) on `Mongory::CMatcher` to eliminate `T_DATA` allocator warnings on Ruby 3.2+.
16
47
  - **Core (`mongory-core` submodule)**:
17
48
  - Fix off-by-one capacity growth condition in `mongory_array` and `mongory_table`.
18
49
  - Propagate `extern_ctx` in `mongory_matcher_field_new` so nested custom matchers receive the Ruby matcher context.
@@ -26,6 +26,13 @@ posts.mongory
26
26
  .where(:tags.elem_match => { :name => 'ruby', :priority.gt => 5 })
27
27
  .where(:comments.every => { :approved => true })
28
28
 
29
+ # Implicit array element & index queries (MongoDB-compatible)
30
+ posts.mongory
31
+ .where(:scores.gt => 80) # Matches if any score > 80
32
+ .where(:tags.ne => 'archived') # Matches if no tag is 'archived'
33
+ .where('tags.0' => 'ruby') # Matches if first tag is 'ruby'
34
+ .where('tags.-1' => 'featured') # Matches if last tag is 'featured'
35
+
29
36
  # Since Matcher provide `to_proc` method, you could treat Matcher as a block
30
37
  matcher = Mongory::QueryMatcher.new({
31
38
  :tags.elem_match => { :name => 'ruby', :priority.gt => 5 },
data/docs/clang_bridge.md CHANGED
@@ -69,6 +69,12 @@ query.explain # print core-level matcher tree
69
69
  # Or use CMatcher directly
70
70
  matcher = Mongory::CMatcher.new(:age.gte => 18)
71
71
  records.select { |r| matcher.match?(r) }
72
+
73
+ # Or enable the C extension globally by default in Mongory.configure:
74
+ Mongory.configure do |mc|
75
+ mc.enable_c_extension_by_default!
76
+ end
77
+ records.mongory.where(:age.gte => 18).to_a # automatically uses CQueryBuilder
72
78
  ```
73
79
 
74
80
  ## Tracing and debugging
@@ -60,13 +60,18 @@ if RbConfig::CONFIG['host_os'] =~ /darwin/
60
60
  # Use dynamic_lookup so Ruby symbols (rb_*) are resolved by the host interpreter at dlopen time
61
61
  $LDFLAGS << ' -Wl,-undefined,dynamic_lookup'
62
62
  $DLDFLAGS << ' -Wl,-undefined,dynamic_lookup'
63
+ elsif RbConfig::CONFIG['host_os'] !~ /mswin|mingw|android|haiku/
64
+ # Avoid mkmf link probes (`have_library` -> `have_devel?` executable link test) which can fail
65
+ # on prebuilt toolcache Rubies; pass -lpthread directly where POSIX pthreads may be separate.
66
+ $LOCAL_LIBS << ' -lpthread' unless $LIBS.include?('-lpthread') || $LOCAL_LIBS.include?('-lpthread')
63
67
  end
64
68
 
65
69
  # Let mkmf generate rules by listing all sources and corresponding objects
66
70
  $INCFLAGS << ' -I.'
67
71
  $INCFLAGS << " -I#{File.join(core_src_dir, 'foundations')}"
68
72
  $INCFLAGS << " -I#{File.join(core_src_dir, 'matchers')}"
69
- all_sources = ['mongory_ext.c'] + foundations_src + matchers_src
73
+ ext_src = Dir.glob(File.join(__dir__, '*.c')).map { |src| File.basename(src) }.sort
74
+ all_sources = ext_src + foundations_src + matchers_src
70
75
  $srcs = all_sources
71
76
  $objs = all_sources.map { |src| "#{File.basename(src, '.c')}.o" }
72
77
 
@@ -30,6 +30,22 @@
30
30
  */
31
31
  typedef bool (*mongory_regex_func)(mongory_memory_pool *pool, mongory_value *pattern, mongory_value *value);
32
32
 
33
+ /**
34
+ * @brief Function pointer type for regex matching with `$options` flags.
35
+ *
36
+ * Called instead of `mongory_regex_func` when a `$regex` condition has a
37
+ * non-empty sibling `$options`.
38
+ *
39
+ * @param pool The memory pool to use for any allocations during the match.
40
+ * @param pattern The regex pattern (string or regex type).
41
+ * @param options Validated flags, a non-empty combination of 'i' (caseless),
42
+ * 'm' (multiline anchors) and 's' (dot matches newline).
43
+ * @param value The value to match against (typically a string).
44
+ * @return bool True if the value matches the pattern, false otherwise.
45
+ */
46
+ typedef bool (*mongory_regex_options_func)(mongory_memory_pool *pool, mongory_value *pattern, const char *options,
47
+ mongory_value *value);
48
+
33
49
  /**
34
50
  * @brief Function pointer type for stringifying a regex pattern.
35
51
  *
@@ -114,6 +130,15 @@ void mongory_cleanup();
114
130
  */
115
131
  void mongory_regex_func_set(mongory_regex_func func);
116
132
 
133
+ /**
134
+ * @brief Sets the regex matching function that supports `$options` flags.
135
+ *
136
+ * If not set, compiling a condition with a non-empty `$options` fails.
137
+ *
138
+ * @param func The custom regex function to use.
139
+ */
140
+ void mongory_regex_options_func_set(mongory_regex_options_func func);
141
+
117
142
  /**
118
143
  * @brief Sets the custom regex stringify function.
119
144
  *
@@ -21,6 +21,24 @@
21
21
  #include "mongory-core/foundations/table.h"
22
22
  #include "mongory-core/foundations/value.h"
23
23
 
24
+ #if defined(_WIN32)
25
+ # ifndef WIN32_LEAN_AND_MEAN
26
+ # define WIN32_LEAN_AND_MEAN
27
+ # endif
28
+ # include <windows.h>
29
+ static volatile LONG mongory_config_spinlock = 0;
30
+ static inline void mongory_config_lock(void) {
31
+ while (InterlockedExchange(&mongory_config_spinlock, 1) != 0) {
32
+ }
33
+ }
34
+ static inline void mongory_config_unlock(void) { InterlockedExchange(&mongory_config_spinlock, 0); }
35
+ #else
36
+ # include <pthread.h>
37
+ static pthread_mutex_t mongory_config_mutex = PTHREAD_MUTEX_INITIALIZER;
38
+ static inline void mongory_config_lock(void) { pthread_mutex_lock(&mongory_config_mutex); }
39
+ static inline void mongory_config_unlock(void) { pthread_mutex_unlock(&mongory_config_mutex); }
40
+ #endif
41
+
24
42
  static bool mongory_regex_default_func(mongory_memory_pool *pool, mongory_value *pattern, mongory_value *value);
25
43
  static char *mongory_regex_default_stringify_func(mongory_memory_pool *pool, mongory_value *pattern);
26
44
 
@@ -29,6 +47,7 @@ mongory_memory_pool *mongory_internal_pool = NULL;
29
47
  // Global adapter for regex operations.
30
48
  mongory_regex_adapter mongory_internal_regex_adapter = {
31
49
  .match_func = mongory_regex_default_func,
50
+ .options_match_func = NULL,
32
51
  .stringify_func = mongory_regex_default_stringify_func,
33
52
  };
34
53
  // Global table mapping matcher names (e.g., "$eq") to their build functions.
@@ -90,6 +109,14 @@ void mongory_regex_func_set(mongory_regex_func func) {
90
109
  mongory_internal_regex_adapter.match_func = func;
91
110
  }
92
111
 
112
+ /**
113
+ * @brief Sets the global regex matching function used with `$options`.
114
+ * @param func The custom regex function to use.
115
+ */
116
+ void mongory_regex_options_func_set(mongory_regex_options_func func) {
117
+ mongory_internal_regex_adapter.options_match_func = func;
118
+ }
119
+
93
120
  /**
94
121
  * @brief Sets the global regex stringify function.
95
122
  * Initializes the regex adapter if it's not already.
@@ -127,7 +154,7 @@ static inline void mongory_matcher_mapping_init() {
127
154
  * @param name The name of the matcher (e.g., "$eq", "$in").
128
155
  * @param build_func A function pointer to the matcher's constructor.
129
156
  */
130
- void mongory_matcher_register(char *name, mongory_matcher_build_func build_func) {
157
+ static void mongory_matcher_register_unlocked(char *name, mongory_matcher_build_func build_func) {
131
158
  // Ensure mapping is initialized.
132
159
  if (mongory_matcher_mapping == NULL) {
133
160
  mongory_matcher_mapping_init();
@@ -148,6 +175,12 @@ void mongory_matcher_register(char *name, mongory_matcher_build_func build_func)
148
175
  // TODO: Check return value of set?
149
176
  }
150
177
 
178
+ void mongory_matcher_register(char *name, mongory_matcher_build_func build_func) {
179
+ mongory_config_lock();
180
+ mongory_matcher_register_unlocked(name, build_func);
181
+ mongory_config_unlock();
182
+ }
183
+
151
184
  /**
152
185
  * @brief Retrieves a matcher build function by its name from the global
153
186
  * mapping.
@@ -156,16 +189,16 @@ void mongory_matcher_register(char *name, mongory_matcher_build_func build_func)
156
189
  * constructor, or NULL if not found.
157
190
  */
158
191
  mongory_matcher_build_func mongory_matcher_build_func_get(char *name) {
159
- if (mongory_matcher_mapping == NULL) {
160
- return NULL; // Mapping not initialized or init failed.
161
- }
162
-
163
- mongory_value *value = mongory_matcher_mapping->get(mongory_matcher_mapping, name);
164
- if (value == NULL || value->type != MONGORY_TYPE_POINTER) {
165
- return NULL; // Not found or not a pointer type as expected.
192
+ mongory_config_lock();
193
+ mongory_matcher_build_func result = NULL;
194
+ if (mongory_matcher_mapping != NULL) {
195
+ mongory_value *value = mongory_matcher_mapping->get(mongory_matcher_mapping, name);
196
+ if (value != NULL && value->type == MONGORY_TYPE_POINTER) {
197
+ result = (mongory_matcher_build_func)value->data.ptr;
198
+ }
166
199
  }
167
-
168
- return (mongory_matcher_build_func)value->data.ptr;
200
+ mongory_config_unlock();
201
+ return result;
169
202
  }
170
203
 
171
204
  /**
@@ -219,6 +252,7 @@ void mongory_matcher_trace_result_colorful_set(bool colorful) {
219
252
  * This function MUST be called before using most other library features.
220
253
  */
221
254
  void mongory_init() {
255
+ mongory_config_lock();
222
256
  // Initialize all global components. Order can be important if one init
223
257
  // depends on another (e.g., most depend on the pool).
224
258
  mongory_internal_pool_init();
@@ -229,23 +263,24 @@ void mongory_init() {
229
263
  // mongory_matcher_mapping being successfully initialized.
230
264
  // TODO: Add checks to ensure initializations were successful before
231
265
  // proceeding.
232
- mongory_matcher_register("$in", mongory_matcher_in_new);
233
- mongory_matcher_register("$nin", mongory_matcher_not_in_new);
234
- mongory_matcher_register("$eq", mongory_matcher_equal_new);
235
- mongory_matcher_register("$ne", mongory_matcher_not_equal_new);
236
- mongory_matcher_register("$gt", mongory_matcher_greater_than_new);
237
- mongory_matcher_register("$gte", mongory_matcher_greater_than_or_equal_new);
238
- mongory_matcher_register("$lt", mongory_matcher_less_than_new);
239
- mongory_matcher_register("$lte", mongory_matcher_less_than_or_equal_new);
240
- mongory_matcher_register("$exists", mongory_matcher_exists_new);
241
- mongory_matcher_register("$present", mongory_matcher_present_new);
242
- mongory_matcher_register("$regex", mongory_matcher_regex_new);
243
- mongory_matcher_register("$and", mongory_matcher_and_new);
244
- mongory_matcher_register("$or", mongory_matcher_or_new);
245
- mongory_matcher_register("$elemMatch", mongory_matcher_elem_match_new);
246
- mongory_matcher_register("$every", mongory_matcher_every_new);
247
- mongory_matcher_register("$not", mongory_matcher_not_new);
248
- mongory_matcher_register("$size", mongory_matcher_size_new);
266
+ mongory_matcher_register_unlocked("$in", mongory_matcher_in_new);
267
+ mongory_matcher_register_unlocked("$nin", mongory_matcher_not_in_new);
268
+ mongory_matcher_register_unlocked("$eq", mongory_matcher_equal_new);
269
+ mongory_matcher_register_unlocked("$ne", mongory_matcher_not_equal_new);
270
+ mongory_matcher_register_unlocked("$gt", mongory_matcher_greater_than_new);
271
+ mongory_matcher_register_unlocked("$gte", mongory_matcher_greater_than_or_equal_new);
272
+ mongory_matcher_register_unlocked("$lt", mongory_matcher_less_than_new);
273
+ mongory_matcher_register_unlocked("$lte", mongory_matcher_less_than_or_equal_new);
274
+ mongory_matcher_register_unlocked("$exists", mongory_matcher_exists_new);
275
+ mongory_matcher_register_unlocked("$present", mongory_matcher_present_new);
276
+ mongory_matcher_register_unlocked("$regex", mongory_matcher_regex_new);
277
+ mongory_matcher_register_unlocked("$and", mongory_matcher_and_new);
278
+ mongory_matcher_register_unlocked("$or", mongory_matcher_or_new);
279
+ mongory_matcher_register_unlocked("$elemMatch", mongory_matcher_elem_match_new);
280
+ mongory_matcher_register_unlocked("$every", mongory_matcher_every_new);
281
+ mongory_matcher_register_unlocked("$not", mongory_matcher_not_new);
282
+ mongory_matcher_register_unlocked("$size", mongory_matcher_size_new);
283
+ mongory_config_unlock();
249
284
  }
250
285
 
251
286
  /**
@@ -256,6 +291,7 @@ void mongory_init() {
256
291
  * prevent memory leaks.
257
292
  */
258
293
  void mongory_cleanup() {
294
+ mongory_config_lock();
259
295
  if (mongory_internal_pool != NULL) {
260
296
  // Freeing the pool should handle all allocations made from it,
261
297
  // including the regex_adapter, matcher_mapping table (and its contents if
@@ -267,4 +303,5 @@ void mongory_cleanup() {
267
303
  // Set other global pointers to NULL to indicate they are no longer valid.
268
304
  // The memory they pointed to should have been managed by the internal pool.
269
305
  mongory_matcher_mapping = NULL; // The table itself and its nodes.
306
+ mongory_config_unlock();
270
307
  }
@@ -7,6 +7,7 @@
7
7
 
8
8
  typedef struct mongory_regex_adapter {
9
9
  mongory_regex_func match_func;
10
+ mongory_regex_options_func options_match_func;
10
11
  mongory_regex_stringify_func stringify_func;
11
12
  } mongory_regex_adapter;
12
13
 
@@ -7,11 +7,41 @@
7
7
  * chunk is allocated and added to the list. Freeing the pool deallocates all
8
8
  * chunks. It also supports tracing externally allocated memory.
9
9
  */
10
+ #if !defined(_WIN32) && (!defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L)
11
+ # define _POSIX_C_SOURCE 200809L
12
+ #endif
13
+
14
+ #include "memory_pool_private.h"
10
15
  #include <mongory-core/foundations/memory_pool.h>
11
16
  #include <stdio.h> // For NULL, though stdlib.h or stddef.h is more common
12
17
  #include <stdlib.h> // For calloc, free, etc.
13
18
  #include <string.h> // For memset
14
19
 
20
+ #if defined(_WIN32)
21
+ # ifndef WIN32_LEAN_AND_MEAN
22
+ # define WIN32_LEAN_AND_MEAN
23
+ # endif
24
+ # include <windows.h>
25
+ typedef CRITICAL_SECTION mongory_mutex_t;
26
+ static inline void mongory_mutex_init(mongory_mutex_t *mtx) { InitializeCriticalSection(mtx); }
27
+ static inline void mongory_mutex_lock(mongory_mutex_t *mtx) { EnterCriticalSection(mtx); }
28
+ static inline void mongory_mutex_unlock(mongory_mutex_t *mtx) { LeaveCriticalSection(mtx); }
29
+ static inline void mongory_mutex_destroy(mongory_mutex_t *mtx) { DeleteCriticalSection(mtx); }
30
+ #else
31
+ # include <pthread.h>
32
+ typedef pthread_mutex_t mongory_mutex_t;
33
+ static inline void mongory_mutex_init(mongory_mutex_t *mtx) {
34
+ pthread_mutexattr_t attr;
35
+ pthread_mutexattr_init(&attr);
36
+ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
37
+ pthread_mutex_init(mtx, &attr);
38
+ pthread_mutexattr_destroy(&attr);
39
+ }
40
+ static inline void mongory_mutex_lock(mongory_mutex_t *mtx) { pthread_mutex_lock(mtx); }
41
+ static inline void mongory_mutex_unlock(mongory_mutex_t *mtx) { pthread_mutex_unlock(mtx); }
42
+ static inline void mongory_mutex_destroy(mongory_mutex_t *mtx) { pthread_mutex_destroy(mtx); }
43
+ #endif
44
+
15
45
  /**
16
46
  * @def MONGORY_INITIAL_CHUNK_SIZE
17
47
  * @brief The initial size in bytes for the first memory chunk allocated by the
@@ -58,6 +88,7 @@ typedef struct mongory_memory_pool_ctx {
58
88
  mongory_memory_node *head; /**< Head of the list of memory chunks. */
59
89
  mongory_memory_node *current; /**< Current chunk to allocate from. */
60
90
  mongory_memory_node *extra; /**< Head of list for externally traced memory. */
91
+ mongory_mutex_t build_lock; /**< Recursive lock for lazy matcher construction. */
61
92
  } mongory_memory_pool_ctx;
62
93
 
63
94
  /**
@@ -208,6 +239,7 @@ static inline void mongory_memory_pool_destroy(mongory_memory_pool *pool) {
208
239
  mongory_memory_pool_node_list_free(ctx->head);
209
240
  // Free the list of externally traced memory chunks.
210
241
  mongory_memory_pool_node_list_free(ctx->extra);
242
+ mongory_mutex_destroy(&ctx->build_lock);
211
243
 
212
244
  memset(ctx, 0,
213
245
  sizeof(mongory_memory_pool_ctx)); // Clear the context structure.
@@ -285,6 +317,7 @@ mongory_memory_pool *mongory_memory_pool_new() {
285
317
  ctx->head = first_chunk;
286
318
  ctx->current = first_chunk;
287
319
  ctx->extra = NULL; // No extra traced allocations initially.
320
+ mongory_mutex_init(&ctx->build_lock);
288
321
 
289
322
  // Initialize pool fields.
290
323
  pool->ctx = ctx;
@@ -296,3 +329,19 @@ mongory_memory_pool *mongory_memory_pool_new() {
296
329
 
297
330
  return pool;
298
331
  }
332
+
333
+ void mongory_memory_pool_lock(mongory_memory_pool *pool) {
334
+ if (!pool || !pool->ctx || pool->alloc != mongory_memory_pool_alloc) {
335
+ return;
336
+ }
337
+ mongory_memory_pool_ctx *ctx = (mongory_memory_pool_ctx *)pool->ctx;
338
+ mongory_mutex_lock(&ctx->build_lock);
339
+ }
340
+
341
+ void mongory_memory_pool_unlock(mongory_memory_pool *pool) {
342
+ if (!pool || !pool->ctx || pool->alloc != mongory_memory_pool_alloc) {
343
+ return;
344
+ }
345
+ mongory_memory_pool_ctx *ctx = (mongory_memory_pool_ctx *)pool->ctx;
346
+ mongory_mutex_unlock(&ctx->build_lock);
347
+ }
@@ -0,0 +1,45 @@
1
+ #ifndef MONGORY_FOUNDATIONS_MEMORY_POOL_PRIVATE_H
2
+ #define MONGORY_FOUNDATIONS_MEMORY_POOL_PRIVATE_H
3
+
4
+ /**
5
+ * @file memory_pool_private.h
6
+ * @brief Internal synchronization and atomic helpers for mongory-core.
7
+ *
8
+ * Keeps platform-specific primitives out of public headers while enabling
9
+ * thread-safe double-checked lazy initialization on shared matcher pools.
10
+ */
11
+
12
+ #include "mongory-core/foundations/memory_pool.h"
13
+
14
+ #if defined(_MSC_VER)
15
+ # ifndef WIN32_LEAN_AND_MEAN
16
+ # define WIN32_LEAN_AND_MEAN
17
+ # endif
18
+ # include <windows.h>
19
+ # define mongory_atomic_load_ptr_acquire(ptr) \
20
+ InterlockedCompareExchangePointer((PVOID volatile *)(ptr), NULL, NULL)
21
+ # define mongory_atomic_load_ptr_relaxed(ptr) (*(ptr))
22
+ # define mongory_atomic_store_ptr_release(ptr, val) \
23
+ InterlockedExchangePointer((PVOID volatile *)(ptr), (PVOID)(val))
24
+ #elif defined(__GNUC__) || defined(__clang__)
25
+ # define mongory_atomic_load_ptr_acquire(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE)
26
+ # define mongory_atomic_load_ptr_relaxed(ptr) __atomic_load_n((ptr), __ATOMIC_RELAXED)
27
+ # define mongory_atomic_store_ptr_release(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELEASE)
28
+ #else
29
+ # define mongory_atomic_load_ptr_acquire(ptr) (*(ptr))
30
+ # define mongory_atomic_load_ptr_relaxed(ptr) (*(ptr))
31
+ # define mongory_atomic_store_ptr_release(ptr, val) (*(ptr) = (val))
32
+ #endif
33
+
34
+ /**
35
+ * @brief Acquires the pool's internal recursive build lock.
36
+ * Safe no-op if `pool` is NULL or uses a custom allocator without a core ctx.
37
+ */
38
+ void mongory_memory_pool_lock(mongory_memory_pool *pool);
39
+
40
+ /**
41
+ * @brief Releases the pool's internal recursive build lock.
42
+ */
43
+ void mongory_memory_pool_unlock(mongory_memory_pool *pool);
44
+
45
+ #endif /* MONGORY_FOUNDATIONS_MEMORY_POOL_PRIVATE_H */
@@ -49,11 +49,8 @@ bool mongory_try_parse_int(const char *key, int *out) {
49
49
  errno = 0; // Clear errno before calling strtol.
50
50
  long val = strtol(key, &endptr, 10); // Base 10 conversion.
51
51
 
52
- if (*endptr != '\0') {
53
- return false; // Additional characters after the number.
54
- }
55
- if (val < INT_MIN || val > INT_MAX) {
56
- return false; // Value out of range for int.
52
+ if (*endptr != '\0' || errno == ERANGE || val < INT_MIN || val > INT_MAX) {
53
+ return false; // Additional characters or value out of range for int.
57
54
  }
58
55
 
59
56
  if (out != NULL) {
@@ -301,14 +301,51 @@ mongory_value *mongory_value_wrap_a(mongory_memory_pool *pool, struct mongory_ar
301
301
  return value;
302
302
  }
303
303
 
304
- /** Compares two MONGORY_TYPE_TABLE values. Currently unsupported (always fails). */
304
+ /** Context for comparing two tables key by key. */
305
+ typedef struct mongory_table_compare_context {
306
+ struct mongory_table *other_table;
307
+ bool equal;
308
+ } mongory_table_compare_context;
309
+
310
+ static inline bool mongory_value_table_compare_foreach(char *key, mongory_value *val_a, void *acc) {
311
+ mongory_table_compare_context *ctx = (mongory_table_compare_context *)acc;
312
+ mongory_value *val_b = ctx->other_table->get(ctx->other_table, key);
313
+ if (val_b == NULL) {
314
+ ctx->equal = false;
315
+ return false;
316
+ }
317
+ bool a_is_null = (val_a == NULL || val_a->type == MONGORY_TYPE_NULL);
318
+ bool b_is_null = (val_b->type == MONGORY_TYPE_NULL);
319
+ if (a_is_null && b_is_null) {
320
+ return true;
321
+ }
322
+ if (a_is_null || b_is_null || !val_a->comp || val_a->comp(val_a, val_b) != 0) {
323
+ ctx->equal = false;
324
+ return false;
325
+ }
326
+ return true;
327
+ }
328
+
329
+ /** Compares two MONGORY_TYPE_TABLE values for equality. */
305
330
  static inline int mongory_value_table_compare(mongory_value *a, mongory_value *b) {
306
- (void)a; // Unused.
307
- (void)b; // Unused.
308
- // True table comparison is complex because the order of keys is not
309
- // significant. It would require iterating over keys of one table and checking
310
- // for their presence and value equality in the other. This is not
311
- // implemented. Therefore, tables are considered incomparable.
331
+ if (b->type != MONGORY_TYPE_TABLE || a->data.t == NULL || b->data.t == NULL) {
332
+ return mongory_value_compare_fail;
333
+ }
334
+ struct mongory_table *table_a = a->data.t;
335
+ struct mongory_table *table_b = b->data.t;
336
+ if (table_a->count != table_b->count) {
337
+ return mongory_value_compare_fail;
338
+ }
339
+ if (table_b->each && table_a->get) {
340
+ mongory_table_compare_context ctx = {table_a, true};
341
+ table_b->each(table_b, &ctx, mongory_value_table_compare_foreach);
342
+ return ctx.equal ? 0 : mongory_value_compare_fail;
343
+ }
344
+ if (table_a->each && table_b->get) {
345
+ mongory_table_compare_context ctx = {table_b, true};
346
+ table_a->each(table_a, &ctx, mongory_value_table_compare_foreach);
347
+ return ctx.equal ? 0 : mongory_value_compare_fail;
348
+ }
312
349
  return mongory_value_compare_fail;
313
350
  }
314
351
 
@@ -45,8 +45,12 @@ typedef struct mongory_matcher_array_record_parse_table_context {
45
45
  * Iterates through the main condition table:
46
46
  * - If `key` is "$elemMatch" and `value` is a table, its contents are added to
47
47
  * `context->elem_match_table`.
48
- * - If `key` starts with '$' (another operator) or is numeric (array index),
49
- * it's added to `context->parsed_table`.
48
+ * - If `key` is an element-level comparison operator (`$gt`, `$gte`, `$lt`,
49
+ * `$lte`, `$regex` with its `$options`, or non-array `$eq`), it's added to
50
+ * `context->elem_match_table`.
51
+ * - If `key` starts with '$' (container operator like `$size`, `$in`, `$nin`,
52
+ * `$every`, `$ne`, or array `$eq`) or is a valid integer index, it's added to
53
+ * `context->parsed_table`.
50
54
  * - Otherwise (plain field name), it's considered part of an implicit element
51
55
  * match and added to `context->elem_match_table`.
52
56
  *
@@ -55,6 +59,18 @@ typedef struct mongory_matcher_array_record_parse_table_context {
55
59
  * @param acc Pointer to `mongory_matcher_array_record_parse_table_context`.
56
60
  * @return Always true to continue.
57
61
  */
62
+ static inline bool mongory_is_elem_match_operator(char *key, mongory_value *value) {
63
+ if (strcmp(key, "$gt") == 0 || strcmp(key, "$gte") == 0 ||
64
+ strcmp(key, "$lt") == 0 || strcmp(key, "$lte") == 0 ||
65
+ strcmp(key, "$regex") == 0 || strcmp(key, "$options") == 0) {
66
+ return true;
67
+ }
68
+ if (strcmp(key, "$eq") == 0) {
69
+ return value == NULL || value->type != MONGORY_TYPE_ARRAY;
70
+ }
71
+ return false;
72
+ }
73
+
58
74
  static inline bool mongory_matcher_array_record_parse_table_foreach(char *key, mongory_value *value, void *acc) {
59
75
  mongory_matcher_array_record_parse_table_context *context = (mongory_matcher_array_record_parse_table_context *)acc;
60
76
  mongory_table *parsed_table_for_operators = context->parsed_table;
@@ -63,8 +79,11 @@ static inline bool mongory_matcher_array_record_parse_table_foreach(char *key, m
63
79
  if (strcmp(key, "$elemMatch") == 0 && value->type == MONGORY_TYPE_TABLE && value->data.t != NULL) {
64
80
  // Explicit $elemMatch: iterate its sub-table and add to elem_match_table
65
81
  mongory_table_merge(table_for_elem_match_conditions, value->data.t);
82
+ } else if (mongory_is_elem_match_operator(key, value)) {
83
+ // Element-level comparison operators apply to array elements via $elemMatch
84
+ table_for_elem_match_conditions->set(table_for_elem_match_conditions, key, value);
66
85
  } else if (*key == '$' || mongory_try_parse_int(key, NULL)) {
67
- // Operator (like $size) or numeric index: goes to parsed_table
86
+ // Array-level operator (like $size, $in, $nin, $every, $ne) or numeric index: goes to parsed_table
68
87
  parsed_table_for_operators->set(parsed_table_for_operators, key, value);
69
88
  } else {
70
89
  // Regular field name: implies a condition on elements, goes to
@@ -86,19 +105,21 @@ static inline bool mongory_matcher_array_record_parse_table_foreach(char *key, m
86
105
  * @return A new `mongory_value` (table) containing the parsed and restructured
87
106
  * condition. Returns NULL if input is not a table or on allocation failure.
88
107
  */
89
- static inline mongory_value *mongory_matcher_array_record_parse_table(mongory_value *condition) {
90
- if (!condition->data.t || !condition->pool) {
91
- mongory_error *error = MG_ALLOC_PTR(condition->pool, mongory_error);
108
+ static inline mongory_value *mongory_matcher_array_record_parse_table(mongory_memory_pool *pool, mongory_value *condition) {
109
+ if (!pool) {
110
+ return NULL;
111
+ }
112
+ if (!condition || !condition->data.t) {
113
+ mongory_error *error = MG_ALLOC_PTR(pool, mongory_error);
92
114
  if (!error) {
93
- condition->pool->error = &MONGORY_ALLOC_ERROR;
115
+ pool->error = &MONGORY_ALLOC_ERROR;
94
116
  return NULL;
95
117
  }
96
118
  error->type = MONGORY_ERROR_INVALID_TYPE;
97
119
  error->message = "Expected condition to be a table, got a non-table value";
98
- condition->pool->error = error; // TODO: This is a hack, we should use a better error handling mechanism
120
+ pool->error = error; // TODO: This is a hack, we should use a better error handling mechanism
99
121
  return NULL; // Invalid input
100
122
  }
101
- mongory_memory_pool *pool = condition->pool;
102
123
  mongory_table *parsed_table = mongory_table_new(pool);
103
124
  mongory_table *elem_match_sub_table = mongory_table_new(pool);
104
125
 
@@ -146,7 +167,7 @@ mongory_matcher *mongory_matcher_array_record_new(mongory_memory_pool *pool, mon
146
167
  switch (condition->type) {
147
168
  case MONGORY_TYPE_TABLE:
148
169
  return mongory_matcher_table_cond_new(pool,
149
- mongory_matcher_array_record_parse_table(condition),
170
+ mongory_matcher_array_record_parse_table(pool, condition),
150
171
  extern_ctx
151
172
  );
152
173
  case MONGORY_TYPE_ARRAY:
@@ -51,6 +51,8 @@ mongory_matcher *mongory_matcher_base_new(mongory_memory_pool *pool, mongory_val
51
51
  matcher->match = NULL; // Specific match function must be set by derived type.
52
52
  matcher->explain = mongory_matcher_base_explain; // Specific explain function must be set by derived type.
53
53
  matcher->traverse = mongory_matcher_leaf_traverse;
54
+ matcher->trace_stack = NULL;
55
+ matcher->trace_level = 0;
54
56
  matcher->extern_ctx = extern_ctx; // Set the external context.
55
57
  matcher->priority = 1.0; // Set the priority to 1.0.
56
58
  return matcher;