#include "database.h" int findRec(Dbrec *db,dbkeytype key, dbdatatype *data, indextype *idx) /* Preconditions: The keys of the records are in order. Action: Find key in the list of records. Returns whether or not it was found. If found, data is set to the data, (*idx)->it points to the record. If not found, (*idx)->it points to the record whose key immediately follows key (possibly NULL). In either case, (*idx)->prior points to the record before (*idx)->it (possibly NULL). */ { Dbrec rec=*db,prior=NULL; int cmp; while(rec && (cmp=comparedbkey(key,rec->key)) > 0) { /* LI: (1) All the keys in the list db up to, but not including rec, are less than key. (2) prior points to the record before rec in the list. */ prior = rec; rec = rec->next; } idx->it = rec; idx->prior = prior; if(rec&&cmp==0) { copydbdata(rec->data,*data); return 1; } return 0; } int createRec(Dbrec *db,dbkeytype key, dbdatatype data, indextype *idx) /* Precondition: idx->prior points to the record after which the new record should be inserted. (If NULL, the new record is inserted at the head of the list. idx->it points to the record after idx->prior. Action: If the database is not full, adds the record with key key and data data, and returns 1. Otherwise, returns 0. */ { Dbrec rec; rec=(Dbrec)malloc(sizeof(struct dbrec)); if(rec==NULL) return 0; copydbkey(key,rec->key); copydbdata(data,rec->data); rec->next=idx->it; if(idx->prior) idx->prior->next = rec; else *db = rec; idx->it=rec; return 1; } int deleteRec(Dbrec *db,indextype idx) /* Precondition: idx->it points to the record to be deleted. idx->prior points to the record before it, or NULL if none before it. Postcondition: idx->it is deleted. */ { if(idx.prior) idx.prior->next = idx.it->next; else *db = idx.it->next; free((void *)idx.it); } void initDb(Dbrec *db) /* Initialize the database *db. */ { *db = NULL; } void eachRec(Dbrec *db,void (*fn)(dbkeytype,dbdatatype)) /* Apply fn to each record in *db. */ { Dbrec rec; for(rec=*db;rec;rec=rec->next) (*fn)(rec->key,rec->data); } void setRec(Dbrec *db,indextype idx, dbdatatype data) /* Change the data of record idx to become data. */ { copydbdata(data,idx.it->data); }