Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-hash-ext/src/hash-ext.c

raw
1 /*
2 ** hash.c - Hash class
3 **
4 ** See Copyright Notice in mruby.h
5 */
6
7 #include <mruby.h>
8 #include <mruby/array.h>
9 #include <mruby/hash.h>
10
11 /*
12 * call-seq:
13 * hsh.values_at(key, ...) -> array
14 *
15 * Return an array containing the values associated with the given keys.
16 * Also see <code>Hash.select</code>.
17 *
18 * h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
19 * h.values_at("cow", "cat") #=> ["bovine", "feline"]
20 */
21
22 static mrb_value
23 hash_values_at(mrb_state *mrb, mrb_value hash)
24 {
25 const mrb_value *argv;
26 mrb_value result;
27 mrb_int argc, i;
28 int ai;
29
30 mrb_get_args(mrb, "*", &argv, &argc);
31 result = mrb_ary_new_capa(mrb, argc);
32 if (argc == 0) return result;
33 ai = mrb_gc_arena_save(mrb);
34 for (i = 0; i < argc; i++) {
35 mrb_ary_push(mrb, result, mrb_hash_get(mrb, hash, argv[i]));
36 mrb_gc_arena_restore(mrb, ai);
37 }
38 return result;
39 }
40
41 /*
42 * call-seq:
43 * hsh.slice(*keys) -> a_hash
44 *
45 * Returns a hash containing only the given keys and their values.
46 *
47 * h = { a: 100, b: 200, c: 300 }
48 * h.slice(:a) #=> {:a=>100}
49 * h.slice(:b, :c, :d) #=> {:b=>200, :c=>300}
50 */
51 static mrb_value
52 hash_slice(mrb_state *mrb, mrb_value hash)
53 {
54 const mrb_value *argv;
55 mrb_value result;
56 mrb_int argc, i;
57
58 mrb_get_args(mrb, "*", &argv, &argc);
59 result = mrb_hash_new_capa(mrb, argc);
60 if (argc == 0) return result; /* empty hash */
61 for (i = 0; i < argc; i++) {
62 mrb_value key = argv[i];
63 mrb_value val;
64
65 val = mrb_hash_fetch(mrb, hash, key, mrb_undef_value());
66 if (!mrb_undef_p(val)) {
67 mrb_hash_set(mrb, result, key, val);
68 }
69 }
70 return result;
71 }
72
73 /*
74 * call-seq:
75 * hsh.except(*keys) -> a_hash
76 *
77 * Returns a hash excluding the given keys and their values.
78 *
79 * h = { a: 100, b: 200, c: 300 }
80 * h.except(:a) #=> {:b=>200, :c=>300}
81 * h.except(:b, :c, :d) #=> {:a=>100}
82 */
83 static mrb_value
84 hash_except(mrb_state *mrb, mrb_value hash)
85 {
86 const mrb_value *argv;
87 mrb_value result;
88 mrb_int argc, i;
89
90 mrb_get_args(mrb, "*", &argv, &argc);
91 result = mrb_hash_dup(mrb, hash);
92 for (i = 0; i < argc; i++) {
93 mrb_hash_delete_key(mrb, result, argv[i]);
94 }
95 return result;
96 }
97
98 void
99 mrb_mruby_hash_ext_gem_init(mrb_state *mrb)
100 {
101 struct RClass *h;
102
103 h = mrb->hash_class;
104 mrb_define_method(mrb, h, "values_at", hash_values_at, MRB_ARGS_ANY());
105 mrb_define_method(mrb, h, "slice", hash_slice, MRB_ARGS_ANY());
106 mrb_define_method(mrb, h, "except", hash_except, MRB_ARGS_ANY());
107 }
108
109 void
110 mrb_mruby_hash_ext_gem_final(mrb_state *mrb)
111 {
112 }