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