PageRenderTime 23ms CodeModel.GetById 11ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/vm/tinyrb/hash.c

http://github.com/feyeleanor/RubyGoLightly
C | 61 lines | 53 code | 7 blank | 1 comment | 6 complexity | 0b9b10272f28a1c0f5e634225531fdf0 MD5 | raw file
 1#include "tr.h"
 2#include "internal.h"
 3
 4OBJ TrHash_new(VM) {
 5  TrHash *h = TR_INIT_CORE_OBJECT(Hash);
 6  h->kh = kh_init(OBJ);
 7  return (OBJ)h;
 8}
 9
10OBJ TrHash_new2(VM, size_t n, OBJ items[]) {
11  TrHash *h = (TrHash *)TrHash_new(vm);
12  size_t i;
13  int ret;
14  for (i = 0; i < n; i+=2) {
15    khiter_t k = kh_put(OBJ, h->kh, items[i], &ret);
16    kh_value(h->kh, k) = items[i+1];
17  }
18  return (OBJ)h;
19}
20
21static OBJ TrHash_size(VM, OBJ self) {
22  TrHash *h = TR_CHASH(self);
23  return TR_INT2FIX(kh_size(h->kh));
24}
25
26/* TODO use Object#hash as the key */
27static OBJ TrHash_get(VM, OBJ self, OBJ key) {
28  TrHash *h = TR_CHASH(self);
29  khiter_t k = kh_get(OBJ, h->kh, key);
30  if (k != kh_end(h->kh)) return kh_value(h->kh, k);
31  return TR_NIL;
32}
33
34static OBJ TrHash_set(VM, OBJ self, OBJ key, OBJ value) {
35  TrHash *h = TR_CHASH(self);
36  int ret;
37  khiter_t k = kh_put(OBJ, h->kh, key, &ret);
38  if (!ret) kh_del(OBJ, h->kh, k);
39  kh_value(h->kh, k) = value;
40  return value;
41}
42
43static OBJ TrHash_delete(VM, OBJ self, OBJ key) {
44  TrHash *h = TR_CHASH(self);
45  khiter_t k = kh_get(OBJ, h->kh, key);
46  if (k != kh_end(h->kh)) {
47    OBJ value = kh_value(h->kh, k);
48    kh_del(OBJ, h->kh, k);
49    return value;
50  }
51  return TR_NIL;
52}
53
54void TrHash_init(VM) {
55  OBJ c = TR_INIT_CORE_CLASS(Hash, Object);
56  tr_def(c, "length", TrHash_size, 0);
57  tr_def(c, "size", TrHash_size, 0);
58  tr_def(c, "[]", TrHash_get, 1);
59  tr_def(c, "[]=", TrHash_set, 2);
60  tr_def(c, "delete", TrHash_delete, 1);
61}