Ruby 4.1.0dev (2026-11-25 revision 6c39222a9cf89799239a3eda89eb156233de42cd)
weakmap.c (6c39222a9cf89799239a3eda89eb156233de42cd)
1#include "internal.h"
2#include "internal/array.h"
3#include "internal/gc.h"
4#include "internal/hash.h"
5#include "internal/proc.h"
6#include "internal/sanitizers.h"
7#include "ruby/st.h"
8
9/* ===== WeakMap =====
10 *
11 * WeakMap contains one ST table which contains a pointer to the object as the
12 * key and a pointer to the object as the value. This means that the key and
13 * value of the table are both of the type `VALUE *`.
14 *
15 * The objects are not directly stored as keys and values in the table because
16 * `rb_gc_mark_weak` requires a pointer to the memory location to overwrite
17 * when the object is reclaimed. Using a pointer into the ST table entry is not
18 * safe because the pointer can change when the ST table is resized.
19 *
20 * WeakMap hashes and compares using the pointer address of the object.
21 *
22 * For performance and memory efficiency reasons, the key and value
23 * are allocated at the same time and adjacent to each other.
24 *
25 * During GC and while iterating, reclaimed entries (i.e. either the key or
26 * value points to `Qundef`) are removed from the ST table.
27 */
28
29struct weakmap {
30 st_table *table;
31};
32
34 VALUE key;
35 VALUE val;
36};
37
38static void
39wmap_free(void *ptr)
40{
41 struct weakmap *w = ptr;
42
43 st_free_table(w->table);
44}
45
46static size_t
47wmap_memsize(const void *ptr)
48{
49 const struct weakmap *w = ptr;
50
51 size_t size = 0;
52 if (w->table) {
53 size += st_memsize(w->table);
54 }
55
56 return size;
57}
58
60 st_table *table;
61 struct weakmap_entry *dead_entry;
62};
63
64static int
65wmap_compact_table_each_i(st_data_t k, st_data_t v, st_data_t d, int error)
66{
67 st_table *table = (st_table *)d;
68
69 VALUE key = (VALUE)k;
70 VALUE val = (VALUE)v;
71
72 VALUE moved_key = rb_gc_location(key);
73 VALUE moved_val = rb_gc_location(val);
74
75 /* If the key object moves, then we must reinsert because the hash is
76 * based on the pointer rather than the object itself. */
77 if (key != moved_key) {
78 st_insert(table, (st_data_t)moved_key, (st_data_t)moved_val);
79
80 return ST_DELETE;
81 }
82 else if (val != moved_val) {
83 return ST_REPLACE;
84 }
85 else {
86 return ST_CONTINUE;
87 }
88}
89
90static int
91wmap_compact_table_replace_i(st_data_t *k, st_data_t *v, st_data_t d, int existing)
92{
93 RUBY_ASSERT((VALUE)*k == rb_gc_location((VALUE)*k));
94
95 rb_gc_update_moved((VALUE *)v);
96
97 return ST_CONTINUE;
98}
99
100static void
101wmap_compact(void *ptr)
102{
103 struct weakmap *w = ptr;
104
105 if (w->table) {
106 DURING_GC_COULD_MALLOC_REGION_START();
107 {
108 st_foreach_with_replace(w->table, wmap_compact_table_each_i, wmap_compact_table_replace_i, (st_data_t)w->table);
109 }
110 DURING_GC_COULD_MALLOC_REGION_END();
111 }
112}
113
114static int
115rb_wmap_handle_weak_references_i(st_data_t key, st_data_t val, st_data_t arg)
116{
117 void *objspace = (void *)arg;
118
119 if (rb_gc_handle_weak_references_alive_p(objspace, key) &&
120 rb_gc_handle_weak_references_alive_p(objspace, val)) {
121 return ST_CONTINUE;
122 }
123 else {
124 return ST_DELETE;
125 }
126}
127
128static void
129wmap_handle_weak_references(void *ptr, void *objspace)
130{
131 struct weakmap *w = ptr;
132
133 st_foreach(w->table, rb_wmap_handle_weak_references_i, (st_data_t)objspace);
134}
135
136static const rb_data_type_t rb_weakmap_type = {
137 "weakmap",
138 {
139 NULL,
140 wmap_free,
141 wmap_memsize,
142 wmap_compact,
143 wmap_handle_weak_references,
144 },
145 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
146};
147
148static int
149wmap_cmp(st_data_t x, st_data_t y)
150{
151 return x != y;
152}
153
154static st_index_t
155wmap_hash(st_data_t n)
156{
157 return st_numhash(n);
158}
159
160static const struct st_hash_type wmap_hash_type = {
161 wmap_cmp,
162 wmap_hash,
163};
164
165static VALUE
166wmap_allocate(VALUE klass)
167{
168 struct weakmap *w;
169 VALUE obj = TypedData_Make_Struct(klass, struct weakmap, &rb_weakmap_type, w);
170
171 w->table = st_init_table(&wmap_hash_type);
172
173 rb_gc_declare_weak_references(obj);
174
175 return obj;
176}
177
178static int
179wmap_foreach_snapshot_i(st_data_t k, st_data_t v, st_data_t data)
180{
181 VALUE ary = (VALUE)data;
182
183 rb_ary_push(ary, (VALUE)k);
184 rb_ary_push(ary, (VALUE)v);
185
186 return ST_CONTINUE;
187}
188
189/* Calls func with each entry of the map. The entries are first copied into a
190 * hidden array, because func may run arbitrary code (or allocate and trigger
191 * a compaction) and modify the table under a running st_foreach, which can
192 * then visit entries twice or stop early. Entries removed before they are
193 * reached are skipped. */
194static void
195wmap_foreach(struct weakmap *w, void (*func)(VALUE key, VALUE val, VALUE arg), VALUE arg)
196{
197 VALUE ary = rb_ary_hidden_new(w->table->num_entries * 2);
198 st_foreach(w->table, wmap_foreach_snapshot_i, (st_data_t)ary);
199
200 for (long i = 0; i < RARRAY_LEN(ary); i += 2) {
201 VALUE key = RARRAY_AREF(ary, i);
202 st_data_t val;
203
204 if (st_lookup(w->table, (st_data_t)key, &val)) {
205 func(key, (VALUE)val, arg);
206 }
207 }
208
209 RB_GC_GUARD(ary);
210}
211
212static VALUE
213wmap_inspect_append(VALUE str, VALUE obj)
214{
215 if (SPECIAL_CONST_P(obj)) {
216 return rb_str_append(str, rb_inspect(obj));
217 }
218 else {
219 return rb_str_append(str, rb_any_to_s(obj));
220 }
221}
222
223static void
224wmap_inspect_i(VALUE key, VALUE val, VALUE str)
225{
226 if (RSTRING_PTR(str)[0] == '#') {
227 rb_str_cat2(str, ", ");
228 }
229 else {
230 rb_str_cat2(str, ": ");
231 RSTRING_PTR(str)[0] = '#';
232 }
233
234 wmap_inspect_append(str, key);
235 rb_str_cat2(str, " => ");
236 wmap_inspect_append(str, val);
237}
238
239/* call-seq:
240 * inspect -> new_string
241 *
242 * Returns a new string containing the \WeakMap entries:
243 *
244 * m = ObjectSpace::WeakMap.new
245 * m["one"] = 1
246 * m["two"] = 2
247 * m.inspect
248 * # => "#<ObjectSpace::WeakMap:0x00007c457b2523e8: #<String:0x00007c457b2674f0> => 1, #<String:0x00007c457b27b8d8> => 2>"
249 */
250static VALUE
251wmap_inspect(VALUE self)
252{
253 VALUE c = rb_class_name(CLASS_OF(self));
254 struct weakmap *w;
255 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
256
257 VALUE str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void *)self);
258
259 wmap_foreach(w, wmap_inspect_i, str);
260
261 RSTRING_PTR(str)[0] = '#';
262 rb_str_cat2(str, ">");
263
264 return str;
265}
266
267static void
268wmap_each_i(VALUE key, VALUE val, VALUE _)
269{
270 rb_yield_values(2, key, val);
271}
272
273/*
274 * call-seq:
275 * map.each {|key, val| ... } -> self
276 *
277 * Iterates over keys and values. Note that unlike other collections,
278 * +each+ without block isn't supported.
279 *
280 */
281static VALUE
282wmap_each(VALUE self)
283{
284 struct weakmap *w;
285 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
286
287 wmap_foreach(w, wmap_each_i, Qnil);
288
289 return self;
290}
291
292static void
293wmap_each_key_i(VALUE key, VALUE _val, VALUE _)
294{
295 rb_yield(key);
296}
297
298/*
299 * call-seq:
300 * map.each_key {|key| ... } -> self
301 *
302 * Iterates over keys. Note that unlike other collections,
303 * +each_key+ without block isn't supported.
304 *
305 */
306static VALUE
307wmap_each_key(VALUE self)
308{
309 struct weakmap *w;
310 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
311
312 wmap_foreach(w, wmap_each_key_i, Qnil);
313
314 return self;
315}
316
317static void
318wmap_each_value_i(VALUE _key, VALUE val, VALUE _)
319{
320 rb_yield(val);
321}
322
323/*
324 * call-seq:
325 * map.each_value {|val| ... } -> self
326 *
327 * Iterates over values. Note that unlike other collections,
328 * +each_value+ without block isn't supported.
329 *
330 */
331static VALUE
332wmap_each_value(VALUE self)
333{
334 struct weakmap *w;
335 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
336
337 wmap_foreach(w, wmap_each_value_i, Qnil);
338
339 return self;
340}
341
342static int
343wmap_keys_i(st_data_t k, st_data_t v, st_data_t data)
344{
345 VALUE ary = (VALUE)data;
346
347 rb_ary_push(ary, (VALUE)k);
348
349 return ST_CONTINUE;
350}
351
352/*
353 * call-seq:
354 * map.keys -> new_array
355 *
356 * Returns a new Array containing all keys in the map.
357 *
358 */
359static VALUE
360wmap_keys(VALUE self)
361{
362 struct weakmap *w;
363 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
364
365 VALUE ary = rb_ary_new_capa(w->table->num_entries);
366 st_foreach(w->table, wmap_keys_i, (st_data_t)ary);
367
368 return ary;
369}
370
371static int
372wmap_values_i(st_data_t k, st_data_t v, st_data_t data)
373{
374 VALUE ary = (VALUE)data;
375
376 rb_ary_push(ary, (VALUE)v);
377
378 return ST_CONTINUE;
379}
380
381/*
382 * call-seq:
383 * map.values -> new_array
384 *
385 * Returns a new Array containing all values in the map.
386 *
387 */
388static VALUE
389wmap_values(VALUE self)
390{
391 struct weakmap *w;
392 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
393
394 VALUE ary = rb_ary_new_capa(w->table->num_entries);
395 st_foreach(w->table, wmap_values_i, (st_data_t)ary);
396
397 return ary;
398}
399
400/*
401 * call-seq:
402 * map[key] = value -> value
403 *
404 * Associates the given +value+ with the given +key+.
405 *
406 * If the given +key+ exists, replaces its value with the given +value+;
407 * the ordering is not affected.
408 */
409static VALUE
410wmap_aset(VALUE self, VALUE key, VALUE val)
411{
412 struct weakmap *w;
413 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
414
415 st_insert(w->table, (st_data_t)key, (st_data_t)val);
416
417 RB_OBJ_WRITTEN(self, Qundef, key);
418 RB_OBJ_WRITTEN(self, Qundef, val);
419
420 return val;
421}
422
423/* Retrieves a weakly referenced object with the given key */
424static VALUE
425wmap_lookup(VALUE self, VALUE key)
426{
427 struct weakmap *w;
428 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
429
430 st_data_t data;
431 if (!st_lookup(w->table, (st_data_t)key, &data)) return Qundef;
432
433 return (VALUE)data;
434}
435
436/*
437 * call-seq:
438 * map[key] -> value
439 *
440 * Returns the value associated with the given +key+ if found.
441 *
442 * If +key+ is not found, returns +nil+.
443 */
444static VALUE
445wmap_aref(VALUE self, VALUE key)
446{
447 VALUE obj = wmap_lookup(self, key);
448 return !UNDEF_P(obj) ? obj : Qnil;
449}
450
451/*
452 * call-seq:
453 * map.delete(key) -> value or nil
454 * map.delete(key) {|key| ... } -> object
455 *
456 * Deletes the entry for the given +key+ and returns its associated value.
457 *
458 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
459 * m = ObjectSpace::WeakMap.new
460 * key = "foo"
461 * m[key] = 1
462 * m.delete(key) # => 1
463 * m[key] # => nil
464 *
465 * If no block is given and +key+ is not found, returns +nil+.
466 *
467 * If a block is given and +key+ is found, ignores the block,
468 * deletes the entry, and returns the associated value:
469 * m = ObjectSpace::WeakMap.new
470 * key = "foo"
471 * m[key] = 2
472 * m.delete(key) { |key| raise 'Will never happen'} # => 2
473 *
474 * If a block is given and +key+ is not found,
475 * yields the +key+ to the block and returns the block's return value:
476 * m = ObjectSpace::WeakMap.new
477 * m.delete("nosuch") { |key| "Key #{key} not found" } # => "Key nosuch not found"
478 */
479static VALUE
480wmap_delete(VALUE self, VALUE key)
481{
482 struct weakmap *w;
483 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
484
485 st_data_t orig_key = (st_data_t)key;
486 st_data_t orig_val;
487 if (st_delete(w->table, &orig_key, &orig_val)) {
488 return (VALUE)orig_val;
489 }
490
491 if (rb_block_given_p()) {
492 return rb_yield(key);
493 }
494 else {
495 return Qnil;
496 }
497}
498
499/*
500 * call-seq:
501 * map.key?(key) -> true or false
502 *
503 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
504 */
505static VALUE
506wmap_has_key(VALUE self, VALUE key)
507{
508 return RBOOL(!UNDEF_P(wmap_lookup(self, key)));
509}
510
511/*
512 * call-seq:
513 * map.size -> number
514 *
515 * Returns the number of referenced objects
516 */
517static VALUE
518wmap_size(VALUE self)
519{
520 struct weakmap *w;
521 TypedData_Get_Struct(self, struct weakmap, &rb_weakmap_type, w);
522
523 st_index_t n = st_table_size(w->table);
524
525#if SIZEOF_ST_INDEX_T <= SIZEOF_LONG
526 return ULONG2NUM(n);
527#else
528 return ULL2NUM(n);
529#endif
530}
531
532VALUE
533rb_wmap_new_hidden(void)
534{
535 return wmap_allocate(0);
536}
537
538VALUE
539rb_wmap_lookup(VALUE self, VALUE key)
540{
541 return wmap_lookup(self, key);
542}
543
544void
545rb_wmap_aset(VALUE self, VALUE key, VALUE val)
546{
547 wmap_aset(self, key, val);
548}
549
550/* ===== WeakKeyMap =====
551 *
552 * WeakKeyMap contains one ST table which contains a pointer to the object as
553 * the key and the object as the value. This means that the key is of the type
554 * `VALUE *` while the value is of the type `VALUE`.
555 *
556 * The object is not directly stored as keys in the table because
557 * `rb_gc_mark_weak` requires a pointer to the memory location to overwrite
558 * when the object is reclaimed. Using a pointer into the ST table entry is not
559 * safe because the pointer can change when the ST table is resized.
560 *
561 * WeakKeyMap hashes and compares using the `#hash` and `#==` methods of the
562 * object, respectively.
563 *
564 * During GC and while iterating, reclaimed entries (i.e. the key points to
565 * `Qundef`) are removed from the ST table.
566 */
567
569 st_table *table;
570};
571
572static int
573wkmap_mark_table_i(st_data_t key, st_data_t val_obj, st_data_t _data)
574{
575 rb_gc_mark_movable((VALUE)val_obj);
576
577 return ST_CONTINUE;
578}
579
580static void
581wkmap_mark(void *ptr)
582{
583 struct weakkeymap *w = ptr;
584 if (w->table) {
585 st_foreach(w->table, wkmap_mark_table_i, (st_data_t)0);
586 }
587}
588
589static void
590wkmap_free(void *ptr)
591{
592 struct weakkeymap *w = ptr;
593
594 st_free_table(w->table);
595}
596
597static size_t
598wkmap_memsize(const void *ptr)
599{
600 const struct weakkeymap *w = ptr;
601
602 size_t size = 0;
603 if (w->table) {
604 size += st_memsize(w->table);
605 }
606
607 return size;
608}
609
610static int
611wkmap_compact_table_i(st_data_t key, st_data_t val, st_data_t _data, int _error)
612{
613 if ((VALUE)key != rb_gc_location((VALUE)key) || (VALUE)val != rb_gc_location((VALUE)val)) {
614 return ST_REPLACE;
615 }
616
617 return ST_CONTINUE;
618}
619
620static int
621wkmap_compact_table_replace(st_data_t *key_ptr, st_data_t *val_ptr, st_data_t _data, int existing)
622{
623 RUBY_ASSERT(existing);
624
625 rb_gc_update_moved((VALUE *)key_ptr);
626 rb_gc_update_moved((VALUE *)val_ptr);
627
628 return ST_CONTINUE;
629}
630
631static void
632wkmap_compact(void *ptr)
633{
634 struct weakkeymap *w = ptr;
635
636 if (w->table) {
637 st_foreach_with_replace(w->table, wkmap_compact_table_i, wkmap_compact_table_replace, (st_data_t)0);
638 }
639}
640
641static int
642rb_wkmap_handle_weak_references_i(st_data_t key, st_data_t val, st_data_t arg)
643{
644 if (rb_gc_handle_weak_references_alive_p((void *)arg, key)) {
645 return ST_CONTINUE;
646 }
647 else {
648 return ST_DELETE;
649 }
650}
651
652static void
653wkmap_handle_weak_references(void *ptr, void *objspace)
654{
655 struct weakkeymap *w = ptr;
656
657 st_foreach(w->table, rb_wkmap_handle_weak_references_i, (st_data_t)objspace);
658}
659
660static const rb_data_type_t rb_weakkeymap_type = {
661 "weakkeymap",
662 {
663 wkmap_mark,
664 wkmap_free,
665 wkmap_memsize,
666 wkmap_compact,
667 wkmap_handle_weak_references,
668 },
669 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
670};
671
672static int
673wkmap_cmp(st_data_t x, st_data_t y)
674{
675 VALUE x_obj = (VALUE)x;
676 VALUE y_obj = (VALUE)y;
677
678 return rb_any_cmp(x_obj, y_obj);
679}
680
681static st_index_t
682wkmap_hash(st_data_t n)
683{
684 VALUE obj = (VALUE)n;
685
686 return rb_any_hash(obj);
687}
688
689static const struct st_hash_type wkmap_hash_type = {
690 wkmap_cmp,
691 wkmap_hash,
692};
693
694static VALUE
695wkmap_allocate(VALUE klass)
696{
697 struct weakkeymap *w;
698
699 VALUE obj = TypedData_Make_Struct(klass, struct weakkeymap, &rb_weakkeymap_type, w);
700
701 w->table = st_init_table(&wkmap_hash_type);
702
703 rb_gc_declare_weak_references(obj);
704
705 return obj;
706}
707
708static VALUE
709wkmap_lookup(VALUE self, VALUE key)
710{
711 struct weakkeymap *w;
712 TypedData_Get_Struct(self, struct weakkeymap, &rb_weakkeymap_type, w);
713
714 st_data_t data;
715 if (!st_lookup(w->table, (st_data_t)key, &data)) return Qundef;
716
717 return (VALUE)data;
718}
719
720/*
721 * call-seq:
722 * map[key] -> value
723 *
724 * Returns the value associated with the given +key+ if found.
725 *
726 * If +key+ is not found, returns +nil+.
727 */
728static VALUE
729wkmap_aref(VALUE self, VALUE key)
730{
731 VALUE obj = wkmap_lookup(self, key);
732 return !UNDEF_P(obj) ? obj : Qnil;
733}
734
736 VALUE new_key;
737 VALUE new_val;
738};
739
740/*
741 * call-seq:
742 * map[key] = value -> value
743 *
744 * Associates the given +value+ with the given +key+
745 *
746 * The reference to +key+ is weak, so when there is no other reference
747 * to +key+ it may be garbage collected.
748 *
749 * If the given +key+ exists, replaces its value with the given +value+;
750 * the ordering is not affected
751 */
752static VALUE
753wkmap_aset(VALUE self, VALUE key, VALUE val)
754{
755 struct weakkeymap *w;
756 TypedData_Get_Struct(self, struct weakkeymap, &rb_weakkeymap_type, w);
757
758 if (!FL_ABLE(key) || SYMBOL_P(key) || RB_BIGNUM_TYPE_P(key) || RB_TYPE_P(key, T_FLOAT)) {
759 rb_raise(rb_eArgError, "WeakKeyMap keys must be garbage collectable");
761 }
762
763 st_insert(w->table, (st_data_t)key, (st_data_t)val);
764
765 RB_OBJ_WRITTEN(self, Qundef, key);
766 RB_OBJ_WRITTEN(self, Qundef, val);
767
768 return val;
769}
770
771/*
772 * call-seq:
773 * map.delete(key) -> value or nil
774 * map.delete(key) {|key| ... } -> object
775 *
776 * Deletes the entry for the given +key+ and returns its associated value.
777 *
778 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
779 * m = ObjectSpace::WeakKeyMap.new
780 * key = "foo" # to hold reference to the key
781 * m[key] = 1
782 * m.delete("foo") # => 1
783 * m["foo"] # => nil
784 *
785 * If no block given and +key+ is not found, returns +nil+.
786 *
787 * If a block is given and +key+ is found, ignores the block,
788 * deletes the entry, and returns the associated value:
789 * m = ObjectSpace::WeakKeyMap.new
790 * key = "foo" # to hold reference to the key
791 * m[key] = 2
792 * m.delete("foo") { |key| raise 'Will never happen'} # => 2
793 *
794 * If a block is given and +key+ is not found,
795 * yields the +key+ to the block and returns the block's return value:
796 * m = ObjectSpace::WeakKeyMap.new
797 * m.delete("nosuch") { |key| "Key #{key} not found" } # => "Key nosuch not found"
798 */
799
800static VALUE
801wkmap_delete(VALUE self, VALUE key)
802{
803 struct weakkeymap *w;
804 TypedData_Get_Struct(self, struct weakkeymap, &rb_weakkeymap_type, w);
805
806 st_data_t orig_key = (st_data_t)key;
807 st_data_t orig_val;
808 if (st_delete(w->table, &orig_key, &orig_val)) {
809 return (VALUE)orig_val;
810 }
811
812 if (rb_block_given_p()) {
813 return rb_yield(key);
814 }
815 else {
816 return Qnil;
817 }
818}
819
820/*
821 * call-seq:
822 * map.getkey(key) -> existing_key or nil
823 *
824 * Returns the existing equal key if it exists, otherwise returns +nil+.
825 *
826 * This might be useful for implementing caches, so that only one copy of
827 * some object would be used everywhere in the program:
828 *
829 * value = {amount: 1, currency: 'USD'}
830 *
831 * # Now if we put this object in a cache:
832 * cache = ObjectSpace::WeakKeyMap.new
833 * cache[value] = true
834 *
835 * # ...we can always extract from there and use the same object:
836 * copy = cache.getkey({amount: 1, currency: 'USD'})
837 * copy.object_id == value.object_id #=> true
838 */
839static VALUE
840wkmap_getkey(VALUE self, VALUE key)
841{
842 struct weakkeymap *w;
843 TypedData_Get_Struct(self, struct weakkeymap, &rb_weakkeymap_type, w);
844
845 st_data_t orig_key;
846 if (!st_get_key(w->table, (st_data_t)key, &orig_key)) return Qnil;
847
848 return (VALUE)orig_key;
849}
850
851/*
852 * call-seq:
853 * map.key?(key) -> true or false
854 *
855 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
856 */
857static VALUE
858wkmap_has_key(VALUE self, VALUE key)
859{
860 return RBOOL(!UNDEF_P(wkmap_lookup(self, key)));
861}
862
863/*
864 * call-seq:
865 * map.clear -> self
866 *
867 * Removes all map entries; returns +self+.
868 */
869static VALUE
870wkmap_clear(VALUE self)
871{
872 struct weakkeymap *w;
873 TypedData_Get_Struct(self, struct weakkeymap, &rb_weakkeymap_type, w);
874
875 st_clear(w->table);
876
877 return self;
878}
879
880/*
881 * call-seq:
882 * map.inspect -> new_string
883 *
884 * Returns a new String containing information about the map:
885 *
886 * m = ObjectSpace::WeakKeyMap.new
887 * m[key] = value
888 * m.inspect # => "#<ObjectSpace::WeakKeyMap:0x00000001028dcba8 size=1>"
889 *
890 */
891static VALUE
892wkmap_inspect(VALUE self)
893{
894 struct weakkeymap *w;
895 TypedData_Get_Struct(self, struct weakkeymap, &rb_weakkeymap_type, w);
896
897 st_index_t n = st_table_size(w->table);
898
899#if SIZEOF_ST_INDEX_T <= SIZEOF_LONG
900 const char * format = "#<%"PRIsVALUE":%p size=%lu>";
901#else
902 const char * format = "#<%"PRIsVALUE":%p size=%llu>";
903#endif
904
905 VALUE str = rb_sprintf(format, rb_class_name(CLASS_OF(self)), (void *)self, n);
906 return str;
907}
908
909/*
910 * Document-class: ObjectSpace::WeakMap
911 *
912 * An ObjectSpace::WeakMap is a key-value map that holds weak references
913 * to its keys and values, so they can be garbage-collected when there are
914 * no more references left.
915 *
916 * Keys in the map are compared by identity.
917 *
918 * m = ObjectSpace::WeakMap.new
919 * key1 = "foo"
920 * val1 = Object.new
921 * m[key1] = val1
922 *
923 * key2 = "bar"
924 * val2 = Object.new
925 * m[key2] = val2
926 *
927 * m[key1] #=> #<Object:0x0...>
928 * m[key2] #=> #<Object:0x0...>
929 *
930 * val1 = nil # remove the other reference to value
931 * GC.start
932 *
933 * m[key1] #=> nil
934 * m.keys #=> ["bar"]
935 *
936 * key2 = nil # remove the other reference to key
937 * GC.start
938 *
939 * m[key2] #=> nil
940 * m.keys #=> []
941 *
942 * (Note that GC.start is used here only for demonstrational purposes and might
943 * not always lead to demonstrated results.)
944 *
945 *
946 * See also ObjectSpace::WeakKeyMap map class, which compares keys by value,
947 * and holds weak references only to the keys.
948 */
949
950/*
951 * Document-class: ObjectSpace::WeakKeyMap
952 *
953 * An ObjectSpace::WeakKeyMap is a key-value map that holds weak references
954 * to its keys, so they can be garbage collected when there is no more references.
955 *
956 * Unlike ObjectSpace::WeakMap:
957 *
958 * * references to values are _strong_, so they aren't garbage collected while
959 * they are in the map;
960 * * keys are compared by value (using Object#eql?), not by identity;
961 * * only garbage-collectable objects can be used as keys.
962 *
963 * map = ObjectSpace::WeakKeyMap.new
964 * val = Time.new(2023, 12, 7)
965 * key = "name"
966 * map[key] = val
967 *
968 * # Value is fetched by equality: the instance of string "name" is
969 * # different here, but it is equal to the key
970 * map["name"] #=> 2023-12-07 00:00:00 +0200
971 *
972 * val = nil
973 * GC.start
974 * # There are no more references to `val`, yet the pair isn't
975 * # garbage-collected.
976 * map["name"] #=> 2023-12-07 00:00:00 +0200
977 *
978 * key = nil
979 * GC.start
980 * # There are no more references to `key`, key and value are
981 * # garbage-collected.
982 * map["name"] #=> nil
983 *
984 * (Note that GC.start is used here only for demonstrational purposes and might
985 * not always lead to demonstrated results.)
986 *
987 * The collection is especially useful for implementing caches of lightweight value
988 * objects, so that only one copy of each value representation would be stored in
989 * memory, but the copies that aren't used would be garbage-collected.
990 *
991 * CACHE = ObjectSpace::WeakKeyMap
992 *
993 * def make_value(**)
994 * val = ValueObject.new(**)
995 * if (existing = @cache.getkey(val))
996 * # if the object with this value exists, we return it
997 * existing
998 * else
999 * # otherwise, put it in the cache
1000 * @cache[val] = true
1001 * val
1002 * end
1003 * end
1004 *
1005 * This will result in +make_value+ returning the same object for same set of attributes
1006 * always, but the values that aren't needed anymore wouldn't be sitting in the cache forever.
1007 */
1008
1009void
1010Init_WeakMap(void)
1011{
1012 VALUE rb_mObjectSpace = rb_define_module("ObjectSpace");
1013
1014 VALUE rb_cWeakMap = rb_define_class_under(rb_mObjectSpace, "WeakMap", rb_cObject);
1015 rb_define_alloc_func(rb_cWeakMap, wmap_allocate);
1016 rb_define_method(rb_cWeakMap, "[]=", wmap_aset, 2);
1017 rb_define_method(rb_cWeakMap, "[]", wmap_aref, 1);
1018 rb_define_method(rb_cWeakMap, "delete", wmap_delete, 1);
1019 rb_define_method(rb_cWeakMap, "include?", wmap_has_key, 1);
1020 rb_define_method(rb_cWeakMap, "member?", wmap_has_key, 1);
1021 rb_define_method(rb_cWeakMap, "key?", wmap_has_key, 1);
1022 rb_define_method(rb_cWeakMap, "inspect", wmap_inspect, 0);
1023 rb_define_method(rb_cWeakMap, "each", wmap_each, 0);
1024 rb_define_method(rb_cWeakMap, "each_pair", wmap_each, 0);
1025 rb_define_method(rb_cWeakMap, "each_key", wmap_each_key, 0);
1026 rb_define_method(rb_cWeakMap, "each_value", wmap_each_value, 0);
1027 rb_define_method(rb_cWeakMap, "keys", wmap_keys, 0);
1028 rb_define_method(rb_cWeakMap, "values", wmap_values, 0);
1029 rb_define_method(rb_cWeakMap, "size", wmap_size, 0);
1030 rb_define_method(rb_cWeakMap, "length", wmap_size, 0);
1031 rb_include_module(rb_cWeakMap, rb_mEnumerable);
1032
1033 VALUE rb_cWeakKeyMap = rb_define_class_under(rb_mObjectSpace, "WeakKeyMap", rb_cObject);
1034 rb_define_alloc_func(rb_cWeakKeyMap, wkmap_allocate);
1035 rb_define_method(rb_cWeakKeyMap, "[]=", wkmap_aset, 2);
1036 rb_define_method(rb_cWeakKeyMap, "[]", wkmap_aref, 1);
1037 rb_define_method(rb_cWeakKeyMap, "delete", wkmap_delete, 1);
1038 rb_define_method(rb_cWeakKeyMap, "getkey", wkmap_getkey, 1);
1039 rb_define_method(rb_cWeakKeyMap, "key?", wkmap_has_key, 1);
1040 rb_define_method(rb_cWeakKeyMap, "clear", wkmap_clear, 0);
1041 rb_define_method(rb_cWeakKeyMap, "inspect", wkmap_inspect, 0);
1042}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1773
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
#define Qundef
Old name of RUBY_Qundef.
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FL_ABLE
Old name of RB_FL_ABLE.
Definition fl_type.h:118
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define Qnil
Old name of RUBY_Qnil.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:654
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3949
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1419
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1396
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition st.h:79
Definition weakmap.c:33
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376