~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Cross Reference
BRL-CAD/include/bu.h

Version: ~ [ 7.24.0 ] ~

  1 /*                            B U . H
  2  * BRL-CAD
  3  *
  4  * Copyright (c) 2004-2013 United States Government as represented by
  5  * the U.S. Army Research Laboratory.
  6  *
  7  * This library is free software; you can redistribute it and/or
  8  * modify it under the terms of the GNU Lesser General Public License
  9  * version 2.1 as published by the Free Software Foundation.
 10  *
 11  * This library is distributed in the hope that it will be useful, but
 12  * WITHOUT ANY WARRANTY; without even the implied warranty of
 13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 14  * Lesser General Public License for more details.
 15  *
 16  * You should have received a copy of the GNU Lesser General Public
 17  * License along with this file; see the file named COPYING for more
 18  * information.
 19  */
 20 
 21 /** @defgroup container Data Containers */
 22 /**   @defgroup avs Attribute/Value Sets */
 23 /**   @defgroup bitv Bit Vectors */
 24 /**   @defgroup color Color */
 25 /**   @defgroup hash Hash Tables */
 26 /**   @defgroup list Linked Lists */
 27 /**   @defgroup parse Structure Parsing */
 28 /**   @defgroup ptbl Pointer Tables */
 29 /**   @defgroup rb Red-Black Trees */
 30 /**   @defgroup vlb Variable-length Byte Buffers */
 31 /**   @defgroup vls Variable-length Strings */
 32 /** @defgroup memory Memory Management */
 33 /**   @defgroup magic Magic Numbers */
 34 /**   @defgroup malloc Allocation & Deallocation */
 35 /**   @defgroup mf Memory-mapped Files */
 36 /** @defgroup io Input/Output */
 37 /**   @defgroup log Logging */
 38 /**   @defgroup debug Debugging */
 39 /**   @defgroup file File Processing */
 40 /**   @defgroup vfont Vector Fonts */
 41 /** @defgroup data Data Management */
 42 /**   @defgroup cmd Command History */
 43 /**   @defgroup conv Data Conversion */
 44 /**   @defgroup getopt Command-line Option Parsing*/
 45 /**   @defgroup hton Network Byte-order Conversion */
 46 /**   @defgroup hist Histogram Handling */
 47 /** @defgroup parallel  Parallel Processing */
 48 /**   @defgroup thread Multithreading */
 49 /** @defgroup binding Language Bindings */
 50 /**   @defgroup tcl Tcl Interfacing */
 51 
 52 /** @file bu.h
 53  *
 54  * Main header file for the BRL-CAD Utility Library, LIBBU.
 55  *
 56  * The two letters "BU" stand for "BRL-CAD" and "Utility".  This
 57  * library provides several layers of low-level utility routines,
 58  * providing features that make cross-platform coding easier.
 59  *
 60  * Parallel processing support:  threads, semaphores, parallel-malloc.
 61  * Consolidated logging support:  bu_log(), bu_exit(), and bu_bomb().
 62  *
 63  * The intention is that these routines are general extensions to the
 64  * data types offered by the C language itself, and to the basic C
 65  * runtime support provided by the system LIBC.  All routines in LIBBU
 66  * are designed to be "parallel-safe" (sometimes called "mp-safe" or
 67  * "thread-safe" if parallelism is via threading) to greatly ease code
 68  * development for multiprocessor systems.
 69  *
 70  * All of the data types provided by this library are defined in bu.h;
 71  * none of the routines in this library will depend on data types
 72  * defined in other BRL-CAD header files, such as vmath.h.  Look for
 73  * those routines in LIBBN.
 74  *
 75  * All truly fatal errors detected by the library use bu_bomb() to
 76  * exit with a status of 12.  The LIBBU variants of system calls
 77  * (e.g., bu_malloc()) do not return to the caller (unless there's a
 78  * bomb hook defined) unless they succeed, thus sparing the programmer
 79  * from constantly having to check for NULL return codes.
 80  *
 81  */
 82 #ifndef __BU_H__
 83 #define __BU_H__
 84 
 85 #include "common.h"
 86 
 87 #include <stdlib.h>
 88 #include <sys/types.h>
 89 
 90 __BEGIN_DECLS
 91 
 92 #ifndef BU_EXPORT
 93 #  if defined(BU_DLL_EXPORTS) && defined(BU_DLL_IMPORTS)
 94 #    error "Only BU_DLL_EXPORTS or BU_DLL_IMPORTS can be defined, not both."
 95 #  elif defined(BU_DLL_EXPORTS)
 96 #    define BU_EXPORT __declspec(dllexport)
 97 #  elif defined(BU_DLL_IMPORTS)
 98 #    define BU_EXPORT __declspec(dllimport)
 99 #  else
