mongory 0.8.1 → 0.9.0

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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +66 -0
  3. data/README.md +12 -0
  4. data/docs/advanced_usage.md +7 -0
  5. data/docs/clang_bridge.md +6 -0
  6. data/ext/mongory_ext/extconf.rb +6 -1
  7. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/config.h +25 -0
  8. data/ext/mongory_ext/mongory-core/src/foundations/array.c +22 -15
  9. data/ext/mongory_ext/mongory-core/src/foundations/array_private.h +1 -0
  10. data/ext/mongory_ext/mongory-core/src/foundations/config.c +64 -27
  11. data/ext/mongory_ext/mongory-core/src/foundations/config_private.h +1 -0
  12. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool.c +49 -0
  13. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool_private.h +45 -0
  14. data/ext/mongory_ext/mongory-core/src/foundations/string_buffer.c +0 -2
  15. data/ext/mongory_ext/mongory-core/src/foundations/string_buffer.h +0 -6
  16. data/ext/mongory_ext/mongory-core/src/foundations/table.c +9 -10
  17. data/ext/mongory_ext/mongory-core/src/foundations/utils.c +21 -14
  18. data/ext/mongory_ext/mongory-core/src/foundations/utils.h +2 -2
  19. data/ext/mongory_ext/mongory-core/src/foundations/value.c +54 -9
  20. data/ext/mongory_ext/mongory-core/src/matchers/array_record_matcher.c +31 -10
  21. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.c +2 -0
  22. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.h +2 -0
  23. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.c +32 -13
  24. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.c +34 -13
  25. data/ext/mongory_ext/mongory-core/src/matchers/existance_matcher.c +16 -3
  26. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.c +76 -15
  27. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.h +12 -0
  28. data/ext/mongory_ext/mongory-core/src/matchers/literal_matcher.c +57 -15
  29. data/ext/mongory_ext/mongory-core/src/matchers/matcher.c +43 -7
  30. data/ext/mongory_ext/mongory_ext.c +36 -687
  31. data/ext/mongory_ext/mongory_ext_internal.h +75 -0
  32. data/ext/mongory_ext/rb_mongory_adapters.c +140 -0
  33. data/ext/mongory_ext/rb_mongory_cmatcher.c +386 -0
  34. data/ext/mongory_ext/rb_mongory_value.c +260 -0
  35. data/lib/generators/mongory/install/templates/initializer.rb.erb +5 -0
  36. data/lib/mongory/converters/abstract_converter.rb +6 -5
  37. data/lib/mongory/converters/condition_converter.rb +2 -2
  38. data/lib/mongory/converters/key_converter.rb +1 -1
  39. data/lib/mongory/matchers/abstract_matcher.rb +1 -1
  40. data/lib/mongory/matchers/abstract_multi_matcher.rb +2 -2
  41. data/lib/mongory/matchers/array_record_matcher.rb +23 -11
  42. data/lib/mongory/matchers/elem_match_matcher.rb +2 -0
  43. data/lib/mongory/matchers/eq_matcher.rb +4 -2
  44. data/lib/mongory/matchers/field_matcher.rb +16 -3
  45. data/lib/mongory/matchers/hash_condition_matcher.rb +23 -6
  46. data/lib/mongory/matchers/in_matcher.rb +17 -1
  47. data/lib/mongory/matchers/ne_matcher.rb +7 -6
  48. data/lib/mongory/matchers/nin_matcher.rb +2 -6
  49. data/lib/mongory/matchers/regex_matcher.rb +29 -0
  50. data/lib/mongory/matchers.rb +7 -4
  51. data/lib/mongory/version.rb +1 -1
  52. data/lib/mongory.rb +57 -5
  53. metadata +7 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ea774db3304817acd068531393945fc6c812ac00c8d0b47e71f6740bc8792f67
4
- data.tar.gz: c331c32c9b464249b1e24cac91c2f60bba87065dfe2f48bc5a44faad4bc504b1
3
+ metadata.gz: fd9406b48c39fba6b80ae630bde3ca9a76a245fea66d7ec11e2e997b4bfe92ea
4
+ data.tar.gz: 50cccd91becb71d581cdbeef031ef8a6b42dd21ec1f68829ec6b85a848419c90
5
5
  SHA512:
