size_t hashset_iterator_value(hashset_itr_t itr) { /* Check to verify we're not at a null value, this can happen if an iterator is created * before items are added to the set. */ if(itr->set->items[itr->index] == 0) { hashset_iterator_next(itr); } return itr->set->items[itr->index]; }
static void test_iterating(void) { hashset_t set = hashset_create(); hashset_itr_t iter = hashset_iterator(set); int step; /* fill the hashset */ hashset_add(set, (void *)"Bob"); hashset_add(set, (void *)"Steve"); hashset_add(set, (void *)"Karen"); hashset_add(set, (void *)"Ellen"); step = 0; while(hashset_iterator_has_next(iter)) { if(step == 0) { assert(strncmp((char *)hashset_iterator_value(iter), "Karen", 5) == 0); } if(step == 1) { assert(strncmp((char *)hashset_iterator_value(iter), "Steve", 5) == 0); } if(step == 2) { assert(strncmp((char *)hashset_iterator_value(iter), "Bob", 3) == 0); } if(step == 3) { assert(strncmp((char *)hashset_iterator_value(iter), "Ellen", 5) == 0); } hashset_iterator_next(iter); step++; } assert(hashset_iterator_has_next(iter) == 0); assert(hashset_iterator_next(iter) == -1); }
hashset_itr_t hashset_iterator(hashset_t set) { hashset_itr_t itr = calloc(1, sizeof(struct hashset_itr_st)); if (itr == NULL) return NULL; itr->set = set; itr->index = 0; /* advance to the first item if one is present */ if (set->nitems > 0) hashset_iterator_next(itr); return itr; }