3 SPDX-License-Identifier: BSD-2-Clause
5 Copyright (c) 2018-2021 Gavin D. Howard and contributors.
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
10 * Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.
33 bcl - library of arbitrary precision decimal arithmetic
45 This procedure will allow clients to use signals to interrupt computations
48 **void bcl_handleSignal(**_void_**);**
50 **bool bcl_running(**_void_**);**
54 These items allow clients to set up bcl(3).
56 **BclError bcl_init(**_void_**);**
58 **void bcl_free(**_void_**);**
60 **bool bcl_abortOnFatalError(**_void_**);**
62 **void bcl_setAbortOnFatalError(bool** _abrt_**);**
64 **bool bcl_leadingZeroes(**_void_**);**
66 **void bcl_setLeadingZeroes(bool** _leadingZeroes_**);**
68 **void bcl_gc(**_void_**);**
72 These items will allow clients to handle contexts, which are isolated from each
73 other. This allows more than one client to use bcl(3) in the same program.
77 **typedef struct BclCtxt\* BclContext;**
79 **BclContext bcl_ctxt_create(**_void_**);**
81 **void bcl_ctxt_free(BclContext** _ctxt_**);**
83 **BclError bcl_pushContext(BclContext** _ctxt_**);**
85 **void bcl_popContext(**_void_**);**
87 **BclContext bcl_context(**_void_**);**
89 **void bcl_ctxt_freeNums(BclContext** _ctxt_**);**
91 **size_t bcl_ctxt_scale(BclContext** _ctxt_**);**
93 **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);**
95 **size_t bcl_ctxt_ibase(BclContext** _ctxt_**);**
97 **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);**
99 **size_t bcl_ctxt_obase(BclContext** _ctxt_**);**
101 **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);**
105 These items allow clients to handle errors.
107 **typedef enum BclError BclError;**
109 **BclError bcl_err(BclNumber** _n_**);**
113 These items allow clients to manipulate and query the arbitrary-precision
114 numbers managed by bcl(3).
116 **typedef struct { size_t i; } BclNumber;**
118 **BclNumber bcl_num_create(**_void_**);**
120 **void bcl_num_free(BclNumber** _n_**);**
122 **bool bcl_num_neg(BclNumber** _n_**);**
124 **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);**
126 **size_t bcl_num_scale(BclNumber** _n_**);**
128 **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);**
130 **size_t bcl_num_len(BclNumber** _n_**);**
134 These items allow clients to convert numbers into and from strings and integers.
136 **BclNumber bcl_parse(const char \*restrict** _val_**);**
138 **char\* bcl_string(BclNumber** _n_**);**
140 **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);**
142 **BclNumber bcl_bigdig2num(BclBigDig** _val_**);**
146 These items allow clients to run math on numbers.
148 **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);**
150 **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);**
152 **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);**
154 **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);**
156 **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);**
158 **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);**
160 **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);**
162 **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);**
164 **BclNumber bcl_sqrt(BclNumber** _a_**);**
166 **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);**
168 **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);**
172 These items are miscellaneous.
174 **void bcl_zero(BclNumber** _n_**);**
176 **void bcl_one(BclNumber** _n_**);**
178 **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);**
180 **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);**
182 **BclNumber bcl_dup(BclNumber** _s_**);**
184 ## Pseudo-Random Number Generator
186 These items allow clients to manipulate the seeded pseudo-random number
189 **#define BCL_SEED_ULONGS**
191 **#define BCL_SEED_SIZE**
193 **typedef unsigned long BclBigDig;**
195 **typedef unsigned long BclRandInt;**
197 **BclNumber bcl_irand(BclNumber** _a_**);**
199 **BclNumber bcl_frand(size_t** _places_**);**
201 **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);**
203 **BclError bcl_rand_seedWithNum(BclNumber** _n_**);**
205 **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);**
207 **void bcl_rand_reseed(**_void_**);**
209 **BclNumber bcl_rand_seed2num(**_void_**);**
211 **BclRandInt bcl_rand_int(**_void_**);**
213 **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);**
217 bcl(3) is a library that implements arbitrary-precision decimal math, as
218 standardized by POSIX
219 (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1).
221 bcl(3) is async-signal-safe if **bcl_handleSignal(**_void_**)** is used
222 properly. (See the **SIGNAL HANDLING** section.)
224 bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and
225 **Bc** prefixes for symbol names without collision.
227 All of the items in its interface are described below. See the documentation for
228 each function for what each function can return.
232 **void bcl_handleSignal(**_void_**)**
234 : An async-signal-safe function that can be called from a signal handler. If
235 called from a signal handler on the same thread as any executing bcl(3)
236 functions, it will interrupt the functions and force them to return early.
237 It is undefined behavior if this function is called from a thread that is
238 *not* executing any bcl(3) functions while any bcl(3) functions are
241 If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
242 return to its caller.
244 See the **SIGNAL HANDLING** section.
246 **bool bcl_running(**_void_**)**
248 : An async-signal-safe function that can be called from a signal handler. It
249 will return **true** if any bcl(3) procedures are running, which means it is
250 safe to call **bcl_handleSignal(**_void_**)**. Otherwise, it returns
253 See the **SIGNAL HANDLING** section.
257 **BclError bcl_init(**_void_**)**
259 : Initializes this library. This function can be called multiple times, but
260 each call must be matched by a call to **bcl_free(**_void_**)**. This is to
261 make it possible for multiple libraries and applications to initialize
262 bcl(3) without problem.
264 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
267 * **BCL_ERROR_FATAL_ALLOC_ERR**
269 This function must be the first one clients call. Calling any other
270 function without calling this one first is undefined behavior.
272 **void bcl_free(**_void_**)**
274 : Decrements bcl(3)'s reference count and frees the data associated with it if
275 the reference count is **0**.
277 This function must be the last one clients call. Calling this function
278 before calling any other function is undefined behavior.
280 **bool bcl_abortOnFatalError(**_void_**)**
282 : Queries and returns the current state of calling **abort()** on fatal
283 errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal
286 If activated, clients do not need to check for fatal errors.
288 The default is **false**.
290 **void bcl_setAbortOnFatalError(bool** _abrt_**)**
292 : Sets the state of calling **abort()** on fatal errors. If *abrt* is
293 **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the
294 call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors
297 If activated, clients do not need to check for fatal errors.
299 **bool bcl_leadingZeroes(**_void_**)**
301 : Queries and returns the state of whether leading zeroes are added to strings
302 returned by **bcl_string()** when numbers are greater than **-1**, less than
303 **1**, and not equal to **0**. If **true** is returned, then leading zeroes
306 The default is **false**.
308 **void bcl_setLeadingZeroes(bool** _leadingZeroes_**)**
310 : Sets the state of whether leading zeroes are added to strings returned by
311 **bcl_string()** when numbers are greater than **-1**, less than **1**, and
312 not equal to **0**. If *leadingZeroes* is **true**, leading zeroes will be
313 added to strings returned by **bcl_string()**.
315 **void bcl_gc(**_void_**)**
317 : Garbage collects cached instances of arbitrary-precision numbers. This only
318 frees the memory of numbers that are *not* in use, so it is safe to call at
323 All procedures that take a **BclContext** parameter a require a valid context as
328 : A forward declaration for a hidden **struct** type. Clients cannot access
329 the internals of the **struct** type directly. All interactions with the
330 type are done through pointers. See **BclContext** below.
334 : A typedef to a pointer of **struct BclCtxt**. This is the only handle
335 clients can get to **struct BclCtxt**.
337 A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
338 well as a list of numbers.
340 **scale** is a value used to control how many decimal places calculations
341 should use. A value of **0** means that calculations are done on integers
342 only, where applicable, and a value of 20, for example, means that all
343 applicable calculations return results with 20 decimal places. The default
346 **ibase** is a value used to control the input base. The minimum **ibase**
347 is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are
348 parsed as though they are in binary, and any digits larger than **1** are
349 clamped. Likewise, a value of **10** means that numbers are parsed as though
350 they are decimal, and any larger digits are clamped. The default is **10**.
352 **obase** is a value used to control the output base. The minimum **obase**
353 is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section).
355 Numbers created in one context are not valid in another context. It is
356 undefined behavior to use a number created in a different context. Contexts
357 are meant to isolate the numbers used by different clients in the same
360 **BclContext bcl_ctxt_create(**_void_**)**
362 : Creates a context and returns it. Returns **NULL** if there was an error.
364 **void bcl_ctxt_free(BclContext** _ctxt_**)**
366 : Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
367 attempt to use an invalid context.
369 **BclError bcl_pushContext(BclContext** _ctxt_**)**
371 : Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
372 with **bcl_ctxt_create(**_void_**)**.
374 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
377 * **BCL_ERROR_FATAL_ALLOC_ERR**
379 There *must* be a valid context to do any arithmetic.
381 **void bcl_popContext(**_void_**)**
383 : Pops the current context off of the stack, if one exists.
385 **BclContext bcl_context(**_void_**)**
387 : Returns the current context, or **NULL** if no context exists.
389 **void bcl_ctxt_freeNums(BclContext** _ctxt_**)**
391 : Frees all numbers in use that are associated with *ctxt*. It is undefined
392 behavior to attempt to use a number associated with *ctxt* after calling
393 this procedure unless such numbers have been created with
394 **bcl_num_create(**_void_**)** after calling this procedure.
396 **size_t bcl_ctxt_scale(BclContext** _ctxt_**)**
398 : Returns the **scale** for given context.
400 **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)**
402 : Sets the **scale** for the given context to the argument *scale*.
404 **size_t bcl_ctxt_ibase(BclContext** _ctxt_**)**
406 : Returns the **ibase** for the given context.
408 **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)**
410 : Sets the **ibase** for the given context to the argument *ibase*. If the
411 argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is
412 clamped to **2**, and any values above **36** are clamped to **36**.
414 **size_t bcl_ctxt_obase(BclContext** _ctxt_**)**
416 : Returns the **obase** for the given context.
418 **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)**
420 : Sets the **obase** for the given context to the argument *obase*.
426 : An **enum** of possible error codes. See the **ERRORS** section for a
427 complete listing the codes.
429 **BclError bcl_err(BclNumber** _n_**)**
431 : Checks for errors in a **BclNumber**. All functions that can return a
432 **BclNumber** can encode an error in the number, and this function will
433 return the error, if any. If there was no error, it will return
436 There must be a valid current context.
440 All procedures in this section require a valid current context.
444 : A handle to an arbitrary-precision number. The actual number type is not
445 exposed; the **BclNumber** handle is the only way clients can refer to
446 instances of arbitrary-precision numbers.
448 **BclNumber bcl_num_create(**_void_**)**
450 : Creates and returns a **BclNumber**.
452 bcl(3) will encode an error in the return value, if there was one. The error
453 can be queried with **bcl_err(BclNumber)**. Possible errors include:
455 * **BCL_ERROR_INVALID_CONTEXT**
456 * **BCL_ERROR_FATAL_ALLOC_ERR**
458 **void bcl_num_free(BclNumber** _n_**)**
460 : Frees *n*. It is undefined behavior to use *n* after calling this function.
462 **bool bcl_num_neg(BclNumber** _n_**)**
464 : Returns **true** if *n* is negative, **false** otherwise.
466 **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)**
468 : Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
471 **size_t bcl_num_scale(BclNumber** _n_**)**
473 : Returns the *scale* of *n*.
475 The *scale* of a number is the number of decimal places it has after the
476 radix (decimal point).
478 **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)**
480 : Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is
481 greater than the *scale* of *n*, *n* is extended. If the argument *scale* is
482 less than the *scale* of *n*, *n* is truncated.
484 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
487 * **BCL_ERROR_INVALID_NUM**
488 * **BCL_ERROR_INVALID_CONTEXT**
489 * **BCL_ERROR_FATAL_ALLOC_ERR**
491 **size_t bcl_num_len(BclNumber** _n_**)**
493 : Returns the number of *significant decimal digits* in *n*.
497 All procedures in this section require a valid current context.
499 All procedures in this section consume the given **BclNumber** arguments that
500 are not given to pointer arguments. See the **Consumption and Propagation**
503 **BclNumber bcl_parse(const char \*restrict** _val_**)**
505 : Parses a number string according to the current context's **ibase** and
506 returns the resulting number.
508 *val* must be non-**NULL** and a valid string. See
509 **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
512 bcl(3) will encode an error in the return value, if there was one. The error
513 can be queried with **bcl_err(BclNumber)**. Possible errors include:
515 * **BCL_ERROR_INVALID_NUM**
516 * **BCL_ERROR_INVALID_CONTEXT**
517 * **BCL_ERROR_PARSE_INVALID_STR**
518 * **BCL_ERROR_FATAL_ALLOC_ERR**
520 **char\* bcl_string(BclNumber** _n_**)**
522 : Returns a string representation of *n* according the the current context's
523 **ibase**. The string is dynamically allocated and must be freed by the
526 *n* is consumed; it cannot be used after the call. See the
527 **Consumption and Propagation** subsection below.
529 **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)**
531 : Converts *n* into a **BclBigDig** and returns the result in the space
532 pointed to by *result*.
534 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
536 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
539 * **BCL_ERROR_INVALID_NUM**
540 * **BCL_ERROR_INVALID_CONTEXT**
541 * **BCL_ERROR_MATH_OVERFLOW**
543 *n* is consumed; it cannot be used after the call. See the
544 **Consumption and Propagation** subsection below.
546 **BclNumber bcl_bigdig2num(BclBigDig** _val_**)**
548 : Creates a **BclNumber** from *val*.
550 bcl(3) will encode an error in the return value, if there was one. The error
551 can be queried with **bcl_err(BclNumber)**. Possible errors include:
553 * **BCL_ERROR_INVALID_CONTEXT**
554 * **BCL_ERROR_FATAL_ALLOC_ERR**
558 All procedures in this section require a valid current context.
560 All procedures in this section can return the following errors:
562 * **BCL_ERROR_INVALID_NUM**
563 * **BCL_ERROR_INVALID_CONTEXT**
564 * **BCL_ERROR_FATAL_ALLOC_ERR**
566 **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)**
568 : Adds *a* and *b* and returns the result. The *scale* of the result is the
569 max of the *scale*s of *a* and *b*.
571 *a* and *b* are consumed; they cannot be used after the call. See the
572 **Consumption and Propagation** subsection below.
574 *a* and *b* can be the same number.
576 bcl(3) will encode an error in the return value, if there was one. The error
577 can be queried with **bcl_err(BclNumber)**. Possible errors include:
579 * **BCL_ERROR_INVALID_NUM**
580 * **BCL_ERROR_INVALID_CONTEXT**
581 * **BCL_ERROR_FATAL_ALLOC_ERR**
583 **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)**
585 : Subtracts *b* from *a* and returns the result. The *scale* of the result is
586 the max of the *scale*s of *a* and *b*.
588 *a* and *b* are consumed; they cannot be used after the call. See the
589 **Consumption and Propagation** subsection below.
591 *a* and *b* can be the same number.
593 bcl(3) will encode an error in the return value, if there was one. The error
594 can be queried with **bcl_err(BclNumber)**. Possible errors include:
596 * **BCL_ERROR_INVALID_NUM**
597 * **BCL_ERROR_INVALID_CONTEXT**
598 * **BCL_ERROR_FATAL_ALLOC_ERR**
600 **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)**
602 : Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of
603 *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal
604 to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and
605 **max()** return the obvious values.
607 *a* and *b* are consumed; they cannot be used after the call. See the
608 **Consumption and Propagation** subsection below.
610 *a* and *b* can be the same number.
612 bcl(3) will encode an error in the return value, if there was one. The error
613 can be queried with **bcl_err(BclNumber)**. Possible errors include:
615 * **BCL_ERROR_INVALID_NUM**
616 * **BCL_ERROR_INVALID_CONTEXT**
617 * **BCL_ERROR_FATAL_ALLOC_ERR**
619 **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)**
621 : Divides *a* by *b* and returns the result. The *scale* of the result is the
622 *scale* of the current context.
626 *a* and *b* are consumed; they cannot be used after the call. See the
627 **Consumption and Propagation** subsection below.
629 *a* and *b* can be the same number.
631 bcl(3) will encode an error in the return value, if there was one. The error
632 can be queried with **bcl_err(BclNumber)**. Possible errors include:
634 * **BCL_ERROR_INVALID_NUM**
635 * **BCL_ERROR_INVALID_CONTEXT**
636 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
637 * **BCL_ERROR_FATAL_ALLOC_ERR**
639 **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)**
641 : Divides *a* by *b* to the *scale* of the current context, computes the
642 modulus **a-(a/b)\*b**, and returns the modulus.
646 *a* and *b* are consumed; they cannot be used after the call. See the
647 **Consumption and Propagation** subsection below.
649 *a* and *b* can be the same number.
651 bcl(3) will encode an error in the return value, if there was one. The error
652 can be queried with **bcl_err(BclNumber)**. Possible errors include:
654 * **BCL_ERROR_INVALID_NUM**
655 * **BCL_ERROR_INVALID_CONTEXT**
656 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
657 * **BCL_ERROR_FATAL_ALLOC_ERR**
659 **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)**
661 : Calculates *a* to the power of *b* to the *scale* of the current context.
662 *b* must be an integer, but can be negative. If it is negative, *a* must
665 *b* must be an integer. If *b* is negative, *a* must not be **0**.
667 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
669 *a* and *b* are consumed; they cannot be used after the call. See the
670 **Consumption and Propagation** subsection below.
672 *a* and *b* can be the same number.
674 bcl(3) will encode an error in the return value, if there was one. The error
675 can be queried with **bcl_err(BclNumber)**. Possible errors include:
677 * **BCL_ERROR_INVALID_NUM**
678 * **BCL_ERROR_INVALID_CONTEXT**
679 * **BCL_ERROR_MATH_NON_INTEGER**
680 * **BCL_ERROR_MATH_OVERFLOW**
681 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
682 * **BCL_ERROR_FATAL_ALLOC_ERR**
684 **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)**
686 : Shifts *a* left (moves the radix right) by *b* places and returns the
687 result. This is done in decimal. *b* must be an integer.
689 *b* must be an integer.
691 *a* and *b* are consumed; they cannot be used after the call. See the
692 **Consumption and Propagation** subsection below.
694 *a* and *b* can be the same number.
696 bcl(3) will encode an error in the return value, if there was one. The error
697 can be queried with **bcl_err(BclNumber)**. Possible errors include:
699 * **BCL_ERROR_INVALID_NUM**
700 * **BCL_ERROR_INVALID_CONTEXT**
701 * **BCL_ERROR_MATH_NON_INTEGER**
702 * **BCL_ERROR_FATAL_ALLOC_ERR**
704 **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)**
706 : Shifts *a* right (moves the radix left) by *b* places and returns the
707 result. This is done in decimal. *b* must be an integer.
709 *b* must be an integer.
711 *a* and *b* are consumed; they cannot be used after the call. See the
712 **Consumption and Propagation** subsection below.
714 *a* and *b* can be the same number.
716 bcl(3) will encode an error in the return value, if there was one. The error
717 can be queried with **bcl_err(BclNumber)**. Possible errors include:
719 * **BCL_ERROR_INVALID_NUM**
720 * **BCL_ERROR_INVALID_CONTEXT**
721 * **BCL_ERROR_MATH_NON_INTEGER**
722 * **BCL_ERROR_FATAL_ALLOC_ERR**
724 **BclNumber bcl_sqrt(BclNumber** _a_**)**
726 : Calculates the square root of *a* and returns the result. The *scale* of the
727 result is equal to the **scale** of the current context.
729 *a* cannot be negative.
731 *a* is consumed; it cannot be used after the call. See the
732 **Consumption and Propagation** subsection below.
734 bcl(3) will encode an error in the return value, if there was one. The error
735 can be queried with **bcl_err(BclNumber)**. Possible errors include:
737 * **BCL_ERROR_INVALID_NUM**
738 * **BCL_ERROR_INVALID_CONTEXT**
739 * **BCL_ERROR_MATH_NEGATIVE**
740 * **BCL_ERROR_FATAL_ALLOC_ERR**
742 **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)**
744 : Divides *a* by *b* and returns the quotient in a new number which is put
745 into the space pointed to by *c*, and puts the modulus in a new number which
746 is put into the space pointed to by *d*.
750 *a* and *b* are consumed; they cannot be used after the call. See the
751 **Consumption and Propagation** subsection below.
753 *c* and *d* cannot point to the same place, nor can they point to the space
754 occupied by *a* or *b*.
756 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
759 * **BCL_ERROR_INVALID_NUM**
760 * **BCL_ERROR_INVALID_CONTEXT**
761 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
762 * **BCL_ERROR_FATAL_ALLOC_ERR**
764 **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)**
766 : Computes a modular exponentiation where *a* is the base, *b* is the
767 exponent, and *c* is the modulus, and returns the result. The *scale* of the
768 result is equal to the **scale** of the current context.
770 *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
773 *a*, *b*, and *c* are consumed; they cannot be used after the call. See the
774 **Consumption and Propagation** subsection below.
776 bcl(3) will encode an error in the return value, if there was one. The error
777 can be queried with **bcl_err(BclNumber)**. Possible errors include:
779 * **BCL_ERROR_INVALID_NUM**
780 * **BCL_ERROR_INVALID_CONTEXT**
781 * **BCL_ERROR_MATH_NEGATIVE**
782 * **BCL_ERROR_MATH_NON_INTEGER**
783 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
784 * **BCL_ERROR_FATAL_ALLOC_ERR**
788 **void bcl_zero(BclNumber** _n_**)**
792 **void bcl_one(BclNumber** _n_**)**
796 **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)**
798 : Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if
799 *a* is less than *b*, and **>0** if *a* is greater than *b*.
801 **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)**
803 : Copies *s* into *d*.
805 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
808 * **BCL_ERROR_INVALID_NUM**
809 * **BCL_ERROR_INVALID_CONTEXT**
810 * **BCL_ERROR_FATAL_ALLOC_ERR**
812 **BclNumber bcl_dup(BclNumber** _s_**)**
814 : Creates and returns a new **BclNumber** that is a copy of *s*.
816 bcl(3) will encode an error in the return value, if there was one. The error
817 can be queried with **bcl_err(BclNumber)**. Possible errors include:
819 * **BCL_ERROR_INVALID_NUM**
820 * **BCL_ERROR_INVALID_CONTEXT**
821 * **BCL_ERROR_FATAL_ALLOC_ERR**
823 ## Pseudo-Random Number Generator
825 The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
826 seed twice, it will produce the same sequence of pseudo-random numbers twice.
828 By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
829 that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
830 then calling **rand()** for each byte, since **rand()** is only guaranteed to
833 This should provide fairly good seeding in the standard case while also
834 remaining fairly portable.
836 If necessary, the PRNG can be reseeded with one of the following functions:
838 * **bcl_rand_seedWithNum(BclNumber)**
839 * **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])**
840 * **bcl_rand_reseed(**_void_**)**
842 The following items allow clients to use the pseudo-random number generator. All
843 procedures require a valid current context.
847 : The number of **unsigned long**'s in a seed for bcl(3)'s random number
852 : The size, in **char**'s, of a seed for bcl(3)'s random number generator.
856 : bcl(3)'s overflow type (see the **PERFORMANCE** section).
860 : An unsigned integer type returned by bcl(3)'s random number generator.
862 **BclNumber bcl_irand(BclNumber** _a_**)**
864 : Returns a random number that is not larger than *a* in a new number. If *a*
865 is **0** or **1**, the new number is equal to **0**. The bound is unlimited,
866 so it is not bound to the size of **BclRandInt**. This is done by generating
867 as many random numbers as necessary, multiplying them by certain exponents,
868 and adding them all together.
870 *a* must be an integer and non-negative.
872 *a* is consumed; it cannot be used after the call. See the
873 **Consumption and Propagation** subsection below.
875 This procedure requires a valid current context.
877 bcl(3) will encode an error in the return value, if there was one. The error
878 can be queried with **bcl_err(BclNumber)**. Possible errors include:
880 * **BCL_ERROR_INVALID_NUM**
881 * **BCL_ERROR_INVALID_CONTEXT**
882 * **BCL_ERROR_MATH_NEGATIVE**
883 * **BCL_ERROR_MATH_NON_INTEGER**
884 * **BCL_ERROR_FATAL_ALLOC_ERR**
886 **BclNumber bcl_frand(size_t** _places_**)**
888 : Returns a random number between **0** (inclusive) and **1** (exclusive) that
889 has *places* decimal digits after the radix (decimal point). There are no
892 This procedure requires a valid current context.
894 bcl(3) will encode an error in the return value, if there was one. The error
895 can be queried with **bcl_err(BclNumber)**. Possible errors include:
897 * **BCL_ERROR_INVALID_CONTEXT**
898 * **BCL_ERROR_FATAL_ALLOC_ERR**
900 **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)**
902 : Returns a random number less than *a* with *places* decimal digits after the
903 radix (decimal point). There are no limits on *a* or *places*.
905 *a* must be an integer and non-negative.
907 *a* is consumed; it cannot be used after the call. See the
908 **Consumption and Propagation** subsection below.
910 This procedure requires a valid current context.
912 bcl(3) will encode an error in the return value, if there was one. The error
913 can be queried with **bcl_err(BclNumber)**. Possible errors include:
915 * **BCL_ERROR_INVALID_NUM**
916 * **BCL_ERROR_INVALID_CONTEXT**
917 * **BCL_ERROR_MATH_NEGATIVE**
918 * **BCL_ERROR_MATH_NON_INTEGER**
919 * **BCL_ERROR_FATAL_ALLOC_ERR**
921 **BclError bcl_rand_seedWithNum(BclNumber** _n_**)**
923 : Seeds the PRNG with *n*.
925 *n* is *not* consumed.
927 This procedure requires a valid current context.
929 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
932 * **BCL_ERROR_INVALID_NUM**
933 * **BCL_ERROR_INVALID_CONTEXT**
935 Note that if **bcl_rand_seed2num(**_void_**)** or
936 **bcl_rand_seed2num_err(BclNumber)** are called right after this function,
937 they are not guaranteed to return a number equal to *n*.
939 **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])**
941 : Seeds the PRNG with the bytes in *seed*.
943 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
946 * **BCL_ERROR_INVALID_CONTEXT**
948 **void bcl_rand_reseed(**_void_**)**
950 : Reseeds the PRNG with the default reseeding behavior. First, it attempts to
951 read data from **/dev/urandom** and falls back to **libc**'s **rand()**.
953 This procedure cannot fail.
955 **BclNumber bcl_rand_seed2num(**_void_**)**
957 : Returns the current seed of the PRNG as a **BclNumber**.
959 This procedure requires a valid current context.
961 bcl(3) will encode an error in the return value, if there was one. The error
962 can be queried with **bcl_err(BclNumber)**. Possible errors include:
964 * **BCL_ERROR_INVALID_CONTEXT**
965 * **BCL_ERROR_FATAL_ALLOC_ERR**
967 **BclRandInt bcl_rand_int(**_void_**)**
969 : Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
971 This procedure cannot fail.
973 **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)**
975 : Returns a random integer between **0** and *bound* (exclusive). Bias is
976 removed before returning the integer.
978 This procedure cannot fail.
980 ## Consumption and Propagation
982 Some functions are listed as consuming some or all of their arguments. This
983 means that the arguments are freed, regardless of if there were errors or not.
985 This is to enable compact code like the following:
987 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
989 If arguments to those functions were not consumed, memory would be leaked until
990 reclaimed with **bcl_ctxt_freeNums(BclContext)**.
992 When errors occur, they are propagated through. The result should always be
993 checked with **bcl_err(BclNumber)**, so the example above should properly
996 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
997 if (bc_num_err(n) != BCL_ERROR_NONE) {
1003 Most functions in bcl(3) return, directly or indirectly, any one of the error
1004 codes defined in **BclError**. The complete list of codes is the following:
1008 : Success; no error occurred.
1010 **BCL_ERROR_INVALID_NUM**
1012 : An invalid **BclNumber** was given as a parameter.
1014 **BCL_ERROR_INVALID_CONTEXT**
1016 : An invalid **BclContext** is being used.
1018 **BCL_ERROR_SIGNAL**
1020 : A signal interrupted execution.
1022 **BCL_ERROR_MATH_NEGATIVE**
1024 : A negative number was given as an argument to a parameter that cannot accept
1025 negative numbers, such as for square roots.
1027 **BCL_ERROR_MATH_NON_INTEGER**
1029 : A non-integer was given as an argument to a parameter that cannot accept
1030 non-integer numbers, such as for the second parameter of **bcl_num_pow()**.
1032 **BCL_ERROR_MATH_OVERFLOW**
1034 : A number that would overflow its result was given as an argument, such as
1035 for converting a **BclNumber** to a **BclBigDig**.
1037 **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
1039 : A divide by zero occurred.
1041 **BCL_ERROR_PARSE_INVALID_STR**
1043 : An invalid number string was passed to a parsing function.
1045 A valid number string can only be one radix (period). In addition, any
1046 lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is
1047 allowed for the first character to be a dash. In that case, the number is
1048 considered to be negative.
1050 There is one exception to the above: one lowercase **e** is allowed in the
1051 number, after the radix, if it exists. If the letter **e** exists, the
1052 number is considered to be in scientific notation, where the part before the
1053 **e** is the number, and the part after, which must be an integer, is the
1054 exponent. There can be a dash right after the **e** to indicate a negative
1057 **WARNING**: Both the number and the exponent in scientific notation are
1058 interpreted according to the current **ibase**, but the number is still
1059 multiplied by **10\^exponent** regardless of the current **ibase**. For
1060 example, if **ibase** is **16** and bcl(3) is given the number string
1061 **FFeA**, the resulting decimal number will be **2550000000000**, and if
1062 bcl(3) is given the number string **10e-4**, the resulting decimal number
1065 **BCL_ERROR_FATAL_ALLOC_ERR**
1067 : bcl(3) failed to allocate memory.
1069 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1070 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1071 be turned off later by calling that same function with a **false** argument.
1072 By default, this behavior is off.
1074 It is highly recommended that client libraries do *not* activate this
1077 **BCL_ERROR_FATAL_UNKNOWN_ERR**
1079 : An unknown error occurred.
1081 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1082 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1083 be turned off later by calling that same function with a **false** argument.
1084 By default, this behavior is off.
1086 It is highly recommended that client libraries do *not* activate this
1091 When **bcl_handleSignal(**_void_**)** is used properly, bcl(3) is
1094 bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one
1099 Most bc(1) implementations use **char** types to calculate the value of **1**
1100 decimal digit at a time, but that can be slow. bcl(3) does something
1103 It uses large integers to calculate more than **1** decimal digit at a time. If
1104 built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1105 **64**, then each integer has **9** decimal digits. If built in an environment
1106 where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1107 value (the number of decimal digits per large integer) is called
1110 In addition, this bcl(3) uses an even larger integer for overflow checking. This
1111 integer type depends on the value of **BC_LONG_BIT**, but is always at least
1112 twice as large as the integer type used to store digits.
1116 The following are the limits on bcl(3):
1120 : The number of bits in the **long** type in the environment where bcl(3) was
1121 built. This determines how many decimal digits can be stored in a single
1122 large integer (see the **PERFORMANCE** section).
1126 : The number of decimal digits per large integer (see the **PERFORMANCE**
1127 section). Depends on **BC_LONG_BIT**.
1131 : The max decimal number that each large integer can store (see
1132 **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1136 : The max number that the overflow type (see the **PERFORMANCE** section) can
1137 hold. Depends on **BC_LONG_BIT**.
1141 : The maximum output base. Set at **BC_BASE_POW**.
1145 : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1149 : The maximum length of a number (in decimal digits), which includes digits
1150 after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1154 : The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
1155 Set at **2\^BC_LONG_BIT-1**.
1159 : The maximum allowable exponent (positive or negative). Set at
1160 **BC_OVERFLOW_MAX**.
1162 These limits are meant to be effectively non-existent; the limits are so large
1163 (at least on 64-bit machines) that there should not be any point at which they
1164 become a problem. In fact, memory should be exhausted before these limits should
1169 If a signal handler calls **bcl_handleSignal(**_void_**)** from the same thread
1170 that there are bcl(3) functions executing in, it will cause all execution to
1171 stop as soon as possible, interrupting long-running calculations, if necessary
1172 and cause the function that was executing to return. If possible, the error code
1173 **BC_ERROR_SIGNAL** is returned.
1175 If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
1176 return to its caller.
1178 It is undefined behavior if **bcl_handleSignal(**_void_**)** is called from
1179 a thread that is not executing bcl(3) functions, if bcl(3) functions are
1188 bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017
1189 (“POSIX.1-2017”) specification at
1190 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html for bc(1).
1192 Note that the specification explicitly says that bc(1) only accepts numbers that
1193 use a period (**.**) as a radix point, regardless of the value of
1194 **LC_NUMERIC**. This is also true of bcl(3).
1198 None are known. Report bugs at https://git.yzena.com/gavin/bc.
1202 Gavin D. Howard <gavin@yzena.com> and contributors.