/* Implementacija apstraktnog tipa skup pomocu niza */ #include /* Definicija NULL */ #include /* Potrebno zbog assert */ #include "Collection.h" /* ucitava specifikaciju */ extern void *ItemKey( void * ); struct t_Collection { int item_cnt; int max_items; /* Nije apsolutno neophodno */ int size; /* Potrebno zbog FindInCollection */ void **items; }; Collection ConsCollection(int max_items, int item_size ) /* Kreiraj novi skup Pre-uslov: (max_items > 0) && (item_size > 0) Post-uslov: vraca pointer na prazan skup */ { Collection c; assert( max_items > 0 ); assert( item_size > 0 ); c = (Collection)calloc( 1, sizeof(struct t_Collection) ); c->items = (void **)calloc(max_items,sizeof(void *)); c->size = item_size; c->max_items = max_items; return c; } void DeleteCollection( Collection c ) { assert( c != NULL ); assert( c->items != NULL ); free( c->items ); free( c ); } void AddToCollection( Collection c, void *item ) /* Dodaje objekat u skup Pre-uslov: (c je skup kreiran pozivom ConsCollection) && (postojeci broj objekata < max_items) && (item != NULL) Post-uslov: objekat je dodat u skup c */ { assert( c != NULL); assert( c->item_cnt < c->max_items ); assert( item != NULL); c->items[c->item_cnt++] = item; /* Post-uslov */ assert( FindInCollection( c, ItemKey( item ) ) != NULL ); } void DeleteFromCollection( Collection c, void *item ) /* Brise objekat iz skupa Pre-uslov: (c je skup kreiran pozivom ConsCollection) && (postojeci broj objekata >= 1) && (item != NULL) Post-uslov: objekat je obrisan iz skupa c */ { int i; assert( c != NULL ); assert( c->item_cnt >= 1 ); assert( item != NULL ); for(i=0;iitem_cnt;i++) { if ( item == c->items[i] ) { /* Pronadjen objekat koji treba obrisati, pomeri preostale jedno mesto unapred */ while( i < c->item_cnt ) { c->items[i] = c->items[i+1]; i++; } c->item_cnt--; break; } } } void *FindInCollection( Collection c, void *key ) /* Trazi objekat u skupu Pre-condition: (c je skup kreiran pozivom ConsCollection) && (key != NULL) Post-uslov: vraca objekat identifikovan kljucem key ako takav postoji, u suprotnom vraca NULL */ { int i; assert( c != NULL ); assert( key != NULL ); for(i=0;iitem_cnt;i++) { if (memcmp(ItemKey(c->items[i]),key,c->size)==0) return c->items[i]; } return NULL; }