6
- metadata.gz: 49764016c348ef886f1e05a0303cb139d793340b20790ef6d8b39328cc8b5621f097ecff587e76b62157d8b6dadf26ef6ab57d6bca6d9dccf9c3e1643e914045
7
- data.tar.gz: 2e5b5067ee8df7d94778c5e47dc2bd0e3fc8c17e31e958d16b50a8c21d0821cd65f360c42116b30d05d58251e1e30cbba58c1482a5aabb915fec94c8e4a6abea
6
+ metadata.gz: ac4301dfcc524da53e37131ed093aa415d370104e56d98c13acc2c6923e6b46692ccb2cc9106378824f366a8f2cef49142dd1819c1113fcd2428dae2cf422c24
7
+ data.tar.gz: 6e9d5618b2559d8b9210a0c45f465d86763fe5eff260ef4a810268dc06eeebf018728e3f9fbd1eb5ce9ffbca1eb144934abbbd4047d30c17b6abc6cd7cf8e9cd
data/CHANGELOG.md CHANGED
@@ -1,4 +1,70 @@
1
1
  # Changelog
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
+
30
+ ## [0.8.2] - 2026-11-14
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
+
35
+ ### Fixes
36
+ - **Key & Array Index Matching (`QueryMatcher` & `CMatcher`)**:
37
+ - Normalize `Integer` condition keys to `String` in `KeyConverter` (consistent with `Symbol` keys), preventing `TypeError` in `CMatcher` and `NoMethodError` in `FieldMatcher`.
38
+ - Enforce strict integer index format (`\A(?:0|-?[1-9]\d*)\z`) when matching against arrays so keys with leading zeros (e.g., `"01"`, `"-0"`) or multiline strings are treated as document field keys rather than array indices.
39
+ - Treat valid numeric keys on `Array` records strictly as array indices in both `FieldMatcher` and `mongory-core`.
40
+ - **C Extension (`mongory_ext`)**:
41
+ - Fix GC use-after-free crash when `$regex` condition is given as a `String` pattern by registering the compiled `Regexp` in the matcher's GC `mark_list`.
42
+ - Fix NULL pointer dereference crash when calling `CMatcher#disable_trace` or `CMatcher#print_trace` before `enable_trace`.
43
+ - Fix memory pool type mismatch and out-of-bounds `owner` read in `CMatcher#trace` and uninitialized `owner` pointer in `CMatcher#enable_trace`.
44
+ - Prevent memory leaks when `CMatcher.new`, `trace`, `enable_trace`, or `disable_trace` raises `Mongory::TypeError`.
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+.
47
+ - **Core (`mongory-core` submodule)**:
48
+ - Fix off-by-one capacity growth condition in `mongory_array` and `mongory_table`.
49
+ - Propagate `extern_ctx` in `mongory_matcher_field_new` so nested custom matchers receive the Ruby matcher context.
50
+ - Sync trace state across `literal_matcher`'s `delegate_matcher` and `array_record_matcher`.
51
+ - Return `mongory_value_compare_fail` when comparing `NaN` float/double values instead of treating `NaN` as equal.
52
+
53
+ ## [0.8.1] - 2025-08-30
54
+
55
+ ### Fixes
56
+ - Use `require_relative` instead of `require` for internal file loading.
57
+
58
+ ### Docs & Chores
59
+ - Deprecate `QueryBuilder#fast` and update YARD documentation and README.
60
+
61
+ ## [0.8.0] - 2025-08-30
62
+
63
+ ### Features
64
+ - Add trace mode support to `QueryBuilder` and `CQueryBuilder`, printing trace output and resetting trace pool on each match.
65
+ - Expose `CMatcher.trace_result_colorful=` configuration option.
66
+ - Support cross-platform precompiled native gems for Linux (`x86_64`, `aarch64`, musl/glibc), macOS (`x86_64-darwin`, `arm64-darwin`), and Windows (`x64-mingw32`, `x64-mingw-ucrt`).
67
+
2
68
  ## [0.7.1] - 2025-08-17
