glibc 의 hsearchr 함수

2702 단어 chash
hsearch_r 함수
int
hsearch_r (item, action, retval, htab)
     ENTRY item;
     ACTION action;
     ENTRY **retval;
     struct hsearch_data *htab;
{
  unsigned int hval;
  unsigned int count;
  unsigned int len = strlen (item.key);
  unsigned int idx;


  /** Compute an value for the given string. Perhaps use a better method. */
  hval = len;
  count = len;
  while (count-- > 0)
    {
      hval <<= 4;
      hval += item.key[count];
    }


  /** First hash function: simply take the modul but prevent zero. */
  idx = hval % htab->size + 1;


  if (htab->table[idx].used)
    {
      /** Further action might be required according to the action value. */
      if (htab->table[idx].used == hval
 && strcmp (item.key, htab->table[idx].entry.key) == 0)
{
 *retval = &htab->table[idx].entry;
 return 1;
}


      /** Second hash function, as suggested in [Knuth] */
      unsigned int hval2 = 1 + hval % (htab->size - 2);
      unsigned int first_idx = idx;


      do
{
 /** Because SIZE is prime this guarantees to step through all
             available indeces.  */
          if (idx <= hval2)
   idx = htab->size + idx - hval2;
 else
   idx -= hval2;


 /** If we visited all entries leave the loop unsuccessfully.  */
 if (idx == first_idx)
   break;


            /** If entry is found use it. */
          if (htab->table[idx].used == hval
     && strcmp (item.key, htab->table[idx].entry.key) == 0)
   {
     *retval = &htab->table[idx].entry;
     return 1;
   }
}
      while (htab->table[idx].used);
    }


  /** An empty bucket has been found. */
  if (action == ENTER)
    {
      /** If table is full and another entry should be entered return
with error.  */
      if (htab->filled == htab->size)
{
 __set_errno (ENOMEM);
 *retval = NULL;
 return 0;
}


      htab->table[idx].used  = hval;
      htab->table[idx].entry = item;


      ++htab->filled;


      *retval = &htab->table[idx].entry;
      return 1;
    }


  __set_errno (ESRCH);
  *retval = NULL;
  return 0;
}

함수 가 실 행 될 때 action 이 왜 든 먼저 찾 고 명중 하면 있 는 것 으로 되 돌아 가 며 명중 노드 가 없 으 면 action 이 ENTER 이면 hashadd 작업.

좋은 웹페이지 즐겨찾기