search.texi 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. @node Searching and Sorting, Pattern Matching, Message Translation, Top
  2. @c %MENU% General searching and sorting functions
  3. @chapter Searching and Sorting
  4. This chapter describes functions for searching and sorting arrays of
  5. arbitrary objects. You pass the appropriate comparison function to be
  6. applied as an argument, along with the size of the objects in the array
  7. and the total number of elements.
  8. @menu
  9. * Comparison Functions:: Defining how to compare two objects.
  10. Since the sort and search facilities
  11. are general, you have to specify the
  12. ordering.
  13. * Array Search Function:: The @code{bsearch} function.
  14. * Array Sort Function:: The @code{qsort} function.
  15. * Search/Sort Example:: An example program.
  16. * Hash Search Function:: The @code{hsearch} function.
  17. * Tree Search Function:: The @code{tsearch} function.
  18. @end menu
  19. @node Comparison Functions
  20. @section Defining the Comparison Function
  21. @cindex Comparison Function
  22. In order to use the sorted array library functions, you have to describe
  23. how to compare the elements of the array.
  24. To do this, you supply a comparison function to compare two elements of
  25. the array. The library will call this function, passing as arguments
  26. pointers to two array elements to be compared. Your comparison function
  27. should return a value the way @code{strcmp} (@pxref{String/Array
  28. Comparison}) does: negative if the first argument is ``less'' than the
  29. second, zero if they are ``equal'', and positive if the first argument
  30. is ``greater''.
  31. Here is an example of a comparison function which works with an array of
  32. numbers of type @code{double}:
  33. @smallexample
  34. int
  35. compare_doubles (const void *a, const void *b)
  36. @{
  37. const double *da = (const double *) a;
  38. const double *db = (const double *) b;
  39. return (*da > *db) - (*da < *db);
  40. @}
  41. @end smallexample
  42. The header file @file{stdlib.h} defines a name for the data type of
  43. comparison functions. This type is a GNU extension.
  44. @comment stdlib.h
  45. @comment GNU
  46. @tindex comparison_fn_t
  47. @smallexample
  48. int comparison_fn_t (const void *, const void *);
  49. @end smallexample
  50. @node Array Search Function
  51. @section Array Search Function
  52. @cindex search function (for arrays)
  53. @cindex binary search function (for arrays)
  54. @cindex array search function
  55. Generally searching for a specific element in an array means that
  56. potentially all elements must be checked. @Theglibc{} contains
  57. functions to perform linear search. The prototypes for the following
  58. two functions can be found in @file{search.h}.
  59. @deftypefun {void *} lfind (const void *@var{key}, const void *@var{base}, size_t *@var{nmemb}, size_t @var{size}, comparison_fn_t @var{compar})
  60. @standards{SVID, search.h}
  61. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  62. The @code{lfind} function searches in the array with @code{*@var{nmemb}}
  63. elements of @var{size} bytes pointed to by @var{base} for an element
  64. which matches the one pointed to by @var{key}. The function pointed to
  65. by @var{compar} is used to decide whether two elements match.
  66. The return value is a pointer to the matching element in the array
  67. starting at @var{base} if it is found. If no matching element is
  68. available @code{NULL} is returned.
  69. The mean runtime of this function is @code{*@var{nmemb}}/2. This
  70. function should only be used if elements often get added to or deleted from
  71. the array in which case it might not be useful to sort the array before
  72. searching.
  73. @end deftypefun
  74. @deftypefun {void *} lsearch (const void *@var{key}, void *@var{base}, size_t *@var{nmemb}, size_t @var{size}, comparison_fn_t @var{compar})
  75. @standards{SVID, search.h}
  76. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  77. @c A signal handler that interrupted an insertion and performed an
  78. @c insertion itself would leave the array in a corrupt state (e.g. one
  79. @c new element initialized twice, with parts of both initializations
  80. @c prevailing, and another uninitialized element), but this is just a
  81. @c special case of races on user-controlled objects, that have to be
  82. @c avoided by users.
  83. @c In case of cancellation, we know the array won't be left in a corrupt
  84. @c state; the new element is initialized before the element count is
  85. @c incremented, and the compiler can't reorder these operations because
  86. @c it can't know that they don't alias. So, we'll either cancel after
  87. @c the increment and the initialization are both complete, or the
  88. @c increment won't have taken place, and so how far the initialization
  89. @c got doesn't matter.
  90. The @code{lsearch} function is similar to the @code{lfind} function. It
  91. searches the given array for an element and returns it if found. The
  92. difference is that if no matching element is found the @code{lsearch}
  93. function adds the object pointed to by @var{key} (with a size of
  94. @var{size} bytes) at the end of the array and it increments the value of
  95. @code{*@var{nmemb}} to reflect this addition.
  96. This means for the caller that if it is not sure that the array contains
  97. the element one is searching for the memory allocated for the array
  98. starting at @var{base} must have room for at least @var{size} more
  99. bytes. If one is sure the element is in the array it is better to use
  100. @code{lfind} so having more room in the array is always necessary when
  101. calling @code{lsearch}.
  102. @end deftypefun
  103. To search a sorted array for an element matching the key, use the
  104. @code{bsearch} function. The prototype for this function is in
  105. the header file @file{stdlib.h}.
  106. @pindex stdlib.h
  107. @deftypefun {void *} bsearch (const void *@var{key}, const void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
  108. @standards{ISO, stdlib.h}
  109. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  110. The @code{bsearch} function searches the sorted array @var{array} for an object
  111. that is equivalent to @var{key}. The array contains @var{count} elements,
  112. each of which is of size @var{size} bytes.
  113. The @var{compare} function is used to perform the comparison. This
  114. function is called with two pointer arguments and should return an
  115. integer less than, equal to, or greater than zero corresponding to
  116. whether its first argument is considered less than, equal to, or greater
  117. than its second argument. The elements of the @var{array} must already
  118. be sorted in ascending order according to this comparison function.
  119. The return value is a pointer to the matching array element, or a null
  120. pointer if no match is found. If the array contains more than one element
  121. that matches, the one that is returned is unspecified.
  122. This function derives its name from the fact that it is implemented
  123. using the binary search algorithm.
  124. @end deftypefun
  125. @node Array Sort Function
  126. @section Array Sort Function
  127. @cindex sort function (for arrays)
  128. @cindex quick sort function (for arrays)
  129. @cindex array sort function
  130. To sort an array using an arbitrary comparison function, use the
  131. @code{qsort} function. The prototype for this function is in
  132. @file{stdlib.h}.
  133. @pindex stdlib.h
  134. @deftypefun void qsort (void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
  135. @standards{ISO, stdlib.h}
  136. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@acucorrupt{}}}
  137. The @code{qsort} function sorts the array @var{array}. The array
  138. contains @var{count} elements, each of which is of size @var{size}.
  139. The @var{compare} function is used to perform the comparison on the
  140. array elements. This function is called with two pointer arguments and
  141. should return an integer less than, equal to, or greater than zero
  142. corresponding to whether its first argument is considered less than,
  143. equal to, or greater than its second argument.
  144. @cindex stable sorting
  145. @strong{Warning:} If two objects compare as equal, their order after
  146. sorting is unpredictable. That is to say, the sorting is not stable.
  147. This can make a difference when the comparison considers only part of
  148. the elements. Two elements with the same sort key may differ in other
  149. respects.
  150. Although the object addresses passed to the comparison function lie
  151. within the array, they need not correspond with the original locations
  152. of those objects because the sorting algorithm may swap around objects
  153. in the array before making some comparisons. The only way to perform
  154. a stable sort with @code{qsort} is to first augment the objects with a
  155. monotonic counter of some kind.
  156. Here is a simple example of sorting an array of doubles in numerical
  157. order, using the comparison function defined above (@pxref{Comparison
  158. Functions}):
  159. @smallexample
  160. @{
  161. double *array;
  162. int size;
  163. @dots{}
  164. qsort (array, size, sizeof (double), compare_doubles);
  165. @}
  166. @end smallexample
  167. The @code{qsort} function derives its name from the fact that it was
  168. originally implemented using the ``quick sort'' algorithm.
  169. The implementation of @code{qsort} in this library might not be an
  170. in-place sort and might thereby use an extra amount of memory to store
  171. the array.
  172. @end deftypefun
  173. @node Search/Sort Example
  174. @section Searching and Sorting Example
  175. Here is an example showing the use of @code{qsort} and @code{bsearch}
  176. with an array of structures. The objects in the array are sorted
  177. by comparing their @code{name} fields with the @code{strcmp} function.
  178. Then, we can look up individual objects based on their names.
  179. @comment This example is dedicated to the memory of Jim Henson. RIP.
  180. @smallexample
  181. @include search.c.texi
  182. @end smallexample
  183. @cindex Kermit the frog
  184. The output from this program looks like:
  185. @smallexample
  186. Kermit, the frog
  187. Piggy, the pig
  188. Gonzo, the whatever
  189. Fozzie, the bear
  190. Sam, the eagle
  191. Robin, the frog
  192. Animal, the animal
  193. Camilla, the chicken
  194. Sweetums, the monster
  195. Dr. Strangepork, the pig
  196. Link Hogthrob, the pig
  197. Zoot, the human
  198. Dr. Bunsen Honeydew, the human
  199. Beaker, the human
  200. Swedish Chef, the human
  201. Animal, the animal
  202. Beaker, the human
  203. Camilla, the chicken
  204. Dr. Bunsen Honeydew, the human
  205. Dr. Strangepork, the pig
  206. Fozzie, the bear
  207. Gonzo, the whatever
  208. Kermit, the frog
  209. Link Hogthrob, the pig
  210. Piggy, the pig
  211. Robin, the frog
  212. Sam, the eagle
  213. Swedish Chef, the human
  214. Sweetums, the monster
  215. Zoot, the human
  216. Kermit, the frog
  217. Gonzo, the whatever
  218. Couldn't find Janice.
  219. @end smallexample
  220. @node Hash Search Function
  221. @section The @code{hsearch} function.
  222. The functions mentioned so far in this chapter are for searching in a sorted
  223. or unsorted array. There are other methods to organize information
  224. which later should be searched. The costs of insert, delete and search
  225. differ. One possible implementation is using hashing tables.
  226. The following functions are declared in the header file @file{search.h}.
  227. @deftypefun int hcreate (size_t @var{nel})
  228. @standards{SVID, search.h}
  229. @safety{@prelim{}@mtunsafe{@mtasurace{:hsearch}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  230. @c hcreate @mtasurace:hsearch @ascuheap @acucorrupt @acsmem
  231. @c hcreate_r dup @mtsrace:htab @ascuheap @acucorrupt @acsmem
  232. The @code{hcreate} function creates a hashing table which can contain at
  233. least @var{nel} elements. There is no possibility to grow this table so
  234. it is necessary to choose the value for @var{nel} wisely. The method
  235. used to implement this function might make it necessary to make the
  236. number of elements in the hashing table larger than the expected maximal
  237. number of elements. Hashing tables usually work inefficiently if they are
  238. filled 80% or more. The constant access time guaranteed by hashing can
  239. only be achieved if few collisions exist. See Knuth's ``The Art of
  240. Computer Programming, Part 3: Searching and Sorting'' for more
  241. information.
  242. The weakest aspect of this function is that there can be at most one
  243. hashing table used through the whole program. The table is allocated
  244. in local memory out of control of the programmer. As an extension @theglibc{}
  245. provides an additional set of functions with a reentrant
  246. interface which provides a similar interface but which allows keeping
  247. arbitrarily many hashing tables.
  248. It is possible to use more than one hashing table in the program run if
  249. the former table is first destroyed by a call to @code{hdestroy}.
  250. The function returns a non-zero value if successful. If it returns zero,
  251. something went wrong. This could either mean there is already a hashing
  252. table in use or the program ran out of memory.
  253. @end deftypefun
  254. @deftypefun void hdestroy (void)
  255. @standards{SVID, search.h}
  256. @safety{@prelim{}@mtunsafe{@mtasurace{:hsearch}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  257. @c hdestroy @mtasurace:hsearch @ascuheap @acucorrupt @acsmem
  258. @c hdestroy_r dup @mtsrace:htab @ascuheap @acucorrupt @acsmem
  259. The @code{hdestroy} function can be used to free all the resources
  260. allocated in a previous call of @code{hcreate}. After a call to this
  261. function it is again possible to call @code{hcreate} and allocate a new
  262. table with possibly different size.
  263. It is important to remember that the elements contained in the hashing
  264. table at the time @code{hdestroy} is called are @emph{not} freed by this
  265. function. It is the responsibility of the program code to free those
  266. strings (if necessary at all). Freeing all the element memory is not
  267. possible without extra, separately kept information since there is no
  268. function to iterate through all available elements in the hashing table.
  269. If it is really necessary to free a table and all elements the
  270. programmer has to keep a list of all table elements and before calling
  271. @code{hdestroy} s/he has to free all element's data using this list.
  272. This is a very unpleasant mechanism and it also shows that this kind of
  273. hashing table is mainly meant for tables which are created once and
  274. used until the end of the program run.
  275. @end deftypefun
  276. Entries of the hashing table and keys for the search are defined using
  277. this type:
  278. @deftp {Data type} {struct ENTRY}
  279. Both elements of this structure are pointers to zero-terminated strings.
  280. This is a limiting restriction of the functionality of the
  281. @code{hsearch} functions. They can only be used for data sets which use
  282. the NUL character always and solely to terminate the records. It is not
  283. possible to handle general binary data.
  284. @table @code
  285. @item char *key
  286. Pointer to a zero-terminated string of characters describing the key for
  287. the search or the element in the hashing table.
  288. @item char *data
  289. Pointer to a zero-terminated string of characters describing the data.
  290. If the functions will be called only for searching an existing entry
  291. this element might stay undefined since it is not used.
  292. @end table
  293. @end deftp
  294. @deftypefun {ENTRY *} hsearch (ENTRY @var{item}, ACTION @var{action})
  295. @standards{SVID, search.h}
  296. @safety{@prelim{}@mtunsafe{@mtasurace{:hsearch}}@asunsafe{}@acunsafe{@acucorrupt{/action==ENTER}}}
  297. @c hsearch @mtasurace:hsearch @acucorrupt/action==ENTER
  298. @c hsearch_r dup @mtsrace:htab @acucorrupt/action==ENTER
  299. To search in a hashing table created using @code{hcreate} the
  300. @code{hsearch} function must be used. This function can perform a simple
  301. search for an element (if @var{action} has the value @code{FIND}) or it can
  302. alternatively insert the key element into the hashing table. Entries
  303. are never replaced.
  304. The key is denoted by a pointer to an object of type @code{ENTRY}. For
  305. locating the corresponding position in the hashing table only the
  306. @code{key} element of the structure is used.
  307. If an entry with a matching key is found the @var{action} parameter is
  308. irrelevant. The found entry is returned. If no matching entry is found
  309. and the @var{action} parameter has the value @code{FIND} the function
  310. returns a @code{NULL} pointer. If no entry is found and the
  311. @var{action} parameter has the value @code{ENTER} a new entry is added
  312. to the hashing table which is initialized with the parameter @var{item}.
  313. A pointer to the newly added entry is returned.
  314. @end deftypefun
  315. As mentioned before, the hashing table used by the functions described so
  316. far is global and there can be at any time at most one hashing table in
  317. the program. A solution is to use the following functions which are a
  318. GNU extension. All have in common that they operate on a hashing table
  319. which is described by the content of an object of the type @code{struct
  320. hsearch_data}. This type should be treated as opaque, none of its
  321. members should be changed directly.
  322. @deftypefun int hcreate_r (size_t @var{nel}, struct hsearch_data *@var{htab})
  323. @standards{GNU, search.h}
  324. @safety{@prelim{}@mtsafe{@mtsrace{:htab}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  325. @c Unlike the lsearch array, the htab is (at least in part) opaque, so
  326. @c let's make it absolutely clear that ensuring exclusive access is a
  327. @c caller responsibility.
  328. @c Cancellation is unlikely to leave the htab in a corrupt state: the
  329. @c last field to be initialized is the one that tells whether the entire
  330. @c data structure was initialized, and there's a function call (calloc)
  331. @c in between that will often ensure all other fields are written before
  332. @c the table. However, should this call be inlined (say with LTO), this
  333. @c assumption may not hold. The calloc call doesn't cross our library
  334. @c interface barrier, so let's consider this could happen and mark this
  335. @c with @acucorrupt. It's no safety loss, since we already have
  336. @c @ascuheap anyway...
  337. @c hcreate_r @mtsrace:htab @ascuheap @acucorrupt @acsmem
  338. @c isprime ok
  339. @c calloc dup @ascuheap @acsmem
  340. The @code{hcreate_r} function initializes the object pointed to by
  341. @var{htab} to contain a hashing table with at least @var{nel} elements.
  342. So this function is equivalent to the @code{hcreate} function except
  343. that the initialized data structure is controlled by the user.
  344. This allows having more than one hashing table at one time. The memory
  345. necessary for the @code{struct hsearch_data} object can be allocated
  346. dynamically. It must be initialized with zero before calling this
  347. function.
  348. The return value is non-zero if the operation was successful. If the
  349. return value is zero, something went wrong, which probably means the
  350. program ran out of memory.
  351. @end deftypefun
  352. @deftypefun void hdestroy_r (struct hsearch_data *@var{htab})
  353. @standards{GNU, search.h}
  354. @safety{@prelim{}@mtsafe{@mtsrace{:htab}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  355. @c The table is released while the table pointer still points to it.
  356. @c Async cancellation is thus unsafe, but it already was because we call
  357. @c free(). Using the table in a handler while it's being released would
  358. @c also be dangerous, but calling free() already makes it unsafe, and
  359. @c the requirement on the caller to ensure exclusive access already
  360. @c guarantees this doesn't happen, so we don't get @asucorrupt.
  361. @c hdestroy_r @mtsrace:htab @ascuheap @acucorrupt @acsmem
  362. @c free dup @ascuheap @acsmem
  363. The @code{hdestroy_r} function frees all resources allocated by the
  364. @code{hcreate_r} function for this very same object @var{htab}. As for
  365. @code{hdestroy} it is the program's responsibility to free the strings
  366. for the elements of the table.
  367. @end deftypefun
  368. @deftypefun int hsearch_r (ENTRY @var{item}, ACTION @var{action}, ENTRY **@var{retval}, struct hsearch_data *@var{htab})
  369. @standards{GNU, search.h}
  370. @safety{@prelim{}@mtsafe{@mtsrace{:htab}}@assafe{}@acunsafe{@acucorrupt{/action==ENTER}}}
  371. @c Callers have to ensure mutual exclusion; insertion, if cancelled,
  372. @c leaves the table in a corrupt state.
  373. @c hsearch_r @mtsrace:htab @acucorrupt/action==ENTER
  374. @c strlen dup ok
  375. @c strcmp dup ok
  376. The @code{hsearch_r} function is equivalent to @code{hsearch}. The
  377. meaning of the first two arguments is identical. But instead of
  378. operating on a single global hashing table the function works on the
  379. table described by the object pointed to by @var{htab} (which is
  380. initialized by a call to @code{hcreate_r}).
  381. Another difference to @code{hcreate} is that the pointer to the found
  382. entry in the table is not the return value of the function. It is
  383. returned by storing it in a pointer variable pointed to by the
  384. @var{retval} parameter. The return value of the function is an integer
  385. value indicating success if it is non-zero and failure if it is zero.
  386. In the latter case the global variable @code{errno} signals the reason for
  387. the failure.
  388. @table @code
  389. @item ENOMEM
  390. The table is filled and @code{hsearch_r} was called with a so far
  391. unknown key and @var{action} set to @code{ENTER}.
  392. @item ESRCH
  393. The @var{action} parameter is @code{FIND} and no corresponding element
  394. is found in the table.
  395. @end table
  396. @end deftypefun
  397. @node Tree Search Function
  398. @section The @code{tsearch} function.
  399. Another common form to organize data for efficient search is to use
  400. trees. The @code{tsearch} function family provides a nice interface to
  401. functions to organize possibly large amounts of data by providing a mean
  402. access time proportional to the logarithm of the number of elements.
  403. @Theglibc{} implementation even guarantees that this bound is
  404. never exceeded even for input data which cause problems for simple
  405. binary tree implementations.
  406. The functions described in the chapter are all described in the @w{System
  407. V} and X/Open specifications and are therefore quite portable.
  408. In contrast to the @code{hsearch} functions the @code{tsearch} functions
  409. can be used with arbitrary data and not only zero-terminated strings.
  410. The @code{tsearch} functions have the advantage that no function to
  411. initialize data structures is necessary. A simple pointer of type
  412. @code{void *} initialized to @code{NULL} is a valid tree and can be
  413. extended or searched. The prototypes for these functions can be found
  414. in the header file @file{search.h}.
  415. @deftypefun {void *} tsearch (const void *@var{key}, void **@var{rootp}, comparison_fn_t @var{compar})
  416. @standards{SVID, search.h}
  417. @safety{@prelim{}@mtsafe{@mtsrace{:rootp}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  418. @c The tree is not modified in a thread-safe manner, and rotations may
  419. @c leave the tree in an inconsistent state that could be observed in an
  420. @c asynchronous signal handler (except for the caller-synchronization
  421. @c requirement) or after asynchronous cancellation of the thread
  422. @c performing the rotation or the insertion.
  423. The @code{tsearch} function searches in the tree pointed to by
  424. @code{*@var{rootp}} for an element matching @var{key}. The function
  425. pointed to by @var{compar} is used to determine whether two elements
  426. match. @xref{Comparison Functions}, for a specification of the functions
  427. which can be used for the @var{compar} parameter.
  428. If the tree does not contain a matching entry the @var{key} value will
  429. be added to the tree. @code{tsearch} does not make a copy of the object
  430. pointed to by @var{key} (how could it since the size is unknown).
  431. Instead it adds a reference to this object which means the object must
  432. be available as long as the tree data structure is used.
  433. The tree is represented by a pointer to a pointer since it is sometimes
  434. necessary to change the root node of the tree. So it must not be
  435. assumed that the variable pointed to by @var{rootp} has the same value
  436. after the call. This also shows that it is not safe to call the
  437. @code{tsearch} function more than once at the same time using the same
  438. tree. It is no problem to run it more than once at a time on different
  439. trees.
  440. The return value is a pointer to the matching element in the tree. If a
  441. new element was created the pointer points to the new data (which is in
  442. fact @var{key}). If an entry had to be created and the program ran out
  443. of space @code{NULL} is returned.
  444. @end deftypefun
  445. @deftypefun {void *} tfind (const void *@var{key}, void *const *@var{rootp}, comparison_fn_t @var{compar})
  446. @standards{SVID, search.h}
  447. @safety{@prelim{}@mtsafe{@mtsrace{:rootp}}@assafe{}@acsafe{}}
  448. The @code{tfind} function is similar to the @code{tsearch} function. It
  449. locates an element matching the one pointed to by @var{key} and returns
  450. a pointer to this element. But if no matching element is available no
  451. new element is entered (note that the @var{rootp} parameter points to a
  452. constant pointer). Instead the function returns @code{NULL}.
  453. @end deftypefun
  454. Another advantage of the @code{tsearch} functions in contrast to the
  455. @code{hsearch} functions is that there is an easy way to remove
  456. elements.
  457. @deftypefun {void *} tdelete (const void *@var{key}, void **@var{rootp}, comparison_fn_t @var{compar})
  458. @standards{SVID, search.h}
  459. @safety{@prelim{}@mtsafe{@mtsrace{:rootp}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  460. To remove a specific element matching @var{key} from the tree
  461. @code{tdelete} can be used. It locates the matching element using the
  462. same method as @code{tfind}. The corresponding element is then removed
  463. and a pointer to the parent of the deleted node is returned by the
  464. function. If there is no matching entry in the tree nothing can be
  465. deleted and the function returns @code{NULL}. If the root of the tree
  466. is deleted @code{tdelete} returns some unspecified value not equal to
  467. @code{NULL}.
  468. @end deftypefun
  469. @deftypefun void tdestroy (void *@var{vroot}, __free_fn_t @var{freefct})
  470. @standards{GNU, search.h}
  471. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  472. If the complete search tree has to be removed one can use
  473. @code{tdestroy}. It frees all resources allocated by the @code{tsearch}
  474. functions to generate the tree pointed to by @var{vroot}.
  475. For the data in each tree node the function @var{freefct} is called.
  476. The pointer to the data is passed as the argument to the function. If
  477. no such work is necessary @var{freefct} must point to a function doing
  478. nothing. It is called in any case.
  479. This function is a GNU extension and not covered by the @w{System V} or
  480. X/Open specifications.
  481. @end deftypefun
  482. In addition to the functions to create and destroy the tree data
  483. structure, there is another function which allows you to apply a
  484. function to all elements of the tree. The function must have this type:
  485. @smallexample
  486. void __action_fn_t (const void *nodep, VISIT value, int level);
  487. @end smallexample
  488. The @var{nodep} is the data value of the current node (once given as the
  489. @var{key} argument to @code{tsearch}). @var{level} is a numeric value
  490. which corresponds to the depth of the current node in the tree. The
  491. root node has the depth @math{0} and its children have a depth of
  492. @math{1} and so on. The @code{VISIT} type is an enumeration type.
  493. @deftp {Data Type} VISIT
  494. The @code{VISIT} value indicates the status of the current node in the
  495. tree and how the function is called. The status of a node is either
  496. `leaf' or `internal node'. For each leaf node the function is called
  497. exactly once, for each internal node it is called three times: before
  498. the first child is processed, after the first child is processed and
  499. after both children are processed. This makes it possible to handle all
  500. three methods of tree traversal (or even a combination of them).
  501. @vtable @code
  502. @item preorder
  503. The current node is an internal node and the function is called before
  504. the first child was processed.
  505. @item postorder
  506. The current node is an internal node and the function is called after
  507. the first child was processed.
  508. @item endorder
  509. The current node is an internal node and the function is called after
  510. the second child was processed.
  511. @item leaf
  512. The current node is a leaf.
  513. @end vtable
  514. @end deftp
  515. @deftypefun void twalk (const void *@var{root}, __action_fn_t @var{action})
  516. @standards{SVID, search.h}
  517. @safety{@prelim{}@mtsafe{@mtsrace{:root}}@assafe{}@acsafe{}}
  518. For each node in the tree with a node pointed to by @var{root}, the
  519. @code{twalk} function calls the function provided by the parameter
  520. @var{action}. For leaf nodes the function is called exactly once with
  521. @var{value} set to @code{leaf}. For internal nodes the function is
  522. called three times, setting the @var{value} parameter or @var{action} to
  523. the appropriate value. The @var{level} argument for the @var{action}
  524. function is computed while descending the tree by increasing the value
  525. by one for each descent to a child, starting with the value @math{0} for
  526. the root node.
  527. Since the functions used for the @var{action} parameter to @code{twalk}
  528. must not modify the tree data, it is safe to run @code{twalk} in more
  529. than one thread at the same time, working on the same tree. It is also
  530. safe to call @code{tfind} in parallel. Functions which modify the tree
  531. must not be used, otherwise the behavior is undefined.
  532. @end deftypefun