ptg10805159
778 ADatabase Library Chapter 20
687 while (offset != 0) {
688 nextoffset=_db_readidx(db, offset);
689 if (strlen(db->idxbuf) == keylen && db->datlen == datlen)
690 break; /* found a match */
691 saveoffset=offset;
692 offset=nextoffset;
693 }
694 if (offset == 0) {
695 rc=-1; /* no match found */
696 } else {
697 /*
698 * Found a free record with matching sizes.
699 * The index record was read in by _db_readidx above,
700 * which sets db->ptrval. Also, saveoffset points to
701 * the chain ptr that pointed to this empty record on
702 * the free list. We set this chain ptr to db->ptrval,
703 * which removes the empty record from the free list.
704 */
705 _db_writeptr(db, saveoffset, db->ptrval);
706 rc=0;
707 /*
708 * Notice also that _db_readidx set both db->idxoff
709 * and db->datoff. This is used by the caller, db_store,
710 * to write the new index record and data record.
711 */
712 }
713 /*
714 * Unlock the free list.
715 */
716 if (un_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
717 err_dump("_db_findfree: un_lock error");
718 return(rc);
719 }
[687 – 693] Thewhileloop in_db_findfreegoes through the free list, looking for a
recordwith matching key and data sizes. In this simple implementation, we
reuse a deleted recordonly if the key length and data length equal the
lengths for the new recordbeing inserted. Thereare a variety of better ways
to reuse this deleted space, in exchange for added complexity.
[694 – 712] If we can’t find an available record of the requested key and data sizes, we
set the return code to indicate failure. Otherwise, we write the previous
record’s chain pointer to point to the next chain pointer value of the record
we have found. This removes the recordfromthe free list.
[713 – 719] Once we aredone with the free list, we release the write lock. Then we
return the status to the caller.