3
69
  ### Fixes
4
70
  - Linter error
data/README.md CHANGED
@@ -110,6 +110,18 @@ records = [
110
110
  result = records.mongory
111
111
  .where(:age.gte => 18)
112
112
  .or({ :name => /J/ }, { :name.eq => 'Bob' })
113
+ .to_a
114
+
115
+ # Or input condition via json string from front-end
116
+ result = records.mongory
117
+ .where(JSON.parse('{
118
+ "age": {"$gt": 18},
119
+ "$or": [
120
+ {"name": {"$regex": "J"}},
121
+ {"name": "Bob"}
122
+ ]
123
+ }'))
124
+ .to_a
113
125
 
114
126
  # Using limit to restrict results
115
127
  # Note: limit executes immediately and affects subsequent conditions
@@ -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
  *
@@ -146,8 +146,8 @@ static inline mongory_value *mongory_array_get(mongory_array *self, size_t index
146
146
  */
147
147
  static inline bool mongory_array_set(mongory_array *self, size_t index, mongory_value *value) {
148
148
  mongory_array_private *internal = (mongory_array_private *)self;
149
- // Ensure capacity for the given index (index + 1 elements).
150
- if (!mongory_array_grow_if_needed(self, index + 1)) {
149
+ // Ensure capacity for the given 0-based index.
150
+ if (!mongory_array_grow_if_needed(self, index)) {
151
151
  return false;
152
152
  }
153
153
 
@@ -163,17 +163,10 @@ static inline bool mongory_array_set(mongory_array *self, size_t index, mongory_
163
163
  return true;
164
164
  }
165
165
 
166
- /**
167
- * @brief Creates and initializes a new mongory_array.
168
- *
169
- * Allocates memory for the array structure itself and its initial item storage
170
- * using the provided memory pool. Assigns function pointers for array
171
- * operations.
172
- *
173
- * @param pool The memory pool to use for allocations.
174
- * @return Pointer to the new mongory_array, or NULL on allocation failure.
175
- */
176
- mongory_array *mongory_array_new(mongory_memory_pool *pool) {
166
+ mongory_array *mongory_array_new_with_capacity(mongory_memory_pool *pool, size_t capacity) {
167
+ if (capacity == 0) {
168
+ capacity = MONGORY_ARRAY_INIT_SIZE;
169
+ }
177
170
  // First, allocate the private structure that holds all array metadata.
178
171
  mongory_array_private *internal = MG_ALLOC_PTR(pool, mongory_array_private);
179
172
  if (!internal) {
@@ -182,7 +175,7 @@ mongory_array *mongory_array_new(mongory_memory_pool *pool) {
182
175
  }
183
176
 
184
177
  // Then, allocate the initial block of memory for the array items.
185
- mongory_value **items = MG_ALLOC_ARY(pool, mongory_value*, MONGORY_ARRAY_INIT_SIZE);
178
+ mongory_value **items = MG_ALLOC_ARY(pool, mongory_value*, capacity);
186
179
  if (!items) {
187
180
  // If this fails, the 'internal' struct allocated above will be cleaned up
188
181
  // by the pool, assuming it's a tracing pool.
@@ -200,11 +193,25 @@ mongory_array *mongory_array_new(mongory_memory_pool *pool) {
200
193
 
201
194
  // Initialize the private part of the array structure.
202
195
  internal->items = items;
203
- internal->capacity = MONGORY_ARRAY_INIT_SIZE;
196
+ internal->capacity = capacity;
204
197
 
205
198
  return &internal->base; // Return pointer to the public structure.
206
199
  }
207
200
 
201
+ /**
202
+ * @brief Creates and initializes a new mongory_array.
203
+ *
204
+ * Allocates memory for the array structure itself and its initial item storage
205
+ * using the provided memory pool. Assigns function pointers for array
206
+ * operations.
207
+ *
208
+ * @param pool The memory pool to use for allocations.
209
+ * @return Pointer to the new mongory_array, or NULL on allocation failure.
210
+ */
211
+ mongory_array *mongory_array_new(mongory_memory_pool *pool) {
212
+ return mongory_array_new_with_capacity(pool, MONGORY_ARRAY_INIT_SIZE);
213
+ }
214
+
208
215
  /**
209
216
  * @brief Creates a new mongory_array instance with a nested array.
210
217
  *
@@ -6,6 +6,7 @@
6
6
  #include <stdbool.h>
7
7
 
8
8
  bool mongory_array_resize(mongory_array *self, size_t size); // resize array
9
+ mongory_array *mongory_array_new_with_capacity(mongory_memory_pool *pool, size_t capacity);
9
10
 
10
11
  typedef struct mongory_array_private {
11
12
  mongory_array base; // public array
@@ -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 */
@@ -16,8 +16,6 @@ mongory_string_buffer *mongory_string_buffer_new(mongory_memory_pool *pool) {
16
16
  return buffer;
17
17
  }
18
18
 
19
- void mongory_string_buffer_free(mongory_string_buffer *buffer) { buffer->pool->free(buffer->pool->ctx); }
20
-
21
19
  static inline void mongory_string_buffer_grow(mongory_string_buffer *buffer, size_t additional_size) {
22
20
  bool trigger_grow = false;
23
21
  while (buffer->size + additional_size + 1 > buffer->capacity) {
@@ -40,10 +40,4 @@ char *mongory_string_buffer_cstr(mongory_string_buffer *buffer);
40
40
  */
41
41
  void mongory_string_buffer_clear(mongory_string_buffer *buffer);
42
42
 
43
- /**
44
- * @brief Frees the buffer.
45
- * @param buffer The buffer to free.
46
- */
47
- void mongory_string_buffer_free(mongory_string_buffer *buffer);
48
-
49
43
  #endif
@@ -178,11 +178,12 @@ static inline bool mongory_table_rehash(mongory_table *self) {
178
178
  // might copy elements if count is not zero. We are managing elements manually.
179
179
  internal->array->count = 0;
180
180
 
181
- if (!mongory_array_resize(internal->array, new_capacity)) {
181
+ if (!mongory_array_resize(internal->array, new_capacity) ||
182
+ !internal->array->set(internal->array, new_capacity - 1, NULL)) {
182
183
  // Error: Rehashing failed because the underlying array could not be resized.
183
184
  // The table remains functional but may have a suboptimal load factor.
184
185
  self->pool->error = &MONGORY_ALLOC_ERROR;
185
- internal->array->count = self->count; // Try to restore roughly
186
+ internal->array->count = original_capacity; // Restore previous bucket count
186
187
  return false;
187
188
  }
188
189
  // After resize, internal->array (and old_array_private_view) points to the
@@ -416,14 +417,12 @@ mongory_table *mongory_table_new(mongory_memory_pool *pool) {
416
417
  return NULL; // Must have a valid pool.
417
418
 
418
419
  size_t init_capacity = MONGORY_TABLE_INIT_SIZE;
419
- mongory_array *bucket_array = mongory_array_new(pool);
420
-
421
- // Initialize the bucket array. We resize it to the initial capacity and
422
- // then set the last element to NULL. The `mongory_array_set` function
423
- // will automatically fill all intermediate slots with NULL if the index is
424
- // out of bounds, which perfectly initializes our bucket array.
425
- bool array_init_success = bucket_array && mongory_array_resize(bucket_array, init_capacity) &&
426
- bucket_array->set(bucket_array, init_capacity - 1, NULL);
420
+ mongory_array *bucket_array = mongory_array_new_with_capacity(pool, init_capacity);
421
+
422
+ // Initialize the bucket array by setting the last element to NULL.
423
+ // The `mongory_array_set` function will automatically fill all intermediate
424
+ // slots with NULL without triggering a resize.
425
+ bool array_init_success = bucket_array && bucket_array->set(bucket_array, init_capacity - 1, NULL);
427
426
 
428
427
  if (!array_init_success) {
429
428
  // If array initialization fails, we cannot proceed.