100 #    define BU_EXPORT
101 #  endif
102 #endif
103 
104 /* NOTE: do not rely on these values */
105 #define BRLCAD_OK 0
106 #define BRLCAD_ERROR 1
107 
108 
109 /**
110  * @def BU_DIR_SEPARATOR
111  * the default directory separator character
112  */
113 #ifdef DIR_SEPARATOR
114 #  define BU_DIR_SEPARATOR DIR_SEPARATOR
115 #else
116 #  ifdef DIR_SEPARATOR_2
117 #    define BU_DIR_SEPARATOR DIR_SEPARATOR_2
118 #  else
119 #    ifdef _WIN32
120 #      define BU_DIR_SEPARATOR '\\'
121 #    else
122 #      define BU_DIR_SEPARATOR '/'
123 #    endif  /* _WIN32 */
124 #  endif  /* DIR_SEPARATOR_2 */
125 #endif  /* DIR_SEPARATOR */
126 
127 /**
128  * Maximum length of a filesystem path.  Typically defined in a system
129  * file but if it isn't set, we create it.
130  */
131 #ifndef MAXPATHLEN
132 #  ifdef PATH_MAX
133 #    define MAXPATHLEN PATH_MAX
134 #  else
135 #    ifdef _MAX_PATH
136 #      define MAXPATHLEN _MAX_PATH
137 #    else
138 #      define MAXPATHLEN 1024
139 #    endif
140 #  endif
141 #endif
142 
143 /**
144  * set to the path list separator character
145  */
146 #if defined(PATH_SEPARATOR)
147 #  define BU_PATH_SEPARATOR PATH_SEPARATOR
148 #else
149 #  if defined(_WIN32)
150 #    define BU_PATH_SEPARATOR ';'
151 #  else
152 #    define BU_PATH_SEPARATOR ':'
153 #  endif  /* _WIN32 */
154 #endif  /* PATH_SEPARATOR */
155 
156 
157 /**
158  * @def BU_FLSTR
159  *
160  * Macro for getting a concatenated string of the current file and
161  * line number.  Produces something of the form: "filename.c"":""1234"
162  */
163 #define bu_cpp_str(s) # s
164 #define bu_cpp_xstr(s) bu_cpp_str(s)
165 #define bu_cpp_glue(a, b) a ## b
166 #define bu_cpp_xglue(a, b) bu_cpp_glue(a, b)
167 #define BU_FLSTR __FILE__ ":" bu_cpp_xstr(__LINE__)
168 
169 
170 /**
171  * shorthand declaration of a printf-style functions
172  */
173 #define _BU_ATTR_PRINTF12 __attribute__ ((__format__ (__printf__, 1, 2)))
174 #define _BU_ATTR_PRINTF23 __attribute__ ((__format__ (__printf__, 2, 3)))
175 #define _BU_ATTR_SCANF23 __attribute__ ((__format__ (__scanf__, 2, 3)))
176 
177 /**
178  * shorthand declaration of a function that doesn't return
179  */
180 #define _BU_ATTR_NORETURN __attribute__ ((__noreturn__))
181 
182 /**
183  * shorthand declaration of a function that should always be inline
184  */
185 #define _BU_ATTR_ALWAYS_INLINE __attribute__ ((always_inline))
186 
187 /**
188  *  If we're compiling strict, turn off "format string vs arguments"
189  *  checks - BRL-CAD customizes the arguments to some of these
190  *  function types (adding bu_vls support) and that is a problem with
191  *  strict checking.
192  */
193 #if defined(STRICT_FLAGS)
194 #  undef _BU_ATTR_PRINTF12
195 #  undef _BU_ATTR_PRINTF23
196 #  undef _BU_ATTR_SCANF23
197 #  undef _BU_ATTR_NORETURN
198 #  define _BU_ATTR_PRINTF12
199 #  define _BU_ATTR_PRINTF23
200 #  define _BU_ATTR_SCANF23
201 #  define _BU_ATTR_NORETURN
202 #endif
203 
204 
205 /*
206  * I N T E R F A C E H E A D E R S
207  */
208 
209 /* system interface headers */
210 #include <setjmp.h> /* for bu_setjmp */
211 #include <stddef.h> /* for size_t */
212 #include <limits.h> /* for CHAR_BIT */
213 
214 #ifdef HAVE_STDINT_H
215 #  include <stdint.h> /* for [u]int[16|32|64]_t */
216 #endif
217 
218 #ifdef HAVE_DLFCN_H
219 #  include <dlfcn.h>    /* for RTLD_* */
220 #endif
221 
222 /* common interface headers */
223 #include "tcl.h"        /* Included for Tcl_Interp definition */
224 #include "magic.h"
225 
226 /* FIXME Temporary global interp.  Remove me.  */
227 BU_EXPORT extern Tcl_Interp *brlcad_interp;
228 
229 /**
230  * This macro is used to take the 'C' function name, and convert it at
231  * compile time to the FORTRAN calling convention.
232  *
233  * Lower case, with a trailing underscore.
234  */
235 #define BU_FORTRAN(lc, uc) lc ## _
236 
237 
238 /**
239  * Fast dynamic memory allocation macro for small pointer allocations.
240  * Memory is automatically initialized to zero and, similar to
241  * bu_calloc(), is guaranteed to return non-NULL (or bu_bomb()).
242  *
243  * Memory acquired with BU_GET() should be returned with BU_PUT(), NOT
244  * with bu_free().
245  *
246  * Use BU_ALLOC() for dynamically allocating structures that are
247  * relatively large, infrequently allocated, or otherwise don't need
248  * to be fast.
249  */
250 #if 0
251 #define BU_GET(_ptr, _type) _ptr = (_type *)bu_heap_get(sizeof(_type))
252 #else
253 #define BU_GET(_ptr, _type) _ptr = (_type *)bu_calloc(1, sizeof(_type), #_type " (BU_GET) " BU_FLSTR)
254 #endif
255 
256 /**
257  * Handy dynamic memory deallocator macro.  Deallocated memory has the
258  * first byte zero'd for sanity (and potential early detection of
259  * double-free crashing code) and the pointer is set to NULL.
260  *
261  * Memory acquired with bu_malloc()/bu_calloc() should be returned
262  * with bu_free(), NOT with BU_PUT().
263  */
264 #if 0
265 #define BU_PUT(_ptr, _type) *(uint8_t *)(_type *)(_ptr) = /*zap*/ 0; bu_heap_put(_ptr, sizeof(_type)); _ptr = NULL
266 #else
267 #define BU_PUT(_ptr, _type) do { *(uint8_t *)(_type *)(_ptr) = /*zap*/ 0; bu_free(_ptr, #_type " (BU_PUT) " BU_FLSTR); _ptr = NULL; } while (0)
268 #endif
269 
270 /**
271  * Convenience macro for allocating a single structure on the heap.
272  * Not intended for performance-critical code.  Release memory
273  * acquired with bu_free() or BU_FREE() to dealloc and set NULL.
274  */
275 #define BU_ALLOC(_ptr, _type) _ptr = (_type *)bu_calloc(1, sizeof(_type), #_type " (BU_ALLOC) " BU_FLSTR)
276 
277 /**
278  * Convenience macro for deallocating a single structure allocated on
279  * the heap (with bu_malloc(), bu_calloc(), BU_ALLOC()).
280  */
281 #define BU_FREE(_ptr, _type) do { bu_free(_ptr, #_type " (BU_FREE) " BU_FLSTR); _ptr = (_type *)NULL; } while (0)
282 
283 
284 /**
285  * @def BU_ASSERT(eqn)
286  * Quick and easy macros to generate an informative error message and
287  * abort execution if the specified condition does not hold true.
288  *
289  * @def BU_ASSERT_PTR(eqn)
290  * Quick and easy macros to generate an informative error message and
291  * abort execution if the specified condition does not hold true.
292  *
293  * @def BU_ASSERT_LONG(eqn)
294  * Quick and easy macros to generate an informative error message and
295  * abort execution if the specified condition does not hold true.
296  *
297  * @def BU_ASSERT_DOUBLE(eqn)
298  * Quick and easy macros to generate an informative error message and
299  * abort execution if the specified condition does not hold true.
300  *
301  * Example: BU_ASSERT_LONG(j+7, <, 42);
302  */
303 #ifdef NO_BOMBING_MACROS
304 #  define BU_ASSERT(_equation) IGNORE((_equation))
305 #else
306 #  define BU_ASSERT(_equation)  \
307     if (UNLIKELY(!(_equation))) { \
308         bu_log("BU_ASSERT(" #_equation ") failed, file %s, line %d\n", \
309                __FILE__, __LINE__); \
310         bu_bomb("BU_ASSERT failure\n"); \
311     }
312 #endif
313 
314 #ifdef NO_BOMBING_MACROS
315 #  define BU_ASSERT_PTR(_lhs, _relation, _rhs) IGNORE((_lhs)); IGNORE((_rhs))
316 #else
317 #  define BU_ASSERT_PTR(_lhs, _relation, _rhs)  \
318     if (UNLIKELY(!((_lhs) _relation (_rhs)))) { \
319         bu_log("BU_ASSERT_PTR(" #_lhs #_relation #_rhs ") failed, lhs=%p, rhs=%p, file %s, line %d\n", \
320                (void *)(_lhs), (void *)(_rhs), \
321                __FILE__, __LINE__); \
322         bu_bomb("BU_ASSERT_PTR failure\n"); \
323     }
324 #endif
325 
326 
327 #ifdef NO_BOMBING_MACROS
328 #  define BU_ASSERT_LONG(_lhs, _relation, _rhs) IGNORE((_lhs)); IGNORE((_rhs))
329 #else
330 #  define BU_ASSERT_LONG(_lhs, _relation, _rhs) \
331     if (UNLIKELY(!((_lhs) _relation (_rhs)))) { \
332         bu_log("BU_ASSERT_LONG(" #_lhs #_relation #_rhs ") failed, lhs=%ld, rhs=%ld, file %s, line %d\n", \
333                (long)(_lhs), (long)(_rhs), \
334                __FILE__, __LINE__); \
335         bu_bomb("BU_ASSERT_LONG failure\n"); \
336     }
337 #endif
338 
339 
340 #ifdef NO_BOMBING_MACROS
341 #  define BU_ASSERT_SIZE_T(_lhs, _relation, _rhs) IGNORE((_lhs)); IGNORE((_rhs))
342 #else
343 #  define BU_ASSERT_SIZE_T(_lhs, _relation, _rhs)       \
344     if (UNLIKELY(!((_lhs) _relation (_rhs)))) { \
345         bu_log("BU_ASSERT_SIZE_T(" #_lhs #_relation #_rhs ") failed, lhs=%zd, rhs=%zd, file %s, line %d\n", \
346                (size_t)(_lhs), (size_t)(_rhs), \
347                __FILE__, __LINE__); \
348         bu_bomb("BU_ASSERT_SIZE_T failure\n"); \
349     }
350 #endif
351 
352 
353 #ifdef NO_BOMBING_MACROS
354 #  define BU_ASSERT_SSIZE_T(_lhs, _relation, _rhs) IGNORE((_lhs)); IGNORE((_rhs))
355 #else
356 #  define BU_ASSERT_SSIZE_T(_lhs, _relation, _rhs)      \
357     if (UNLIKELY(!((_lhs) _relation (_rhs)))) { \
358         bu_log("BU_ASSERT_SSIZE_T(" #_lhs #_relation #_rhs ") failed, lhs=%zd, rhs=%zd, file %s, line %d\n", \
359                (ssize_t)(_lhs), (ssize_t)(_rhs), \
360                __FILE__, __LINE__); \
361         bu_bomb("BU_ASSERT_SSIZE_T failure\n"); \
362     }
363 #endif
364 
365 
366 #ifdef NO_BOMBING_MACROS
367 #  define BU_ASSERT_DOUBLE(_lhs, _relation, _rhs) IGNORE((_lhs)); IGNORE((_rhs))
368 #else
369 #  define BU_ASSERT_DOUBLE(_lhs, _relation, _rhs)       \
370     if (UNLIKELY(!((_lhs) _relation (_rhs)))) { \
371         bu_log("BU_ASSERT_DOUBLE(" #_lhs #_relation #_rhs ") failed, lhs=%lf, rhs=%lf, file %s, line %d\n", \
372                (double)(_lhs), (double)(_rhs), \
373                __FILE__, __LINE__); \
374         bu_bomb("BU_ASSERT_DOUBLE failure\n"); \
375     }
376 #endif
377 
378 /** @file libbu/vers.c
379  *
380  * version information about LIBBU
381  *
382  */
383 
384 /**
385  * returns the compile-time version of libbu
386  */
387 BU_EXPORT extern const char *bu_version(void);
388 
389 
390 /**
391  * genptr_t - A portable way of declaring a "generic" pointer that is
392  * wide enough to point to anything, which can be used on both ANSI C
393  * and K&R C environments.  On some machines, pointers to functions
394  * can be wider than pointers to data bytes, so a declaration of
395  * "char*" isn't generic enough.
396  *
397  * DEPRECATED: use void* instead
398  */
399 #if !defined(GENPTR_NULL)
400 typedef void *genptr_t;
401 typedef const void *const_genptr_t;
402 #  define GENPTR_NULL ((genptr_t)0)
403 #endif
404 
405 
406 /**
407  * MAX_PSW - The maximum number of processors that can be expected on
408  * this hardware.  Used to allocate application-specific per-processor
409  * tables at compile-time and represent a hard limit on the number of
410  * processors/threads that may be spawned. The actual number of
411  * available processors is found at runtime by calling bu_avail_cpus()
412  */
413 #define MAX_PSW 1024
414 
415 
416 /*----------------------------------------------------------------------*/
417 /** @addtogroup hton */
418 /** @ingroup data */
419 /** @{ */
420 /**
421  * Sizes of "network" format data.  We use the same convention as the
422  * TCP/IP specification, namely, big-Endian, IEEE format, twos
423  * compliment.  This is the BRL-CAD external data representation
424  * (XDR).  See also the support routines in libbu/xdr.c
425  *
426  */
427 #define SIZEOF_NETWORK_SHORT  2 /* htons(), bu_gshort(), bu_pshort() */
428 #define SIZEOF_NETWORK_LONG   4 /* htonl(), bu_glong(), bu_plong() */
429 #define SIZEOF_NETWORK_FLOAT  4 /* htonf() */
430 #define SIZEOF_NETWORK_DOUBLE 8 /* htond() */
431 /** @} */
432 
433 
434 /*----------------------------------------------------------------------*/
435 
436 /** @addtogroup conv */
437 /** @ingroup data */
438 /** @{*/
439 /** @file libbu/convert.c
440  *
441  * Routines to translate data formats.  The data formats are:
442  *
443  * \li Host/Network             is the data in host format or local format
444  * \li  signed/unsigned         Is the data signed?
445  * \li char/short/int/long/double
446  *                              Is the data 8bits, 16bits, 32bits, 64bits
447  *                              or a double?
448  *
449  * The method of conversion is to convert up to double then back down the
450  * the expected output format.
451  *
452  */
453 
454 
455 /**
456  * convert from one format to another.
457  *
458  * @param in            input pointer
459  * @param out           output pointer
460  * @param count         number of entries to convert
461  * @param size          size of output buffer
462  * @param infmt         input format
463  * @param outfmt        output format
464  *
465  */
466 BU_EXPORT extern size_t bu_cv(genptr_t out, char *outfmt, size_t size, genptr_t in, char *infmt, int count);
467 
468 /**
469  * Set's a bit vector after parsing an input string.
470  *
471  * Set up the conversion tables/flags for vert.
472  *
473  * @param in    format description.
474  *
475  * @return a 32 bit vector.
476  *
477  * Format description:
478  * [channels][h|n][s|u] c|s|i|l|d|8|16|32|64 [N|C|L]
479  *
480  * @n channels must be null or 1
481  * @n Host | Network
482  * @n signed | unsigned
483  * @n char | short | integer | long | double | number of bits of integer
484  * @n Normalize | Clip | low-order
485  */
486 BU_EXPORT extern int bu_cv_cookie(const char *in);
487 
488 /**
489  * It is always more efficient to handle host data, rather than
490  * network.  If host and network formats are the same, and the request
491  * was for network format, modify the cookie to request host format.
492  */
493 BU_EXPORT extern int bu_cv_optimize(int cookie);
494 
495 /**
496  * Returns the number of bytes each "item" of type "cookie" occupies.
497  */
498 BU_EXPORT extern int bu_cv_itemlen(int cookie);
499 
500 /**
501  * convert with cookie
502  *
503  * @param in            input pointer
504  * @param incookie      input format cookie.
505  * @param count         number of entries to convert.
506  * @param out           output pointer.
507  * @param outcookie     output format cookie.
508  * @param size          size of output buffer in bytes;
509  *
510  *
511  * A worst case would be:       ns16 on vax to ns32
512  @code
513         ns16    -> hs16
514                 -> hd
515                 -> hs32
516                 -> ns32
517  @endcode
518  * The worst case is probably the easiest to deal with because all
519  * steps are done.  The more difficult cases are when only a subset of
520  * steps need to be done.
521  *
522  * @par Method:
523  @code
524         HOSTDBL defined as true or false
525         if ! hostother then
526                 hostother = (Endian == END_BIG) ? SAME : DIFFERENT;
527         fi
528         if (infmt == double) then
529                 if (HOSTDBL == SAME) {
530                         inIsHost = host;
531                 fi
532         else
533                 if (hostother == SAME) {
534                         inIsHost = host;
535                 fi
536         fi
537         if (outfmt == double) then
538                 if (HOSTDBL == SAME) {
539                         outIsHost == host;
540         else
541                 if (hostother == SAME) {
542                         outIsHost = host;
543                 fi
544         fi
545         if (infmt == outfmt) {
546                 if (inIsHost == outIsHost) {
547                         copy(in, out)
548                         exit
549                 else if (inIsHost == net) {
550                         ntoh?(in, out);
551                         exit
552                 else
553                         hton?(in, out);
554                         exit
555                 fi
556         fi
557 
558         while not done {
559                 from = in;
560 
561                 if (inIsHost == net) {
562                         ntoh?(from, t1);
563                         from = t1;
564                 fi
565                 if (infmt != double) {
566                         if (outIsHost == host) {
567                                 to = out;
568                         else
569                                 to = t2;
570                         fi
571                         castdbl(from, to);
572                         from = to;
573                 fi
574 
575                 if (outfmt == double) {
576                         if (outIsHost == net) {
577                                 hton?(from, out);
578                         fi
579                 else
580                         if (outIsHost == host) {
581                                 dblcast(from, out);
582                         else
583                                 dblcast(from, t3);
584                                 hton?(t3, out);
585                         fi
586                 fi
587         done
588  @endcode
589  */
590 BU_EXPORT extern size_t bu_cv_w_cookie(genptr_t out, int outcookie, size_t size, genptr_t in, int incookie, size_t count);
591 
592 /**
593  * bu_cv_ntohss
594  *
595  * @brief
596  * Network TO Host Signed Short
597  *
598  * It is assumed that this routine will only be called if there is
599  * real work to do.  Ntohs does no checking to see if it is reasonable
600  * to do any conversions.
601  *
602  * @param in    generic pointer for input.
603  * @param count number of shorts to be generated.
604  * @param out   short pointer for output
605  * @param size  number of bytes of space reserved for out.
606  *
607  * @return      number of conversions done.
608  */
609 BU_EXPORT extern size_t bu_cv_ntohss(signed short *in,
610                                      size_t count,
611                                      genptr_t out,
612                                      size_t size);
613 BU_EXPORT extern size_t bu_cv_ntohus(unsigned short *,
614                                      size_t,
615                                      genptr_t,
616                                      size_t);
617 BU_EXPORT extern size_t bu_cv_ntohsl(signed long int *,
618                                      size_t,
619                                      genptr_t,
620                                      size_t);
621 BU_EXPORT extern size_t bu_cv_ntohul(unsigned long int *,
622                                      size_t,
623                                      genptr_t,
624                                      size_t);
625 BU_EXPORT extern size_t bu_cv_htonss(genptr_t,
626                                      size_t,
627                                      signed short *,
628                                      size_t);
629 BU_EXPORT extern size_t bu_cv_htonus(genptr_t,
630                                      size_t,
631                                      unsigned short *,
632                                      size_t);
633 BU_EXPORT extern size_t bu_cv_htonsl(genptr_t,
634                                      size_t,
635                                      long *,
636                                      size_t);
637 BU_EXPORT extern size_t bu_cv_htonul(genptr_t,
638                                      size_t,
639                                      unsigned long *,
640                                      size_t);
641 
642 #define CV_CHANNEL_MASK 0x00ff
643 #define CV_HOST_MASK    0x0100
644 #define CV_SIGNED_MASK  0x0200
645 #define CV_TYPE_MASK    0x1c00  /* 0001 1100 0000 0000 */
646 #define CV_CONVERT_MASK 0x6000  /* 0110 0000 0000 0000 */
647 
648 #define CV_TYPE_SHIFT    10
649 #define CV_CONVERT_SHIFT 13
650 
651 #define CV_8  0x0400
652 #define CV_16 0x0800
653 #define CV_32 0x0c00
654 #define CV_64 0x1000
655 #define CV_D  0x1400
656 
657 #define CV_CLIP   0x0000
658 #define CV_NORMAL 0x2000
659 #define CV_LIT    0x4000
660 
661 /** deprecated */
662 #define END_NOTSET 0
663 #define END_BIG    1    /* PowerPC/MIPS */
664 #define END_LITTLE 2    /* Intel */
665 #define END_ILL    3    /* PDP-11 */
666 #define END_CRAY   4    /* Old Cray */
667 
668 /** deprecated */
669 #define IND_NOTSET 0
670 #define IND_BIG    1
671 #define IND_LITTLE 2
672 #define IND_ILL    3
673 #define IND_CRAY   4
674 
675 /*----------------------------------------------------------------------*/
676 /** @file libbu/badmagic.c
677  *
678  * Magic checking functions.
679  *
680  */
681 
682 /**
683  * B U _ C K M A G
684  *
685  * Macros to check and validate a structure pointer, given that the
686  * first entry in the structure is a magic number. ((void)(1?0:((_ptr), void(), 0)))
687  */
688 #ifdef NO_BOMBING_MACROS
689 #  define BU_CKMAG(_ptr, _magic, _str) IGNORE((_ptr))
690 #else
691 #  define BU_CKMAG(_ptr, _magic, _str) { \
692         const uintptr_t _ptrval = (const uintptr_t)(_ptr); \
693         if (UNLIKELY((_ptrval == 0) || (_ptrval & (sizeof(_ptrval)-1)) || *((const uint32_t *)(_ptr)) != (uint32_t)(_magic))) { \
694             bu_badmagic((const uint32_t *)(_ptr), (uint32_t)_magic, _str, __FILE__, __LINE__); \
695         } \
696     }
697 #endif
698 
699 
700 /**
701  * b u _ b a d m a g i c
702  *
703  *  Support routine for BU_CKMAG macro.
704  */
705 BU_EXPORT extern void bu_badmagic(const uint32_t *ptr, uint32_t magic, const char *str, const char *file, int line);
706 
707 
708 /**
709  * b u _ i d e n t i f y _ m a g i c
710  *
711  * Given a number which has been found in the magic number field of a
712  * structure (which is typically the first entry), determine what kind
713  * of structure this magic number pertains to.  This is called by the
714  * macro BU_CK_MAGIC() to provide a "hint" as to what sort of pointer
715  * error might have been made.
716  */
717 BU_EXPORT extern const char *bu_identify_magic(uint32_t magic);
718 
719 
720 /*----------------------------------------------------------------------*/
721 /** @file libbu/endian.c
722  *
723  * Run-time byte order detection.
724  *
725  */
726 
727 typedef enum {
728     BU_LITTLE_ENDIAN = 1234, /* LSB first: i386, VAX order */
729     BU_BIG_ENDIAN    = 4321, /* MSB first: 68000, IBM, network order */
730     BU_PDP_ENDIAN    = 3412  /* LSB first in word, MSW first in long */
731 } bu_endian_t;
732 
733 
734 /**
735  * returns the platform byte ordering (e.g., big-/little-endian)
736  */
737 BU_EXPORT extern bu_endian_t bu_byteorder(void);
738 
739 
740 /* provide for 64-bit network/host conversions using ntohl() */
741 #ifndef HAVE_NTOHLL
742 #  define ntohll(_val) ((bu_byteorder() == BU_LITTLE_ENDIAN) ?                          \
743                         ((((uint64_t)ntohl((_val))) << 32) + ntohl((_val) >> 32)) : \
744                         (_val)) /* sorry pdp-endian */
745 #endif
746 #ifndef HAVE_HTONLL
747 #  define htonll(_val) ntohll(_val)
748 #endif
749 
750 
751 /**@}*/
752 
753 /*----------------------------------------------------------------------*/
754 
755 /** @addtogroup list */
756 /** @ingroup container */
757 /** @{ */
758 /** @file libbu/list.c
759  *
760  * @brief Support routines for doubly-linked lists.
761  *
762  * These macros assume that all user-provided structures will have a
763  * "struct bu_list" as their first element (often named "l" [ell]).
764  * Thus, a pointer to the bu_list struct is a "pun" for the
765  * user-provided structure as well, and the pointers can be converted
766  * back and forth safely with type casts.
767  *
768  * Furthermore, the head of the linked list could be a full instance
769  * of the user-provided structure (although the storage-conscious
770  * programmer could make the head just an bu_list structure, with
771  * careful type casting).  This results in a doubly-linked circular
772  * list, with the head having the same shape as all the list members.
773  * The application is free to make use of this symmetry and store data
774  * values in the head, or the extra storage in the head can be
775  * ignored.
776  *
777  * Where a macro expects an argument "p", it should be a pointer to a
778  * user-provided structure.
779  *
780  * Where a macro expects an argument "hp", it should be a pointer to a
781  * "struct bu_list" located in the list head, e.g., &(head.l).
782  *
783  * Where a macro expects an argument "old", "new", or "cur", it should
784  * be a pointer to the "struct bu_list" located either in a
785  * user-provided structure, e.g. &((p)->l), or for the case of "old"
786  * it may also be in the list head.
787  *
788  @code
789  --- BEGIN EXAMPLE ---
790 
791  // make bu_list the first element in your structure
792  struct my_structure {
793    struct bu_list l;
794    int my_data;
795  };
796 
797  // your actual list
798  struct my_structure *my_list = NULL;
799 
800  // allocate and initialize your list head
801  BU_GET(my_list, struct my_structure);
802  BU_LIST_INIT(&(my_list->l));
803  my_list->my_data = -1;
804 
805  // add a new element to your list
806  struct my_structure *new_entry;
807  BU_GET(new_entry, struct my_structure);
808  new_entry->my_data = rand();
809  BU_LIST_PUSH(&(my_list->l), &(new_entry->l));
810 
811  // iterate over your list, remove all items
812  struct my_structure *entry;
813  while (BU_LIST_WHILE(entry, my_structure, &(my_list->l))) {
814    bu_log("Entry value is %d\n", entry->my_data);
815    BU_LIST_DEQUEUE(&(entry->l));
816    BU_PUT(entry, struct my_structure);
817  }
818  BU_PUT(my_list, struct my_structure);
819 
820  --- END EXAMPLE ---
821  @endcode
822  *
823  * Dequeueing the head of a list is a valid and well defined operation
824  * which should be performed with caution.  Unless a pointer to some
825  * other element of the list is retained by the application, the rest
826  * of the linked list can no longer be referred to.
827  *
828  * The "magic" field of the list header _must_ be set to the constant
829  * BU_LIST_HEAD_MAGIC, but the "magic" field of all list members
830  * should be established by user code, to identify the type of
831  * structure that the bu_list structure is embedded in.  It is
832  * permissible for one list to contain an arbitrarily mixed set of
833  * user "magic" numbers, as long as the head is properly marked.
834  *
835  * There is a dual set of terminology used in some of the macros:
836  *
837  * FIRST/ LAST - from the point of view of the list head
838  * NEXT / PREV - from the point of view of a list member
839  * forw / back - the actual pointer names
840  */
841 
842 struct bu_list {
843     uint32_t magic;             /**< @brief Magic # for mem id/check */
844     struct bu_list *forw;               /**< @brief "forward", "next" */
845     struct bu_list *back;               /**< @brief "back", "last" */
846 };
847 typedef struct bu_list bu_list_t;
848 #define BU_LIST_NULL ((struct bu_list *)0)
849 
850 /**
851  * macro for setting the magic number of a non-head list node
852  */
853 #define BU_LIST_MAGIC_SET(_l, _magic) {(_l)->magic = (_magic);}
854 
855 /**
856  * macro for testing whether a list node's magic number is equal to a
857  * specific magic number
858  */
859 #define BU_LIST_MAGIC_EQUAL(_l, _magic) ((_l)->magic == (_magic))
860 
861 /**
862  * there is no reliable way to assert the integrity of an arbitrary
863  * bu_list struct since the magic can be anything, therefore there is
864  * no BU_CK_LIST().  we can, however, check for a valid head node.
865  */
866 #define BU_CK_LIST_HEAD(_p) BU_CKMAG((_p), BU_LIST_HEAD_MAGIC, "bu_list")
867 
868 /**
869  * initializes a bu_list struct as a circular list without allocating
870  * any memory.  call BU_LIST_MAGIC_SET() to change the list type.
871  */
872 #define BU_LIST_INIT(_hp) { \
873         (_hp)->forw = (_hp)->back = (_hp); \
874         (_hp)->magic = BU_LIST_HEAD_MAGIC;      /* used by circ. macros */ }
875 
876 /**
877  * initializes a bu_list struct node with a particular non-head node
878  * magic number without allocating any memory.
879  */
880 #define BU_LIST_INIT_MAGIC(_hp, _magic) { \
881         BU_LIST_INIT((_hp)); \
882         BU_LIST_MAGIC_SET((_hp), (_magic)); \
883     }
884 
885 /**
886  * macro suitable for declaration statement zero-initialization of a
887  * bu_list struct, but not suitably for validation with
888  * BU_CK_LIST_HEAD() as the list pointers are NULL.  does not allocate
889  * memory.
890  */
891 #define BU_LIST_INIT_ZERO { 0, BU_LIST_NULL, BU_LIST_NULL }
892 
893 /**
894  * returns truthfully whether a bu_list has been initialized via
895  * BU_LIST_INIT().  lists initialized with BU_LIST_INIT_ZERO or
896  * zero-allocated will not return true as their forward/backward
897  * pointers reference nothing.
898  */
899 #define BU_LIST_IS_INITIALIZED(_hp) (((struct bu_list *)(_hp) != BU_LIST_NULL) && LIKELY((_hp)->forw != BU_LIST_NULL))
900 
901 
902 /**
903  * Insert "new" item in front of "old" item.  Often, "old" is the
904  * head.  To put the new item at the tail of the list, insert before
905  * the head, e.g.  * BU_LIST_INSERT(&(head.l), &((p)->l));
906  */
907 #define BU_LIST_INSERT(old, new) { \
908         BU_ASSERT((void *)(old) != (void *)NULL); \
909         BU_ASSERT((void *)(new) != (void *)NULL); \
910         (new)->back = (old)->back; \
911         (old)->back = (new); \
912         (new)->forw = (old); \
913         BU_ASSERT((void *)((new)->back) != (void *)NULL); \
914         (new)->back->forw = (new);  }
915 
916 /**
917  * Append "new" item after "old" item.  Often, "old" is the head.  To
918  * put the new item at the head of the list, append after the head,
919  * e.g.  * BU_LIST_APPEND(&(head.l), &((p)->l));
920  */
921 #define BU_LIST_APPEND(old, new) { \
922         BU_ASSERT((void *)(old) != (void *)NULL); \
923         BU_ASSERT((void *)(new) != (void *)NULL); \
924         (new)->forw = (old)->forw; \
925         (new)->back = (old); \
926         (old)->forw = (new); \
927         BU_ASSERT((void *)((old)->forw) != (void *)NULL); \
928         (new)->forw->back = (new);  }
929 
930 /**
931  * Dequeue "cur" item from anywhere in doubly-linked list
932  */
933 #define BU_LIST_DEQUEUE(cur) { \
934         BU_ASSERT((void *)(cur) != (void *)NULL); \
935         if (LIKELY((cur)->forw != NULL)) (cur)->forw->back = (cur)->back; \
936         if (LIKELY((cur)->back != NULL)) (cur)->back->forw = (cur)->forw; \
937         (cur)->forw = (cur)->back = BU_LIST_NULL;  /* sanity */ }
938 
939 /**
940  * Dequeue "cur" but do not fix its links
941  */
942 #define BU_LIST_DQ(cur) {\
943         BU_ASSERT((void *)(cur) != (void *)NULL); \
944         if (LIKELY((cur)->forw != NULL)) (cur)->forw->back = (cur)->back; \
945         if (LIKELY((cur)->back != NULL)) (cur)->back->forw = (cur)->forw; }
946 
947 #define BU_LIST_DQ_T(cur, type) (\
948         (cur)->forw->back = (cur)->back, \
949         (cur)->back->forw = (cur)->forw, \
950         (type *)(cur))
951 
952 /**
953  * This version of BU_LIST_DEQUEUE uses the comma operator inorder to
954  * return a typecast version of the dequeued pointer
955  */
956 #define BU_LIST_DEQUEUE_T(cur, type) (\
957         (cur)->forw->back = (cur)->back, \
958         (cur)->back->forw = (cur)->forw, \
959         (cur)->forw = (cur)->back = BU_LIST_NULL, \
960         (type *)(cur))
961 
962 
963 /**
964  * The Stack Discipline
965  *
966  * BU_LIST_PUSH places p at the tail of hp.  BU_LIST_POP sets p to
967  * last element in hp's list (else NULL) and, if p is non-null,
968  * dequeues it.
969  */
970 #define BU_LIST_PUSH(hp, p)                                     \
971     BU_LIST_APPEND(hp, (struct bu_list *)(p))
972 
973 #define BU_LIST_POP(structure, hp, p)                           \
974     {                                                   \
975         if (BU_LIST_NON_EMPTY(hp)) {                    \
976             (p) = ((struct structure *)((hp)->forw));   \
977             BU_LIST_DEQUEUE((struct bu_list *)(p));     \
978         } else {                                        \
979             (p) = (struct structure *) 0;               \
980         }                                               \
981     }
982 
983 #define BU_LIST_POP_T(hp, type)                                 \
984     (type *)bu_list_pop(hp)
985 
986 /**
987  * "Bulk transfer" all elements from the list headed by src_hd onto
988  * the list headed by dest_hd, without examining every element in the
989  * list.  src_hd is left with a valid but empty list.
990  *
991  * BU_LIST_INSERT_LIST places src_hd elements at head of dest_hd list,
992  * BU_LIST_APPEND_LIST places src_hd elements at end of dest_hd list.
993  */
994 #define BU_LIST_INSERT_LIST(dest_hp, src_hp) \
995     if (LIKELY(BU_LIST_NON_EMPTY(src_hp))) { \
996         struct bu_list *_first = (src_hp)->forw; \
997         struct bu_list *_last = (src_hp)->back; \
998         (dest_hp)->forw->back = _last; \
999         _last->forw = (dest_hp)->forw; \
1000         (dest_hp)->forw = _first; \
1001         _first->back = (dest_hp); \
1002         (src_hp)->forw = (src_hp)->back = (src_hp); \
1003     }
1004 
1005 #define BU_LIST_APPEND_LIST(dest_hp, src_hp) \
1006     if (LIKELY(BU_LIST_NON_EMPTY(src_hp))) {\
1007         struct bu_list *_first = (src_hp)->forw; \
1008         struct bu_list *_last = (src_hp)->back; \
1009         _first->back = (dest_hp)->back; \
1010         (dest_hp)->back->forw = _first; \
1011         (dest_hp)->back = _last; \
1012         _last->forw = (dest_hp); \
1013         (src_hp)->forw = (src_hp)->back = (src_hp); \
1014     }
1015 
1016 /**
1017  * Test if a doubly linked list is empty, given head pointer
1018  */
1019 #define BU_LIST_IS_EMPTY(hp)    ((hp)->forw == (hp))
1020 #define BU_LIST_NON_EMPTY(hp)   ((hp)->forw != (hp))
1021 #define BU_LIST_NON_EMPTY_P(p, structure, hp)   \
1022     (((p)=(struct structure *)((hp)->forw)) != (struct structure *)(hp))
1023 #define BU_LIST_IS_CLEAR(hp)    ((hp)->magic == 0 && \
1024                                  (hp)->forw == BU_LIST_NULL && \
1025                                  (hp)->back == BU_LIST_NULL)
1026 
1027 /* Return re-cast pointer to first element on list.
1028  * No checking is performed to see if list is empty.
1029  */
1030 #define BU_LIST_LAST(structure, hp)     \
1031     ((struct structure *)((hp)->back))
1032 #define BU_LIST_BACK(structure, hp)     \
1033     ((struct structure *)((hp)->back))
1034 #define BU_LIST_PREV(structure, hp)     \
1035     ((struct structure *)((hp)->back))
1036 #define BU_LIST_FIRST(structure, hp)    \
1037     ((struct structure *)((hp)->forw))
1038 #define BU_LIST_FORW(structure, hp)     \
1039     ((struct structure *)((hp)->forw))
1040 #define BU_LIST_NEXT(structure, hp)     \
1041     ((struct structure *)((hp)->forw))
1042 
1043 /**
1044  * Boolean test to see if current list element is the head
1045  */
1046 #define BU_LIST_IS_HEAD(p, hp)  \
1047     (((struct bu_list *)(p)) == (struct bu_list *)(hp))
1048 #define BU_LIST_NOT_HEAD(p, hp) \
1049     (!BU_LIST_IS_HEAD(p, hp))
1050 
1051 /**
1052  * Boolean test to see if previous list element is the head
1053  */
1054 #define BU_LIST_PREV_IS_HEAD(p, hp)\
1055     (((struct bu_list *)(p))->back == (struct bu_list *)(hp))
1056 #define BU_LIST_PREV_NOT_HEAD(p, hp)\
1057     (!BU_LIST_PREV_IS_HEAD(p, hp))
1058 
1059 /**
1060  * Boolean test to see if the next list element is the head
1061  */
1062 #define BU_LIST_NEXT_IS_HEAD(p, hp)     \
1063     (((struct bu_list *)(p))->forw == (struct bu_list *)(hp))
1064 #define BU_LIST_NEXT_NOT_HEAD(p, hp)    \
1065     (!BU_LIST_NEXT_IS_HEAD(p, hp))
1066 
1067 #define BU_LIST_EACH(hp, p, type) \
1068     for ((p)=(type *)BU_LIST_FIRST(bu_list, hp); \
1069          (p) && BU_LIST_NOT_HEAD(p, hp); \
1070          (p)=(type *)BU_LIST_PNEXT(bu_list, p)) \
1071 
1072 #define BU_LIST_REVEACH(hp, p, type) \
1073     for ((p)=(type *)BU_LIST_LAST(bu_list, hp); \
1074          (p) && BU_LIST_NOT_HEAD(p, hp); \
1075          (p)=(type *)BU_LIST_PREV(bu_list, ((struct bu_list *)(p)))) \
1076 
1077 #define BU_LIST_TAIL(hp, start, p, type) \
1078     for ((p)=(type *)start; \
1079          (p) && BU_LIST_NOT_HEAD(p, hp); \
1080          (p)=(type *)BU_LIST_PNEXT(bu_list, (p)))
1081 
1082 /**
1083  * Intended as innards for a for loop to visit all nodes on list, e.g.:
1084  *
1085  * for (BU_LIST_FOR(p, structure, hp)) {
1086  *      work_on(p);
1087  * }
1088  */
1089 #define BU_LIST_FOR(p, structure, hp)   \
1090     (p)=BU_LIST_FIRST(structure, hp); \
1091        (p) && BU_LIST_NOT_HEAD(p, hp); \
1092        (p)=BU_LIST_PNEXT(structure, p)
1093 
1094 #define BU_LIST_FOR_BACKWARDS(p, structure, hp) \
1095     (p)=BU_LIST_LAST(structure, hp); \
1096        (p) && BU_LIST_NOT_HEAD(p, hp); \
1097        (p)=BU_LIST_PLAST(structure, p)
1098 
1099 /**
1100  * Process all the list members except hp and the actual head.  Useful
1101  * when starting somewhere besides the head.
1102  */
1103 #define BU_LIST_FOR_CIRC(p, structure, hp)      \
1104     (p)=BU_LIST_PNEXT_CIRC(structure, hp); \
1105        (p) && BU_LIST_NOT_HEAD(p, hp); \
1106        (p)=BU_LIST_PNEXT_CIRC(structure, p)
1107 
1108 /**
1109  * Intended as innards for a for loop to visit elements of two lists
1110  * in tandem, e.g.:
1111  *
1112  * for (BU_LIST_FOR2(p1, p2, structure, hp1, hp2)) {
1113  *      process(p1, p2);
1114  * }
1115  */
1116 #define BU_LIST_FOR2(p1, p2, structure, hp1, hp2)                               \
1117     (p1)=BU_LIST_FIRST(structure, hp1),                 \
1118         (p2)=BU_LIST_FIRST(structure, hp2);                     \
1119                                       (p1) && BU_LIST_NOT_HEAD((struct bu_list *)(p1), (hp1)) &&        \
1120                                       (p2) && BU_LIST_NOT_HEAD((struct bu_list *)(p2), (hp2));          \
1121                                       (p1)=BU_LIST_NEXT(structure, (struct bu_list *)(p1)),     \
1122         (p2)=BU_LIST_NEXT(structure, (struct bu_list *)(p2))
1123 
1124 /**
1125  * Innards for a while loop that constantly picks off the first
1126  * element.  Useful mostly for a loop that will dequeue every list
1127  * element, e.g.:
1128  *
1129  *      while (BU_LIST_WHILE(p, structure, hp)) {
1130  *@n            BU_LIST_DEQUEUE(&(p->l));
1131  *@n            free((char *)p);
1132  *@n    }
1133  */
1134 #define BU_LIST_WHILE(p, structure, hp) \
1135     (((p)=(struct structure *)((hp)->forw)) != (struct structure *)(hp))
1136 
1137 /**
1138  * Return the magic number of the first (or last) item on a list
1139  */
1140 #define BU_LIST_FIRST_MAGIC(hp)         ((hp)->forw->magic)
1141 #define BU_LIST_LAST_MAGIC(hp)          ((hp)->back->magic)
1142 
1143 /**
1144  * Return pointer to next (or previous) element, which may be the head
1145  */
1146 #define BU_LIST_PNEXT(structure, p)     \
1147     ((struct structure *)(((struct bu_list *)(p))->forw))
1148 #define BU_LIST_PLAST(structure, p)     \
1149     ((struct structure *)(((struct bu_list *)(p))->back))
1150 
1151 /**
1152  * Return pointer two links away, which may include the head
1153  */
1154 #define BU_LIST_PNEXT_PNEXT(structure, p)       \
1155     ((struct structure *)(((struct bu_list *)(p))->forw->forw))
1156 #define BU_LIST_PNEXT_PLAST(structure, p)       \
1157     ((struct structure *)(((struct bu_list *)(p))->forw->back))
1158 #define BU_LIST_PLAST_PNEXT(structure, p)       \
1159     ((struct structure *)(((struct bu_list *)(p))->back->forw))
1160 #define BU_LIST_PLAST_PLAST(structure, p)       \
1161     ((struct structure *)(((struct bu_list *)(p))->back->back))
1162 
1163 /**
1164  * Return pointer to circular next element; i.e., ignoring the list head
1165  */
1166 #define BU_LIST_PNEXT_CIRC(structure, p)        \
1167     ((BU_LIST_FIRST_MAGIC((struct bu_list *)(p)) == BU_LIST_HEAD_MAGIC) ? \
1168      BU_LIST_PNEXT_PNEXT(structure, (struct bu_list *)(p)) : \
1169      BU_LIST_PNEXT(structure, p))
1170 
1171 /**
1172  * Return pointer to circular last element; i.e., ignoring the list head
1173  */
1174 #define BU_LIST_PPREV_CIRC(structure, p)        \
1175     ((BU_LIST_LAST_MAGIC((struct bu_list *)(p)) == BU_LIST_HEAD_MAGIC) ? \
1176      BU_LIST_PLAST_PLAST(structure, (struct bu_list *)(p)) : \
1177      BU_LIST_PLAST(structure, p))
1178 
1179 /**
1180  * Support for membership on multiple linked lists.
1181  *
1182  * When a structure of type '_type' contains more than one bu_list
1183  * structure within it (such as the NMG edgeuse), this macro can be
1184  * used to convert a pointer '_ptr2' to a "midway" bu_list structure
1185  * (an element called '_name2' in structure '_type') back into a
1186  * pointer to the overall enclosing structure.  Examples:
1187  *
1188  * eu = BU_LIST_MAIN_PTR(edgeuse, midway, l2);
1189  *
1190  * eu1 = BU_LIST_MAIN_PTR(edgeuse, BU_LIST_FIRST(bu_list, &eg1->eu_hd2), l2);
1191  *
1192  * Files using BU_LIST_MAIN_PTR will need to include stddef.h
1193  */
1194 #define BU_LIST_MAIN_PTR(_type, _ptr2, _name2)  \
1195     ((struct _type *)(((char *)(_ptr2)) - (bu_offsetof(struct _type, _name2) + bu_offsetof(struct bu_list, magic))))
1196 /** @} */
1197 
1198 
1199 /**
1200  * fastf_t - Intended to be the fastest floating point data type on
1201  * the current machine, with at least 64 bits of precision.  On 16 and
1202  * 32 bit machine, this is typically "double", but on 64 bit machines,
1203  * it is often "float".  Virtually all floating point variables (and
1204  * more complicated data types, like vect_t and mat_t) are defined as
1205  * fastf_t.  The one exception is when a subroutine return is a
1206  * floating point value; that is always declared as "double".
1207  *
1208  * TODO: If used pervasively, it should eventually be possible to make
1209  * fastf_t a GMP C++ type for fixed-precision computations.
1210  */
1211 typedef double fastf_t;
1212 
1213 /**
1214  * Definitions about limits of floating point representation
1215  * Eventually, should be tied to type of hardware (IEEE, IBM, Cray)
1216  * used to implement the fastf_t type.
1217  *
1218  * MAX_FASTF - Very close to the largest value that can be held by a
1219  * fastf_t without overflow.  Typically specified as an integer power
1220  * of ten, to make the value easy to spot when printed.  TODO: macro
1221  * function syntax instead of constant (DEPRECATED)
1222  *
1223  * SQRT_MAX_FASTF - sqrt(MAX_FASTF), or slightly smaller.  Any number
1224  * larger than this, if squared, can be expected to * produce an
1225  * overflow.  TODO: macro function syntax instead of constant
1226  * (DEPRECATED)
1227  *
1228  * SMALL_FASTF - Very close to the smallest value that can be
1229  * represented while still being greater than zero.  Any number
1230  * smaller than this (and non-negative) can be considered to be
1231  * zero; dividing by such a number can be expected to produce a
1232  * divide-by-zero error.  All divisors should be checked against
1233  * this value before actual division is performed.  TODO: macro
1234  * function syntax instead of constant (DEPRECATED)
1235  *
1236  * SQRT_SMALL_FASTF - sqrt(SMALL_FASTF), or slightly larger.  The
1237  * value of this is quite a lot larger than that of SMALL_FASTF.  Any
1238  * number smaller than this, when squared, can be expected to produce
1239  * a zero result.  TODO: macro function syntax instead of constant
1240  * (DEPRECATED)
1241  *
1242  */
1243 #if defined(vax)
1244 /* DEC VAX "D" format, the most restrictive */
1245 #  define MAX_FASTF             1.0e37  /* Very close to the largest number */
1246 #  define SQRT_MAX_FASTF        1.0e18  /* This squared just avoids overflow */
1247 #  define SMALL_FASTF           1.0e-37 /* Anything smaller is zero */
1248 #  define SQRT_SMALL_FASTF      1.0e-18 /* This squared gives zero */
1249 #else
1250 /* IBM format, being the next most restrictive format */
1251 #  define MAX_FASTF             1.0e73  /* Very close to the largest number */
1252 #  define SQRT_MAX_FASTF        1.0e36  /* This squared just avoids overflow */
1253 #  define SMALL_FASTF           1.0e-77 /* Anything smaller is zero */
1254 #  if defined(aux)
1255 #    define SQRT_SMALL_FASTF    1.0e-40 /* _doprnt error in libc */
1256 #  else
1257 #    define SQRT_SMALL_FASTF    1.0e-39 /* This squared gives zero */
1258 #  endif
1259 #endif
1260 
1261 /** DEPRECATED, do not use */
1262 #define SMALL SQRT_SMALL_FASTF
1263 
1264 
1265 /**
1266  * It is necessary to have a representation of 1.0/0.0 or log(0),
1267  * i.e., "infinity" that fits within the dynamic range of the machine
1268  * being used.  This constant places an upper bound on the size object
1269  * which can be represented in the model.  With IEEE 754 floating
1270  * point, this may print as 'inf' and is represented with all 1 bits
1271  * in the biased-exponent field and all 0 bits in the fraction with
1272  * the sign indicating positive (0) or negative (1) infinity.
1273  */
1274 #ifndef INFINITY
1275 #  if defined(HUGE_VAL)
1276 #    define INFINITY ((fastf_t)HUGE_VAL)
1277 #  elif defined(HUGE_VALF)
1278 #    define INFINITY ((fastf_t)HUGE_VALF)
1279 #  elif defined(HUGE)
1280 #    define INFINITY ((fastf_t)HUGE)
1281 #  elif defined(MAXDOUBLE)
1282 #    define INFINITY ((fastf_t)MAXDOUBLE)
1283 #  elif defined(MAXFLOAT)
1284 #    define INFINITY ((fastf_t)MAXFLOAT)
1285 #  else
1286      /* all else fails, just pick something big slightly over 32-bit
1287       * single-precision floating point that has worked well before.
1288       */
1289 #    define INFINITY ((fastf_t)1.0e40)
1290 #  endif
1291 #endif
1292 
1293 
1294 /*----------------------------------------------------------------------*/
1295 /** @addtogroup bitv */
1296 /** @ingroup container */
1297 /** @{*/
1298 /** @file libbu/bitv.c
1299  *
1300  * Routines for managing efficient high-performance bit vectors of
1301  * arbitrary length.
1302  *
1303  * The basic type "bitv_t" is defined in include/bu.h; it is the
1304  * widest integer datatype for which efficient hardware support
1305  * exists.  BU_BITV_SHIFT and BU_BITV_MASK are also defined in bu.h
1306  *
1307  * These bit vectors are "little endian", bit 0 is in the right hand
1308  * side of the [0] word.
1309  *
1310  */
1311 
1312 /**
1313  * bitv_t should be a fast integer type for implementing bit vectors.
1314  *
1315  * On many machines, this is a 32-bit "long", but on some machines a
1316  * compiler/vendor-specific type such as "long long" or even 'char'
1317  * can give access to faster integers.
1318  *
1319  * THE SIZE OF bitv_t MUST MATCH BU_BITV_SHIFT.
1320  */
1321 typedef unsigned char bitv_t;
1322 
1323 /**
1324  * Bit vector shift size
1325  *
1326  * Should equal to: log2(sizeof(bitv_t)*8.0).  Using bu_bitv_shift()
1327  * will return a run-time computed shift size if the size of a bitv_t
1328  * changes.  Performance impact is rather minimal for most models but
1329  * disabled for a handful of primitives that heavily rely on bit
1330  * vectors.
1331  *
1332  * (8-bit type: 3, 16-bit type: 4, 32-bit type: 5, 64-bit type: 6)
1333  */
1334 #ifdef CHAR_BIT
1335 #  if CHAR_BIT == 8
1336 #    define BU_BITV_SHIFT 3
1337 #  elif CHAR_BIT == 16
1338 #    define BU_BITV_SHIFT 4
1339 #  elif CHAR_BIT == 32
1340 #    define BU_BITV_SHIFT 5
1341 #  elif CHAR_BIT == 64
1342 #    define BU_BITV_SHIFT 6
1343 #  endif
1344 #else
1345 #  define BU_BITV_SHIFT bu_bitv_shift()
1346 #endif
1347 
1348 /** Bit vector mask */
1349 #define BU_BITV_MASK ((1<<BU_BITV_SHIFT)-1)
1350 
1351 /**
1352  * Bit vector data structure.
1353  *
1354  * bu_bitv uses a little-endian encoding, placing bit 0 on the right
1355  * side of the 0th word.
1356  *
1357  * This is done only because left-shifting a 1 can be done in an
1358  * efficient word-length-independent manner; going the other way would
1359  * require a compile-time constant with only the sign bit set, and an
1360  * unsigned right shift, which some machines don't have in hardware,
1361  * or an extra subtraction.
1362  *
1363  * Application code should *never* peek at the bit-buffer; use the
1364  * macros.  The external hex form is most significant byte first (bit
1365  * 0 is at the right).  Note that MUVES does it differently.
1366  */
1367 struct bu_bitv {
1368     struct bu_list l;           /**< linked list for caller's use */
1369     size_t nbits;               /**< actual size of bits[], in bits */
1370     bitv_t bits[2];     /**< variable size array */
1371 };
1372 typedef struct bu_bitv bu_bitv_t;
1373 #define BU_BITV_NULL ((struct bu_bitv *)0)
1374 
1375 /**
1376  * asserts the integrity of a non-head node bu_bitv struct.
1377  */
1378 #define BU_CK_BITV(_bp) BU_CKMAG(_bp, BU_BITV_MAGIC, "bu_bitv")
1379 
1380 /**
1381  * initializes a bu_bitv struct without allocating any memory.  this
1382  * macro is not suitable for initializing a head list node.
1383  */
1384 #define BU_BITV_INIT(_bp) { \
1385         BU_LIST_INIT_MAGIC(&(_bp)->l, BU_BITV_MAGIC); \
1386         (_bp)->nbits = 0; \
1387         (_bp)->bits[0] = 0; \
1388         (_bp)->bits[1] = 0; \
1389     }
1390 
1391 /**
1392  * macro suitable for declaration statement initialization of a bu_bitv
1393  * struct.  does not allocate memory.  not suitable for a head node.
1394  */
1395 #define BU_BITV_INIT_ZERO { {BU_BITV_MAGIC, BU_LIST_NULL, BU_LIST_NULL}, 0, {0, 0} }
1396 
1397 /**
1398  * returns truthfully whether a bu_bitv has been initialized
1399  */
1400 #define BU_BITV_IS_INITIALIZED(_bp) (((struct bu_bitv *)(_bp) != BU_BITV_NULL) && LIKELY((_bp)->l.magic == BU_BITV_MAGIC))
1401 
1402 /**
1403  * returns floor(log2(sizeof(bitv_t)*8.0)), i.e. the number of bits
1404  * required with base-2 encoding to index any bit in an array of
1405  * length sizeof(bitv_t)*8.0 bits long.  users should not call this
1406  * directly, instead calling the BU_BITV_SHIFT macro instead.
1407  */
1408 BU_EXPORT extern size_t bu_bitv_shift();
1409 
1410 /*
1411  * Bit-string manipulators for arbitrarily long bit strings stored as
1412  * an array of bitv_t's.
1413  */
1414 #define BU_BITS2BYTES(_nb)      (BU_BITS2WORDS(_nb)*sizeof(bitv_t))
1415 #define BU_BITS2WORDS(_nb)      (((_nb)+BU_BITV_MASK)>>BU_BITV_SHIFT)
1416 #define BU_WORDS2BITS(_nw)      ((_nw)*sizeof(bitv_t)*8)
1417 
1418 
1419 #if 1
1420 #define BU_BITTEST(_bv, bit)    \
1421     (((_bv)->bits[(bit)>>BU_BITV_SHIFT] & (((bitv_t)1)<<((bit)&BU_BITV_MASK)))!=0)
1422 #else
1423 static __inline__ int BU_BITTEST(volatile void * addr, int nr)
1424 {
1425     int oldbit;
1426 
1427     __asm__ __volatile__(
1428         "btl %2, %1\n\tsbbl %0, %0"
1429         :"=r" (oldbit)
1430         :"m" (addr), "Ir" (nr));
1431     return oldbit;
1432 }
1433 #endif
1434 
1435 #define BU_BITSET(_bv, bit)     \
1436     ((_bv)->bits[(bit)>>BU_BITV_SHIFT] |= (((bitv_t)1)<<((bit)&BU_BITV_MASK)))
1437 #define BU_BITCLR(_bv, bit)     \
1438     ((_bv)->bits[(bit)>>BU_BITV_SHIFT] &= ~(((bitv_t)1)<<((bit)&BU_BITV_MASK)))
1439 
1440 /**
1441  * zeros all of the internal storage bytes in a bit vector array
1442  */
1443 #define BU_BITV_ZEROALL(_bv)    \
1444     { \
1445         if (LIKELY((_bv) && (_bv)->nbits != 0)) { \
1446             unsigned char *bvp = (unsigned char *)(_bv)->bits; \
1447             size_t nbytes = BU_BITS2BYTES((_bv)->nbits); \
1448             do { \
1449                 *bvp++ = (unsigned char)0; \
1450             } while (--nbytes != 0); \
1451         } \
1452     }
1453 
1454 
1455 /* This is not done by default for performance reasons */
1456 #ifdef NO_BOMBING_MACROS
1457 #  define BU_BITV_BITNUM_CHECK(_bv, _bit) IGNORE((_bv))
1458 #else
1459 #  define BU_BITV_BITNUM_CHECK(_bv, _bit)       /* Validate bit number */ \
1460     if (UNLIKELY(((unsigned)(_bit)) >= (_bv)->nbits)) {\
1461         bu_log("BU_BITV_BITNUM_CHECK bit number (%u) out of range (0..%u)\n", \
1462                ((unsigned)(_bit)), (_bv)->nbits); \
1463         bu_bomb("process self-terminating\n");\
1464     }
1465 #endif
1466 
1467 #ifdef NO_BOMBING_MACROS
1468 #  define BU_BITV_NBITS_CHECK(_bv, _nbits) IGNORE((_bv))
1469 #else
1470 #  define BU_BITV_NBITS_CHECK(_bv, _nbits)      /* Validate number of bits */ \
1471     if (UNLIKELY(((unsigned)(_nbits)) > (_bv)->nbits)) {\
1472         bu_log("BU_BITV_NBITS_CHECK number of bits (%u) out of range (> %u)", \
1473                ((unsigned)(_nbits)), (_bv)->nbits); \
1474         bu_bomb("process self-terminating"); \
1475     }
1476 #endif
1477 
1478 
1479 /**
1480  * Macros to efficiently find all the ONE bits in a bit vector.
1481  * Counts words down, counts bits in words going up, for speed &
1482  * portability.  It does not matter if the shift causes the sign bit
1483  * to smear to the right.
1484  *
1485  * @par Example:
1486  @code
1487 
1488  BU_BITV_LOOP_START(bv) {
1489    fiddle(BU_BITV_LOOP_INDEX);
1490  } BU_BITV_LOOP_END;
1491 
1492  @endcode
1493  *
1494  */
1495 #define BU_BITV_LOOP_START(_bv) \
1496     { \
1497         int _wd;        /* Current word number */  \
1498         BU_CK_BITV(_bv); \
1499         for (_wd=BU_BITS2WORDS((_bv)->nbits)-1; _wd>=0; _wd--) {  \
1500             int _b;     /* Current bit-in-word number */  \
1501             bitv_t _val;        /* Current word value */  \
1502             if ((_val = (_bv)->bits[_wd])==0) continue;  \
1503             for (_b=0; _b < BU_BITV_MASK+1; _b++, _val >>= 1) { \
1504                 if (!(_val & 1)) continue;
1505 
1506 /**
1507  * This macro is valid only between a BU_BITV_LOOP_START/LOOP_END
1508  * pair, and gives the bit number of the current iteration.
1509  */
1510 #define BU_BITV_LOOP_INDEX ((_wd << BU_BITV_SHIFT) | _b)
1511 
1512 /**
1513  * Paired with BU_BITV_LOOP_START()
1514  */
1515 #define BU_BITV_LOOP_END        \
1516     } /* end for (_b) */ \
1517             } /* end for (_wd) */ \
1518         } /* end block */
1519 /** @} */
1520 
1521 /*----------------------------------------------------------------------*/
1522 /** @addtogroup hist */
1523 /** @ingroup data */
1524 /** @{ */
1525 /** @file libbu/hist.c
1526  *
1527  * General purpose histogram handling routines.
1528  *
1529  * The subroutine bu_hist_range() is used to record items that may
1530  * extend across multiple "bin"s.
1531  *
1532  */
1533 
1534 /**
1535  * histogram support
1536  */
1537 struct bu_hist  {
1538     uint32_t magic;             /**< magic # for id/check */
1539     fastf_t hg_min;             /**< minimum value */
1540     fastf_t hg_max;             /**< maximum value */
1541     fastf_t hg_clumpsize;       /**< (max-min+1)/nbins+1 */
1542     long hg_nsamples;           /**< total number of samples spread into histogram */
1543     long hg_nbins;              /**< # of bins in hg_bins[]  */
1544     long *hg_bins;              /**< array of counters */
1545 };
1546 typedef struct bu_hist bu_hist_t;
1547 #define BU_HIST_NULL ((struct bu_hist *)0)
1548 
1549 /**
1550  * assert the integrity of a bu_hist struct.
1551  */
1552 #define BU_CK_HIST(_p) BU_CKMAG(_p, BU_HIST_MAGIC, "struct bu_hist")
1553 
1554 /**
1555  * initialize a bu_hist struct without allocating any memory.
1556  */
1557 #define BU_HIST_INIT(_hp) { \
1558         (_hp)->magic = BU_HIST_MAGIC; \
1559         (_hp)->hg_min = (_hp)->hg_max = (_hp)->hg_clumpsize = 0.0; \
1560         (_hp)->hg_nsamples = (_hp)->hg_nbins = 0; \
1561         (_hp)->hg_bins = NULL; \
1562     }
1563 
1564 /**
1565  * macro suitable for declaration statement initialization of a
1566  * bu_hist struct.  does not allocate memory.
1567  */
1568 #define BU_HIST_INIT_ZERO {BU_HIST_MAGIC, 0.0, 0.0, 0.0, 0, 0, NULL}
1569 
1570 /**
1571  * returns truthfully whether a bu_hist has been initialized via
1572  * BU_HIST_INIT() or BU_HIST_INIT_ZERO.
1573  */
1574 #define BU_HIST_IS_INITIALIZED(_hp) (((struct bu_hist *)(_hp) != BU_HIST_NULL) && LIKELY((_hp)->magic == BU_HIST_MAGIC))
1575 
1576 #define BU_HIST_TALLY(_hp, _val) { \
1577         if ((_val) <= (_hp)->hg_min) { \
1578             (_hp)->hg_bins[0]++; \
1579         } else if ((_val) >= (_hp)->hg_max) { \
1580             (_hp)->hg_bins[(_hp)->hg_nbins]++; \
1581         } else { \
1582             (_hp)->hg_bins[(int)(((_val)-(_hp)->hg_min)/(_hp)->hg_clumpsize)]++; \
1583         } \
1584         (_hp)->hg_nsamples++;  }
1585 
1586 #define BU_HIST_TALLY_MULTIPLE(_hp, _val, _count) { \
1587         int __count = (_count); \
1588         if ((_val) <= (_hp)->hg_min) { \
1589             (_hp)->hg_bins[0] += __count; \
1590         } else if ((_val) >= (_hp)->hg_max) { \
1591             (_hp)->hg_bins[(_hp)->hg_nbins] += __count; \
1592         } else { \
1593             (_hp)->hg_bins[(int)(((_val)-(_hp)->hg_min)/(_hp)->hg_clumpsize)] += __count; \
1594         } \
1595         (_hp)->hg_nsamples += __count;  }
1596 
1597 /** @} */
1598 /*----------------------------------------------------------------------*/
1599 /* ptbl.c */
1600 /** @addtogroup ptbl */
1601 /** @ingroup container */
1602 /** @{ */
1603 /** @file libbu/ptbl.c
1604  *
1605  * Support for generalized "pointer tables"
1606  *
1607  * Support for generalized "pointer tables", kept compactly in a
1608  * dynamic array.
1609  *
1610  * The table is currently un-ordered, and is merely an array of
1611  * pointers.  The support routine nmg_tbl manipulates the array for
1612  * you.  Pointers to be operated on (inserted, deleted, searched for)
1613  * are passed as a "pointer to long".
1614  *
1615  */
1616 
1617 
1618 /**
1619  * Support for generalized "pointer tables".
1620  */
1621 struct bu_ptbl {
1622     struct bu_list l; /**< linked list for caller's use */
1623     off_t end; /**< index into buffer of first available location */
1624     size_t blen; /**< # of (long *)'s worth of storage at *buffer */
1625     long **buffer; /**< data storage area */
1626 };
1627 typedef struct bu_ptbl bu_ptbl_t;
1628 #define BU_PTBL_NULL ((struct bu_ptbl *)0)
1629 
1630 /**
1631  * assert the integrity of a non-head node bu_ptbl struct.
1632  */
1633 #define BU_CK_PTBL(_p) BU_CKMAG(_p, BU_PTBL_MAGIC, "bu_ptbl")
1634 
1635 /**
1636  * initialize a bu_ptbl struct without allocating any memory.  this
1637  * macro is not suitable for initializing a list head node.
1638  */
1639 #define BU_PTBL_INIT(_p) { \
1640         BU_LIST_INIT_MAGIC(&(_p)->l, BU_PTBL_MAGIC); \
1641         (_p)->end = 0; \
1642         (_p)->blen = 0; \
1643         (_p)->buffer = NULL; \
1644     }
1645 
1646 /**
1647  * macro suitable for declaration statement initialization of a
1648  * bu_ptbl struct.  does not allocate memory.  not suitable for
1649  * initializing a list head node.
1650  */
1651 #define BU_PTBL_INIT_ZERO { {BU_PTBL_MAGIC, BU_LIST_NULL, BU_LIST_NULL}, 0, 0, NULL }
1652 
1653 /**
1654  * returns truthfully whether a bu_ptbl has been initialized via
1655  * BU_PTBL_INIT() or BU_PTBL_INIT_ZERO.
1656  */
1657 #define BU_PTBL_IS_INITIALIZED(_p) (((struct bu_ptbl *)(_p) != BU_PTBL_NULL) && LIKELY((_p)->l.magic == BU_PTBL_MAGIC))
1658 
1659 
1660 /*
1661  * For those routines that have to "peek" into the ptbl a little bit.
1662  */
1663 #define BU_PTBL_BASEADDR(ptbl)  ((ptbl)->buffer)
1664 #define BU_PTBL_LASTADDR(ptbl)  ((ptbl)->buffer + (ptbl)->end - 1)
1665 #define BU_PTBL_END(ptbl)       ((ptbl)->end)
1666 #define BU_PTBL_LEN(ptbl)       ((size_t)(ptbl)->end)
1667 #define BU_PTBL_GET(ptbl, i)    ((ptbl)->buffer[(i)])
1668 #define BU_PTBL_SET(ptbl, i, val)       ((ptbl)->buffer[(i)] = (long*)(val))
1669 #define BU_PTBL_TEST(ptbl)      ((ptbl)->l.magic == BU_PTBL_MAGIC)
1670 #define BU_PTBL_CLEAR_I(_ptbl, _i) ((_ptbl)->buffer[(_i)] = (long *)0)
1671 
1672 /**
1673  * A handy way to visit all the elements of the table is:
1674  *
1675  * struct edgeuse **eup;
1676  * for (eup = (struct edgeuse **)BU_PTBL_LASTADDR(&eutab); eup >= (struct edgeuse **)BU_PTBL_BASEADDR(&eutab); eup--) {
1677  *     NMG_CK_EDGEUSE(*eup);
1678  * }
1679  * --- OR ---
1680  * for (BU_PTBL_FOR(eup, (struct edgeuse **), &eutab)) {
1681  *     NMG_CK_EDGEUSE(*eup);
1682  * }
1683  */
1684 #define BU_PTBL_FOR(ip, cast, ptbl)     \
1685     ip = cast BU_PTBL_LASTADDR(ptbl); ip >= cast BU_PTBL_BASEADDR(ptbl); ip--
1686 
1687 
1688 /* vlist, vlblock?  But they use vmath.h .. hrm. */
1689 /** @} */
1690 
1691 /*----------------------------------------------------------------------*/
1692 /** @addtogroup mf */
1693 /** @ingroup memory */
1694 /** @{ */
1695 /** @file libbu/mappedfile.c
1696  *
1697  * Routines for sharing large read-only data files.
1698  *
1699  * Routines for sharing large read-only data files like height fields,
1700  * bit map solids, texture maps, etc.  Uses memory mapped files where
1701  * available.
1702  *
1703  * Each instance of the file has the raw data available as element
1704  * "buf".  If a particular application needs to transform the raw data
1705  * in a manner that is identical across all uses of that application
1706  * (e.g. height fields, EBMs, etc.), then the application should
1707  * provide a non-null "appl" string, to tag the format of the "apbuf".
1708  * This will keep different applications from sharing that instance of
1709  * the file.
1710  *
1711  * Thus, if the same filename is opened for interpretation as both an
1712  * EBM and a height field, they will be assigned different mapped file
1713  * structures, so that the "apbuf" pointers are distinct.
1714  *
1715  */
1716 
1717 /**
1718  * @struct bu_mapped_file bu.h
1719  *
1720  * Structure for opening a mapped file.
1721  *
1722  * Each file is opened and mapped only once (per application, as
1723  * tagged by the string in "appl" field).  Subsequent opens require an
1724  * exact match on both strings.
1725  *
1726  * Before allocating apbuf and performing data conversion into it,
1727  * openers should check to see if the file has already been opened and
1728  * converted previously.
1729  *
1730  * When used in RT, the mapped files are not closed at the end of a
1731  * frame, so that subsequent frames may take advantage of the large
1732  * data files having already been read and converted.  Examples
1733  * include EBMs, texture maps, and height fields.
1734  *
1735  * For appl == "db_i", file is a ".g" database & apbuf is (struct db_i *).
1736  */
1737 struct bu_mapped_file {
1738     struct bu_list l;
1739     char *name;         /**< bu_strdup() of file name */
1740     genptr_t buf;       /**< In-memory copy of file (may be mmapped)  */
1741     size_t buflen;      /**< # bytes in 'buf'  */
1742     int is_mapped;      /**< 1=mmap() used, 0=bu_malloc/fread */
1743     char *appl;         /**< bu_strdup() of tag for application using 'apbuf'  */
1744     genptr_t apbuf;     /**< opt: application-specific buffer */
1745     size_t apbuflen;    /**< opt: application-specific buflen */
1746     time_t modtime;     /**< date stamp, in case file is modified */
1747     int uses;           /**< # ptrs to this struct handed out */
1748     int dont_restat;    /**< 1=on subsequent opens, don't re-stat()  */
1749 };
1750 typedef struct bu_mapped_file bu_mapped_file_t;
1751 #define BU_MAPPED_FILE_NULL ((struct bu_mapped_file *)0)
1752 
1753 /**
1754  * assert the integrity of a bu_mapped_file struct.
1755  */
1756 #define BU_CK_MAPPED_FILE(_mf) BU_CKMAG(_mf, BU_MAPPED_FILE_MAGIC, "bu_mapped_file")
1757 
1758 /**
1759  * initialize a bu_mapped_file struct without allocating any memory.
1760  */
1761 #define BU_MAPPED_FILE_INIT(_mf) { \
1762         BU_LIST_INIT_MAGIC(&(_mf)->l, BU_MAPPED_FILE_MAGIC); \
1763         (_mf)->name = (_mf)->buf = NULL; \
1764         (_mf)->buflen = (_mf)->is_mapped = 0; \
1765         (_mf)->appl = (_mf)->apbuf = NULL; \
1766         (_mf)->apbuflen = (_mf)->modtime = (_mf)->uses = (_mf)->dont_restat = 0; \
1767     }
1768 
1769 /**
1770  * macro suitable for declaration statement initialization of a
1771  * bu_mapped_file struct.  does not allocate memory.
1772  */
1773 #define BU_MAPPED_FILE_INIT_ZERO { {BU_MAPPED_FILE_MAGIC, BU_LIST_NULL, BU_LIST_NULL}, NULL, NULL, 0, 0, NULL, NULL, 0, 0, 0, 0 }
1774 
1775 /**
1776  * returns truthfully whether a bu_mapped_file has been initialized via
1777  * BU_MAPPED_FILE_INIT() or BU_MAPPED_FILE_INIT_ZERO.
1778  */
1779 #define BU_MAPPED_FILE_IS_INITIALIZED(_hp) (((struct bu_mapped_file *)(_hp) != BU_MAPPED_FILE_NULL) && LIKELY((_hp)->l.magic == BU_MAPPED_FILE_MAGIC))
1780 
1781 
1782 /** @} */
1783 /*----------------------------------------------------------------------*/
1784 
1785 /* formerly rt_g.rtg_logindent, now use bu_log_indent_delta() */
1786 typedef int (*bu_hook_t)(genptr_t, genptr_t);
1787 
1788 struct bu_hook_list {
1789     struct bu_list l; /**< linked list */
1790     bu_hook_t hookfunc; /**< function to call */
1791     genptr_t clientdata; /**< data for caller */
1792 };
1793 typedef struct bu_hook_list bu_hook_list_t;
1794 #define BU_HOOK_LIST_NULL ((struct bu_hook_list *) 0)
1795 
1796 /**
1797  * assert the integrity of a non-head node bu_hook_list struct.
1798  */
1799 #define BU_CK_HOOK_LIST(_hl) BU_CKMAG(_hl, BU_HOOK_LIST_MAGIC, "bu_hook_list")
1800 
1801 /**
1802  * initialize a bu_hook_list struct without allocating any memory.
1803  * this macro is not suitable for initialization of a list head node.
1804  */
1805 #define BU_HOOK_LIST_INIT(_hl) { \
1806         BU_LIST_INIT_MAGIC(&(_hl)->l, BU_HOOK_LIST_MAGIC); \
1807         (_hl)->hookfunc = (_hl)->clientdata = NULL; \
1808     }
1809 
1810 /**
1811  * macro suitable for declaration statement initialization of a
1812  * bu_hook_list struct.  does not allocate memory.  not suitable for
1813  * initialization of a list head node.
1814  */
1815 #define BU_HOOK_LIST_INIT_ZERO { {BU_HOOK_LIST_MAGIC, BU_LIST_NULL, BU_LIST_NULL}, NULL, NULL }
1816 
1817 /**
1818  * returns truthfully whether a non-head node bu_hook_list has been
1819  * initialized via BU_HOOK_LIST_INIT() or BU_HOOK_LIST_INIT_ZERO.
1820  */
1821 #define BU_HOOK_LIST_IS_INITIALIZED(_p) (((struct bu_hook_list *)(_p) != BU_HOOK_LIST_NULL) && LIKELY((_p)->l.magic == BU_HOOK_LIST_MAGIC))
1822 
1823 
1824 /*----------------------------------------------------------------------*/
1825 /** @addtogroup avs */
1826 /** @ingroup container */
1827 /** @{ */
1828 /** @file libbu/avs.c
1829  *
1830  * Routines to manage attribute/value sets.
1831  */
1832 
1833 /**
1834  * These strings may or may not be individually allocated, it depends
1835  * on usage.
1836  */
1837 struct bu_attribute_value_pair {
1838     const char *name;   /**< attribute name */
1839     const char *value; /**< attribute value */
1840 };
1841 
1842 
1843 /**
1844  * A variable-sized attribute-value-pair array.
1845  *
1846  * avp points to an array of [max] slots.  The interface routines will
1847  * realloc to extend as needed.
1848  *
1849  * In general, each of the names and values is a local copy made with
1850  * bu_strdup(), and each string needs to be freed individually.
1851  * However, if a name or value pointer is between readonly_min and
1852  * readonly_max, then it is part of a big malloc block that is being
1853  * freed by the caller, and should not be individually freed.
1854  */
1855 struct bu_attribute_value_set {
1856     uint32_t magic;
1857     unsigned int count; /**< # valid entries in avp */
1858     unsigned int max;   /**< # allocated slots in avp */
1859     genptr_t readonly_min;
1860     genptr_t readonly_max;
1861     struct bu_attribute_value_pair *avp;        /**< array[max]  */
1862 };
1863 typedef struct bu_attribute_value_set bu_avs_t;
1864 #define BU_AVS_NULL ((struct bu_attribute_value_set *)0)
1865 
1866 /**
1867  * assert the integrity of a non-head node bu_attribute_value_set struct.
1868  */
1869 #define BU_CK_AVS(_ap) BU_CKMAG(_ap, BU_AVS_MAGIC, "bu_attribute_value_set")
1870 
1871 /**
1872  * initialize a bu_attribute_value_set struct without allocating any memory.
1873  */
1874 #define BU_AVS_INIT(_ap) { \
1875         (_ap)->magic = BU_AVS_MAGIC; \
1876         (_ap)->count = (_ap)->max = 0; \
1877         (_ap)->readonly_min = (_ap)->readonly_max = (_ap)->avp = NULL; \
1878     }
1879 
1880 /**
1881  * macro suitable for declaration statement initialization of a
1882  * bu_attribute_value_set struct.  does not allocate memory.
1883  */
1884 #define BU_AVS_INIT_ZERO { BU_AVS_MAGIC, 0, 0, NULL, NULL, NULL }
1885 
1886 /**
1887  * returns truthfully whether a bu_attribute_value_set has been initialized via
1888  * BU_AVS_INIT() or BU_AVS_INIT_ZERO.
1889  */
1890 #define BU_AVS_IS_INITIALIZED(_ap) (((struct bu_attribute_value_set *)(_ap) != BU_AVS_NULL) && LIKELY((_ap)->magic == BU_AVS_MAGIC))
1891 
1892 
1893 /**
1894  * For loop iterator for avs structures.
1895  *
1896  * Provide an attribute value pair struct pointer and an attribute
1897  * value set, and this will iterate over all entries.  iteration order
1898  * is not defined but should iterate over each AVS entry once.
1899  *
1900  * Example Use:
1901  @code
1902  void
1903  print_avs(struct bu_attribute_value_set *avs) {
1904    struct bu_attribute_value_pair *avpp;
1905 
1906    for (BU_AVS_FOR(avpp, avs)) {
1907      bu_log("key=%s, value=%s\n", avpp->name, avpp->value);
1908    }
1909  }
1910  @endcode
1911  *
1912  */
1913 #define BU_AVS_FOR(_pp, _avp) \
1914     (_pp) = ((const void *)(_avp) != (const void *)NULL) ? ((_avp)->count > 0 ? &(_avp)->avp[(_avp)->count-1] : NULL) : NULL; ((const void *)(_pp) != (const void *)NULL) && ((const void *)(_avp) != (const void *)NULL) && (_avp)->avp && (_pp) >= (_avp)->avp; (_pp)--
1915 
1916 /**
1917  * Some (but not all) attribute name and value string pointers are
1918  * taken from an on-disk format bu_external block, while others have
1919  * been bu_strdup()ed and need to be freed.  This macro indicates
1920  * whether the pointer needs to be freed or not.
1921  */
1922 #define AVS_IS_FREEABLE(_avsp, _p)      \
1923     ((_avsp)->readonly_max == NULL \
1924      || (const_genptr_t)(_p) < (_avsp)->readonly_min \
1925      || (const_genptr_t)(_p) > (_avsp)->readonly_max)
1926 
1927 /** @} */
1928 
1929 /*----------------------------------------------------------------------*/
1930 /** @addtogroup vls */
1931 /** @ingroup container */
1932 /** @{ */
1933 /** @file libbu/vls.c
1934  *
1935  @brief
1936  * Variable Length Strings
1937  *
1938  * This structure provides support for variable length strings,
1939  * freeing the programmer from concerns about having character arrays
1940  * large enough to hold strings.
1941  *
1942  * Assumption:  libc-provided sprintf() function is safe to use in parallel,
1943  * on parallel systems.
1944  */
1945 
1946 /**
1947  *
1948  */
1949 struct bu_vls  {
1950     uint32_t vls_magic;
1951     char *vls_str;      /**< Dynamic memory for buffer */
1952     size_t vls_offset;  /**< Offset into vls_str where data is good */
1953     size_t vls_len;     /**< Length, not counting the null */
1954     size_t vls_max;
1955 };
1956 typedef struct bu_vls bu_vls_t;
1957 #define BU_VLS_NULL ((struct bu_vls *)0)
1958 
1959 /**
1960  * assert the integrity of a bu_vls struct.
1961  */
1962 #define BU_CK_VLS(_vp) BU_CKMAG(_vp, BU_VLS_MAGIC, "bu_vls")
1963 
1964 /**
1965  * initializes a bu_vls struct without allocating any memory.
1966  */
1967 #define BU_VLS_INIT(_vp) { \
1968         (_vp)->vls_magic = BU_VLS_MAGIC; \
1969         (_vp)->vls_str = NULL; \
1970         (_vp)->vls_offset = (_vp)->vls_len = (_vp)->vls_max = 0; \
1971     }
1972 
1973 /**
1974  * macro suitable for declaration statement initialization of a bu_vls
1975  * struct.  does not allocate memory.
1976  */
1977 #define BU_VLS_INIT_ZERO { BU_VLS_MAGIC, NULL, 0, 0, 0 }
1978 
1979 /**
1980  * returns truthfully whether a bu_vls struct has been initialized.
1981  * is not reliable unless the struct has been allocated with
1982  * BU_ALLOC(), bu_calloc(), or a previous call to bu_vls_init() or
1983  * BU_VLS_INIT() has been made.
1984  */
1985 #define BU_VLS_IS_INITIALIZED(_vp) (((struct bu_vls *)(_vp) != BU_VLS_NULL) && ((_vp)->vls_magic == BU_VLS_MAGIC))
1986 
1987 
1988 /** @} */
1989 
1990 /*----------------------------------------------------------------------*/
1991 /** @addtogroup vlb */
1992 /** @ingroup container */
1993 /** @{ */
1994 /** @file libbu/vlb.c
1995  *
1996  * The variable length buffer package.
1997  *
1998  * The variable length buffer package.
1999  *
2000  */
2001 
2002 /**
2003  * Variable Length Buffer: bu_vlb support
2004  */
2005 struct bu_vlb {
2006     uint32_t magic;
2007     unsigned char *buf;     /**< Dynamic memory for the buffer */
2008     size_t bufCapacity;     /**< Current capacity of the buffer */
2009     size_t nextByte;        /**< Number of bytes currently used in the buffer */
2010 };
2011 typedef struct bu_vlb bu_vlb_t;
2012 #define BU_VLB_NULL ((struct bu_vlb *)0)
2013 
2014 /**
2015  * assert the integrity of a bu_vlb struct.
2016  */
2017 #define BU_CK_VLB(_vp) BU_CKMAG(_vp, BU_VLB_MAGIC, "bu_vlb")
2018 
2019 /**
2020  * initializes a bu_vlb struct without allocating any memory.
2021  */
2022 #define BU_VLB_INIT(_vp) { \
2023         (_vp)->magic = BU_VLB_MAGIC; \
2024         (_vp)->buf = NULL; \
2025         (_vp)->bufCapacity = (_vp)->nextByte = 0; \
2026     }
2027 
2028 /**
2029  * macro suitable for declaration statement initialization of a bu_vlb
2030  * struct.  does not allocate memory.
2031  */
2032 #define BU_VLB_INIT_ZERO { BU_VLB_MAGIC, NULL, 0, 0 }
2033 
2034 /**
2035  * returns truthfully whether a bu_vlb struct has been initialized.
2036  * is not reliable unless the struct has been allocated with
2037  * BU_ALLOC(), bu_calloc(), or a previous call to bu_vlb_init() or
2038  * BU_VLB_INIT() has been made.
2039  */
2040 #define BU_VLB_IS_INITIALIZED(_vp) (((struct bu_vlb *)(_vp) != BU_VLB_NULL) && ((_vp)->magic == BU_VLB_MAGIC))
2041 
2042 
2043 /** @} */
2044 
2045 
2046 /*----------------------------------------------------------------------*/
2047 /** @addtogroup debug Debugging */
2048 /** @ingroup io */
2049 /** @{ */
2050 
2051 /**
2052  * controls the libbu debug level
2053  */
2054 BU_EXPORT extern int bu_debug;
2055 
2056 /**
2057  * Section for BU_DEBUG values
2058  *
2059  * These can be set from the command-line of RT-compatible programs
2060  * using the "-!" option.
2061  *
2062  * These definitions are each for one bit.
2063  */
2064 #define BU_DEBUG_OFF 0  /* No debugging */
2065 
2066 #define BU_DEBUG_COREDUMP       0x00000001      /* bu_bomb() should dump core on exit */
2067 #define BU_DEBUG_MEM_CHECK      0x00000002      /* Mem barrier & leak checking */
2068 #define BU_DEBUG_MEM_LOG        0x00000004      /* Print all dynamic memory operations */
2069 #define BU_DEBUG_UNUSED_0       0x00000008      /* unused */
2070 
2071 #define BU_DEBUG_PARALLEL       0x00000010      /* Parallel debug logging */
2072 #define BU_DEBUG_MEM_QCHECK     0x00000020      /* Fast mem leak checking (won't work with corruption) */
2073 #define BU_DEBUG_BACKTRACE      0x00000040      /* Log backtrace details during abnormal exit */
2074 #define BU_DEBUG_ATTACH         0x00000080      /* Waits for a debugger to attach during a crash */
2075 
2076 #define BU_DEBUG_MATH           0x00000100      /* Fundamental math routines (plane.c, mat.c) */
2077 #define BU_DEBUG_PTBL           0x00000200      /* bu_ptbl_*() logging */
2078 #define BU_DEBUG_AVS            0x00000400      /* bu_avs_*() logging */
2079 #define BU_DEBUG_MAPPED_FILE    0x00000800      /* bu_mapped_file logging */
2080 
2081 #define BU_DEBUG_PATHS          0x00001000      /* File and path debug logging */
2082 #define BU_DEBUG_UNUSED_1       0x00002000      /* unused */
2083 #define BU_DEBUG_UNUSED_2       0x00004000      /* unused */
2084 #define BU_DEBUG_UNUSED_3       0x00008000      /* unused */
2085 
2086 #define BU_DEBUG_TABDATA        0x00010000      /* LIBBN: tabdata */
2087 #define BU_DEBUG_UNUSED_4       0x00020000      /* unused */
2088 #define BU_DEBUG_UNUSED_5       0x00040000      /* unused */
2089 #define BU_DEBUG_UNUSED_6       0x00080000      /* unused */
2090 
2091 /* Format string for bu_printb() */
2092 #define BU_DEBUG_FORMAT \
2093     "\020\
2094 \025TABDATA\
2095 \015?\
2096 \014MAPPED_FILE\013AVS\012PTBL\011MATH\010?\7?\6MEM_QCHECK\5PARALLEL\
2097 \4?\3MEM_LOG\2MEM_CHECK\1COREDUMP"
2098 
2099 /** @} */
2100 /*----------------------------------------------------------------------*/
2101 /* parse.c */
2102 /** @addtogroup parse */
2103 /** @ingroup container */
2104 /** @{ */
2105 /*
2106  * Structure parse/print
2107  *
2108  * Definitions and data structures needed for routines that assign
2109  * values to elements of arbitrary data structures, the layout of
2110  * which is described by tables of "bu_structparse" structures.
2111  */
2112 
2113 /**
2114  * The general problem of word-addressed hardware where (int *) and
2115  * (char *) have different representations is handled in the parsing
2116  * routines that use sp_offset, because of the limitations placed on
2117  * compile-time initializers.
2118  *
2119  * Files using bu_offsetof or bu_offsetofarray will need to include
2120  * stddef.h in order to get offsetof()
2121  */
2122 /* FIXME - this is a temporary cast. The bu_structparse sp_offset member
2123  *         should be a size_t.
2124  */
2125 #ifndef offsetof
2126 #  define offsetof(_t, _m) (size_t)(&(((_t *)0)->_m))
2127 #endif
2128 #define bu_offsetof(_t, _m) (size_t)offsetof(_t, _m)
2129 #define bu_offsetofarray(_t, _a, _d, _i) bu_offsetof(_t, _a) + sizeof(_d) * _i
2130 
2131 
2132 /**
2133  * Convert address of global data object into byte "offset" from
2134  * address 0.
2135  *
2136  * Strictly speaking, the C language only permits initializers of the
2137  * form: address +- constant, where here the intent is to measure the
2138  * byte address of the indicated variable.  Matching compensation code
2139  * for the CRAY is located in librt/parse.c
2140  */
2141 #if defined(__ia64__) || defined(__x86_64__) || defined(__sparc64__) || defined(_HPUX_SOURCE) || defined(__clang__)
2142 #    define bu_byteoffset(_i)   ((size_t)((char *)&(_i)))
2143 #else
2144 /* "Conservative" way of finding # bytes as diff of 2 char ptrs */
2145 #  define bu_byteoffset(_i)     ((size_t)(((char *)&(_i))-((char *)0)))
2146 #endif
2147 
2148 
2149 /**
2150  * The "bu_structparse" struct describes one element of a structure.
2151  * Collections of these are combined to describe entire structures (or at
2152  * least those portions for which parse/print/import/export support is
2153  * desired.
2154  *
2155  * Provides a convenient way of describing a C data structure, and
2156  * reading and writing it in both human-readable ASCII and efficient
2157  * binary forms.
2158  *
2159  * For example:
2160  *
2161  @code
2162 
2163  struct data_structure {
2164    char a_char;
2165    char str[32];
2166    short a_short;
2167    int a_int;
2168    fastf_t a_fastf_t;
2169    double a_double;
2170  }
2171 
2172  struct data_structure default = { 'c', "the default string", 32767, 1, 1.0, 1.0 };
2173 
2174  struct data_structure my_values;
2175 
2176  struct bu_structparse data_sp[] ={
2177    {"%c", 1,     "a_char",   bu_offsetof(data_structure, a_char), BU_STRUCTPARSE_FUNC_NULL,                      "a single character", (void*)&default.a_char},
2178    {"%s", 32,       "str", bu_offsetofarray(data_structure, str), BU_STRUCTPARSE_FUNC_NULL,         "This is a full character string", (void*)default.str},
2179    {"%i", 1,    "a_short",  bu_offsetof(data_structure, a_short), BU_STRUCTPARSE_FUNC_NULL,                         "A 16bit integer", (void*)&default.a_short},
2180    {"%d", 1,      "a_int",    bu_offsetof(data_structure, a_int), BU_STRUCTPARSE_FUNC_NULL,                          "A full integer", (void*)&default.a_int},
2181    {"%f", 1,   "a_fastf_t", bu_offsetof(data_structure, a_fastf_t), BU_STRUCTPARSE_FUNC_NULL, "A variable-precision fasf_t floating point value", (void*)&default.a_fastf_t},
2182    {"%g", 1,   "a_double", bu_offsetof(data_structure, a_double), BU_STRUCTPARSE_FUNC_NULL, "A double-precision fasf_t floating point value", (void*)&default.a_double},
2183    {  "", 0, (char *)NULL,                                     0, BU_STRUCTPARSE_FUNC_NULL,                              (char *)NULL, (void *)NULL}
2184  };
2185 
2186  @endcode
2187  *
2188  * To parse a string, call:
2189  *
2190  * bu_struct_parse(vls_string, data_sp, (char *)my_values)
2191  *
2192  * this will parse the vls string and assign values to the members of
2193  * the structure my_values
2194  *
2195  * A gross hack: To set global variables (or others for that matter)
2196  * you can store the actual address of the variable in the sp_offset
2197  * field and pass a null pointer as the last argument to
2198  * bu_struct_parse.  If you don't understand why this would work, you
2199  * probably shouldn't use this technique.
2200  */
2201 struct bu_structparse {
2202     const char sp_fmt[4];               /**< "%i" or "%f", etc. */
2203     size_t sp_count;            /**< number of elements */
2204     const char *sp_name;                /**< Element's symbolic name */
2205     size_t sp_offset;           /**< Byte offset in struct */
2206     void (*sp_hook)();          /**< Optional hooked function, or indir ptr */
2207     const char *sp_desc;                /**< description of element */
2208     void *sp_default;           /**< ptr to default value */
2209 };
2210 typedef struct bu_structparse bu_structparse_t;
2211 #define BU_STRUCTPARSE_NULL ((struct bu_structparse *)0)
2212 
2213 /* FIXME: parameterless k&r-style function declarations are not proper
2214  * with ansi.  need to declare the callback completely.
2215  */
2216 #define BU_STRUCTPARSE_FUNC_NULL ((void (*)())0)
2217 
2218 /**
2219  * assert the integrity of a bu_structparse struct.
2220  */
2221 #define BU_CK_STRUCTPARSE(_sp) /* nothing to do */
2222 
2223 /**
2224  * initialize a bu_structparse struct without allocating any memory.
2225  */
2226 #define BU_STRUCTPARSE_INIT(_sp) { \
2227         (_sp)->sp_fmt[0] = (_sp)->sp_fmt[1] = (_sp)->sp_fmt[2] = (_sp)->sp_fmt[3] = '\0'; \
2228         (_sp)->sp_count = 0; \
2229         (_sp)->sp_name = NULL; \
2230         (_sp)->sp_offset = 0; \
2231         (_sp)->sp_hook = BU_STRUCTPARSE_FUNC_NULL; \
2232         (_sp)->sp_desc = NULL; \
2233         (_sp)->sp_default = NULL; \
2234     }
2235 
2236 /**
2237  * macro suitable for declaration statement initialization of a bu_structparse
2238  * struct.  does not allocate memory.
2239  */
2240 #define BU_STRUCTPARSE_INIT_ZERO { {'\0', '\0', '\0', '\0'}, 0, NULL, 0, BU_STRUCTPARSE_FUNC_NULL, NULL, NULL }
2241 
2242 /**
2243  * returns truthfully whether a bu_structparse struct has been
2244  * initialized.  validates whether pointer is non-NULL.
2245  */
2246 #define BU_STRUCTPARSE_IS_INITIALIZED(_sp) ((struct bu_structparse *)(_sp) != BU_STRUCTPARSE_NULL)
2247 
2248 
2249 /*----------------------------------------------------------------------*/
2250 /**
2251  * An "opaque" handle for holding onto objects, typically in some kind
2252  * of external form that is not directly usable without passing
2253  * through an "importation" function.
2254  *
2255  * A "bu_external" struct holds the "external binary" representation
2256  * of a structure or other block of arbitrary data.
2257  */
2258 struct bu_external  {
2259     uint32_t ext_magic;
2260     size_t ext_nbytes;
2261     uint8_t *ext_buf;
2262 };
2263 typedef struct bu_external bu_external_t;
2264 #define BU_EXTERNAL_NULL ((struct bu_external *)0)
2265 
2266 /**
2267  * assert the integrity of a bu_external struct.
2268  */
2269 #define BU_CK_EXTERNAL(_p) BU_CKMAG(_p, BU_EXTERNAL_MAGIC, "bu_external")
2270 
2271 /**
2272  * initializes a bu_external struct without allocating any memory.
2273  */
2274 #define BU_EXTERNAL_INIT(_p) { \
2275         (_p)->ext_magic = BU_EXTERNAL_MAGIC; \
2276         (_p)->ext_nbytes = 0; \
2277         (_p)->ext_buf = NULL; \
2278     }
2279 
2280 /**
2281  * macro suitable for declaration statement initialization of a
2282  * bu_external struct. does not allocate memory.
2283  */
2284 #define BU_EXTERNAL_INIT_ZERO { BU_EXTERNAL_MAGIC, 0, NULL }
2285 
2286 /**
2287  * returns truthfully whether a bu_external struct has been
2288  * initialized.  is not reliable unless the struct has been
2289  * initialized with BU_EXTERNAL_INIT().
2290  */
2291 #define BU_EXTERNAL_IS_INITIALIZED(_p) (((struct bu_external *)(_p) != BU_EXTERNAL_NULL) && (_p)->ext_magic == BU_EXTERNAL_MAGIC)
2292 
2293 
2294 /** @} */
2295 /*----------------------------------------------------------------------*/
2296 /* color.c */
2297 
2298 #define RED 0
2299 #define GRN 1
2300 #define BLU 2
2301 
2302 #define HUE 0
2303 #define SAT 1
2304 #define VAL 2
2305 
2306 #define ACHROMATIC      -1.0
2307 
2308 struct bu_color
2309 {
2310     uint32_t buc_magic;
2311     fastf_t buc_rgb[3];
2312 };
2313 typedef struct bu_color bu_color_t;
2314 #define BU_COLOR_NULL ((struct bu_color *) 0)
2315 
2316 /**
2317  * asserts the integrity of a bu_color struct.
2318  */
2319 #define BU_CK_COLOR(_c) BU_CKMAG(_c, BU_COLOR_MAGIC, "bu_color")
2320 
2321 /**
2322  * initializes a bu_bitv struct without allocating any memory.
2323  */
2324 #define BU_COLOR_INIT(_c) { \
2325         (_c)->buc_magic = BU_COLOR_MAGIC; \
2326         (_c)->buc_rgb[0] = (_c)->buc_rgb[1] = (_c)->buc_rgb[2] = 0; \
2327     }
2328 
2329 /**
2330  * macro suitable for declaration statement initialization of a bu_color
2331  * struct.  does not allocate memory.
2332  */
2333 #define BU_COLOR_INIT_ZERO { BU_COLOR_MAGIC, {0, 0, 0} }
2334 
2335 /**
2336  * returns truthfully whether a bu_color has been initialized
2337  */
2338 #define BU_COLOR_IS_INITIALIZED(_c) (((struct bu_color *)(_c) != BU_COLOR_NULL) && LIKELY((_c)->magic == BU_COLOR_MAGIC))
2339 
2340 
2341 /*----------------------------------------------------------------------*/
2342 /** @addtogroup rb */
2343 /** @ingroup container */
2344 /** @{ */
2345 /*
2346  * The data structures and constants for red-black trees.
2347  *
2348  * Many of these routines are based on the algorithms in chapter 13 of
2349  * Thomas H. Cormen, Charles E. Leiserson, and Ronald L. Rivest,
2350  * "Introduction to Algorithms", MIT Press, Cambridge, MA, 1990.
2351  *
2352  * FIXME:  check implementation given the following note:
2353  *
2354  * Note that the third edition was published in 2009 and the book
2355  * has had significant updates since the first edition.  Quoting the
2356  * authors in the preface:  "The way we delete a node from binary search
2357  * trees (which includes red-black trees) now guarantees that the node
2358  * requested for deletion is the node that is actually deleted.  In the
2359  * first two editions, in certain cases, some other node would be
2360  * deleted, with its contents moving into the node passed to the
2361  * deletion procedure.  With our new way to delete nodes, if other
2362  * components of a program maintain pointers to nodes in the tree, they
2363  * will not mistakenly end up with stale pointers to nodes that have
2364  * been deleted."
2365  *
2366  * The implementation of balanced binary red-black tree operations
2367  * provides all the basic dynamic set operations (e.g., insertion,
2368  * deletion, search, minimum, maximum, predecessor, and successor) and
2369  * order-statistic operations (i.e., select and rank) with optimal
2370  * O(log(n)) performance while sorting on multiple keys.
2371  */
2372 
2373 /**
2374  * List of nodes or packages.
2375  *
2376  * The red-black tree package uses this structure to maintain lists of
2377  * all the nodes and all the packages in the tree.  Applications
2378  * should not muck with these things.  They are maintained only to
2379  * facilitate freeing bu_rb_trees.
2380  *
2381  * This is a PRIVATE structure.
2382  */
2383 struct bu_rb_list
2384 {
2385     struct bu_list l;
2386     union
2387     {
2388         struct bu_rb_node *rbl_n;
2389         struct bu_rb_package *rbl_p;
2390     } rbl_u;
2391 };
2392 #define rbl_magic l.magic
2393 #define rbl_node rbl_u.rbl_n
2394 #define rbl_package rbl_u.rbl_p
2395 #define BU_RB_LIST_NULL ((struct bu_rb_list *) 0)
2396 
2397 
2398 /**
2399  * This is the only data structure used in the red-black tree package
2400  * to which application software need make any explicit reference.
2401  *
2402  * The members of this structure are grouped into three classes:
2403  *
2404  * Class I:     Reading is appropriate, when necessary,
2405  *              but applications should not modify.
2406  * Class II:    Reading and modifying are both appropriate,
2407  *              when necessary.
2408  * Class III:   All access should be through routines
2409  *              provided in the package.  Touch these
2410  *              at your own risk!
2411  */
2412 struct bu_rb_tree {
2413     /***** CLASS I - Applications may read directly. ****************/
2414     uint32_t rbt_magic;           /**< Magic no. for integrity check */
2415     int rbt_nm_nodes;                  /**< Number of nodes */
2416 
2417     /**** CLASS II - Applications may read/write directly. **********/
2418     void (*rbt_print)(void *);         /**< Data pretty-print function */
2419     int rbt_debug;                     /**< Debug bits */
2420     char *rbt_description;             /**< Comment for diagnostics */
2421 
2422     /*** CLASS III - Applications should NOT manipulate directly. ***/
2423     int rbt_nm_orders;                 /**< Number of simultaneous orders */
2424     int (**rbt_order)();               /**< Comparison functions */
2425     struct bu_rb_node **rbt_root;      /**< The actual trees */
2426     char *rbt_unique;                  /**< Uniqueness flags */
2427     struct bu_rb_node *rbt_current;    /**< Current node */
2428     struct bu_rb_list rbt_nodes;       /**< All nodes */
2429     struct bu_rb_list rbt_packages;    /**< All packages */
2430     struct bu_rb_node *rbt_empty_node; /**< Sentinel representing nil */
2431 };
2432 typedef struct bu_rb_tree bu_rb_tree_t;
2433 #define BU_RB_TREE_NULL ((struct bu_rb_tree *) 0)
2434 
2435 /**
2436  * asserts the integrity of a bu_rb_tree struct.
2437  */
2438 #define BU_CK_RB_TREE(_rb) BU_CKMAG(_rb, BU_RB_TREE_MAGIC, "bu_rb_tree")
2439 
2440 /**
2441  * initializes a bu_rb_tree struct without allocating any memory.
2442  */
2443 #define BU_RB_TREE_INIT(_rb) { \
2444         (_rb)->rbt_magic = BU_RB_TREE_MAGIC; \
2445         (_rb)->rbt_nm_nodes = 0; \
2446         (_rb)->rbt_print = NULL; \
2447         (_rb)->rbt_debug = 0; \
2448         (_rb)->rbt_description = NULL; \
2449         (_rb)->rbt_nm_orders = 0; \
2450         (_rb)->rbt_order = NULL; \
2451         (_rb)->rbt_root = (_rb)->rbt_unique = (_rb)->rbt_current = NULL; \
2452         BU_LIST_INIT(&(_rb)->rbt_nodes.l); \
2453         (_rb)->rbt_nodes.rbl_u.rbl_n = (_rb)->rbt_nodes.rbl_u.rbl_p = NULL; \
2454         BU_LIST_INIT(&(_rb)->rbt_packages.l); \
2455         (_rb)->rbt_packages.rbl_u.rbl_n = (_rb)->rbt_packages.rbl_u.rbl_p = NULL; \
2456         (_rb)->rbt_empty_node = NULL; \
2457     }
2458 
2459 /**
2460  * macro suitable for declaration statement initialization of a
2461  * bu_rb_tree struct.  does not allocate memory.
2462  */
2463 #define BU_RB_TREE_INIT_ZERO { BU_RB_TREE_MAGIC, 0, NULL, 0, NULL, 0, NULL, NULL, NULL, NULL, \
2464         { BU_LIST_INIT_ZER0, {NULL, NULL} }, { BU_LIST_INIT_ZER0, {NULL, NULL} }, NULL, NULL, NULL }
2465 
2466 /**
2467  * returns truthfully whether a bu_rb_tree has been initialized.
2468  */
2469 #define BU_RB_TREE_IS_INITIALIZED(_rb) (((struct bu_rb_tree *)(_rb) != BU_RB_TREE_NULL) && LIKELY((_rb)->rbt_magic == BU_RB_TREE_MAGIC))
2470 
2471 
2472 /*
2473  * Debug bit flags for member rbt_debug
2474  */
2475 #define BU_RB_DEBUG_INSERT 0x00000001   /**< Insertion process */
2476 #define BU_RB_DEBUG_UNIQ 0x00000002     /**< Uniqueness of inserts */
2477 #define BU_RB_DEBUG_ROTATE 0x00000004   /**< Rotation process */
2478 #define BU_RB_DEBUG_OS 0x00000008       /**< Order-statistic operations */
2479 #define BU_RB_DEBUG_DELETE 0x00000010   /**< Deletion process */
2480 
2481 /**
2482  * Wrapper for application data.
2483  *
2484  * This structure provides a level of indirection between the
2485  * application software's data and the red-black nodes in which the
2486  * data is stored.  It is necessary because of the algorithm for
2487  * deletion, which generally shuffles data among nodes in the tree.
2488  * The package structure allows the application data to remember which
2489  * node "contains" it for each order.
2490  */
2491 struct bu_rb_package
2492 {
2493     uint32_t rbp_magic; /**< Magic no. for integrity check */
2494     struct bu_rb_node **rbp_node;       /**< Containing nodes */
2495     struct bu_rb_list *rbp_list_pos;    /**< Place in the list of all pkgs.  */
2496     void *rbp_data;     /**< Application data */
2497 };
2498 #define BU_RB_PKG_NULL ((struct bu_rb_package *) 0)
2499 
2500 /**
2501  * For the most part, there is a one-to-one correspondence between
2502  * nodes and chunks of application data.  When a node is created, all
2503  * of its package pointers (one per order of the tree) point to the
2504  * same chunk of data.  However, subsequent deletions usually muddy
2505  * this tidy state of affairs.
2506  */
2507 struct bu_rb_node
2508 {
2509     uint32_t rbn_magic;         /**< Magic no. for integrity check */
2510     struct bu_rb_tree *rbn_tree;        /**< Tree containing this node */
2511     struct bu_rb_node **rbn_parent;     /**< Parents */
2512     struct bu_rb_node **rbn_left;       /**< Left subtrees */
2513     struct bu_rb_node **rbn_right;      /**< Right subtrees */
2514     char *rbn_color;                    /**< Colors of this node */
2515     int *rbn_size;                      /**< Sizes of subtrees rooted here */
2516     struct bu_rb_package **rbn_package; /**< Contents of this node */
2517     int rbn_pkg_refs;                   /**< How many orders are being used?  */
2518     struct bu_rb_list *rbn_list_pos;    /**< Place in the list of all nodes */
2519 };
2520 #define BU_RB_NODE_NULL ((struct bu_rb_node *) 0)
2521 
2522 /*
2523  * Applications interface to bu_rb_extreme()
2524  */
2525 #define SENSE_MIN 0
2526 #define SENSE_MAX 1
2527 #define bu_rb_min(t, o) bu_rb_extreme((t), (o), SENSE_MIN)
2528 #define bu_rb_max(t, o) bu_rb_extreme((t), (o), SENSE_MAX)
2529 #define bu_rb_pred(t, o) bu_rb_neighbor((t), (o), SENSE_MIN)
2530 #define bu_rb_succ(t, o) bu_rb_neighbor((t), (o), SENSE_MAX)
2531 
2532 /*
2533  * Applications interface to bu_rb_walk()
2534  */
2535 #define PREORDER        0
2536 #define INORDER         1
2537 #define POSTORDER       2
2538 
2539 
2540 /**
2541  * TBD
2542  */
2543 struct bu_observer {
2544     struct bu_list l;
2545     struct bu_vls observer;
2546     struct bu_vls cmd;
2547 };
2548 typedef struct bu_observer bu_observer_t;
2549 #define BU_OBSERVER_NULL ((struct bu_observer *)0)
2550 
2551 /**
2552  * asserts the integrity of a non-head node bu_observer struct.
2553  */
2554 #define BU_CK_OBSERVER(_op) BU_CKMAG(_op, BU_OBSERVER_MAGIC, "bu_observer magic")
2555 
2556 /**
2557  * initializes a bu_observer struct without allocating any memory.
2558  */
2559 #define BU_OBSERVER_INIT(_op) { \
2560         BU_LIST_INIT_MAGIC(&(_op)->l, BU_OBSERVER_MAGIC); \
2561         BU_VLS_INIT(&(_op)->observer); \
2562         BU_VLS_INIT(&(_op)->cmd); \
2563     }
2564 
2565 /**
2566  * macro suitable for declaration statement initialization of a bu_observer
2567  * struct.  does not allocate memory.  not suitable for a head node.
2568  */
2569 #define BU_OBSERVER_INIT_ZERO { {BU_OBSERVER_MAGIC, BU_LIST_NULL, BU_LIST_NULL}, BU_VLS_INIT_ZERO, BU_VLS_INIT_ZERO }
2570 
2571 /**
2572  * returns truthfully whether a bu_observer has been initialized.
2573  */
2574 #define BU_OBSERVER_IS_INITIALIZED(_op) (((struct bu_observer *)(_op) != BU_OBSERVER_NULL) && LIKELY((_op)->magic == BU_OBSERVER_MAGIC))
2575 
2576 
2577 /**
2578  * DEPRECATED.
2579  *
2580  * Usage not recommended due to k&r callback (provides no type
2581  * checking)
2582  */
2583 struct bu_cmdtab {
2584     char *ct_name;
2585     int (*ct_func)(void *data, int argc, const char *argv[]);
2586 };
2587 
2588 
2589 /*----------------------------------------------------------------------*/
2590 /* Miscellaneous macros */
2591 #define bu_made_it() bu_log("Made it to %s:%d\n",       \
2592                             __FILE__, __LINE__)
2593 /*----------------------------------------------------------------------*/
2594 /*
2595  * Declarations of external functions in LIBBU.  Source file names
2596  * listed alphabetically.
2597  */
2598 /**@}*/
2599 
2600 /** @addtogroup avs */
2601 /** @ingroup container */
2602 /** @{ */
2603 /* avs.c */
2604 
2605 
2606 /**
2607  * Initialize avs with storage for len entries.
2608  */
2609 BU_EXPORT extern void bu_avs_init(struct bu_attribute_value_set *avp,
2610                                   int len,
2611                                   const char *str);
2612 
2613 /**
2614  * Initialize an empty avs.
2615  */
2616 BU_EXPORT extern void bu_avs_init_empty(struct bu_attribute_value_set *avp);
2617 
2618 /**
2619  * Allocate storage for a new attribute/value set, with at least 'len'
2620  * slots pre-allocated.
2621  */
2622 BU_EXPORT extern struct bu_attribute_value_set *bu_avs_new(int len,
2623                                                            const char *str);
2624 
2625 /**
2626  * If the given attribute exists it will receive the new value,
2627  * otherwise the set will be extended to have a new attribute/value
2628  * pair.
2629  *
2630  * Returns -
2631  * 0 some error occurred
2632  * 1 existing attribute updated with new value
2633  * 2 set extended with new attribute/value pair
2634  */
2635 BU_EXPORT extern int bu_avs_add(struct bu_attribute_value_set *avp,
2636                                 const char *attribute,
2637                                 const char *value);
2638 
2639 /**
2640  * Add a bu_vls string as an attribute to a given attribute set.
2641  */
2642 BU_EXPORT extern int bu_avs_add_vls(struct bu_attribute_value_set *avp,
2643                                     const char *attribute,
2644                                     const struct bu_vls *value_vls);
2645 
2646 /**
2647  * Take all the attributes from 'src' and merge them into 'dest' by
2648  * replacing an attribute if it already exists.
2649  */
2650 BU_EXPORT extern void bu_avs_merge(struct bu_attribute_value_set *dest,
2651                                    const struct bu_attribute_value_set *src);
2652 
2653 /**
2654  * Get the value of a given attribute from an attribute set.
2655  */
2656 BU_EXPORT extern const char *bu_avs_get(const struct bu_attribute_value_set *avp,
2657                                         const char *attribute);
2658 
2659 /**
2660  * Remove the given attribute from an attribute set.
2661  *
2662  * @return
2663  *      -1      attribute not found in set
2664  * @return
2665  *       0      OK
2666  */
2667 BU_EXPORT extern int bu_avs_remove(struct bu_attribute_value_set *avp,
2668                                    const char *attribute);
2669 
2670 /**
2671  * Release all attributes in an attribute set.
2672  */
2673 BU_EXPORT extern void bu_avs_free(struct bu_attribute_value_set *avp);
2674 
2675 /**
2676  * Print all attributes in an attribute set in "name = value" form,
2677  * using the provided title.
2678  */
2679 BU_EXPORT extern void bu_avs_print(const struct bu_attribute_value_set *avp,
2680                                    const char *title);
2681 
2682 /**
2683  * Add a name/value pair even if the name already exists in this AVS.
2684  */
2685 BU_EXPORT extern void bu_avs_add_nonunique(struct bu_attribute_value_set *avsp,
2686                                            const char *attribute,
2687                                            const char *value);
2688 /** @} */
2689 
2690 /** @addtogroup bitv */
2691 /** @ingroup container */
2692 /** @{ */
2693 
2694 /**
2695  * Allocate storage for a new bit vector of at least 'nbits' in
2696  * length.  The bit vector itself is guaranteed to be initialized to
2697  * all zero.
2698  */
2699 BU_EXPORT extern struct bu_bitv *bu_bitv_new(size_t nbits);
2700 
2701 /**
2702  * Release all internal storage for this bit vector.
2703  *
2704  * It is the caller's responsibility to not use the pointer 'bv' any
2705  * longer.  It is the caller's responsibility to dequeue from any
2706  * linked list first.
2707  */
2708 BU_EXPORT extern void bu_bitv_free(struct bu_bitv *bv);
2709 
2710 /**
2711  * Set all the bits in the bit vector to zero.
2712  *
2713  * Also available as a BU_BITV_ZEROALL macro if you don't desire the
2714  * pointer checking.
2715  */
2716 BU_EXPORT extern void bu_bitv_clear(struct bu_bitv *bv);
2717 
2718 /**
2719  * TBD
2720  */
2721 BU_EXPORT extern void bu_bitv_or(struct bu_bitv *ov,  const struct bu_bitv *iv);
2722 
2723 /**
2724  * TBD
2725  */
2726 BU_EXPORT extern void bu_bitv_and(struct bu_bitv *ov, const struct bu_bitv *iv);
2727 
2728 /**
2729  * Print the bits set in a bit vector.
2730  */
2731 BU_EXPORT extern void bu_bitv_vls(struct bu_vls *v, const struct bu_bitv *bv);
2732 
2733 /**
2734  * Print the bits set in a bit vector.  Use bu_vls stuff, to make only
2735  * a single call to bu_log().
2736  */
2737 BU_EXPORT extern void bu_pr_bitv(const char *str, const struct bu_bitv *bv);
2738 
2739 /**
2740  * Convert a bit vector to an ascii string of hex digits.  The string
2741  * is from MSB to LSB (bytes and bits).
2742  */
2743 BU_EXPORT extern void bu_bitv_to_hex(struct bu_vls *v, const struct bu_bitv *bv);
2744 
2745 /**
2746  * Convert a string of HEX digits (as produces by bu_bitv_to_hex) into
2747  * a bit vector.
2748  */
2749 BU_EXPORT extern struct bu_bitv *bu_hex_to_bitv(const char *str);
2750 
2751 /**
2752  * Make a copy of a bit vector
2753  */
2754 BU_EXPORT extern struct bu_bitv *bu_bitv_dup(const struct bu_bitv *bv);
2755 
2756 
2757 /** @} */
2758 
2759 /** @addtogroup log */
2760 /** @ingroup io */
2761 /** @{ */
2762 /** @file libbu/backtrace.c
2763  *
2764  * Extract a backtrace of the current call stack.
2765  *
2766  */
2767 
2768 /**
2769  * this routine provides a trace of the call stack to the caller,
2770  * generally called either directly, via a signal handler, or through
2771  * bu_bomb() with the appropriate bu_debug flags set.
2772  *
2773  * the routine waits indefinitely (in a spin loop) until a signal
2774  * (SIGINT) is received, at which point execution continues, or until
2775  * some other signal is received that terminates the application.
2776  *
2777  * the stack backtrace will be written to the provided 'fp' file
2778  * pointer.  it's the caller's responsibility to open and close
2779  * that pointer if necessary.  If 'fp' is NULL, stdout will be used.
2780  *
2781  * returns truthfully if a backtrace was attempted.
2782  */
2783 BU_EXPORT extern int bu_backtrace(FILE *fp);
2784 
2785 /**
2786  * Adds a hook to the list of bu_bomb hooks.  The top (newest) one of these
2787  * will be called with its associated client data and a string to be
2788  * processed.  Typically, these hook functions will display the output
2789  * (possibly in an X window) or record it.
2790  *
2791  * NOTE: The hook functions are all non-PARALLEL.
2792  */
2793 BU_EXPORT extern void bu_bomb_add_hook(bu_hook_t func, genptr_t clientdata);
2794 
2795 /**
2796  * Abort the running process.
2797  *
2798  * The bu_bomb routine is called on a fatal error, generally where no
2799  * recovery is possible.  Error handlers may, however, be registered
2800  * with BU_SETJUMP.  This routine intentionally limits calls to other
2801  * functions and intentionally uses no stack variables.  Just in case
2802  * the application is out of memory, bu_bomb deallocates a small
2803  * buffer of memory.
2804  *
2805  * Before termination, it optionally performs the following operations
2806  * in the order listed:
2807  *
2808  * 1. Outputs str to standard error
2809  *
2810  * 2. Calls any callback functions set in the global bu_bomb_hook_list
2811  *    variable with str passed as an argument.
2812  *
2813  * 3. Jumps to any user specified error handler registered with the
2814  *    bu_setjmp_valid/bu_jmpbuf setjmp facility.
2815  *
2816  * 4. Outputs str to the terminal device in case standard error is
2817  *    redirected.
2818  *
2819  * 5. Aborts abnormally (via abort()) if BU_DEBUG_COREDUMP is defined.
2820  *
2821  * 6. Exits with exit(12).
2822  *
2823  * Only produce a core-dump when that debugging bit is set.  Note that
2824  * this function is meant to be a last resort semi-graceful abort.
2825  *
2826  * This routine should never return unless there is a bu_setjmp
2827  * handler registered.
2828  */
2829 BU_EXPORT extern void bu_bomb(const char *str) _BU_ATTR_NORETURN;
2830 
2831 /**
2832  * Semi-graceful termination of the application that doesn't cause a
2833  * stack trace, exiting with the specified status after printing the
2834  * given message.  It's okay for this routine to use the stack,
2835  * contrary to bu_bomb's behavior since it should be called for
2836  * expected termination situations.
2837  *
2838  * This routine should generally not be called within a library.  Use
2839  * bu_bomb or (better) cascade the error back up to the application.
2840  *
2841  * This routine should never return.
2842  */
2843 BU_EXPORT extern void bu_exit(int status, const char *fmt, ...) _BU_ATTR_NORETURN _BU_ATTR_PRINTF23;
2844 
2845 /** @file libbu/crashreport.c
2846  *
2847  * Generate a crash report file, including a call stack backtrace and
2848  * other system details.
2849  *
2850  */
2851 
2852 /**
2853  * this routine writes out details of the currently running process to
2854  * the specified file, including an informational header about the
2855  * execution environment, stack trace details, kernel and hardware
2856  * information, and current version information.
2857  *
2858  * returns truthfully if the crash report was written.
2859  *
2860  * due to various reasons, this routine is NOT thread-safe.
2861  */
2862 BU_EXPORT extern int bu_crashreport(const char *filename);
2863 
2864 /** @file libbu/fgets.c
2865  *
2866  * fgets replacement function that also handles CR as an EOL marker
2867  *
2868  */
2869 
2870 /**
2871  * Reads in at most one less than size characters from stream and
2872  * stores them into the buffer pointed to by s. Reading stops after an
2873  * EOF, CR, LF, or a CR/LF combination. If a LF or CR is read, it is
2874  * stored into the buffer. If a CR/LF is read, just a CR is stored
2875  * into the buffer. A '\\' is stored after the last character in the
2876  * buffer. Returns s on success, and NULL on error or when end of file
2877  * occurs while no characters have been read.
2878  */
2879 BU_EXPORT extern char *bu_fgets(char *s, int size, FILE *stream);
2880 
2881 /** @} */
2882 /** @addtogroup color */
2883 /** @ingroup container */
2884 /** @{ */
2885 
2886 /**
2887  * Convert between RGB and HSV color models
2888  *
2889  * R, G, and B are in {0, 1, ..., 255},
2890  *
2891  * H is in [0.0, 360.0), and S and V are in [0.0, 1.0],
2892  *
2893  * unless S = 0.0, in which case H = ACHROMATIC.
2894  *
2895  * These two routines are adapted from:
2896  * pp. 592-3 of J.D. Foley, A. van Dam, S.K. Feiner, and J.F. Hughes,
2897  * _Computer graphics: principles and practice_, 2nd ed., Addison-Wesley,
2898  * Reading, MA, 1990.
2899  */
2900 
2901 /* color.c */
2902 BU_EXPORT extern void bu_rgb_to_hsv(unsigned char *rgb, fastf_t *hsv);
2903 BU_EXPORT extern int bu_hsv_to_rgb(fastf_t *hsv, unsigned char *rgb);
2904 BU_EXPORT extern int bu_str_to_rgb(char *str, unsigned char *rgb);
2905 BU_EXPORT extern int bu_color_from_rgb_floats(struct bu_color *cp, fastf_t *rgb);
2906 BU_EXPORT extern int bu_color_to_rgb_floats(struct bu_color *cp, fastf_t *rgb);
2907 
2908 /* UNIMPLEMENTED
2909  *
2910  * BU_EXPORT export void bu_color_from_rgb_chars(struct bu_color *cp, unsigned char *rgb);
2911  * BU_EXPORT export int bu_color_to_rgb_chars(struct bu_color *cp, unsigned char *rgb);
2912  * BU_EXPORT export int bu_color_from_hsv_floats(struct bu_color *cp, fastf_t *hsv);
2913  * BU_EXPORT export int bu_color_to_hsv_floats(struct bu_color *cp, fastf_t *hsv);
2914  */
2915 
2916 
2917 /** @} */
2918 /** @addtogroup file */
2919 /** @ingroup io */
2920 /** @{ */
2921 
2922 /** @file libbu/file.c
2923  *
2924  * Support routines for identifying properties of files and
2925  * directories such as whether they exist or are the same as another
2926  * given file.
2927  *
2928  */
2929 
2930 /**
2931  * Returns truthfully whether the given file path exists or not.  An
2932  * empty or NULL path name is treated as a non-existent file and, as
2933  * such, will return false.  If fd is non-NULL, it will be set to an
2934  * open file descriptor for the provided path.
2935  *
2936  * @return >0 The given filename exists.
2937  * @return 0 The given filename does not exist.
2938  */
2939 BU_EXPORT extern int bu_file_exists(const char *path, int *fd);
2940 
2941 /**
2942  * Returns truthfully as to whether the two provided filenames are the
2943  * same file.  If either file does not exist, the result is false.  If
2944  * either filename is empty or NULL, it is treated as non-existent
2945  * and, as such, will also return false.
2946  */
2947 BU_EXPORT extern int bu_same_file(const char *fn1, const char *fn2);
2948 
2949 /**
2950  * returns truthfully as to whether or not the two provided file
2951  * descriptors are the same file.  if either file does not exist, the
2952  * result is false.
2953  */
2954 BU_EXPORT extern int bu_same_fd(int fd1, int fd2);
2955 
2956 /**
2957  * returns truthfully if current user can read the specified file or
2958  * directory.
2959  */
2960 BU_EXPORT extern int bu_file_readable(const char *path);
2961 
2962 /**
2963  * returns truthfully if current user can write to the specified file
2964  * or directory.
2965  */
2966 BU_EXPORT extern int bu_file_writable(const char *path);
2967 
2968 /**
2969  * returns truthfully if current user can run the specified file or
2970  * directory.
2971  */
2972 BU_EXPORT extern int bu_file_executable(const char *path);
2973 
2974 /**
2975  * Returns truthfully whether the given file path is a directory.  An
2976  * empty or NULL path name is treated as a non-existent directory and,
2977  * as such, will return false.
2978  *
2979  * @return >0 The given filename is a directory
2980  * @return 0 The given filename is not a directory.
2981  */
2982 BU_EXPORT extern int bu_file_directory(const char *path);
2983 
2984 /**
2985  * Returns truthfully whether the given file path is a symbolic link.
2986  * An empty or NULL path name is treated as a non-existent link and,
2987  * as such, will return false.
2988  *
2989  * @return >0 The given filename is a symbolic link
2990  * @return 0 The given filename is not a symbolic link.
2991  */
2992 BU_EXPORT extern int bu_file_symbolic(const char *path);
2993 
2994 /**
2995  * forcibly attempts to delete a specified file.  if the file can be
2996  * deleted by relaxing file permissions, they will be changed in order
2997  * to delete the file.
2998  *
2999  * returns truthfully if the specified file was deleted.
3000  */
3001 BU_EXPORT extern int bu_file_delete(const char *path);
3002 
3003 /**
3004  * matches a filepath pattern to directory entries.  if non-NULL,
3005  * matching paths are dynamically allocated, stored into the provided
3006  * 'matches' array, and followed by a terminating NULL entry.
3007  *
3008  * If '*matches' is NULL, the caller is expected to free the matches
3009  * array with bu_free_argv() If '*matches' is non-NULL (i.e., string
3010  * array is already allocated or on the stack), the caller is expected
3011  * to ensure adequate entries are allocated and call bu_free_array()
3012  * to clean up.  If 'matches' is NULL, no entries will be allocated or
3013  * stored, but the number of matches will still be returned.
3014  *
3015  * Example:
3016  *
3017  * char **my_matches = NULL;
3018  * bu_file_glob("src/libbu/[a-e]*.c", &my_matches);
3019  *
3020  * This will allocate an array for storing glob matches, filling in
3021  * the array with all of the directory entries starting with 'a'
3022  * through 'e' and ending with a '.c' suffix in the src/libbu
3023  * directory.
3024  *
3025  * returns the number of matches
3026  */
3027 BU_EXPORT extern size_t bu_file_glob(const char *pattern, char ***matches);
3028 
3029 /**
3030  * Call canonicalization routines to both expand and validate
3031  * a path name.
3032  *
3033  * returns a pointer to the canonical path.  Caller must free
3034  * the path.
3035  */
3036 BU_EXPORT extern char * bu_file_path_canonicalize(const char *path);
3037 
3038 /** @file libbu/fnmatch.c
3039  *
3040  */
3041 
3042 #define BU_FNMATCH_NOESCAPE    0x01 /**< bu_fnmatch() flag.  Backslash escaping. */
3043 #define BU_FNMATCH_PATHNAME    0x02 /**< bu_fnmatch() flag.  Slash must be matched by slash. */
3044 #define BU_FNMATCH_PERIOD      0x04 /**< bu_fnmatch() flag.  Period must be matched by period. */
3045 #define BU_FNMATCH_LEADING_DIR 0x08 /**< bu_fnmatch() flag.  Ignore /<tail> after Imatch. */
3046 #define BU_FNMATCH_CASEFOLD    0x10 /**< bu_fnmatch() flag.  Case-insensitive searching. */
3047 
3048 /**
3049  * bu_fnmatch() return value when no match is found (0 if found)
3050  */
3051 #define BU_FNMATCH_NOMATCH 1       /* Match failed. */
3052 
3053 /**
3054  * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6.
3055  * Compares a string filename or pathname to a pattern.
3056  *
3057  * Returns 0 if a match is found or BU_FNMATCH_NOMATCH otherwise.
3058  *
3059  */
3060 BU_EXPORT extern int bu_fnmatch(const char *pattern, const char *pathname, int flags);
3061 
3062 
3063 /** @file libbu/dirent.c
3064  *
3065  * Functionality for accessing all files in a directory.
3066  *
3067  */
3068 
3069 /**
3070  * Returns the number of directory entries for a given path matching
3071  * an optional glob pattern.  If the caller provides a pointer to an
3072  * argv-style 'files' array, this function will allocate the array
3073  * with dynamically allocated strings for any matching file(s).
3074  *
3075  * It is the caller's responsibility to free a non-NULL 'files' array
3076  * with bu_free_argv().
3077  */
3078 BU_EXPORT extern size_t bu_dir_list(const char *path, const char *pattern, char ***files);
3079 
3080 
3081 /** @file libbu/realpath.c
3082  *
3083  */
3084 
3085 /**
3086  * Call canonicalization routines to both expand and validate
3087  * a path name.
3088  *
3089  * Returns a pointer to the canonical path. If resolved_path is
3090  * NULL, caller is responsible for freeing the returned path
3091  * via bu_free.  If supplying a result string, the string must hold
3092  * at least MAXPATHLEN characters.
3093  */
3094 BU_EXPORT extern char * bu_realpath(const char *path, char *resolved_path);
3095 
3096 
3097 /** @file libbu/brlcad_path.c
3098  *
3099  * @brief
3100  * A support routine to provide the executable code with the path
3101  * to where the BRL-CAD programs and libraries are installed.
3102  *
3103  */
3104 
3105 /**
3106  * DEPRECATED: This routine is replaced by bu_argv0_full_path().
3107  *             Do not use.
3108  *
3109  * this routine is used by the brlcad-path-finding routines when
3110  * attempting to locate binaries, libraries, and resources.  This
3111  * routine will set argv0 if path is provided and should generally be
3112  * set early on by bu_setprogname().
3113  *
3114  * this routine will return "(unknown)" if argv[0] cannot be
3115  * identified but should never return NULL.
3116  */
3117 DEPRECATED BU_EXPORT extern const char *bu_argv0(void);
3118 
3119 /**
3120  * DEPRECATED: This routine is replaced by bu_getcwd().
3121  *             Do not use.
3122  *
3123  * returns the full path to argv0, regardless of how the application
3124  * was invoked.
3125  *
3126  * this routine will return "(unknown)" if argv[0] cannot be
3127  * identified but should never return NULL.
3128  *
3129  */
3130 BU_EXPORT extern const char *bu_argv0_full_path(void);
3131 
3132 /**
3133  * get the name of the running application if they ran
3134  * bu_setprogname() first or if we know what it's supposed to be
3135  * anyways.
3136  */
3137 BU_EXPORT extern const char *bu_getprogname(void);
3138 
3139 /**
3140  * Set the name of the running application.  This isn't necessary on
3141  * modern systems that support getprogname() and call setprogname()
3142  * before main() for you, but necessary otherwise for portability.
3143  */
3144 BU_EXPORT extern void bu_setprogname(const char *path);
3145 
3146 /**
3147  * returns the pathname for the current working directory.
3148  *
3149  */
3150 BU_EXPORT extern char *bu_getcwd(char *buf, size_t size);
3151 
3152 /**
3153  * Report the relative paths being used to hold BRL-CAD applications,
3154  * libraries, and data.
3155  *
3156  * Recognized keys include:
3157  *
3158  *   bin     - Directory containing binary applications
3159  *   lib     - Directory containing libraries
3160  *   include - Directory containing headers
3161  *   data    - Directory containing shared data
3162  *   share   - Directory containing shared data
3163  *   doc     - Directory containing documentation
3164  *   man     - Directory containing Unix man pages
3165  *
3166  * @return
3167  * A STATIC buffer is returned.  It is the caller's responsibility to
3168  * call bu_strdup() or make other provisions to save the returned
3169  * string, before calling again.
3170  */
3171 BU_EXPORT extern const char *bu_brlcad_dir(const char *dirkey, int fail_quietly);
3172 
3173 /**
3174  * Locate where the BRL-CAD applications and libraries are installed.
3175  *
3176  * The BRL-CAD root is searched for in the following order of
3177  * precedence by testing for the rhs existence if provided or the
3178  * directory existence otherwise:
3179  *
3180  *   BRLCAD_ROOT environment variable if set
3181  *   BRLCAD_ROOT compile-time path
3182  *   run-time path identification
3183  *   /usr/brlcad static path
3184  *   current directory
3185  *
3186  * @return
3187  * A STATIC buffer is returned.  It is the caller's responsibility to
3188  * call bu_strdup() or make other provisions to save the returned
3189  * string, before calling again.
3190  */
3191 BU_EXPORT extern const char *bu_brlcad_root(const char *rhs, int fail_quietly);
3192 
3193 /**
3194  * Locate where the BRL-CAD data resources are installed.
3195  *
3196  * The BRL-CAD data resources are searched for in the following order
3197  * of precedence by testing for the existence of rhs if provided or
3198  * the directory existence otherwise:
3199  *
3200  *   BRLCAD_DATA environment variable if set
3201  *   BRLCAD_DATA compile-time path
3202  *   bu_brlcad_root/DATA_DIR path
3203  *   bu_brlcad_root/share path
3204  *   current directory
3205  *
3206  * A STATIC buffer is returned.  It is the caller's responsibility to
3207  * call bu_strdup() or make other provisions to save the returned
3208  * string, before calling again.
3209  */
3210 BU_EXPORT extern const char *bu_brlcad_data(const char *rhs, int fail_quietly);
3211 
3212 /**
3213  * returns the first USER path match to a given executable name.
3214  *
3215  * Routine to provide BSD "which" functionality, locating binaries of
3216  * specified programs from the user's PATH. This is useful to locate
3217  * binaries and resources at run-time.
3218  *
3219  * caller should not free the result, though it will not be preserved
3220  * between calls either.  the caller should strdup the result if they
3221  * need to keep it around.
3222  *
3223  * routine will return NULL if the executable command cannot be found.
3224  */
3225 BU_EXPORT extern const char *bu_which(const char *cmd);
3226 
3227 /**
3228  * returns the first SYSTEM path match to a given executable cmd name.
3229  *
3230  * Routine to provide BSD "whereis" functionality, locating binaries
3231  * of specified programs from the SYSTEM path.  This is useful to
3232  * locate binaries and resources at run-time.
3233  *
3234  * caller should not free the result, though it will not be preserved
3235  * between calls either.  the caller should strdup the result if they
3236  * need to keep it around.
3237  *
3238  * routine will return NULL if the executable command cannot be found.
3239  */
3240 BU_EXPORT extern const char *bu_whereis(const char *cmd);
3241 
3242 /** @file libbu/temp.c
3243  *
3244  * Routine to open a temporary file.
3245  *
3246  */
3247 
3248 /**
3249  * Create a temporary file.  The first readable/writable directory
3250  * will be used, searching TMPDIR/TEMP/TMP environment variable
3251  * directories followed by default system temp directories and
3252  * ultimately trying the current directory.
3253  *
3254  * This routine is guaranteed to return a new unique file or return
3255  * NULL on failure.  The temporary file will be automatically unlinked
3256  * on application exit.  It is the caller's responsibility to set file
3257  * access settings, preserve file contents, or destroy file contents
3258  * if the default behavior is non-optimal.
3259  *
3260  * The name of the temporary file will be copied into a user-provided
3261  * (filepath) buffer if it is a non-NULL pointer and of a sufficient
3262  * (len) length to contain the filename.
3263  *
3264  * This routine is NOT thread-safe.
3265  *
3266  * Typical Use:
3267  @code
3268   FILE *fp;
3269   char filename[MAXPATHLEN];
3270   fp = bu_temp_file(&filename, MAXPATHLEN); // get file name
3271   ...
3272   fclose(fp); // close the file when you're done
3273   ...
3274   fp = bu_temp_file(NULL, 0); // don't need file name
3275   bu_fchmod(fileno(fp), 0777);
3276   ...
3277   rewind(fp);
3278   while (fputc(0, fp) == 0);
3279   fclose(fp);
3280  @endcode
3281  */
3282 BU_EXPORT extern FILE *bu_temp_file(char *filepath, size_t len);
3283 
3284 /** @} */
3285 /** @addtogroup getopt */
3286 /** @ingroup data */
3287 /** @{ */
3288 
3289 /** @file libbu/getopt.c
3290  *
3291  * @brief
3292  * Special portable re-entrant version of getopt.
3293  *
3294  * Everything is prefixed with bu_, to distinguish it from the various
3295  * getopt routines found in libc.
3296  *
3297  * Important note -
3298  * If bu_getopt() is going to be used more than once, it is necessary
3299  * to reinitialize bu_optind=1 before beginning on the next argument
3300  * list.
3301  */
3302 
3303 /**
3304  * for bu_getopt().  set to zero to suppress errors.
3305  */
3306 BU_EXPORT extern int bu_opterr;
3307 
3308 /**
3309  * for bu_getopt().  current index into parent argv vector.
3310  */
3311 BU_EXPORT extern int bu_optind;
3312 
3313 /**
3314  * for bu_getopt().  current option being checked for validity.
3315  */
3316 BU_EXPORT extern int bu_optopt;
3317 
3318 /**
3319  * for bu_getopt().  current argument associated with current option.
3320  */
3321 BU_EXPORT extern char *bu_optarg;
3322 
3323 /**
3324  * Get option letter from argument vector.
3325  *
3326  * returns the next known option character in ostr.  If bu_getopt()
3327  * encounters a character not found in ostr or if it detects a missing
3328  * option argument, it returns `?' (question mark).  If ostr has a
3329  * leading `:' then a missing option argument causes `:' to be
3330  * returned instead of `?'.  In either case, the variable bu_optopt is
3331  * set to the character that caused the error.  The bu_getopt()
3332  * function returns -1 when the argument list is exhausted.
3333  */
3334 BU_EXPORT extern int bu_getopt(int nargc, char * const nargv[], const char *ostr);
3335 
3336 /** @} */
3337 /** @addtogroup hist */
3338 /** @ingroup data */
3339 /** @{ */
3340 
3341 /* hist.c */
3342 /* These are a set of data histogramming routines. */
3343 
3344 /**
3345  */
3346 BU_EXPORT extern void bu_hist_free(struct bu_hist *histp);
3347 
3348 /**
3349  * Initialize a bu_hist structure.
3350  *
3351  * It is expected that the structure is junk upon entry.
3352  */
3353 BU_EXPORT extern void bu_hist_init(struct bu_hist *histp, fastf_t min, fastf_t max, unsigned int nbins);
3354 
3355 /**
3356  */
3357 BU_EXPORT extern void bu_hist_range(struct bu_hist *hp, fastf_t low, fastf_t high);
3358 
3359 /**
3360  * Print a histogram.
3361  */
3362 BU_EXPORT extern void bu_hist_pr(const struct bu_hist *histp, const char *title);
3363 
3364 /** @} */
3365 
3366 /** @addtogroup hton */
3367 /** @ingroup data */
3368 /** @{ */
3369 /** @file libbu/htond.c
3370  *
3371  * Convert doubles to host/network format.
3372  *
3373  * Library routines for conversion between the local host 64-bit
3374  * ("double precision") representation, and 64-bit IEEE double
3375  * precision representation, in "network order", i.e., big-endian, the
3376  * MSB in byte [0], on the left.
3377  *
3378  * As a quick review, the IEEE double precision format is as follows:
3379  * sign bit, 11 bits of exponent (bias 1023), and 52 bits of mantissa,
3380  * with a hidden leading one (0.1 binary).
3381  *
3382  * When the exponent is 0, IEEE defines a "denormalized number", which
3383  * is not supported here.
3384  *
3385  * When the exponent is 2047 (all bits set), and:
3386  *      all mantissa bits are zero,
3387  *      value is infinity*sign,
3388  *      mantissa is non-zero, and:
3389  *              msb of mantissa=0:  signaling NAN
3390  *              msb of mantissa=1:  quiet NAN
3391  *
3392  * Note that neither the input or output buffers need be word aligned,
3393  * for greatest flexibility in converting data, even though this
3394  * imposes a speed penalty here.
3395  *
3396  * These subroutines operate on a sequential block of numbers, to save
3397  * on subroutine linkage execution costs, and to allow some hope for
3398  * vectorization.
3399  *
3400  * On brain-damaged machines like the SGI 3-D, where type "double"
3401  * allocates only 4 bytes of space, these routines *still* return 8
3402  * bytes in the IEEE buffer.
3403  *
3404  */
3405 
3406 /**
3407  * Host to Network Doubles
3408  */
3409 BU_EXPORT extern void htond(unsigned char *out,
3410                             const unsigned char *in,
3411                             size_t count);
3412 
3413 /**
3414  * Network to Host Doubles
3415  */
3416 BU_EXPORT extern void ntohd(unsigned char *out,
3417                             const unsigned char *in,
3418                             size_t count);
3419 
3420 /** @file libbu/htonf.c
3421  *
3422  * convert floats to host/network format
3423  *
3424  * Host to Network Floats  +  Network to Host Floats.
3425  *
3426  */
3427 
3428 /**
3429  * Host to Network Floats
3430  */
3431 BU_EXPORT extern void htonf(unsigned char *out,
3432                             const unsigned char *in,
3433                             size_t count);
3434 
3435 /**
3436  * Network to Host Floats
3437  */
3438 BU_EXPORT extern void ntohf(unsigned char *out,
3439                             const unsigned char *in,
3440                             size_t count);
3441 
3442 /** @} */
3443 
3444 /** @addtogroup thread */
3445 /** @ingroup parallel */
3446 /** @{ */
3447 /** @file libbu/parallel.c
3448  *
3449  * subroutine to determine if we are multi-threaded
3450  *
3451  * This subroutine is separated off from parallel.c so that bu_bomb()
3452  * and others can call it, without causing either parallel.c or
3453  * semaphore.c to get referenced and thus causing the loader to drag
3454  * in all the parallel processing stuff from the vendor library.
3455  *
3456  */
3457 
3458 /**
3459  * A clean way for bu_bomb() to tell if this is a parallel
3460  * application.  If bu_parallel() is active, this routine will return
3461  * non-zero.
3462  */
3463 BU_EXPORT extern int bu_is_parallel();
3464 
3465 /**
3466  * Used by bu_bomb() to help terminate parallel threads,
3467  * without dragging in the whole parallel library if it isn't being used.
3468  */
3469 BU_EXPORT extern void bu_kill_parallel();
3470 
3471 /**
3472  * returns the CPU number of the current bu_parallel() invoked thread.
3473  */
3474 BU_EXPORT extern int bu_parallel_id(void);
3475 
3476 
3477 /** @} */
3478 
3479 /** @addtogroup log */
3480 /** @ingroup io */
3481 /** @{ */
3482 /** @file libbu/linebuf.c
3483  *
3484  * A portable way of doing setlinebuf().
3485  *
3486  */
3487 
3488 BU_EXPORT extern void bu_setlinebuf(FILE *fp);
3489 
3490 /** @} */
3491 
3492 /** @addtogroup list */
3493 /** @ingroup container */
3494 /** @{ */
3495 
3496 /**
3497  * Creates and initializes a bu_list head structure
3498  */
3499 BU_EXPORT extern struct bu_list *bu_list_new();
3500 
3501 /**
3502  * Returns the results of BU_LIST_POP
3503  */
3504 BU_EXPORT extern struct bu_list *bu_list_pop(struct bu_list *hp);
3505 
3506 /**
3507  * Returns the number of elements on a bu_list brand linked list.
3508  */
3509 BU_EXPORT extern int bu_list_len(const struct bu_list *hd);
3510 
3511 /**
3512  * Reverses the order of elements in a bu_list linked list.
3513  */
3514 BU_EXPORT extern void bu_list_reverse(struct bu_list *hd);
3515 
3516 /**
3517  * Given a list of structures allocated with bu_malloc() or
3518  * bu_calloc() enrolled on a bu_list head, walk the list and free the
3519  * structures.  This routine can only be used when the structures have
3520  * no interior pointers.
3521  */
3522 BU_EXPORT extern void bu_list_free(struct bu_list *hd);
3523 
3524 /**
3525  * Simple parallel-safe routine for appending a data structure to the
3526  * end of a bu_list doubly-linked list.
3527  *
3528  * @par Issues:
3529  *      Only one semaphore shared by all list heads.
3530  * @n   No portable way to notify waiting thread(s) that are sleeping
3531  */
3532 BU_EXPORT extern void bu_list_parallel_append(struct bu_list *headp,
3533                                               struct bu_list *itemp);
3534 
3535 /**
3536  * Simple parallel-safe routine for dequeueing one data structure from
3537  * the head of a bu_list doubly-linked list.
3538  * If the list is empty, wait until some other thread puts something on
3539  * the list.
3540  *
3541  * @par Issues:
3542  * No portable way to not spin and burn CPU time while waiting
3543  * @n   for something to show up on the list.
3544  */
3545 BU_EXPORT extern struct bu_list *bu_list_parallel_dequeue(struct bu_list *headp);
3546 
3547 /**
3548  * Generic bu_list doubly-linked list checker.
3549  */
3550 BU_EXPORT extern void bu_ck_list(const struct bu_list *hd,
3551                                  const char *str);
3552 
3553 /**
3554  * bu_list doubly-linked list checker which checks the magic number for
3555  * all elements in the linked list
3556  */
3557 BU_EXPORT extern void bu_ck_list_magic(const struct bu_list *hd,
3558                                        const char *str,
3559                                        const uint32_t magic);
3560 
3561 /** @} */
3562 
3563 /** @addtogroup log */
3564 /** @ingroup io */
3565 /** @{ */
3566 /** @file libbu/hook.c
3567  *
3568  * @brief
3569  * BRL-CAD support library's hook utility.
3570  *
3571  */
3572 BU_EXPORT extern void bu_hook_list_init(struct bu_hook_list *hlp);
3573 BU_EXPORT extern void bu_hook_add(struct bu_hook_list *hlp,
3574                                   bu_hook_t func,
3575                                   genptr_t clientdata);
3576 BU_EXPORT extern void bu_hook_delete(struct bu_hook_list *hlp,
3577                                      bu_hook_t func,
3578                                      genptr_t clientdata);
3579 BU_EXPORT extern void bu_hook_call(struct bu_hook_list *hlp,
3580                                    genptr_t buf);
3581 BU_EXPORT extern void bu_hook_save_all(struct bu_hook_list *hlp,
3582                                        struct bu_hook_list *save_hlp);
3583 BU_EXPORT extern void bu_hook_delete_all(struct bu_hook_list *hlp);
3584 BU_EXPORT extern void bu_hook_restore_all(struct bu_hook_list *hlp,
3585                                           struct bu_hook_list *restore_hlp);
3586 
3587 /** @} */
3588 /** @addtogroup log */
3589 /** @ingroup io */
3590 /** @{ */
3591 /** @file libbu/log.c
3592  *
3593  * @brief
3594  * parallel safe version of fprintf for logging
3595  *
3596  * BRL-CAD support library, error logging routine.  Note that the user
3597  * may provide his own logging routine, by replacing these functions.
3598  * That is why this is in file of its own.  For example, LGT and
3599  * RTSRV take advantage of this.
3600  *
3601  * Here is an example of how to set up a custom logging callback.
3602  * While bu_log presently writes to STDERR by default, this behavior
3603  * should not be relied upon and may be changed to STDOUT in the
3604  * future without notice.
3605  *
3606  @code
3607  --- BEGIN EXAMPLE ---
3608 
3609  int log_output_to_file(genptr_t data, genptr_t str)
3610  {
3611    FILE *fp = (FILE *)data;
3612    fprintf(fp, "LOG: %s", str);
3613    return 0;
3614  }
3615 
3616  int main(int ac, char *av[])
3617  {
3618    FILE *fp = fopen("whatever.log", "w+");
3619    bu_log_add_hook(log_output_to_file, (genptr_t)fp);
3620    bu_log("Logging to file.\n");
3621    bu_log_delete_hook(log_output_to_file, (genptr_t)fp);
3622    bu_log("Logging to stderr.\n");
3623    fclose(fp);
3624    return 0;
3625  }
3626 
3627  --- END EXAMPLE ---
3628  @endcode
3629  *
3630  */
3631 
3632 
3633 /**
3634  * Change global indentation level by indicated number of characters.
3635  * Call with a large negative number to cancel all indentation.
3636  */
3637 BU_EXPORT extern void bu_log_indent_delta(int delta);
3638 
3639 /**
3640  * For multi-line vls generators, honor logindent level like bu_log() does,
3641  * and prefix the proper number of spaces.
3642  * Should be called at the front of each new line.
3643  */
3644 BU_EXPORT extern void bu_log_indent_vls(struct bu_vls *v);
3645 
3646 /**
3647  * Adds a hook to the list of bu_log hooks.  The top (newest) one of these
3648  * will be called with its associated client data and a string to be
3649  * processed.  Typically, these hook functions will display the output
3650  * (possibly in an X window) or record it.
3651  *
3652  * NOTE: The hook functions are all non-PARALLEL.
3653  */
3654 BU_EXPORT extern void bu_log_add_hook(bu_hook_t func, genptr_t clientdata);
3655 
3656 /**
3657  * Removes the hook matching the function and clientdata parameters from
3658  * the hook list.  Note that it is not necessarily the active (top) hook.
3659  */
3660 BU_EXPORT extern void bu_log_delete_hook(bu_hook_t func, genptr_t clientdata);
3661 
3662 BU_EXPORT extern void bu_log_hook_save_all(struct bu_hook_list *save_hlp);
3663 BU_EXPORT extern void bu_log_hook_delete_all();
3664 BU_EXPORT extern void bu_log_hook_restore_all(struct bu_hook_list *restore_hlp);
3665 
3666 /**
3667  * Log a single character with no flushing.
3668  */
3669 BU_EXPORT extern void bu_putchar(int c);
3670 
3671 /**
3672  * The routine is primarily called to log library events.
3673  *
3674  * The function is essentially a semaphore-protected version of
3675  * fprintf(stderr) with optional logging hooks and automatic
3676  * indentation options.
3677  */
3678 BU_EXPORT extern void bu_log(const char *, ...) _BU_ATTR_PRINTF12;
3679 
3680 /**
3681  * Log a library event in the Standard way, to a specified file.
3682  */
3683 BU_EXPORT extern void bu_flog(FILE *, const char *, ...) _BU_ATTR_PRINTF23;
3684 
3685 /**
3686  * Custom vsscanf which wraps the system sscanf, and is wrapped by bu_sscanf.
3687  *
3688  * bu_vsscanf differs notably from the underlying system sscanf in that:
3689  *
3690  *  - A maximum field width is required for unsuppressed %s and %[...]
3691  *    conversions. If a %s or %[...] conversion is encountered which does
3692  *    not include a maximum field width, the routine bombs in order to avoid
3693  *    an accidental buffer overrun.
3694  *
3695  *  - %V and %#V have been added as valid conversions. Both expect a pointer to
3696  *    a struct bu_vls as their argument.
3697  *
3698  *    %V is comparable to %[^]. It instructs bu_vsscanf to read arbitrary
3699  *    characters from the source and store them in the vls buffer. The default
3700  *    maximum field width is infinity.
3701  *
3702  *    %#V is comparable to %s. It instructs bu_vsscanf to skip leading
3703  *    whitespace, and then read characters from the source and store them in the
3704  *    vls buffer until the next whitespace character is encountered. The default
3705  *    maximum field width is infinity.
3706  *
3707  *  - 0 is always a valid field width for unsuppressed %c, %s, and %[...]
3708  *    conversions and causes '\0' to be written to the supplied char*
3709  *    argument.
3710  *
3711  *  - a/e/f/g and A/E/F/G are always synonyms for float conversion.
3712  *
3713  *  - The C99 conversions hh[diouxX], z[diouxX], and t[diouxX] are always
3714  *    supported.
3715  *
3716  * This routine has an associated test program named test_sscanf, which
3717  * compares its behavior to the system sscanf.
3718  */
3719 BU_EXPORT extern int bu_vsscanf(const char *src, const char *fmt, va_list ap);
3720 
3721 /**
3722  * Initializes the va_list, then calls bu_vsscanf.
3723  *
3724  * This routine has an associated test program named test_sscanf, which
3725  * compares its behavior to the system sscanf.
3726  */
3727 BU_EXPORT extern int bu_sscanf(const char *src, const char *fmt, ...) _BU_ATTR_SCANF23;
3728 
3729 /** @} */
3730 
3731 /** @addtogroup malloc */
3732 /** @ingroup memory */
3733 /** @{ */
3734 /** @file libbu/malloc.c
3735  *
3736  * @brief
3737  * Parallel-protected debugging-enhanced wrapper around system malloc().
3738  *
3739  * Provides a parallel-safe interface to the system memory allocator
3740  * with standardized error checking, optional memory-use logging, and
3741  * optional run-time pointer and memory corruption testing.
3742  *
3743  * The bu_*alloc() routines can't use bu_log() because that uses the
3744  * bu_vls() routines which depend on bu_malloc().  So it goes direct
3745  * to stderr, semaphore protected.
3746  *
3747  */
3748 
3749 BU_EXPORT extern long bu_n_malloc;
3750 BU_EXPORT extern long bu_n_free;
3751 BU_EXPORT extern long bu_n_realloc;
3752 
3753 /**
3754  * This routine only returns on successful allocation.  We promise
3755  * never to return a NULL pointer; caller doesn't have to check.
3756  * Allocation failure results in bu_bomb() being called.
3757  */
3758 BU_EXPORT extern genptr_t bu_malloc(size_t siz,
3759                                     const char *str);
3760 
3761 /**
3762  * This routine only returns on successful allocation.
3763  * We promise never to return a NULL pointer; caller doesn't have to check.
3764  * Failure results in bu_bomb() being called.
3765  */
3766 BU_EXPORT extern genptr_t bu_calloc(size_t nelem,
3767                                     size_t elsize,
3768                                     const char *str);
3769 
3770 /**
3771  */
3772 BU_EXPORT extern void bu_free(genptr_t ptr,
3773                               const char *str);
3774 
3775 /**
3776  * bu_malloc()/bu_free() compatible wrapper for realloc().
3777  *
3778  * this routine mimics the C99 standard behavior of realloc() except
3779  * that NULL will never be returned.  it will bomb if siz is zero and
3780  * ptr is NULL.  it will return a minimum allocation suitable for
3781  * bu_free() if siz is zero and ptr is non-NULL.
3782  *
3783  * While the string 'str' is provided for the log messages, don't
3784  * disturb the str value, so that this storage allocation can be
3785  * tracked back to its original creator.
3786  */
3787 BU_EXPORT extern genptr_t bu_realloc(genptr_t ptr,
3788                                      size_t siz,
3789                                      const char *str);
3790 
3791 /**
3792  * Print map of memory currently in use.
3793  */
3794 BU_EXPORT extern void bu_prmem(const char *str);
3795 
3796 /**
3797  * On systems with the CalTech malloc(), the amount of storage
3798  * ACTUALLY ALLOCATED is the amount requested rounded UP to the
3799  * nearest power of two.  For structures which are acquired and
3800  * released often, this works well, but for structures which will
3801  * remain unchanged for the duration of the program, this wastes as
3802  * much as 50% of the address space (and usually memory as well).
3803  * Here, we round up a byte size to the nearest power of two, leaving
3804  * off the malloc header, so as to ask for storage without wasting
3805  * any.
3806  *
3807  * On systems with the traditional malloc(), this strategy will just
3808  * consume the memory in somewhat larger chunks, but overall little
3809  * unused memory will be consumed.
3810  */
3811 BU_EXPORT extern int bu_malloc_len_roundup(int nbytes);
3812 
3813 /**
3814  * For a given pointer allocated by bu_malloc(), bu_calloc(), or
3815  * BU_ALLOC() check the magic number stored after the allocation area
3816  * when BU_DEBUG_MEM_CHECK is set.
3817  *
3818  * This is the individual version of bu_mem_barriercheck().
3819  *
3820  * returns if pointer good or BU_DEBUG_MEM_CHECK not set, bombs if
3821  * memory is corrupted.
3822  */
3823 BU_EXPORT extern void bu_ck_malloc_ptr(genptr_t ptr, const char *str);
3824 
3825 /**
3826  * Check *all* entries in the memory debug table for barrier word
3827  * corruption.  Intended to be called periodically through an
3828  * application during debugging.  Has to run single-threaded, to
3829  * prevent table mutation.
3830  *
3831  * This is the bulk version of bu_ck_malloc_ptr()
3832  *
3833  * Returns -
3834  *  -1  something is wrong
3835  *   0  all is OK;
3836  */
3837 BU_EXPORT extern int bu_mem_barriercheck();
3838 
3839 /**
3840  * really fast heap-based memory allocation intended for "small"
3841  * allocation sizes (e.g., single structs).
3842  *
3843  * the implementation allocates chunks of memory ('pages') in order to
3844  * substantially reduce calls to system malloc.  it has a nice
3845  * property of having O(1) constant time complexity and profiles
3846  * significantly faster than system malloc().
3847  *
3848  * release memory with bu_heap_put() only.
3849  */
3850 BU_EXPORT extern void *bu_heap_get(size_t sz);
3851 
3852 /**
3853  * counterpart to bu_heap_get() for releasing fast heap-based memory
3854  * allocations.
3855  *
3856  * the implementation may do nothing, relying on free-on-exit, or may
3857  * mark deallocations for reuse.  pass a NULL pointer and zero size to
3858  * force compaction of any unused memory.
3859  */
3860 BU_EXPORT extern void bu_heap_put(void *ptr, size_t sz);
3861 
3862 /** @} */
3863 
3864 /** @addtogroup log */
3865 /** @ingroup io */
3866 /** @{ */
3867 /** @file libbu/dirname.c
3868  *
3869  * @brief
3870  * Routines to process file and path names.
3871  *
3872  */
3873 
3874 /**
3875  * Given a string containing a hierarchical path, return a dynamic
3876  * string to the parent path.
3877  *
3878  * This function is similar if not identical to most dirname() BSD
3879  * system function implementations; but that system function cannot be
3880  * used due to significantly inconsistent behavior across platforms.
3881  *
3882  * This function always recognizes paths separated by a '/' (i.e.,
3883  * geometry paths) as well as whatever the native platform directory
3884  * separator may be.  It is assumed that all file and directory names
3885  * in the path will not contain a path separator, even if escaped.
3886  *
3887  * It is the caller's responsibility to bu_free() the pointer returned
3888  * from this routine.
3889  *
3890  * Examples of strings returned:
3891  *
3892  *      /usr/dir/file   /usr/dir
3893  * @n   /usr/dir/       /usr
3894  * @n   /usr/file       /usr
3895  * @n   /usr/           /
3896  * @n   /usr            /
3897  * @n   /               /
3898  * @n   .               .
3899  * @n   ..              .
3900  * @n   usr             .
3901  * @n   a/b             a
3902  * @n   a/              .
3903  * @n   ../a/b          ../a
3904  *
3905  * This routine will return "." if other valid results are not available
3906  * but should never return NULL.
3907  */
3908 BU_EXPORT extern char *bu_dirname(const char *path);
3909 
3910 /**
3911  * Given a string containing a hierarchical path, return a dynamic
3912  * string to the portion after the last path separator.
3913  *
3914  * This function is similar if not identical to most basename() BSD
3915  * system function implementations; but that system function cannot be
3916  * used due to significantly inconsistent behavior across platforms.
3917  *
3918  * This function always recognizes paths separated by a '/' (i.e.,
3919  * geometry paths) as well as whatever the native platform directory
3920  * separator may be.  It is assumed that all file and directory names
3921  * in the path will not contain a path separator, even if escaped.
3922  *
3923  * It is the caller's responsibility to bu_free() the pointer returned
3924  * from this routine.
3925  *
3926  * Examples of strings returned:
3927  *
3928  *      /usr/dir/file   file
3929  * @n   /usr/dir/       dir
3930  * @n   /usr/           usr
3931  * @n   /usr            usr
3932  * @n   /               /
3933  * @n   .               .
3934  * @n   ..              ..
3935  * @n   usr             usr
3936  * @n   a/b             b
3937  * @n   a/              a
3938  * @n   ///             /
3939  */
3940 BU_EXPORT extern char *bu_basename(const char *path);
3941 
3942 /** @} */
3943 
3944 /** @addtogroup mf */
3945 /** @ingroup io */
3946 /** @{ */
3947 
3948 /**
3949  * Provides a standardized interface for acquiring the entire contents
3950  * of an existing file mapped into the current address space, using
3951  * the virtual memory capabilities of the operating system (such as
3952  * mmap()) where available, or by allocating sufficient dynamic memory
3953  * and reading the entire file.
3954  *
3955  * If the file can not be opened, as descriptive an error message as
3956  * possible will be printed, to simplify code handling in the caller.
3957  *
3958  * Mapped files are always opened read-only.
3959  *
3960  * If the system does not support mapped files, the data is read into
3961  * memory.
3962  */
3963 BU_EXPORT extern struct bu_mapped_file *bu_open_mapped_file(const char *name,
3964                                                             const char *appl);
3965 
3966 /**
3967  * Release a use of a mapped file.  Because it may be re-used shortly,
3968  * e.g. by the next frame of an animation, don't release the memory
3969  * even on final close, so that it's available when next needed.
3970  *
3971  * Call bu_free_mapped_files() after final close to reclaim space.
3972  * But only do that if you're SURE that ALL these files will never
3973  * again need to be mapped by this process.  Such as when running
3974  * multi-frame animations.
3975  */
3976 BU_EXPORT extern void bu_close_mapped_file(struct bu_mapped_file *mp);
3977 
3978 /**
3979  */
3980 BU_EXPORT extern void bu_pr_mapped_file(const char *title,
3981                                         const struct bu_mapped_file *mp);
3982 
3983 /**
3984  * Release storage being used by mapped files with no remaining users.
3985  * This entire routine runs inside a critical section, for parallel
3986  * protection.  Only call this routine if you're SURE that ALL these
3987  * files will never again need to be mapped by this process.  Such as
3988  * when running multi-frame animations.
3989  */
3990 BU_EXPORT extern void bu_free_mapped_files(int verbose);
3991 
3992 /**
3993  * A wrapper for bu_open_mapped_file() which uses a search path to
3994  * locate the file.
3995  *
3996  * The search path is specified as a normal C argv array, terminated
3997  * by a null string pointer.  If the file name begins with a slash
3998  * ('/') the path is not used.
3999  */
4000 BU_EXPORT extern struct bu_mapped_file *bu_open_mapped_file_with_path(char * const *path,
4001                                                                       const char *name,
4002                                                                       const char *appl);
4003 
4004 
4005 /** @} */
4006 
4007 /** @addtogroup thread */
4008 /** @ingroup parallel */
4009 /** @{ */
4010 /** @file libbu/kill.c
4011  *
4012  * terminate a given process.
4013  *
4014  */
4015 
4016 /**
4017  * terminate a given process.
4018  *
4019  * returns truthfully whether the process could be killed.
4020  */
4021 BU_EXPORT extern int bu_terminate(int process);
4022 
4023 /** @file libbu/process.c
4024  *
4025  * process management routines
4026  *
4027  */
4028 
4029 /**
4030  * returns the process ID of the calling process
4031  */
4032 BU_EXPORT extern int bu_process_id();
4033 
4034 /** @file libbu/parallel.c
4035  *
4036  * routines for parallel processing
4037  *
4038  * Machine-specific routines for portable parallel processing.
4039  *
4040  */
4041 
4042 /**
4043  * Without knowing what the current UNIX "nice" value is, change to a
4044  * new absolute "nice" value.  (The system routine makes a relative
4045  * change).
4046  */
4047 BU_EXPORT extern void bu_nice_set(int newnice);
4048 
4049 /**
4050  * Return the maximum number of physical CPUs that are considered to
4051  * be available to this process now.
4052  */
4053 BU_EXPORT extern int bu_avail_cpus();
4054 
4055 /**
4056  * Create 'ncpu' copies of function 'func' all running in parallel,
4057  * with private stack areas.  Locking and work dispatching are handled
4058  * by 'func' using a "self-dispatching" paradigm.
4059  *
4060  * 'func' is called with one parameter, its thread number.  Threads
4061  * are given increasing numbers, starting with zero.  Processes may
4062  * also call bu_parallel_id() to obtain their thread number.
4063  *
4064  * Threads created with bu_parallel() automatically set CPU affinity
4065  * where available for improved performance.  This behavior can be
4066  * disabled at runtime by setting the LIBBU_AFFINITY environment
4067  * variable to 0.
4068  *
4069  * This function will not return control until all invocations of the
4070  * subroutine are finished.
4071  */
4072 BU_EXPORT extern void bu_parallel(void (*func)(int ncpu, genptr_t arg), int ncpu, genptr_t arg);
4073 
4074 /** @} */
4075 
4076 /** @addtogroup parse */
4077 /** @ingroup container */
4078 /** @{ */
4079 /** @file libbu/parse.c
4080  *
4081  * routines for parsing arbitrary structures
4082  *
4083  * Routines to assign values to elements of arbitrary structures.  The
4084  * layout of a structure to be processed is described by a structure
4085  * of type "bu_structparse", giving element names, element formats, an
4086  * offset from the beginning of the structure, and a pointer to an
4087  * optional "hooked" function that is called whenever that structure
4088  * element is changed.
4089  */
4090 
4091 /**
4092  * ASCII to struct elements.
4093  *
4094  * Parse the structure element description in the vls string "vls"
4095  * according to the structure description in "parsetab"
4096  *
4097  * @return <0 failure
4098  * @return  0 OK
4099  */
4100 BU_EXPORT extern int bu_struct_parse(const struct bu_vls *in_vls,
4101                                      const struct bu_structparse *desc,
4102                                      const char *base);
4103 
4104 /**
4105  * struct elements to ASCII.
4106  */
4107 BU_EXPORT extern void bu_struct_print(const char *title,
4108                                       const struct bu_structparse *parsetab,
4109                                       const char *base);
4110 
4111 /**
4112  * struct elements to machine-independent binary.
4113  *
4114  * copies ext data to base
4115  */
4116 BU_EXPORT extern int bu_struct_export(struct bu_external *ext,
4117                                       const genptr_t base,
4118                                       const struct bu_structparse *imp);
4119 
4120 /**
4121  * machine-independent binary to struct elements.
4122  *
4123  * copies ext data to base
4124  */
4125 BU_EXPORT extern int bu_struct_import(genptr_t base,
4126                                       const struct bu_structparse *imp,
4127                                       const struct bu_external *ext);
4128 
4129 /**
4130  * Put a structure in external form to a stdio file.  All formatting
4131  * must have been accomplished previously.
4132  *
4133  * Returns number of bytes written.  On error, a short byte count (or
4134  * zero) is returned.  Use feof(3) or ferror(3) to determine which
4135  * errors occur.
4136  */
4137 BU_EXPORT extern size_t bu_struct_put(FILE *fp,
4138                                       const struct bu_external *ext);
4139 
4140 /**
4141  * Obtain the next structure in external form from a stdio file.
4142  *
4143  * Returns number of bytes read into the bu_external.  On error, zero
4144  * is returned.
4145  */
4146 BU_EXPORT extern size_t bu_struct_get(struct bu_external *ext,
4147                                       FILE *fp);
4148 
4149 /**
4150  * Given a buffer with an external representation of a structure
4151  * (e.g. the ext_buf portion of the output from bu_struct_export),
4152  * check it for damage in shipment, and if it's OK, wrap it up in an
4153  * bu_external structure, suitable for passing to bu_struct_import().
4154  */
4155 BU_EXPORT extern void bu_struct_wrap_buf(struct bu_external *ext,
4156                                          genptr_t buf);
4157 
4158 /**
4159  * This differs from bu_struct_print in that this output is less
4160  * readable by humans, but easier to parse with the computer.
4161  */
4162 BU_EXPORT extern void bu_vls_struct_print(struct bu_vls *vls,
4163                                           const struct bu_structparse *sdp,
4164                                           const char *base);
4165 
4166 /**
4167  * This differs from bu_struct_print in that it prints to a vls.
4168  */
4169 BU_EXPORT extern void bu_vls_struct_print2(struct bu_vls *vls,
4170                                            const char *title,
4171                                            const struct bu_structparse *sdp,
4172                                            const char *base);
4173 
4174 /**
4175  * Convert a structure element (indicated by sdp) to its ASCII
4176  * representation in a VLS.
4177  */
4178 BU_EXPORT extern void bu_vls_struct_item(struct bu_vls *vp,
4179                                          const struct bu_structparse *sdp,
4180                                          const char *base,
4181                                          int sep_char);
4182 
4183 /**
4184  * Convert a structure element called "name" to an ASCII
4185  * representation in a VLS.
4186  */
4187 BU_EXPORT extern int bu_vls_struct_item_named(struct bu_vls *vp,
4188                                               const struct bu_structparse *sdp,
4189                                               const char *name,
4190                                               const char *base,
4191                                               int sep_char);
4192 
4193 /**
4194  * This allows us to specify the "size" parameter as values like ".5m"
4195  * or "27in" rather than using mm all the time.
4196  */
4197 BU_EXPORT extern void bu_parse_mm(const struct bu_structparse *sdp,
4198                                   const char *name,
4199                                   char *base,
4200                                   const char *value);
4201 
4202 /**
4203  */
4204 BU_EXPORT extern int bu_key_eq_to_key_val(const char *in,
4205                                           const char **next,
4206                                           struct bu_vls *vls);
4207 
4208 /**
4209  * Take an old v4 shader specification of the form
4210  *
4211  *   shadername arg1=value1 arg2=value2 color=1/2/3
4212  *
4213  * and convert it into the v5 {} list form
4214  *
4215  *   shadername {arg1 value1 arg2 value2 color 1/2/3}
4216  *
4217  * Note -- the input string is smashed with nulls.
4218  *
4219  * Note -- the v5 version is used everywhere internally, and in v5
4220  * databases.
4221  *
4222  * @return 1 error
4223  * @return 0 OK
4224  */
4225 BU_EXPORT extern int bu_shader_to_list(const char *in, struct bu_vls *vls);
4226 
4227 /**
4228  *
4229  */
4230 BU_EXPORT extern int bu_shader_to_key_eq(const char *in, struct bu_vls *vls);
4231 
4232 /**
4233  * Take a block of memory, and write it into a file.
4234  *
4235  * Caller is responsible for freeing memory of external representation,
4236  * using bu_free_external().
4237  *
4238  * @return <0 error
4239  * @return  0 OK
4240  */
4241 BU_EXPORT extern int bu_fwrite_external(FILE *fp,
4242                                         const struct bu_external *ep);
4243 
4244 /**
4245  */
4246 BU_EXPORT extern void bu_hexdump_external(FILE *fp, const struct bu_external *ep,
4247                                           const char *str);
4248 
4249 /**
4250  */
4251 BU_EXPORT extern void bu_free_external(struct bu_external *ep);
4252 
4253 /**
4254  */
4255 BU_EXPORT extern void bu_copy_external(struct bu_external *op,
4256                                        const struct bu_external *ip);
4257 
4258 /**
4259  * Advance pointer through string over current token,
4260  * across white space, to beginning of next token.
4261  */
4262 BU_EXPORT extern char *bu_next_token(char *str);
4263 
4264 /**
4265  *
4266  */
4267 BU_EXPORT extern void bu_structparse_get_terse_form(struct bu_vls *logstr,
4268                                                     const struct bu_structparse *sp);
4269 
4270 /**
4271  * Support routine for db adjust and db put.  Much like the
4272  * bu_struct_parse routine which takes its input as a bu_vls. This
4273  * routine, however, takes the arguments as lists, a more Tcl-friendly
4274  * method. There is a log vls for storing messages.
4275  *
4276  * Operates on argv[0] and argv[1], then on argv[2] and argv[3], ...
4277  *
4278  * @param str  - vls for dumping info that might have gone to bu_log
4279  * @param argc - number of elements in argv
4280  * @param argv - contains the keyword-value pairs
4281  * @param desc - structure description
4282  * @param base - base addr of users struct
4283  *
4284  * @retval BRLCAD_OK if successful,
4285  * @retval BRLCAD_ERROR on failure
4286  */
4287 BU_EXPORT extern int bu_structparse_argv(struct bu_vls *str,
4288                                          int argc,
4289                                          const char **argv,
4290                                          const struct bu_structparse *desc,
4291                                          char *base);
4292 
4293 /**
4294  * Skip the separator(s) (i.e. whitespace and open-braces)
4295  *
4296  * @param _cp   - character pointer
4297  */
4298 #define BU_SP_SKIP_SEP(_cp) { \
4299         while (*(_cp) && (*(_cp) == ' ' || *(_cp) == '\n' || \
4300                           *(_cp) == '\t' || *(_cp) == '{'))  ++(_cp); \
4301     }
4302 
4303 
4304 /** @file libbu/booleanize.c
4305  *
4306  * routines for parsing boolean values from strings
4307  */
4308 
4309 /**
4310  * Returns truthfully if a given input string represents an
4311  * "affirmative string".
4312  *
4313  * Input values that are null, empty, begin with the letter 'n', or
4314  * are 0-valued return as false.  Any other input value returns as
4315  * true.  Strings that strongly indicate true return as 1, other
4316  * values still return as true but may be a value greater than 1.
4317  */
4318 BU_EXPORT extern int bu_str_true(const char *str);
4319 
4320 /**
4321  * Returns truthfully if a given input string represents a
4322  * "negative string".
4323  *
4324  * Input values that are null, empty, begin with the letter 'n', or
4325  * are 0-valued return as true.  Any other input value returns as
4326  * false.
4327  */
4328 BU_EXPORT extern int bu_str_false(const char *str);
4329 
4330 
4331 /** @} */
4332 /** @addtogroup bitv */
4333 /** @ingroup container */
4334 /** @{ */
4335 /** @file libbu/printb.c
4336  *
4337  * print bitfields
4338  *
4339  */
4340 
4341 /**
4342  * Format a value a la the %b format of the kernel's printf
4343  *
4344  * @param   vls variable length string to put output in
4345  * @param    s          title string
4346  * @param   v           the integer with the bits in it
4347  * @param   bits        a string which starts with the desired base (8 or 16)
4348  * as \\010 or \\020, followed by
4349  * words preceded with embedded low-value bytes indicating
4350  * bit number plus one,
4351  * in little-endian order, e.g.:
4352  * "\010\2Bit_one\1BIT_zero"
4353  */
4354 BU_EXPORT extern void bu_vls_printb(struct bu_vls *vls,
4355                                     const char *s, unsigned long v,
4356                                     const char *bits);
4357 
4358 /**
4359  * Format and print, like bu_vls_printb().
4360  */
4361 BU_EXPORT extern void bu_printb(const char *s,
4362                                 unsigned long v,
4363                                 const char *bits);
4364 
4365 /** @} */
4366 
4367 /** @addtogroup ptbl */
4368 /** @ingroup container */
4369 /** @{ */
4370 /**
4371  * This collection of routines implements a "pointer table" data
4372  * structure providing a convenient mechanism for managing a collection
4373  * of pointers to objects.  This is useful where the size of the array
4374  * is not known in advance and may change with time.  It's convenient
4375  * to be able to write code that can say "remember this object", and
4376  * then later on iterate through the collection of remembered objects.
4377  *
4378  * When combined with the concept of placing "magic numbers" as the
4379  * first field of each data structure, the pointers to the objects
4380  * become automatically typed.
4381  */
4382 
4383 /**
4384  * Initialize struct & get storage for table.
4385  * Recommend 8 or 64 for initial len.
4386  */
4387 BU_EXPORT extern void bu_ptbl_init(struct bu_ptbl *b,
4388                                    size_t len,
4389                                    const char *str);
4390 
4391 /**
4392  * Reset the table to have no elements, but retain any existing
4393  * storage.
4394  */
4395 BU_EXPORT extern void bu_ptbl_reset(struct bu_ptbl *b);
4396 
4397 /**
4398  * Append/Insert a (long *) item to/into the table.
4399  */
4400 BU_EXPORT extern int bu_ptbl_ins(struct bu_ptbl *b,
4401                                  long *p);
4402 
4403 /**
4404  * locate a (long *) in an existing table
4405  *
4406  *
4407  * @return index of first matching element in array, if found
4408  * @return -1 if not found
4409  *
4410  * We do this a great deal, so make it go as fast as possible.  this
4411  * is the biggest argument I can make for changing to an ordered list.
4412  * Someday....
4413  */
4414 BU_EXPORT extern int bu_ptbl_locate(const struct bu_ptbl *b,
4415                                     const long *p);
4416 
4417 /**
4418  * Set all occurrences of "p" in the table to zero.  This is different
4419  * than deleting them.
4420  */
4421 BU_EXPORT extern void bu_ptbl_zero(struct bu_ptbl *b,
4422                                    const long *p);
4423 
4424 /**
4425  * Append item to table, if not already present.  Unique insert.
4426  *
4427  * @return index of first matching element in array, if found.  (table unchanged)
4428  * @return -1 if table extended to hold new element
4429  *
4430  * We do this a great deal, so make it go as fast as possible.  this
4431  * is the biggest argument I can make for changing to an ordered list.
4432  * Someday....
4433  */
4434 BU_EXPORT extern int bu_ptbl_ins_unique(struct bu_ptbl *b, long *p);
4435 
4436 /**
4437  * Remove all occurrences of an item from a table
4438  *
4439  * @return Number of copies of 'p' that were removed from the table.
4440  * @return 0 if none found.
4441  *
4442  * we go backwards down the table looking for occurrences of p to
4443  * delete.  We do it backwards to reduce the amount of data moved when
4444  * there is more than one occurrence of p in the table.  A pittance
4445  * savings, unless you're doing a lot of it.
4446  */
4447 BU_EXPORT extern int bu_ptbl_rm(struct bu_ptbl *b,
4448                                 const long *p);
4449 
4450 /**
4451  * Catenate one table onto end of another.  There is no checking for
4452  * duplication.
4453  */
4454 BU_EXPORT extern void bu_ptbl_cat(struct bu_ptbl *dest,
4455                                   const struct bu_ptbl *src);
4456 
4457 /**
4458  * Catenate one table onto end of another, ensuring that no entry is
4459  * duplicated.  Duplications between multiple items in 'src' are not
4460  * caught.  The search is a nasty n**2 one.  The tables are expected
4461  * to be short.
4462  */
4463 BU_EXPORT extern void bu_ptbl_cat_uniq(struct bu_ptbl *dest,
4464                                        const struct bu_ptbl *src);
4465 
4466 /**
4467  * Deallocate dynamic buffer associated with a table, and render this
4468  * table unusable without a subsequent bu_ptbl_init().
4469  */
4470 BU_EXPORT extern void bu_ptbl_free(struct bu_ptbl *b);
4471 
4472 /**
4473  * Print a bu_ptbl array for inspection.
4474  */
4475 BU_EXPORT extern void bu_pr_ptbl(const char *title,
4476                                  const struct bu_ptbl *tbl,
4477                                  int verbose);
4478 
4479 /**
4480  * truncate a bu_ptbl
4481  */
4482 BU_EXPORT extern void bu_ptbl_trunc(struct bu_ptbl *tbl,
4483                                     int end);
4484 
4485 /** @} */
4486 
4487 /** @addtogroup rb */
4488 /** @ingroup container */
4489 /** @{ */
4490 /** @file libbu/rb_create.c
4491  *
4492  * Routines to create a red-black tree
4493  *
4494  */
4495 
4496 /**
4497  * Create a red-black tree
4498  *
4499  * This function has three parameters: a comment describing the tree
4500  * to create, the number of linear orders to maintain simultaneously,
4501  * and the comparison functions (one per order).  bu_rb_create()
4502  * returns a pointer to the red-black tree header record.
4503  */
4504 BU_EXPORT extern struct bu_rb_tree *bu_rb_create(char *description, int nm_orders, int (**order_funcs)());
4505 
4506 /**
4507  * Create a single-order red-black tree
4508  *
4509  * This function has two parameters: a comment describing the tree to
4510  * create and a comparison function.  bu_rb_create1() builds an array
4511  * of one function pointer and passes it to bu_rb_create().
4512  * bu_rb_create1() returns a pointer to the red-black tree header
4513  * record.
4514  *
4515  * N.B. - Since this function allocates storage for the array of
4516  * function pointers, in order to avoid memory leaks on freeing the
4517  * tree, applications should call bu_rb_free1(), NOT bu_rb_free().
4518  */
4519 BU_EXPORT extern struct bu_rb_tree *bu_rb_create1(char *description, int (*order_func)());
4520 
4521 /** @file libbu/rb_delete.c
4522  *
4523  * Routines to delete a node from a red-black tree
4524  *
4525  */
4526 
4527 /**
4528  * Applications interface to _rb_delete()
4529  *
4530  * This function has two parameters: the tree and order from which to
4531  * do the deleting.  bu_rb_delete() removes the data block stored in
4532  * the current node (in the position of the specified order) from
4533  * every order in the tree.
4534  */
4535 BU_EXPORT extern void bu_rb_delete(struct bu_rb_tree *tree,
4536                                    int order);
4537 #define bu_rb_delete1(t) bu_rb_delete((t), 0)
4538 
4539 /** @file libbu/rb_diag.c
4540  *
4541  * Diagnostic routines for red-black tree maintenance
4542  *
4543  */
4544 
4545 /**
4546  * Produce a diagnostic printout of a red-black tree
4547  *
4548  * This function has three parameters: the root and order of the tree
4549  * to print out and the type of traversal (preorder, inorder, or
4550  * postorder).
4551  */
4552 BU_EXPORT extern void bu_rb_diagnose_tree(struct bu_rb_tree *tree,
4553                                           int order,
4554                                           int trav_type);
4555 
4556 /**
4557  * Describe a red-black tree
4558  *
4559  * This function has one parameter: a pointer to a red-black tree.
4560  * bu_rb_summarize_tree() prints out the header information for the
4561  * tree.  It is intended for diagnostic purposes.
4562  */
4563 BU_EXPORT extern void bu_rb_summarize_tree(struct bu_rb_tree *tree);
4564 
4565 /** @file libbu/rb_extreme.c
4566  *
4567  * Routines to extract mins, maxes, adjacent, and current nodes
4568  * from a red-black tree
4569  *
4570  */
4571 
4572 
4573 /**
4574  * Applications interface to rb_extreme()
4575  *
4576  * This function has three parameters: the tree in which to find an
4577  * extreme node, the order on which to do the search, and the sense
4578  * (min or max).  On success, bu_rb_extreme() returns a pointer to the
4579  * data in the extreme node.  Otherwise it returns NULL.
4580  */
4581 BU_EXPORT extern void *bu_rb_extreme(struct bu_rb_tree *tree,
4582                                      int order,
4583                                      int sense);
4584 
4585 /**
4586  * Return a node adjacent to the current red-black node
4587  *
4588  * This function has three parameters: the tree and order on which to
4589  * do the search and the sense (min or max, which is to say
4590  * predecessor or successor) of the search.  bu_rb_neighbor() returns
4591  * a pointer to the data in the node adjacent to the current node in
4592  * the specified direction, if that node exists.  Otherwise, it
4593  * returns NULL.
4594  */
4595 BU_EXPORT extern void *bu_rb_neighbor(struct bu_rb_tree *tree,
4596                                       int order,
4597                                       int sense);
4598 
4599 /**
4600  * Return the current red-black node
4601  *
4602  * This function has two parameters: the tree and order in which to
4603  * find the current node.  bu_rb_curr() returns a pointer to the data
4604  * in the current node, if it exists.  Otherwise, it returns NULL.
4605  */
4606 BU_EXPORT extern void *bu_rb_curr(struct bu_rb_tree *tree,
4607                                   int order);
4608 #define bu_rb_curr1(t) bu_rb_curr((t), 0)
4609 
4610 /** @file libbu/rb_free.c
4611  *
4612  * Routines to free a red-black tree
4613  *
4614  */
4615 
4616 /**
4617  * Free a red-black tree
4618  *
4619  * This function has two parameters: the tree to free and a function
4620  * to handle the application data.  bu_rb_free() traverses tree's
4621  * lists of nodes and packages, freeing each one in turn, and then
4622  * frees tree itself.  If free_data is non-NULL, then bu_rb_free()
4623  * calls it just* before freeing each package, passing it the
4624  * package's rbp_data member.  Otherwise, the application data is left
4625  * untouched.
4626  */
4627 BU_EXPORT extern void bu_rb_free(struct bu_rb_tree *tree, void (*free_data)());
4628 #define BU_RB_RETAIN_DATA ((void (*)()) 0)
4629 #define bu_rb_free1(t, f)                                       \
4630     {                                                   \
4631         BU_CKMAG((t), BU_RB_TREE_MAGIC, "red-black tree");      \
4632         bu_free((char *) ((t) -> rbt_order),            \
4633                 "red-black order function");            \
4634         bu_rb_free(t, f);                                       \
4635     }
4636 
4637 /** @file libbu/rb_insert.c
4638  *
4639  * Routines to insert into a red-black tree
4640  *
4641  */
4642 
4643 /**
4644  * Applications interface to _rb_insert()
4645  *
4646  * This function has two parameters: the tree into which to insert the
4647  * new node and the contents of the node.  If a uniqueness requirement
4648  * would be violated, bu_rb_insert() does nothing but return a number
4649  * from the set {-1, -2, ..., -nm_orders} of which the absolute value
4650  * is the first order for which a violation exists.  Otherwise, it
4651  * returns the number of orders for which the new node was equal to a
4652  * node already in the tree.
4653  */
4654 BU_EXPORT extern int bu_rb_insert(struct bu_rb_tree *tree,
4655                                   void *data);
4656 
4657 /**
4658  * Query the uniqueness flag for one order of a red-black tree
4659  *
4660  * This function has two parameters: the tree and the order for which
4661  * to query uniqueness.
4662  */
4663 BU_EXPORT extern int bu_rb_is_uniq(struct bu_rb_tree *tree,
4664                                    int order);
4665 #define bu_rb_is_uniq1(t) bu_rb_is_uniq((t), 0)
4666 
4667 /**
4668  * Set the uniqueness flags for all the linear orders of a red-black
4669  * tree
4670  *
4671  * This function has two parameters: the tree and a bitv_t encoding
4672  * the flag values.  bu_rb_set_uniqv() sets the flags according to the
4673  * bits in flag_rep.  For example, if flag_rep = 1011_2, then the
4674  * first, second, and fourth orders are specified unique, and the
4675  * third is specified not-necessarily unique.
4676  */
4677 BU_EXPORT extern void bu_rb_set_uniqv(struct bu_rb_tree *tree,
4678                                       bitv_t vec);
4679 
4680 /**
4681  * These functions have one parameter: the tree for which to
4682  * require uniqueness/permit nonuniqueness.
4683  */
4684 BU_EXPORT extern void bu_rb_uniq_all_off(struct bu_rb_tree *tree);
4685 
4686 /**
4687  * These functions have one parameter: the tree for which to
4688  * require uniqueness/permit nonuniqueness.
4689  */
4690 BU_EXPORT extern void bu_rb_uniq_all_on(struct bu_rb_tree *tree);
4691 
4692 /**
4693  * Has two parameters: the tree and the order for which to require
4694  * uniqueness/permit nonuniqueness.  Each sets the specified flag to
4695  * the specified value and returns the previous value of the flag.
4696  */
4697 BU_EXPORT extern int bu_rb_uniq_on(struct bu_rb_tree *tree,
4698                                    int order);
4699 #define bu_rb_uniq_on1(t) bu_rb_uniq_on((t), 0)
4700 
4701 /**
4702  * Has two parameters: the tree and the order for which to require
4703  * uniqueness/permit nonuniqueness.  Each sets the specified flag to
4704  * the specified value and returns the previous value of the flag.
4705  */
4706 BU_EXPORT extern int bu_rb_uniq_off(struct bu_rb_tree *tree,
4707                                     int order);
4708 #define bu_rb_uniq_off1(t) bu_rb_uniq_off((t), 0)
4709 
4710 /** @file libbu/rb_order_stats.c
4711  *
4712  * Routines to support order-statistic operations for a red-black tree
4713  *
4714  */
4715 
4716 /**
4717  * Determines the rank of a node in one order of a red-black tree.
4718  *
4719  * This function has two parameters: the tree in which to search and
4720  * the order on which to do the searching.  If the current node is
4721  * null, bu_rb_rank() returns 0.  Otherwise, it returns the rank of
4722  * the current node in the specified order.  bu_rb_rank() is an
4723  * implementation of the routine OS-RANK on p. 283 of Cormen et al.
4724  */
4725 BU_EXPORT extern int bu_rb_rank(struct bu_rb_tree *tree,
4726                                 int order);
4727 #define bu_rb_rank1(t) bu_rb_rank1((t), 0)
4728 
4729 /**
4730  * This function has three parameters: the tree in which to search,
4731  * the order on which to do the searching, and the rank of interest.
4732  * On success, bu_rb_select() returns a pointer to the data block in
4733  * the discovered node.  Otherwise, it returns NULL.
4734  */
4735 BU_EXPORT extern void *bu_rb_select(struct bu_rb_tree *tree,
4736                                     int order,
4737                                     int k);
4738 #define bu_rb_select1(t, k) bu_rb_select((t), 0, (k))
4739 
4740 /** @file libbu/rb_search.c
4741  *
4742  * Routines to search for a node in a red-black tree
4743  *
4744  */
4745 
4746 /**
4747  * This function has three parameters: the tree in which to search,
4748  * the order on which to do the searching, and a data block containing
4749  * the desired value of the key.  On success, bu_rb_search() returns a
4750  * pointer to the data block in the discovered node.  Otherwise, it
4751  * returns NULL.
4752  */
4753 BU_EXPORT extern void *bu_rb_search(struct bu_rb_tree *tree,
4754                                     int order,
4755                                     void *data);
4756 #define bu_rb_search1(t, d) bu_rb_search((t), 0, (d))
4757 
4758 /** @file libbu/rb_walk.c
4759  *
4760  * Routines for traversal of red-black trees
4761  *
4762  * The function burb_walk() is defined in terms of the function
4763  * rb_walk(), which, in turn, calls any of the six functions
4764  *
4765  * @arg         - static void prewalknodes()
4766  * @arg         - static void inwalknodes()
4767  * @arg         - static void postwalknodes()
4768  * @arg         - static void prewalkdata()
4769  * @arg         - static void inwalkdata()
4770  * @arg         - static void postwalkdata()
4771  *
4772  * depending on the type of traversal desired and the objects
4773  * to be visited (nodes themselves, or merely the data stored
4774  * in them).  Each of these last six functions has four parameters:
4775  * the root of the tree to traverse, the order on which to do the
4776  * walking, the function to apply at each visit, and the current
4777  * depth in the tree.
4778  */
4779 
4780 /**
4781  * This function has four parameters: the tree to traverse, the order
4782  * on which to do the walking, the function to apply to each node, and
4783  * the type of traversal (preorder, inorder, or postorder).
4784  */
4785 BU_EXPORT extern void bu_rb_walk(struct bu_rb_tree *tree, int order, void (*visit)(), int trav_type);
4786 #define bu_rb_walk1(t, v, d) bu_rb_walk((t), 0, (v), (d))
4787 
4788 /** @} */
4789 /** @addtogroup thread */
4790 /** @ingroup parallel */
4791 /** @{ */
4792 
4793 /** @file libbu/semaphore.c
4794  *
4795  * semaphore implementation
4796  *
4797  * Machine-specific routines for parallel processing.  Primarily for
4798  * handling semaphores to protect critical sections of code.
4799  *
4800  * The new paradigm: semaphores are referred to, not by a pointer, but
4801  * by a small integer.  This module is now responsible for obtaining
4802  * whatever storage is needed to implement each semaphore.
4803  *
4804  * Note that these routines can't use bu_log() for error logging,
4805  * because bu_log() acquires semaphore #0 (BU_SEM_SYSCALL).
4806  */
4807 
4808 /*
4809  * Section for manifest constants for bu_semaphore_acquire()
4810  */
4811 #define BU_SEM_SYSCALL 0
4812 #define BU_SEM_LISTS 1
4813 #define BU_SEM_BN_NOISE 2
4814 #define BU_SEM_MAPPEDFILE 3
4815 #define BU_SEM_THREAD 4
4816 #define BU_SEM_LAST (BU_SEM_THREAD+1)   /* allocate this many for LIBBU+LIBBN */
4817 /*
4818  * Automatic restart capability in bu_bomb().  The return from
4819  * BU_SETJUMP is the return from the setjmp().  It is 0 on the first
4820  * pass through, and non-zero when re-entered via a longjmp() from
4821  * bu_bomb().  This is only safe to use in non-parallel applications.
4822  */
4823 #define BU_SETJUMP setjmp((bu_setjmp_valid=1, bu_jmpbuf))
4824 #define BU_UNSETJUMP (bu_setjmp_valid=0)
4825 /* These are global because BU_SETJUMP must be macro.  Please don't touch. */
4826 BU_EXPORT extern int bu_setjmp_valid;           /* !0 = bu_jmpbuf is valid */
4827 BU_EXPORT extern jmp_buf bu_jmpbuf;                     /* for BU_SETJUMP() */
4828 
4829 
4830 /**
4831  * Prepare 'nsemaphores' independent critical section semaphores.  Die
4832  * on error.
4833  *
4834  * Takes the place of 'n' separate calls to old RES_INIT().  Start by
4835  * allocating array of "struct bu_semaphores", which has been arranged
4836  * to contain whatever this system needs.
4837  *
4838  */
4839 BU_EXPORT extern void bu_semaphore_init(unsigned int nsemaphores);
4840 
4841 /**
4842  * Release all initialized semaphores and any associated memory.
4843  */
4844 BU_EXPORT extern void bu_semaphore_free();
4845 
4846 /**
4847  * Prepare 'nsemaphores' independent critical section semaphores.  Die
4848  * on error.
4849  */
4850 BU_EXPORT extern void bu_semaphore_reinit(unsigned int nsemaphores);
4851 
4852 /**
4853  */
4854 BU_EXPORT extern void bu_semaphore_acquire(unsigned int i);
4855 
4856 /**
4857  */
4858 BU_EXPORT extern void bu_semaphore_release(unsigned int i);
4859 
4860 /** @} */
4861 /** @addtogroup vls */
4862 /** @ingroup container */
4863 /** @{ */
4864 
4865 /**
4866  * No storage should be allocated at this point, and bu_vls_addr()
4867  * must be able to live with that.
4868  */
4869 BU_EXPORT extern void bu_vls_init(struct bu_vls *vp);
4870 
4871 /**
4872  * DEPRECATED: use if (!vls) bu_vls_init(vls)
4873  *
4874  * If a VLS is uninitialized, initialize it.  If it is already
4875  * initialized, leave it alone, caller wants to append to it.
4876  */
4877 DEPRECATED BU_EXPORT extern void bu_vls_init_if_uninit(struct bu_vls *vp);
4878 
4879 /**
4880  * Allocate storage for a struct bu_vls, call bu_vls_init on it, and
4881  * return the result.  Allows for creation of dynamically allocated
4882  * VLS strings.
4883  */
4884 BU_EXPORT extern struct bu_vls *bu_vls_vlsinit();
4885 
4886 /**
4887  * Return a pointer to the null-terminated string in the vls array.
4888  * If no storage has been allocated yet, give back a valid string.
4889  */
4890 BU_EXPORT extern char *bu_vls_addr(const struct bu_vls *vp);
4891 
4892 /**
4893  * Ensure that the provided VLS has at least 'extra' characters of
4894  * space available.  Additional space is allocated in minimum step
4895  * sized amounts and may allocate more than requested.
4896  */
4897 BU_EXPORT extern void bu_vls_extend(struct bu_vls *vp,
4898                                     unsigned int extra);
4899 
4900 /**
4901  * Ensure that the vls has a length of at least 'newlen', and make
4902  * that the current length.
4903  *
4904  * Useful for subroutines that are planning on mucking with the data
4905  * array themselves.  Not advisable, but occasionally useful.
4906  *
4907  * Does not change the offset from the front of the buffer, if any.
4908  * Does not initialize the value of any of the new bytes.
4909  */
4910 BU_EXPORT extern void bu_vls_setlen(struct bu_vls *vp,
4911                                     size_t newlen);
4912 /**
4913  * Return length of the string, in bytes, not including the null
4914  * terminator.
4915  */
4916 BU_EXPORT extern size_t bu_vls_strlen(const struct bu_vls *vp);
4917 
4918 /**
4919  * Truncate string to at most 'len' characters.  If 'len' is negative,
4920  * trim off that many from the end.  If 'len' is zero, don't release
4921  * storage -- user is probably just going to refill it again,
4922  * e.g. with bu_vls_gets().
4923  */
4924 BU_EXPORT extern void bu_vls_trunc(struct bu_vls *vp,
4925                                    int len);
4926 
4927 /**
4928  * Son of bu_vls_trunc().  Same as bu_vls_trunc() except that it
4929  * doesn't truncate (or do anything) if the len is negative.
4930  */
4931 BU_EXPORT extern void bu_vls_trunc2(struct bu_vls *vp,
4932                                     int len);
4933 
4934 /**
4935  * "Nibble" 'len' characters off the front of the string.  Changes the
4936  * length and offset; no data is copied.
4937  *
4938  * 'len' may be positive or negative. If negative, characters are
4939  * un-nibbled.
4940  */
4941 BU_EXPORT extern void bu_vls_nibble(struct bu_vls *vp,
4942                                     int len);
4943 
4944 /**
4945  * Releases the memory used for the string buffer.
4946  */
4947 BU_EXPORT extern void bu_vls_free(struct bu_vls *vp);
4948 
4949 /**
4950  * Releases the memory used for the string buffer and the memory for
4951  * the vls structure
4952  */
4953 BU_EXPORT extern void bu_vls_vlsfree(struct bu_vls *vp);
4954 /**
4955  * Return a dynamic copy of a vls.  Memory for the string being
4956  * returned is acquired using bu_malloc() implying the caller must
4957  * bu_free() the returned string.
4958  */
4959 BU_EXPORT extern char *bu_vls_strdup(const struct bu_vls *vp);
4960 
4961 /**
4962  * Like bu_vls_strdup(), but destructively grab the string from the
4963  * source argument 'vp'.  This is more efficient than bu_vls_strdup()
4964  * for those instances where the source argument 'vp' is no longer
4965  * needed by the caller, as it avoids a potentially long buffer copy.
4966  *
4967  * The source string is destroyed, as if bu_vls_free() had been
4968  * called.
4969  */
4970 BU_EXPORT extern char *bu_vls_strgrab(struct bu_vls *vp);
4971 
4972 /**
4973  * Empty the vls string, and copy in a regular string.
4974  */
4975 BU_EXPORT extern void bu_vls_strcpy(struct bu_vls *vp,
4976                                     const char *s);
4977 
4978 /**
4979  * Empty the vls string, and copy in a regular string, up to N bytes
4980  * long.
4981  */
4982 BU_EXPORT extern void bu_vls_strncpy(struct bu_vls *vp,
4983                                      const char *s,
4984                                      size_t n);
4985 
4986 /**
4987  * Concatenate a new string onto the end of the existing vls string.
4988  */
4989 BU_EXPORT extern void bu_vls_strcat(struct bu_vls *vp,
4990                                     const char *s);
4991 
4992 /**
4993  * Concatenate a new string onto the end of the existing vls string.
4994  */
4995 BU_EXPORT extern void bu_vls_strncat(struct bu_vls *vp,
4996                                      const char *s,
4997                                      size_t n);
4998 
4999 /**
5000  * Concatenate a new vls string onto the end of an existing vls
5001  * string.  The storage of the source string is not affected.
5002  */
5003 BU_EXPORT extern void bu_vls_vlscat(struct bu_vls *dest,
5004                                     const struct bu_vls *src);
5005 
5006 /**
5007  * Concatenate a new vls string onto the end of an existing vls
5008  * string.  The storage of the source string is released (zapped).
5009  */
5010 BU_EXPORT extern void bu_vls_vlscatzap(struct bu_vls *dest,
5011                                        struct bu_vls *src);
5012 
5013 /**
5014  * Lexicographically compare two vls strings.  Returns an integer
5015  * greater than, equal to, or less than 0, according as the string s1
5016  * is greater than, equal to, or less than the string s2.
5017  */
5018 BU_EXPORT extern int bu_vls_strcmp(struct bu_vls *s1,
5019                                    struct bu_vls *s2);
5020 
5021 /**
5022  * Lexicographically compare two vls strings up to n characters.
5023  * Returns an integer greater than, equal to, or less than 0,
5024  * according as the string s1 is greater than, equal to, or less than
5025  * the string s2.
5026  */
5027 BU_EXPORT extern int bu_vls_strncmp(struct bu_vls *s1,
5028                                     struct bu_vls *s2,
5029                                     size_t n);
5030 
5031 /**
5032  * Given and argc & argv pair, convert them into a vls string of
5033  * space-separated words.
5034  */
5035 BU_EXPORT extern void bu_vls_from_argv(struct bu_vls *vp,
5036                                        int argc,
5037                                        const char *argv[]);
5038 
5039 /**
5040  * Write the VLS to the provided file pointer.
5041  */
5042 BU_EXPORT extern void bu_vls_fwrite(FILE *fp,
5043                                     const struct bu_vls *vp);
5044 
5045 /**
5046  * Write the VLS to the provided file descriptor.
5047  */
5048 BU_EXPORT extern void bu_vls_write(int fd,
5049                                    const struct bu_vls *vp);
5050 
5051 /**
5052  * Read the remainder of a UNIX file onto the end of a vls.
5053  *
5054  * Returns -
5055  * nread number of characters read
5056  *  0 if EOF encountered immediately
5057  * -1 read error
5058  */
5059 BU_EXPORT extern int bu_vls_read(struct bu_vls *vp,
5060                                  int fd);
5061 
5062 /**
5063  * Append a newline-terminated string from the file pointed to by "fp"
5064  * to the end of the vls pointed to by "vp".  The newline from the
5065  * file is read, but not stored into the vls.
5066  *
5067  * The most common error is to forget to bu_vls_trunc(vp, 0) before
5068  * reading the next line into the vls.
5069  *
5070  * Returns -
5071  *   >=0  the length of the resulting vls
5072  *   -1   on EOF where no characters were read or added to the vls
5073  */
5074 BU_EXPORT extern int bu_vls_gets(struct bu_vls *vp,
5075                                  FILE *fp);
5076 
5077 /**
5078  * Append the given character to the vls.
5079  */
5080 BU_EXPORT extern void bu_vls_putc(struct bu_vls *vp,
5081                                   int c);
5082 
5083 /**
5084  * Remove leading and trailing white space from a vls string.
5085  */
5086 BU_EXPORT extern void bu_vls_trimspace(struct bu_vls *vp);
5087 
5088 
5089 /**
5090  * Format a string into a vls using a varargs list.
5091  *
5092  * %s continues to be a regular null-terminated 'C' string (char *).
5093  * %V is a libbu variable-length string (struct bu_vls *).
5094  *
5095  * Other format specifiers should behave identical to printf().
5096  *
5097  * This routine appends to the given vls similar to how vprintf
5098  * appends to stdout (see bu_vls_sprintf for overwriting the vls).
5099  */
5100 BU_EXPORT extern void bu_vls_vprintf(struct bu_vls *vls,
5101                                      const char *fmt,
5102                                      va_list ap);
5103 
5104 /**
5105  * Format a string into a vls using standard variable arguments.
5106  *
5107  * %s continues to be a regular null-terminated 'C' string (char *).
5108  * %V is a libbu variable-length string (struct bu_vls *).
5109  *
5110  * Other format specifiers should behave identical to printf().
5111  *
5112  * This routine appends to the given vls similar to how vprintf
5113  * appends to stdout (see bu_vls_sprintf for overwriting the vls).
5114  * The implementation ends up calling bu_vls_vprintf().
5115  */
5116 BU_EXPORT extern void bu_vls_printf(struct bu_vls *vls,
5117                                     const char *fmt, ...) _BU_ATTR_PRINTF23;
5118 
5119 /**
5120  * Format a string into a vls, setting the vls to the given print
5121  * specifier expansion.  This routine truncates any existing vls
5122  * contents beforehand (i.e. it doesn't append, see bu_vls_vprintf for
5123  * appending to the vls).
5124  *
5125  * %s continues to be a regular 'C' string, null terminated.
5126  * %V is a pointer to a (struct bu_vls *) string.
5127  */
5128 BU_EXPORT extern void bu_vls_sprintf(struct bu_vls *vls,
5129                                      const char *fmt, ...) _BU_ATTR_PRINTF23;
5130 
5131 /**
5132  * Efficiently append 'cnt' spaces to the current vls.
5133  */
5134 BU_EXPORT extern void bu_vls_spaces(struct bu_vls *vp,
5135                                     int cnt);
5136 
5137 /**
5138  * Returns number of printed spaces used on final output line of a
5139  * potentially multi-line vls.  Useful for making decisions on when to
5140  * line-wrap.
5141  *
5142  * Accounts for normal UNIX tab-expansion:
5143  *               1         2         3         4
5144  *      1234567890123456789012345678901234567890
5145  *              x       x       x       x
5146  *
5147  *      0-7 --> 8, 8-15 --> 16, 16-23 --> 24, etc.
5148  */
5149 BU_EXPORT extern int bu_vls_print_positions_used(const struct bu_vls *vp);
5150 
5151 /**
5152  * Given a vls, return a version of that string which has had all
5153  * "tab" characters converted to the appropriate number of spaces
5154  * according to the UNIX tab convention.
5155  */
5156 BU_EXPORT extern void bu_vls_detab(struct bu_vls *vp);
5157 
5158 /**
5159  * Add a string to the beginning of the vls.
5160  */
5161 BU_EXPORT extern void bu_vls_prepend(struct bu_vls *vp,
5162                                      char *str);
5163 
5164 /**
5165  * given an input string, wrap the string in double quotes if there is
5166  * a space and append it to the provided bu_vls.  escape any existing
5167  * double quotes.
5168  *
5169  * TODO: consider a specifiable quote character and octal encoding
5170  * instead of double quote wrapping.  perhaps specifiable encode type:
5171  *   BU_ENCODE_QUOTE
5172  *   BU_ENCODE_OCTAL
5173  *   BU_ENCODE_XML
5174  *
5175  * the behavior of this routine is subject to change but should remain
5176  * a reversible operation when used in conjunction with
5177  * bu_vls_decode().
5178  *
5179  * returns a pointer to the encoded string (i.e., the substring held
5180  * within the bu_vls)
5181  */
5182 BU_EXPORT extern const char *bu_vls_encode(struct bu_vls *vp, const char *str);
5183 
5184 
5185 /**
5186  * given an encoded input string, unwrap the string from any
5187  * surrounding double quotes and unescape any embedded double quotes.
5188  *
5189  * the behavior of this routine is subject to change but should remain
5190  * the reverse operation of bu_vls_encode().
5191  *
5192  * returns a pointer to the decoded string (i.e., the substring held
5193  * within the bu_vls)
5194  */
5195 BU_EXPORT extern const char *bu_vls_decode(struct bu_vls *vp, const char *str);
5196 
5197 
5198 /** @} */
5199 /** @addtogroup vlb */
5200 /** @ingroup container */
5201 /** @{ */
5202 
5203 /**
5204  * Initialize the specified bu_vlb structure and mallocs the initial
5205  * block of memory.
5206  *
5207  * @param vlb Pointer to an uninitialized bu_vlb structure
5208  */
5209 BU_EXPORT extern void bu_vlb_init(struct bu_vlb *vlb);
5210 
5211 /**
5212  * Initialize the specified bu_vlb structure and mallocs the initial
5213  * block of memory with the specified size
5214  *
5215  * @param vlb Pointer to an uninitialized bu_vlb structure
5216  * @param initialSize The desired initial size of the buffer
5217  */
5218 BU_EXPORT extern void bu_vlb_initialize(struct bu_vlb *vlb,
5219                                         size_t initialSize);
5220 
5221 /**
5222  * Write some bytes to the end of the bu_vlb structure. If necessary,
5223  * additional memory will be allocated.
5224  *
5225  * @param vlb Pointer to the bu_vlb structure to receive the bytes
5226  * @param start Pointer to the first byte to be copied to the bu_vlb structure
5227  * @param len The number of bytes to copy to the bu_vlb structure
5228  */
5229 BU_EXPORT extern void bu_vlb_write(struct bu_vlb *vlb,
5230                                    unsigned char *start,
5231                                    size_t len);
5232 
5233 /**
5234  * Reset the bu_vlb counter to the start of its byte array. This
5235  * essentially ignores any bytes currently in the buffer, but does not
5236  * free any memory.
5237  *
5238  * @param vlb Pointer to the bu_vlb structure to be reset
5239  */
5240 BU_EXPORT extern void bu_vlb_reset(struct bu_vlb *vlb);
5241 
5242 /**
5243  * Get a pointer to the byte array held by the bu_vlb structure
5244  *
5245  * @param vlb Pointer to the bu_vlb structure
5246  * @return A pointer to the byte array contained by the bu_vlb structure
5247  */
5248 BU_EXPORT extern unsigned char *bu_vlb_addr(struct bu_vlb *vlb);
5249 
5250 /**
5251  * Return the number of bytes used in the bu_vlb structure
5252  *
5253  * @param vlb Pointer to the bu_vlb structure
5254  * @return The number of bytes written to the bu_vlb structure
5255  */
5256 BU_EXPORT extern size_t bu_vlb_buflen(struct bu_vlb *vlb);
5257 
5258 /**
5259  * Free the memory allocated for the byte array in the bu_vlb
5260  * structure.  Also uninitializes the structure.
5261  *
5262  * @param vlb Pointer to the bu_vlb structure
5263  */
5264 BU_EXPORT extern void bu_vlb_free(struct bu_vlb *vlb);
5265 /**
5266  * Write the current byte array from the bu_vlb structure to a file
5267  *
5268  * @param vlb Pointer to the bu_vlb structure that is the source of the bytes
5269  * @param fd Pointer to a FILE to receive the bytes
5270  */
5271 BU_EXPORT extern void bu_vlb_print(struct bu_vlb *vlb,
5272                                    FILE *fd);
5273 
5274 /**
5275  * Print the bytes set in a variable-length byte array.
5276  */
5277 BU_EXPORT extern void bu_pr_vlb(const char *title, const struct bu_vlb *vlb);
5278 
5279 
5280 /** @file libbu/str.c
5281  *
5282  * Compatibility routines to various string processing functions
5283  * including strlcat and strlcpy.
5284  *
5285  */
5286 
5287 /**
5288  * concatenate one string onto the end of another, returning the
5289  * length of the dst string after the concatenation.
5290  *
5291  * bu_strlcat() is a macro to bu_strlcatm() so that we can report the
5292  * file name and line number of any erroneous callers.
5293  */
5294 BU_EXPORT extern size_t bu_strlcatm(char *dst, const char *src, size_t size, const char *label);
5295 #define bu_strlcat(dst, src, size) bu_strlcatm(dst, src, size, BU_FLSTR)
5296 
5297 /**
5298  * copies one string into another, returning the length of the dst
5299  * string after the copy.
5300  *
5301  * bu_strlcpy() is a macro to bu_strlcpym() so that we can report the
5302  * file name and line number of any erroneous callers.
5303  */
5304 BU_EXPORT extern size_t bu_strlcpym(char *dst, const char *src, size_t size, const char *label);
5305 #define bu_strlcpy(dst, src, size) bu_strlcpym(dst, src, size, BU_FLSTR)
5306 
5307 /**
5308  * Given a string, allocate enough memory to hold it using
5309  * bu_malloc(), duplicate the strings, returns a pointer to the new
5310  * string.
5311  *
5312  * bu_strdup() is a macro that includes the current file name and line
5313  * number that can be used when bu debugging is enabled.
5314  */
5315 BU_EXPORT extern char *bu_strdupm(const char *cp, const char *label);
5316 #define bu_strdup(s) bu_strdupm(s, BU_FLSTR)
5317 
5318 /**
5319  * Compares two strings for equality.  It performs the comparison more
5320  * robustly than the standard library's strcmp() function by defining
5321  * consistent behavior for NULL and empty strings.  It accepts NULL as
5322  * valid input values and considers "" and NULL as equal.  Returns 0
5323  * if the strings match.
5324  */
5325 BU_EXPORT extern int bu_strcmp(const char *string1, const char *string2);
5326 
5327 /**
5328  * Compares two strings for equality.  No more than n-characters are
5329  * compared.  It performs the comparison more robustly than the
5330  * standard library's strncmp() function by defining consistent
5331  * behavior for NULL and empty strings.  It accepts NULL as valid
5332  * input values and considers "" and NULL as equal.  Returns 0 if the
5333  * strings match.
5334  */
5335 BU_EXPORT extern int bu_strncmp(const char *string1, const char *string2, size_t n);
5336 
5337 /**
5338  * Compares two strings for equality without regard for the case in
5339  * the string.  It performs the comparison more robustly than the
5340  * standard strcasecmp()/stricmp() function by defining consistent
5341  * behavior for NULL and empty strings.  It accepts NULL as valid
5342  * input values and considers "" and NULL as equal.  Returns 0 if the
5343  * strings match.
5344  */
5345 BU_EXPORT extern int bu_strcasecmp(const char *string1, const char *string2);
5346 
5347 /**
5348  * Compares two strings for equality without regard for the case in
5349  * the string.  No more than n-characters are compared.  It performs
5350  * the comparison more robustly than the standard
5351  * strncasecmp()/strnicmp() function by defining consistent behavior
5352  * for NULL and empty strings.  It accepts NULL as valid input values
5353  * and considers "" and NULL as equal.  Returns 0 if the strings
5354  * match.
5355  */
5356 BU_EXPORT extern int bu_strncasecmp(const char *string1, const char *string2, size_t n);
5357 
5358 /**
5359  * BU_STR_EMPTY() is a convenience macro that tests a string for
5360  * emptiness, i.e. "" or NULL.
5361  */
5362 #define BU_STR_EMPTY(s) (bu_strcmp((s), "") == 0)
5363 
5364 /**
5365  * BU_STR_EQUAL() is a convenience macro for testing two
5366  * null-terminated strings for equality.  It is equivalent to
5367  * (bu_strcmp(s1, s2) == 0) whereby NULL strings are allowed and
5368  * equivalent to an empty string.  Evaluates true when the strings
5369  * match and false if they do not.
5370  */
5371 #define BU_STR_EQUAL(s1, s2) (bu_strcmp((s1), (s2)) == 0)
5372 
5373 /**
5374  * BU_STR_EQUIV() is a convenience macro that compares two
5375  * null-terminated strings for equality without regard for case.  Two
5376  * strings are equivalent if they are a case-insensitive match.  NULL
5377  * strings are allowed and equivalent to an empty string.  Evaluates
5378  * true if the strings are similar and false if they are not.
5379  */
5380 #define BU_STR_EQUIV(s1, s2) (bu_strcasecmp((s1), (s2)) == 0)
5381 
5382 
5383 /** @file escape.c
5384  *
5385  * These routines implement support for escaping and unescaping
5386  * generalized strings that may represent filesystem paths, URLs,
5387  * object lists, and more.
5388  *
5389  */
5390 
5391 /**
5392  * Escapes an input string with preceding '\'s for any characters
5393  * defined in the 'expression' string.  The input string is written to the
5394  * specified output buffer of 'size' capacity.  The input and output
5395  * pointers may overlap or be the same memory (assuming adequate space
5396  * is available).  If 'output' is NULL, then dynamic memory will be
5397  * allocated and returned.
5398  *
5399  * The 'expression' parameter is a regular "bracket expression"
5400  * commonly used in globbing and POSIX regular expression character
5401  * matching.  An expression can be either a matching list (default) or
5402  * a non-matching list (starting with a circumflex '^' character).
5403  * For example, "abc" matches any of the characters 'a', 'b', or 'c'.
5404  * Specifying a non-matching list expression matches any character
5405  * except for the ones listed after the circumflex.  For example,
5406  * "^abc" matches any character except 'a', 'b', or 'c'.
5407  *
5408  * Backslash escape sequences are not allowed (e.g., \t or \x01) as
5409  * '\' will be matched literally.
5410  *
5411  * A range expression consists of two characters separated by a hyphen
5412  * and will match any single character between the two characters.
5413  * For example, "0-9a-c" is equivalent to "0123456789abc".  To match a
5414  * '-' dash literally, include it as the last or first (after any '^')
5415  * character within the expression.
5416  *
5417  * The expression may also contain named character classes but only
5418  * for ASCII input strings:
5419  *
5420  * [:alnum:] Alphanumeric characters: a-zA-Z0-9
5421  * [:alpha:] Alphabetic characters: a-zA-Z
5422  * [:blank:] Space and TAB characters
5423  * [:cntrl:] Control characters: ACSII 0x00-0X7F
5424  * [:digit:] Numeric characters: 0-9
5425  * [:graph:] Characters that are both printable and visible: ASCII 0x21-0X7E
5426  * [:lower:] Lowercase alphabetic characters: a-z
5427  * [:print:] Visible and space characters (not control characters): ASCII 0x20-0X7E
5428  * [:punct:] Punctuation characters (not letters, digits, control, or space): ][!"#$%&'()*+,./:;<=>?@^_`{|}~-\
5429  * [:upper:] Uppercase alphabetic characters: A-Z
5430  * [:xdigit:] Hexadecimal digits: a-fA-F0-9
5431  * [:word:] (non-POSIX) Alphanumeric plus underscore: a-zA-Z0-9_
5432  *
5433  * A non-NULL output string is always returned.  This allows
5434  * expression chaining and embedding as function arguments but care
5435  * should be taken to free the dynamic memory being returned when
5436  * 'output' is NULL.
5437  *
5438  * If output 'size' is inadequate for holding the escaped input
5439  * string, bu_bomb() is called.
5440  *
5441  * Example:
5442  *   char *result;
5443  *   char buf[128];
5444  *   result = bu_str_escape("my fair lady", " ", buf, 128);
5445  *   :: result == buf == "my\ fair\ lady"
5446  *   result = bu_str_escape(buf, "\", NULL, 0);
5447  *   :: result == "my\\ fair\\ lady"
5448  *   :: buf == "my\ fair\ lady"
5449  *   bu_free(result, "bu_str_escape");
5450  *   result = bu_str_escape(buf, "a-zA-Z", buf, 128);
5451  *   :: result == buf == "\m\y\ \f\a\i\r\ \l\a\d\y"
5452  *
5453  * This function should be thread safe and re-entrant if the
5454  * input/output buffers are not shared (and strlen() is threadsafe).
5455  */
5456 BU_EXPORT extern char *bu_str_escape(const char *input, const char *expression, char *output, size_t size);
5457 
5458 /**
5459  * Removes one level of '\' escapes from an input string.  The input
5460  * string is written to the specified output buffer of 'size'
5461  * capacity.  The input and output pointers may overlap or be the same
5462  * memory.  If 'output' is NULL, then dynamic memory will be allocated
5463  * and returned.
5464  *
5465  * A non-NULL output string is always returned.  This allows
5466  * expression chaining and embedding as function arguments but care
5467  * should be taken to free the dynamic memory being returned when
5468  * 'output' is NULL.
5469  *
5470  * If output 'size' is inadequate for holding the unescaped input
5471  * string, bu_bomb() is called.
5472  *
5473  * Example:
5474  *   char *result;
5475  *   char buf[128];
5476  *   result = bu_str_unescape("\m\y\\ \f\a\i\r\\ \l\a\d\y", buf, 128);
5477  *   :: result == buf == "my\ fair\ lady"
5478  *   result = bu_str_unescape(buf, NULL, 0);
5479  *   :: result == "my fair lady"
5480  *   :: buf == "my\ fair\ lady"
5481  *   bu_free(result, "bu_str_unescape");
5482  *
5483  * This function should be thread safe and re-entrant if the
5484  * input/output buffers are not shared (and strlen() is threadsafe).
5485  */
5486 BU_EXPORT extern char *bu_str_unescape(const char *input, char *output, size_t size);
5487 
5488 
5489 /** @} */
5490 
5491 /** @addtogroup log */
5492 /** @ingroup io */
5493 /** @{ */
5494 
5495 /** @file libbu/units.c
5496  *
5497  * Module of libbu to handle units conversion between strings and mm.
5498  *
5499  */
5500 
5501 /**
5502  * Given a string representation of a unit of distance (e.g., "feet"),
5503  * return the multiplier which will convert that unit into the default
5504  * unit for the dimension (millimeters for length, mm^3 for volume,
5505  * and grams for mass.)
5506  *
5507  * Returns 0.0 on error and >0.0 on success
5508  */
5509 BU_EXPORT extern double bu_units_conversion(const char *str);
5510 
5511 /**
5512  * Given a conversion factor to mm, search the table to find what unit
5513  * this represents.
5514  *
5515  * To accommodate floating point fuzz, a "near miss" is allowed.  The
5516  * algorithm depends on the table being sorted small-to-large.
5517  *
5518  * Returns -
5519  * char* units string
5520  * NULL No known unit matches this conversion factor.
5521  */
5522 BU_EXPORT extern const char *bu_units_string(const double mm);
5523 BU_EXPORT extern struct bu_vls *bu_units_strings_vls();
5524 
5525 /**
5526  * Given a conversion factor to mm, search the table to find the
5527  * closest matching unit.
5528  *
5529  * Returns -
5530  * char* units string
5531  * NULL Invalid conversion factor (non-positive)
5532  */
5533 BU_EXPORT extern const char *bu_nearest_units_string(const double mm);
5534 
5535 /**
5536  * Given a string of the form "25cm" or "5.2ft" returns the
5537  * corresponding distance in mm.
5538  *
5539  * Returns -
5540  * -1 on error
5541  * >0 on success
5542  */
5543 BU_EXPORT extern double bu_mm_value(const char *s);
5544 
5545 /**
5546  * Used primarily as a hooked function for bu_structparse tables to
5547  * allow input of floating point values in other units.
5548  */
5549 BU_EXPORT extern void bu_mm_cvt(const struct bu_structparse *sdp,
5550                                 const char *name,
5551                                 char *base,
5552                                 const char *value);
5553 
5554 /** @} */
5555 
5556 /** @addtogroup hton */
5557 /** @ingroup data */
5558 /** @{ */
5559 /** @file libbu/htester.c
5560  *
5561  * @brief
5562  * Test network float conversion.
5563  *
5564  * Expected to be used in pipes, or with TTCP links to other machines,
5565  * or with files RCP'ed between machines.
5566  *
5567  */
5568 
5569 /** @file libbu/xdr.c
5570  *
5571  * DEPRECATED.
5572  *
5573  * Routines to implement an external data representation (XDR)
5574  * compatible with the usual InterNet standards, e.g.:
5575  * big-endian, twos-compliment fixed point, and IEEE floating point.
5576  *
5577  * Routines to insert/extract short/long's into char arrays,
5578  * independent of machine byte order and word-alignment.
5579  * Uses encoding compatible with routines found in libpkg,
5580  * and BSD system routines htonl(), htons(), ntohl(), ntohs().
5581  *
5582  */
5583 
5584 /**
5585  * DEPRECATED: use ntohll()
5586  * Macro version of library routine bu_glonglong()
5587  * The argument is expected to be of type "unsigned char *"
5588  */
5589 #define BU_GLONGLONG(_cp)       \
5590     ((((uint64_t)((_cp)[0])) << 56) |   \
5591      (((uint64_t)((_cp)[1])) << 48) |   \
5592      (((uint64_t)((_cp)[2])) << 40) |   \
5593      (((uint64_t)((_cp)[3])) << 32) |   \
5594      (((uint64_t)((_cp)[4])) << 24) |   \
5595      (((uint64_t)((_cp)[5])) << 16) |   \
5596      (((uint64_t)((_cp)[6])) <<  8) |   \
5597      ((uint64_t)((_cp)[7])))
5598 /**
5599  * DEPRECATED: use ntohl()
5600  * Macro version of library routine bu_glong()
5601  * The argument is expected to be of type "unsigned char *"
5602  */
5603 #define BU_GLONG(_cp)   \
5604     ((((uint32_t)((_cp)[0])) << 24) |   \
5605      (((uint32_t)((_cp)[1])) << 16) |   \
5606      (((uint32_t)((_cp)[2])) <<  8) |   \
5607      ((uint32_t)((_cp)[3])))
5608 /**
5609  * DEPRECATED: use ntohs()
5610  * Macro version of library routine bu_gshort()
5611  * The argument is expected to be of type "unsigned char *"
5612  */
5613 #define BU_GSHORT(_cp)  \
5614     ((((uint16_t)((_cp)[0])) << 8) | \
5615      (_cp)[1])
5616 
5617 /**
5618  * DEPRECATED: use ntohs()
5619  */
5620 DEPRECATED BU_EXPORT extern uint16_t bu_gshort(const unsigned char *msgp);
5621 
5622 /**
5623  * DEPRECATED: use ntohl()
5624  */
5625 DEPRECATED BU_EXPORT extern uint32_t bu_glong(const unsigned char *msgp);
5626 
5627 /**
5628  * DEPRECATED: use htons()
5629  */
5630 DEPRECATED BU_EXPORT extern unsigned char *bu_pshort(unsigned char *msgp, uint16_t s);
5631 
5632 /**
5633  * DEPRECATED: use htonl()
5634  */
5635 DEPRECATED BU_EXPORT extern unsigned char *bu_plong(unsigned char *msgp, uint32_t l);
5636 
5637 /**
5638  * DEPRECATED: use htonll()
5639  */
5640 DEPRECATED BU_EXPORT extern unsigned char *bu_plonglong(unsigned char *msgp, uint64_t l);
5641 
5642 /** @} */
5643 
5644 /** @addtogroup tcl */
5645 /** @ingroup binding */
5646 /** @{ */
5647 /** @file libbu/observer.c
5648  *
5649  * @brief
5650  * Routines for implementing the observer pattern.
5651  *
5652  */
5653 
5654 /**
5655  * runs a given command, calling the corresponding observer callback
5656  * if it matches.
5657  */
5658 BU_EXPORT extern int bu_observer_cmd(void *clientData, int argc, const char *argv[]);
5659 
5660 /**
5661  * Notify observers.
5662  */
5663 BU_EXPORT extern void bu_observer_notify(Tcl_Interp *interp, struct bu_observer *headp, char *self);
5664 
5665 /**
5666  * Free observers.
5667  */
5668 BU_EXPORT extern void bu_observer_free(struct bu_observer *);
5669 
5670 /**
5671  * Bu_Init
5672  *
5673  * Allows LIBBU to be dynamically loaded to a vanilla tclsh/wish with
5674  * "load /usr/brlcad/lib/libbu.so"
5675  *
5676  * @param interp        - tcl interpreter in which this command was registered.
5677  *
5678  * @return BRLCAD_OK if successful, otherwise, BRLCAD_ERROR.
5679  */
5680 BU_EXPORT extern int Bu_Init(void *interp);
5681 
5682 
5683 /** @} */
5684 
5685 /** @addtogroup log */
5686 /** @ingroup io */
5687 /** @{ */
5688 /** @file libbu/lex.c
5689  *
5690  */
5691 
5692 #define BU_LEX_ANY 0    /* pseudo type */
5693 struct bu_lex_t_int {
5694     int type;
5695     int value;
5696 };
5697 #define BU_LEX_INT 1
5698 struct bu_lex_t_dbl {
5699     int type;
5700     double value;
5701 };
5702 #define BU_LEX_DOUBLE 2
5703 struct bu_lex_t_key {
5704     int type;
5705     int value;
5706 };
5707 #define BU_LEX_SYMBOL 3
5708 #define BU_LEX_KEYWORD 4
5709 struct bu_lex_t_id {
5710     int type;
5711     char *value;
5712 };
5713 #define BU_LEX_IDENT 5
5714 #define BU_LEX_NUMBER 6 /* Pseudo type */
5715 union bu_lex_token {
5716     int type;
5717     struct bu_lex_t_int t_int;
5718     struct bu_lex_t_dbl t_dbl;
5719     struct bu_lex_t_key t_key;
5720     struct bu_lex_t_id t_id;
5721 };
5722 struct bu_lex_key {
5723     int tok_val;
5724     char *string;
5725 };
5726 #define BU_LEX_NEED_MORE 0
5727 
5728 
5729 /**
5730  */
5731 BU_EXPORT extern int bu_lex(union bu_lex_token *token,
5732                             struct bu_vls *rtstr,
5733                             struct bu_lex_key *keywords,
5734                             struct bu_lex_key *symbols);
5735 
5736 
5737 /** @file libbu/mread.c
5738  *
5739  * multiple-read to fill a buffer
5740  *
5741  * Provide a general means to a read some count of items from a file
5742  * descriptor reading multiple times until the quantity desired is
5743  * obtained.  This is useful for pipes and network connections that
5744  * don't necessarily deliver data with the same grouping as it is
5745  * written with.
5746  *
5747  * If a read error occurs, a negative value will be returns and errno
5748  * should be set (by read()).
5749  *
5750  */
5751 
5752 /**
5753  * "Multiple try" read.  Read multiple times until quantity is
5754  * obtained or an error occurs.  This is useful for pipes.
5755  */
5756 BU_EXPORT extern long int bu_mread(int fd, void *bufp, long int n);
5757 
5758 /** @} */
5759 
5760 /** @addtogroup hash */
5761 /** @ingroup container */
5762 /** @{ */
5763 /** @file libbu/hash.c
5764  *
5765  * @brief
5766  * An implementation of hash tables.
5767  */
5768 
5769 /**
5770  * A hash entry
5771  */
5772 struct bu_hash_entry {
5773     uint32_t magic;
5774     unsigned char *key;
5775     unsigned char *value;
5776     int key_len;
5777     struct bu_hash_entry *next;
5778 };
5779 typedef struct bu_hash_entry bu_hash_entry_t;
5780 #define BU_HASH_ENTRY_NULL ((struct bu_hash_entry *)0)
5781 
5782 /**
5783  * asserts the integrity of a non-head node bu_hash_entry struct.
5784  */
5785 #define BU_CK_HASH_ENTRY(_ep) BU_CKMAG(_ep, BU_HASH_ENTRY_MAGIC, "bu_hash_entry")
5786 
5787 /**
5788  * initializes a bu_hash_entry struct without allocating any memory.
5789  */
5790 #define BU_HASH_ENTRY_INIT(_h) { \
5791         (_h)->magic = BU_HASH_ENTRY_MAGIC; \
5792         (_h)->key = (_h)->value = NULL; \
5793         (_h)->key_len = 0; \
5794         (_h)->next = NULL; \
5795     }
5796 
5797 /**
5798  * macro suitable for declaration statement initialization of a
5799  * bu_hash_entry struct.  does not allocate memory.
5800  */
5801 #define BU_HASH_ENTRY_INIT_ZERO { BU_HASH_ENTRY_MAGIC, NULL, NULL, 0, NULL }
5802 
5803 /**
5804  * returns truthfully whether a bu_hash_entry has been initialized.
5805  */
5806 #define BU_HASH_ENTRY_IS_INITIALIZED(_h) (((struct bu_hash_entry *)(_h) != BU_HASH_ENTRY_NULL) && LIKELY((_h)->magic == BU_HASH_ENTRY_MAGIC))
5807 
5808 
5809 /**
5810  * A table of hash entries
5811  */
5812 struct bu_hash_tbl {
5813     uint32_t magic;
5814     unsigned long mask;
5815     unsigned long num_lists;
5816     unsigned long num_entries;
5817     struct bu_hash_entry **lists;
5818 };
5819 typedef struct bu_hash_tbl bu_hash_tbl_t;
5820 #define BU_HASH_TBL_NULL ((struct bu_hash_tbl *)0)
5821 
5822 /**
5823  * asserts the integrity of a non-head node bu_hash_tbl struct.
5824  */
5825 #define BU_CK_HASH_TBL(_hp) BU_CKMAG(_hp, BU_HASH_TBL_MAGIC, "bu_hash_tbl")
5826 
5827 /**
5828  * initializes a bu_hash_tbl struct without allocating any memory.
5829  */
5830 #define BU_HASH_TBL_INIT(_h) { \
5831         (_h)->magic = BU_HASH_TBL_MAGIC; \
5832         (_h)->mask = (_h)->num_lists = (_h)->num_entries = 0; \
5833         (_h)->lists = NULL; \
5834     }
5835 
5836 /**
5837  * macro suitable for declaration statement initialization of a
5838  * bu_hash_tbl struct.  does not allocate memory.
5839  */
5840 #define BU_HASH_TBL_INIT_ZERO { BU_HASH_TBL_MAGIC, 0, 0, 0, NULL }
5841 
5842 /**
5843  * returns truthfully whether a bu_hash_tbl has been initialized.
5844  */
5845 #define BU_HASH_TBL_IS_INITIALIZED(_h) (((struct bu_hash_tbl *)(_h) != BU_HASH_TBL_NULL) && LIKELY((_h)->magic == BU_HASH_TBL_MAGIC))
5846 
5847 
5848 /**
5849  * A hash table entry record
5850  */
5851 struct bu_hash_record {
5852     uint32_t magic;
5853     struct bu_hash_tbl *tbl;
5854     unsigned long index;
5855     struct bu_hash_entry *hsh_entry;
5856 };
5857 typedef struct bu_hash_record bu_hash_record_t;
5858 #define BU_HASH_RECORD_NULL ((struct bu_hash_record *)0)
5859 
5860 /**
5861  * asserts the integrity of a non-head node bu_hash_record struct.
5862  */
5863 #define BU_CK_HASH_RECORD(_rp) BU_CKMAG(_rp, BU_HASH_RECORD_MAGIC, "bu_hash_record")
5864 
5865 /**
5866  * initializes a bu_hash_record struct without allocating any memory.
5867  */
5868 #define BU_HASH_RECORD_INIT(_h) { \
5869         (_h)->magic = BU_HASH_RECORD_MAGIC; \
5870         (_h)->tbl = NULL; \
5871         (_h)->index = 0; \
5872         (_h)->hsh_entry = NULL; \
5873     }
5874 
5875 /**
5876  * macro suitable for declaration statement initialization of a
5877  * bu_hash_record struct.  does not allocate memory.
5878  */
5879 #define BU_HASH_RECORD_INIT_ZERO { BU_HASH_RECORD_MAGIC, NULL, 0, NULL }
5880 
5881 /**
5882  * returns truthfully whether a bu_hash_record has been initialized.
5883  */
5884 #define BU_HASH_RECORD_IS_INITIALIZED(_h) (((struct bu_hash_record *)(_h) != BU_HASH_RECORD_NULL) && LIKELY((_h)->magic == BU_HASH_RECORD_MAGIC))
5885 
5886 
5887 /**
5888  * the hashing function
5889  */
5890 BU_EXPORT extern unsigned long bu_hash(unsigned char *str,
5891                                        int len);
5892 
5893 /**
5894  * Create an empty hash table
5895  *
5896  * The input is the number of desired hash bins.  This number will be
5897  * rounded up to the nearest power of two.
5898  */
5899 BU_EXPORT extern struct bu_hash_tbl *bu_create_hash_tbl(unsigned long tbl_size);
5900 
5901 /**
5902  * Find the hash table entry corresponding to the provided key
5903  *
5904  * @param[in] hsh_tbl - The hash table to look in
5905  * @param[in] key - the key to look for
5906  * @param[in] key_len - the length of the key in bytes
5907  *
5908  * Output:
5909  * @param[out] prev - the previous hash table entry (non-null for entries that not the first in hash bin)
5910  * @param[out] idx - the index of the hash bin for this key
5911  *
5912  * @return
5913  * the hash table entry corresponding to the provided key, or NULL if
5914  * not found.
5915  */
5916 BU_EXPORT extern struct bu_hash_entry *bu_find_hash_entry(struct bu_hash_tbl *hsh_tbl,
5917                                                           unsigned char *key,
5918                                                           int key_len,
5919                                                           struct bu_hash_entry **prev,
5920                                                           unsigned long *idx);
5921 
5922 /**
5923  * Set the value for a hash table entry
5924  *
5925  * Note that this is just a pointer copy, the hash table does not
5926  * maintain its own copy of this value.
5927  */
5928 BU_EXPORT extern void bu_set_hash_value(struct bu_hash_entry *hsh_entry,
5929                                         unsigned char *value);
5930 
5931 /**
5932  * get the value pointer stored for the specified hash table entry
5933  */
5934 BU_EXPORT extern unsigned char *bu_get_hash_value(struct bu_hash_entry *hsh_entry);
5935 
5936 /**
5937  * get the key pointer stored for the specified hash table entry
5938  */
5939 BU_EXPORT extern unsigned char *bu_get_hash_key(struct bu_hash_entry *hsh_entry);
5940 
5941 /**
5942  * Add an new entry to a hash table
5943  *
5944  * @param[in] hsh_tbl - the hash table to accept the new entry
5945  * @param[in] key - the key (any byte string)
5946  * @param[in] key_len - the number of bytes in the key
5947  *
5948  * @param[out] new_entry - a flag, non-zero indicates that a new entry
5949  * was created.  zero indicates that an entry already exists with the
5950  * specified key and key length
5951  *
5952  * @return
5953  * a hash table entry. If "new" is non-zero, a new, empty entry is
5954  * returned.  if "new" is zero, the returned entry is the one matching
5955  * the specified key and key_len.
5956  */
5957 BU_EXPORT extern struct bu_hash_entry *bu_hash_add_entry(struct bu_hash_tbl *hsh_tbl,
5958                                                          unsigned char *key,
5959                                                          int key_len,
5960                                                          int *new_entry);
5961 
5962 /**
5963  * Print the specified hash table to stderr.
5964  *
5965  * (Note that the keys and values are printed as pointers)
5966  */
5967 BU_EXPORT extern void bu_hash_tbl_pr(struct bu_hash_tbl *hsh_tbl,
5968                                      char *str);
5969 
5970 /**
5971  * Free all the memory associated with the specified hash table.
5972  *
5973  * Note that the keys are freed (they are copies), but the "values"
5974  * are not freed.  (The values are merely pointers)
5975  */
5976 BU_EXPORT extern void bu_hash_tbl_free(struct bu_hash_tbl *hsh_tbl);
5977 
5978 /**
5979  * get the "first" entry in a hash table
5980  *
5981  * @param[in] hsh_tbl - the hash table of interest
5982  * @param[in] rec - an empty "bu_hash_record" structure for use by this routine and "bu_hash_tbl_next"
5983  *
5984  * @return
5985  * the first non-null entry in the hash table, or NULL if there are no
5986  * entries (Note that the order of entries is not likely to have any
5987  * significance)
5988  */
5989 BU_EXPORT extern struct bu_hash_entry *bu_hash_tbl_first(struct bu_hash_tbl *hsh_tbl,
5990                                                          struct bu_hash_record *rec);
5991 
5992 /**
5993  * get the "next" entry in a hash table
5994  *
5995  * input:
5996  * rec - the "bu_hash_record" structure that was passed to
5997  * "bu_hash_tbl_first"
5998  *
5999  * return:
6000  * the "next" non-null hash entry in this hash table
6001  */
6002 BU_EXPORT extern struct bu_hash_entry *bu_hash_tbl_next(struct bu_hash_record *rec);
6003 
6004 
6005 /** @} */
6006 
6007 /** @addtogroup file */
6008 /** @ingroup io */
6009 /** @{ */
6010 /** @file libbu/fchmod.c
6011  *
6012  * Wrapper around fchmod.
6013  *
6014  */
6015 
6016 /**
6017  * Portable wrapper for setting a file descriptor's permissions ala
6018  * fchmod().
6019  */
6020 BU_EXPORT extern int bu_fchmod(int fd, unsigned long pmode);
6021 
6022 
6023 /** @file libbu/argv.c
6024  *
6025  * Functions related to argv processing.
6026  *
6027  */
6028 
6029 /**
6030  * Build argv[] array from input buffer, by splitting whitespace
6031  * separated "words" into null terminated strings.
6032  *
6033  * 'lim' indicates the maximum number of elements that can be stored
6034  * in the argv[] array not including a terminating NULL.
6035  *
6036  * The 'lp' input buffer is altered by this process.  The argv[] array
6037  * points into the input buffer.
6038  *
6039  * The argv[] array needs to have at least lim+1 pointers allocated
6040  * for lim items plus a terminating pointer to NULL.  The input buffer
6041  * should not be freed until argv has been freed or passes out of
6042  * scope.
6043  *
6044  * Returns -
6045  * 0    no words in input
6046  * argc number of words of input, now in argv[]
6047  */
6048 BU_EXPORT extern size_t bu_argv_from_string(char *argv[],
6049                                             size_t lim,
6050                                             char *lp);
6051 
6052 /**
6053  * Deallocate all strings in a given argv array and the array itself
6054  *
6055  * This call presumes the array has been allocated with bu_dup_argv()
6056  * or bu_argv_from_path().
6057  */
6058 BU_EXPORT extern void bu_free_argv(int argc, char *argv[]);
6059 
6060 /**
6061  * free up to argc elements of memory allocated to an array without
6062  * free'ing the array itself.
6063  */
6064 BU_EXPORT extern void bu_free_array(int argc, char *argv[], const char *str);
6065 
6066 /**
6067  * Dynamically duplicate an argv array and all elements in the array
6068  *
6069  * Duplicate an argv array by duplicating all strings and the array
6070  * itself.  It is the caller's responsibility to free the array
6071  * returned including all elements in the array by calling bu_free()
6072  * or bu_free_argv().
6073  */
6074 BU_EXPORT extern char **bu_dup_argv(int argc, const char *argv[]);
6075 
6076 /**
6077  * Combine two argv arrays into one new (duplicated) argv array.
6078  *
6079  * If insert is negative, the insertArgv array elements will be
6080  * prepended into the new argv array.  If insert is greater than or
6081  * equal to argc, the insertArgv array elements will be appended after
6082  * all duplicated elements in the specified argv array.  Otherwise,
6083  * the insert argument is the position where the insertArgv array
6084  * elements will be merged with the specified argv array.
6085  */
6086 BU_EXPORT extern char **bu_dupinsert_argv(int insert, int insertArgc, const char *insertArgv[], int argc, const char *argv[]);
6087 
6088 /**
6089  * Generate an argv array from a path
6090  *
6091  * Given a path string, separate the path elements into a dynamically
6092  * allocated argv array with the path separators removed.  It is the
6093  * caller's responsibility to free the array that is returned as well
6094  * as all elements in the array using bu_free_argv() or manually
6095  * calling bu_free().
6096  */
6097 BU_EXPORT extern char **bu_argv_from_path(const char *path, int *ac);
6098 
6099 
6100 /** @file libbu/interrupt.c
6101  *
6102  * Routines for managing signals.  In particular, provide a common
6103  * means to temporarily buffer processing a signal during critical
6104  * write operations.
6105  *
6106  */
6107 
6108 /**
6109  * Defer signal processing and interrupts before critical sections.
6110  *
6111  * Signal processing for a variety of signals that would otherwise
6112  * disrupt the logic of an application are put on hold until
6113  * bu_restore_interrupts() is called.
6114  *
6115  * If an interrupt signal is received while suspended, it will be
6116  * raised when/if interrupts are restored.
6117  *
6118  * Returns 0 on success.
6119  * Returns non-zero on error (with perror set if signal() failure).
6120  */
6121 BU_EXPORT extern int bu_suspend_interrupts();
6122 
6123 /**
6124  * Resume signal processing and interrupts after critical sections.
6125  *
6126  * If a signal was raised since bu_suspend_interrupts() was called,
6127  * the previously installed signal handler will be immediately called
6128  * albeit only once even if multiple signals were received.
6129  *
6130  * Returns 0 on success.
6131  * Returns non-zero on error (with perror set if signal() failure).
6132  */
6133 BU_EXPORT extern int bu_restore_interrupts();
6134 
6135 /** @} */
6136 
6137 /** @addtogroup file */
6138 /** @ingroup io */
6139 /** @{ */
6140 /** @file libbu/simd.c
6141  * Detect SIMD type at runtime.
6142  */
6143 
6144 #define BU_SIMD_SSE4_2 7
6145 #define BU_SIMD_SSE4_1 6
6146 #define BU_SIMD_SSE3 5
6147 #define BU_SIMD_ALTIVEC 4
6148 #define BU_SIMD_SSE2 3
6149 #define BU_SIMD_SSE 2
6150 #define BU_SIMD_MMX 1
6151 #define BU_SIMD_NONE 0
6152 /**
6153  * Detect SIMD capabilities at runtime.
6154  */
6155 BU_EXPORT extern int bu_simd_level();
6156 
6157 /**
6158  * Detect if requested SIMD capabilities are available at runtime.
6159  * Returns 1 if they are, 0 if they are not.
6160  */
6161 BU_EXPORT extern int bu_simd_supported(int level);
6162 
6163 /** @} */
6164 
6165 /** @addtogroup file */
6166 /** @ingroup io */
6167 /** @{ */
6168 /** @file libbu/timer.c
6169  * Return microsecond accuracy time information.
6170  */
6171 BU_EXPORT extern int64_t bu_gettime();
6172 
6173 /** @} */
6174 
6175 /** @addtogroup file */
6176 /** @ingroup io */
6177 /** @{ */
6178 /** @file libbu/dlfcn.c
6179  * Dynamic Library functionality
6180  */
6181 #ifdef HAVE_DLOPEN
6182 # define BU_RTLD_LAZY RTLD_LAZY
6183 # define BU_RTLD_NOW RTLD_NOW
6184 # define BU_RTLD_GLOBAL RTLD_GLOBAL
6185 # define BU_RTLD_LOCAL RTLD_LOCAL
6186 #else
6187 # define BU_RTLD_LAZY 1
6188 # define BU_RTLD_NOW 2
6189 # define BU_RTLD_GLOBAL 0x100
6190 # define BU_RTLD_LOCAL 0
6191 #endif
6192 BU_EXPORT extern void *bu_dlopen(const char *path, int mode);
6193 BU_EXPORT extern void *bu_dlsym(void *path, const char *symbol);
6194 BU_EXPORT extern int bu_dlclose(void *handle);
6195 BU_EXPORT extern const char *bu_dlerror();
6196 
6197 /** NEW: Do not use. */
6198 BU_EXPORT extern int bu_fseek(FILE *stream, off_t offset, int origin);
6199 /** NEW: Do not use. */
6200 BU_EXPORT extern off_t bu_ftell(FILE *stream);
6201 
6202 /** @} file */
6203 
6204 
6205 /** @file libbu/ctype.c
6206  *
6207  * Routines for checking ctypes.
6208  *
6209  */
6210 BU_EXPORT extern int bu_str_isprint(const char *cp);
6211 
6212 /** @file libbu/gethostname.c
6213  *
6214  * Portable gethostname()
6215  *
6216  */
6217 BU_EXPORT extern int bu_gethostname(char *, size_t);
6218 
6219 __END_DECLS
6220 
6221 #endif  /* __BU_H__ */
6222 
6223 /*
6224  * Local Variables:
6225  * mode: C
6226  * tab-width: 8
6227  * indent-tabs-mode: t
6228  * c-file-style: "stroustrup"
6229  * End:
6230  * ex: shiftwidth=4 tabstop=8
6231  */
6232 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.