From b0474aaec21dfb4fb410812023378d4d496f5619 Mon Sep 17 00:00:00 2001 From: Yuichi Nishiwaki Date: Sun, 13 Jul 2014 12:07:07 +0900 Subject: [PATCH] add dictionary operators --- include/picrin/dict.h | 5 ++++ src/dict.c | 55 +++++++++++++++++++++++++++++++++---------- 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/include/picrin/dict.h b/include/picrin/dict.h index 7d969818..ae118e13 100644 --- a/include/picrin/dict.h +++ b/include/picrin/dict.h @@ -19,6 +19,11 @@ struct pic_dict { struct pic_dict *pic_dict_new(pic_state *); +pic_value pic_dict_ref(pic_state *, struct pic_dict *, pic_sym); +void pic_dict_set(pic_state *, struct pic_dict *, pic_sym, pic_value); +void pic_dict_del(pic_state *, struct pic_dict *, pic_sym); +size_t pic_dict_size(pic_state *, struct pic_dict *); + #if defined(__cplusplus) } #endif diff --git a/src/dict.c b/src/dict.c index 9789f117..2f7088cd 100644 --- a/src/dict.c +++ b/src/dict.c @@ -16,6 +16,44 @@ pic_dict_new(pic_state *pic) return dict; } +pic_value +pic_dict_ref(pic_state *pic, struct pic_dict *dict, pic_sym key) +{ + xh_entry *e; + + e = xh_get_int(&dict->hash, key); + if (! e) { + pic_errorf(pic, "element not found for a key: ~s", pic_sym_value(key)); + } + return xh_val(e, pic_value); +} + +void +pic_dict_set(pic_state *pic, struct pic_dict *dict, pic_sym key, pic_value val) +{ + UNUSED(pic); + + xh_put_int(&dict->hash, key, &val); +} + +size_t +pic_dict_size(pic_state *pic, struct pic_dict *dict) +{ + UNUSED(pic); + + return dict->hash.count; +} + +void +pic_dict_del(pic_state *pic, struct pic_dict *dict, pic_sym key) +{ + if (xh_get_int(&dict->hash, key) == NULL) { + pic_errorf(pic, "no slot named ~s found in dictionary", pic_sym_value(key)); + } + + xh_del_int(&dict->hash, key); +} + static pic_value pic_dict_dict(pic_state *pic) { @@ -43,15 +81,10 @@ pic_dict_dict_ref(pic_state *pic) { struct pic_dict *dict; pic_sym key; - xh_entry *e; pic_get_args(pic, "dm", &dict, &key); - e = xh_get_int(&dict->hash, key); - if (! e) { - pic_errorf(pic, "element not found for a key: ~s", pic_sym_value(key)); - } - return xh_val(e, pic_value); + return pic_dict_ref(pic, dict , key); } static pic_value @@ -63,7 +96,7 @@ pic_dict_dict_set(pic_state *pic) pic_get_args(pic, "dmo", &dict, &key, &val); - xh_put_int(&dict->hash, key, &val); + pic_dict_set(pic, dict, key, val); return pic_none_value(); } @@ -76,11 +109,7 @@ pic_dict_dict_del(pic_state *pic) pic_get_args(pic, "dm", &dict, &key); - if (xh_get_int(&dict->hash, key) == NULL) { - pic_errorf(pic, "no slot named ~s found in dictionary", pic_sym_value(key)); - } - - xh_del_int(&dict->hash, key); + pic_dict_del(pic, dict, key); return pic_none_value(); } @@ -92,7 +121,7 @@ pic_dict_dict_size(pic_state *pic) pic_get_args(pic, "d", &dict); - return pic_int_value(dict->hash.count); + return pic_int_value(pic_dict_size(pic, dict)); } void