xref: /freebsd/contrib/bc/manuals/bcl.3.md (revision 84823cc70824c8d842f503d8c2e6d7b0c2d95b61)
1<!---
2
3SPDX-License-Identifier: BSD-2-Clause
4
5Copyright (c) 2018-2021 Gavin D. Howard and contributors.
6
7Redistribution and use in source and binary forms, with or without
8modification, are permitted provided that the following conditions are met:
9
10* Redistributions of source code must retain the above copyright notice, this
11  list of conditions and the following disclaimer.
12
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.
16
17THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27POSSIBILITY OF SUCH DAMAGE.
28
29-->
30
31# NAME
32
33bcl - library of arbitrary precision decimal arithmetic
34
35# SYNOPSIS
36
37## Use
38
39*#include <bcl.h>*
40
41Link with *-lbcl*.
42
43## Signals
44
45This procedure will allow clients to use signals to interrupt computations
46running in bcl(3).
47
48**void bcl_handleSignal(**_void_**);**
49
50**bool bcl_running(**_void_**);**
51
52## Setup
53
54These items allow clients to set up bcl(3).
55
56**BclError bcl_init(**_void_**);**
57
58**void bcl_free(**_void_**);**
59
60**bool bcl_abortOnFatalError(**_void_**);**
61
62**void bcl_setAbortOnFatalError(bool** _abrt_**);**
63
64**bool bcl_leadingZeroes(**_void_**);**
65
66**void bcl_setLeadingZeroes(bool** _leadingZeroes_**);**
67
68**void bcl_gc(**_void_**);**
69
70## Contexts
71
72These items will allow clients to handle contexts, which are isolated from each
73other. This allows more than one client to use bcl(3) in the same program.
74
75**struct BclCtxt;**
76
77**typedef struct BclCtxt\* BclContext;**
78
79**BclContext bcl_ctxt_create(**_void_**);**
80
81**void bcl_ctxt_free(BclContext** _ctxt_**);**
82
83**BclError bcl_pushContext(BclContext** _ctxt_**);**
84
85**void bcl_popContext(**_void_**);**
86
87**BclContext bcl_context(**_void_**);**
88
89**void bcl_ctxt_freeNums(BclContext** _ctxt_**);**
90
91**size_t bcl_ctxt_scale(BclContext** _ctxt_**);**
92
93**void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);**
94
95**size_t bcl_ctxt_ibase(BclContext** _ctxt_**);**
96
97**void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);**
98
99**size_t bcl_ctxt_obase(BclContext** _ctxt_**);**
100
101**void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);**
102
103## Errors
104
105These items allow clients to handle errors.
106
107**typedef enum BclError BclError;**
108
109**BclError bcl_err(BclNumber** _n_**);**
110
111## Numbers
112
113These items allow clients to manipulate and query the arbitrary-precision
114numbers managed by bcl(3).
115
116**typedef struct { size_t i; } BclNumber;**
117
118**BclNumber bcl_num_create(**_void_**);**
119
120**void bcl_num_free(BclNumber** _n_**);**
121
122**bool bcl_num_neg(BclNumber** _n_**);**
123
124**void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);**
125
126**size_t bcl_num_scale(BclNumber** _n_**);**
127
128**BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);**
129
130**size_t bcl_num_len(BclNumber** _n_**);**
131
132## Conversion
133
134These items allow clients to convert numbers into and from strings and integers.
135
136**BclNumber bcl_parse(const char \*restrict** _val_**);**
137
138**char\* bcl_string(BclNumber** _n_**);**
139
140**BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);**
141
142**BclNumber bcl_bigdig2num(BclBigDig** _val_**);**
143
144## Math
145
146These items allow clients to run math on numbers.
147
148**BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);**
149
150**BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);**
151
152**BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);**
153
154**BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);**
155
156**BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);**
157
158**BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);**
159
160**BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);**
161
162**BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);**
163
164**BclNumber bcl_sqrt(BclNumber** _a_**);**
165
166**BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);**
167
168**BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);**
169
170## Miscellaneous
171
172These items are miscellaneous.
173
174**void bcl_zero(BclNumber** _n_**);**
175
176**void bcl_one(BclNumber** _n_**);**
177
178**ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);**
179
180**BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);**
181
182**BclNumber bcl_dup(BclNumber** _s_**);**
183
184## Pseudo-Random Number Generator
185
186These items allow clients to manipulate the seeded pseudo-random number
187generator in bcl(3).
188
189**#define BCL_SEED_ULONGS**
190
191**#define BCL_SEED_SIZE**
192
193**typedef unsigned long BclBigDig;**
194
195**typedef unsigned long BclRandInt;**
196
197**BclNumber bcl_irand(BclNumber** _a_**);**
198
199**BclNumber bcl_frand(size_t** _places_**);**
200
201**BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);**
202
203**BclError bcl_rand_seedWithNum(BclNumber** _n_**);**
204
205**BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);**
206
207**void bcl_rand_reseed(**_void_**);**
208
209**BclNumber bcl_rand_seed2num(**_void_**);**
210
211**BclRandInt bcl_rand_int(**_void_**);**
212
213**BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);**
214
215# DESCRIPTION
216
217bcl(3) is a library that implements arbitrary-precision decimal math, as
218standardized by POSIX
219(https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1).
220
221bcl(3) is async-signal-safe if **bcl_handleSignal(**_void_**)** is used
222properly. (See the **SIGNAL HANDLING** section.)
223
224bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and
225**Bc** prefixes for symbol names without collision.
226
227All of the items in its interface are described below. See the documentation for
228each function for what each function can return.
229
230## Signals
231
232**void bcl_handleSignal(**_void_**)**
233
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
239    executing.
240
241    If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
242    return to its caller.
243
244    See the **SIGNAL HANDLING** section.
245
246**bool bcl_running(**_void_**)**
247
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
251    **false**.
252
253    See the **SIGNAL HANDLING** section.
254
255## Setup
256
257**BclError bcl_init(**_void_**)**
258
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.
263
264    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
265    function can return:
266
267    * **BCL_ERROR_FATAL_ALLOC_ERR**
268
269    This function must be the first one clients call. Calling any other
270    function without calling this one first is undefined behavior.
271
272**void bcl_free(**_void_**)**
273
274:   Decrements bcl(3)'s reference count and frees the data associated with it if
275    the reference count is **0**.
276
277    This function must be the last one clients call. Calling this function
278    before calling any other function is undefined behavior.
279
280**bool bcl_abortOnFatalError(**_void_**)**
281
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
284    error occurs.
285
286    If activated, clients do not need to check for fatal errors.
287
288    The default is **false**.
289
290**void bcl_setAbortOnFatalError(bool** _abrt_**)**
291
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
295    after the call.
296
297    If activated, clients do not need to check for fatal errors.
298
299**bool bcl_leadingZeroes(**_void_**)**
300
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
304    will be added.
305
306    The default is **false**.
307
308**void bcl_setLeadingZeroes(bool** _leadingZeroes_**)**
309
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()**.
314
315**void bcl_gc(**_void_**)**
316
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
319    any time.
320
321## Contexts
322
323All procedures that take a **BclContext** parameter a require a valid context as
324an argument.
325
326**struct BclCtxt**
327
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.
331
332**BclContext**
333
334:   A typedef to a pointer of **struct BclCtxt**. This is the only handle
335    clients can get to **struct BclCtxt**.
336
337    A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
338    well as a list of numbers.
339
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
344    is **0**.
345
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**.
351
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).
354
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
358    application.
359
360**BclContext bcl_ctxt_create(**_void_**)**
361
362:   Creates a context and returns it. Returns **NULL** if there was an error.
363
364**void bcl_ctxt_free(BclContext** _ctxt_**)**
365
366:   Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
367    attempt to use an invalid context.
368
369**BclError bcl_pushContext(BclContext** _ctxt_**)**
370
371:   Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
372    with **bcl_ctxt_create(**_void_**)**.
373
374    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
375    function can return:
376
377    * **BCL_ERROR_FATAL_ALLOC_ERR**
378
379    There *must* be a valid context to do any arithmetic.
380
381**void bcl_popContext(**_void_**)**
382
383:   Pops the current context off of the stack, if one exists.
384
385**BclContext bcl_context(**_void_**)**
386
387:   Returns the current context, or **NULL** if no context exists.
388
389**void bcl_ctxt_freeNums(BclContext** _ctxt_**)**
390
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.
395
396**size_t bcl_ctxt_scale(BclContext** _ctxt_**)**
397
398:   Returns the **scale** for given context.
399
400**void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)**
401
402:   Sets the **scale** for the given context to the argument *scale*.
403
404**size_t bcl_ctxt_ibase(BclContext** _ctxt_**)**
405
406:   Returns the **ibase** for the given context.
407
408**void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)**
409
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**.
413
414**size_t bcl_ctxt_obase(BclContext** _ctxt_**)**
415
416:   Returns the **obase** for the given context.
417
418**void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)**
419
420:   Sets the **obase** for the given context to the argument *obase*.
421
422## Errors
423
424**BclError**
425
426:   An **enum** of possible error codes. See the **ERRORS** section for a
427    complete listing the codes.
428
429**BclError bcl_err(BclNumber** _n_**)**
430
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
434    **BCL_ERROR_NONE**.
435
436    There must be a valid current context.
437
438## Numbers
439
440All procedures in this section require a valid current context.
441
442**BclNumber**
443
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.
447
448**BclNumber bcl_num_create(**_void_**)**
449
450:   Creates and returns a **BclNumber**.
451
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:
454
455    * **BCL_ERROR_INVALID_CONTEXT**
456    * **BCL_ERROR_FATAL_ALLOC_ERR**
457
458**void bcl_num_free(BclNumber** _n_**)**
459
460:   Frees *n*. It is undefined behavior to use *n* after calling this function.
461
462**bool bcl_num_neg(BclNumber** _n_**)**
463
464:   Returns **true** if *n* is negative, **false** otherwise.
465
466**void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)**
467
468:   Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
469    positive.
470
471**size_t bcl_num_scale(BclNumber** _n_**)**
472
473:   Returns the *scale* of *n*.
474
475    The *scale* of a number is the number of decimal places it has after the
476    radix (decimal point).
477
478**BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)**
479
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.
483
484    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
485    function can return:
486
487    * **BCL_ERROR_INVALID_NUM**
488    * **BCL_ERROR_INVALID_CONTEXT**
489    * **BCL_ERROR_FATAL_ALLOC_ERR**
490
491**size_t bcl_num_len(BclNumber** _n_**)**
492
493:   Returns the number of *significant decimal digits* in *n*.
494
495## Conversion
496
497All procedures in this section require a valid current context.
498
499All procedures in this section consume the given **BclNumber** arguments that
500are not given to pointer arguments. See the **Consumption and Propagation**
501subsection below.
502
503**BclNumber bcl_parse(const char \*restrict** _val_**)**
504
505:   Parses a number string according to the current context's **ibase** and
506    returns the resulting number.
507
508    *val* must be non-**NULL** and a valid string. See
509    **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
510    information.
511
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:
514
515    * **BCL_ERROR_INVALID_NUM**
516    * **BCL_ERROR_INVALID_CONTEXT**
517    * **BCL_ERROR_PARSE_INVALID_STR**
518    * **BCL_ERROR_FATAL_ALLOC_ERR**
519
520**char\* bcl_string(BclNumber** _n_**)**
521
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
524    caller.
525
526    *n* is consumed; it cannot be used after the call. See the
527    **Consumption and Propagation** subsection below.
528
529**BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)**
530
531:   Converts *n* into a **BclBigDig** and returns the result in the space
532    pointed to by *result*.
533
534    *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
535
536    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
537    function can return:
538
539    * **BCL_ERROR_INVALID_NUM**
540    * **BCL_ERROR_INVALID_CONTEXT**
541    * **BCL_ERROR_MATH_OVERFLOW**
542
543    *n* is consumed; it cannot be used after the call. See the
544    **Consumption and Propagation** subsection below.
545
546**BclNumber bcl_bigdig2num(BclBigDig** _val_**)**
547
548:   Creates a **BclNumber** from *val*.
549
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:
552
553    * **BCL_ERROR_INVALID_CONTEXT**
554    * **BCL_ERROR_FATAL_ALLOC_ERR**
555
556## Math
557
558All procedures in this section require a valid current context.
559
560All procedures in this section can return the following errors:
561
562* **BCL_ERROR_INVALID_NUM**
563* **BCL_ERROR_INVALID_CONTEXT**
564* **BCL_ERROR_FATAL_ALLOC_ERR**
565
566**BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)**
567
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*.
570
571    *a* and *b* are consumed; they cannot be used after the call. See the
572    **Consumption and Propagation** subsection below.
573
574    *a* and *b* can be the same number.
575
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:
578
579    * **BCL_ERROR_INVALID_NUM**
580    * **BCL_ERROR_INVALID_CONTEXT**
581    * **BCL_ERROR_FATAL_ALLOC_ERR**
582
583**BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)**
584
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*.
587
588    *a* and *b* are consumed; they cannot be used after the call. See the
589    **Consumption and Propagation** subsection below.
590
591    *a* and *b* can be the same number.
592
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:
595
596    * **BCL_ERROR_INVALID_NUM**
597    * **BCL_ERROR_INVALID_CONTEXT**
598    * **BCL_ERROR_FATAL_ALLOC_ERR**
599
600**BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)**
601
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.
606
607    *a* and *b* are consumed; they cannot be used after the call. See the
608    **Consumption and Propagation** subsection below.
609
610    *a* and *b* can be the same number.
611
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:
614
615    * **BCL_ERROR_INVALID_NUM**
616    * **BCL_ERROR_INVALID_CONTEXT**
617    * **BCL_ERROR_FATAL_ALLOC_ERR**
618
619**BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)**
620
621:   Divides *a* by *b* and returns the result. The *scale* of the result is the
622    *scale* of the current context.
623
624    *b* cannot be **0**.
625
626    *a* and *b* are consumed; they cannot be used after the call. See the
627    **Consumption and Propagation** subsection below.
628
629    *a* and *b* can be the same number.
630
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:
633
634    * **BCL_ERROR_INVALID_NUM**
635    * **BCL_ERROR_INVALID_CONTEXT**
636    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
637    * **BCL_ERROR_FATAL_ALLOC_ERR**
638
639**BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)**
640
641:   Divides *a* by *b* to the *scale* of the current context, computes the
642    modulus **a-(a/b)\*b**, and returns the modulus.
643
644    *b* cannot be **0**.
645
646    *a* and *b* are consumed; they cannot be used after the call. See the
647    **Consumption and Propagation** subsection below.
648
649    *a* and *b* can be the same number.
650
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:
653
654    * **BCL_ERROR_INVALID_NUM**
655    * **BCL_ERROR_INVALID_CONTEXT**
656    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
657    * **BCL_ERROR_FATAL_ALLOC_ERR**
658
659**BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)**
660
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
663    be non-zero.
664
665    *b* must be an integer. If *b* is negative, *a* must not be **0**.
666
667    *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
668
669    *a* and *b* are consumed; they cannot be used after the call. See the
670    **Consumption and Propagation** subsection below.
671
672    *a* and *b* can be the same number.
673
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:
676
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**
683
684**BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)**
685
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.
688
689    *b* must be an integer.
690
691    *a* and *b* are consumed; they cannot be used after the call. See the
692    **Consumption and Propagation** subsection below.
693
694    *a* and *b* can be the same number.
695
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:
698
699    * **BCL_ERROR_INVALID_NUM**
700    * **BCL_ERROR_INVALID_CONTEXT**
701    * **BCL_ERROR_MATH_NON_INTEGER**
702    * **BCL_ERROR_FATAL_ALLOC_ERR**
703
704**BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)**
705
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.
708
709    *b* must be an integer.
710
711    *a* and *b* are consumed; they cannot be used after the call. See the
712    **Consumption and Propagation** subsection below.
713
714    *a* and *b* can be the same number.
715
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:
718
719    * **BCL_ERROR_INVALID_NUM**
720    * **BCL_ERROR_INVALID_CONTEXT**
721    * **BCL_ERROR_MATH_NON_INTEGER**
722    * **BCL_ERROR_FATAL_ALLOC_ERR**
723
724**BclNumber bcl_sqrt(BclNumber** _a_**)**
725
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.
728
729    *a* cannot be negative.
730
731    *a* is consumed; it cannot be used after the call. See the
732    **Consumption and Propagation** subsection below.
733
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:
736
737    * **BCL_ERROR_INVALID_NUM**
738    * **BCL_ERROR_INVALID_CONTEXT**
739    * **BCL_ERROR_MATH_NEGATIVE**
740    * **BCL_ERROR_FATAL_ALLOC_ERR**
741
742**BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)**
743
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*.
747
748    *b* cannot be **0**.
749
750    *a* and *b* are consumed; they cannot be used after the call. See the
751    **Consumption and Propagation** subsection below.
752
753    *c* and *d* cannot point to the same place, nor can they point to the space
754    occupied by *a* or *b*.
755
756    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
757    function can return:
758
759    * **BCL_ERROR_INVALID_NUM**
760    * **BCL_ERROR_INVALID_CONTEXT**
761    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
762    * **BCL_ERROR_FATAL_ALLOC_ERR**
763
764**BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)**
765
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.
769
770    *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
771    negative.
772
773    *a*, *b*, and *c* are consumed; they cannot be used after the call. See the
774    **Consumption and Propagation** subsection below.
775
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:
778
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**
785
786## Miscellaneous
787
788**void bcl_zero(BclNumber** _n_**)**
789
790:   Sets *n* to **0**.
791
792**void bcl_one(BclNumber** _n_**)**
793
794:   Sets *n* to **1**.
795
796**ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)**
797
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*.
800
801**BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)**
802
803:   Copies *s* into *d*.
804
805    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
806    function can return:
807
808    * **BCL_ERROR_INVALID_NUM**
809    * **BCL_ERROR_INVALID_CONTEXT**
810    * **BCL_ERROR_FATAL_ALLOC_ERR**
811
812**BclNumber bcl_dup(BclNumber** _s_**)**
813
814:   Creates and returns a new **BclNumber** that is a copy of *s*.
815
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:
818
819    * **BCL_ERROR_INVALID_NUM**
820    * **BCL_ERROR_INVALID_CONTEXT**
821    * **BCL_ERROR_FATAL_ALLOC_ERR**
822
823## Pseudo-Random Number Generator
824
825The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
826seed twice, it will produce the same sequence of pseudo-random numbers twice.
827
828By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
829that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
830then calling **rand()** for each byte, since **rand()** is only guaranteed to
831return **15** bits.
832
833This should provide fairly good seeding in the standard case while also
834remaining fairly portable.
835
836If necessary, the PRNG can be reseeded with one of the following functions:
837
838* **bcl_rand_seedWithNum(BclNumber)**
839* **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])**
840* **bcl_rand_reseed(**_void_**)**
841
842The following items allow clients to use the pseudo-random number generator. All
843procedures require a valid current context.
844
845**BCL_SEED_ULONGS**
846
847:   The number of **unsigned long**'s in a seed for bcl(3)'s random number
848    generator.
849
850**BCL_SEED_SIZE**
851
852:   The size, in **char**'s, of a seed for bcl(3)'s random number generator.
853
854**BclBigDig**
855
856:   bcl(3)'s overflow type (see the **PERFORMANCE** section).
857
858**BclRandInt**
859
860:   An unsigned integer type returned by bcl(3)'s random number generator.
861
862**BclNumber bcl_irand(BclNumber** _a_**)**
863
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.
869
870    *a* must be an integer and non-negative.
871
872    *a* is consumed; it cannot be used after the call. See the
873    **Consumption and Propagation** subsection below.
874
875    This procedure requires a valid current context.
876
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:
879
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**
885
886**BclNumber bcl_frand(size_t** _places_**)**
887
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
890    limits on *places*.
891
892    This procedure requires a valid current context.
893
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:
896
897    * **BCL_ERROR_INVALID_CONTEXT**
898    * **BCL_ERROR_FATAL_ALLOC_ERR**
899
900**BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)**
901
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*.
904
905    *a* must be an integer and non-negative.
906
907    *a* is consumed; it cannot be used after the call. See the
908    **Consumption and Propagation** subsection below.
909
910    This procedure requires a valid current context.
911
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:
914
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**
920
921**BclError bcl_rand_seedWithNum(BclNumber** _n_**)**
922
923:   Seeds the PRNG with *n*.
924
925    *n* is *not* consumed.
926
927    This procedure requires a valid current context.
928
929    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
930    function can return:
931
932    * **BCL_ERROR_INVALID_NUM**
933    * **BCL_ERROR_INVALID_CONTEXT**
934
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*.
938
939**BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])**
940
941:   Seeds the PRNG with the bytes in *seed*.
942
943    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
944    function can return:
945
946    * **BCL_ERROR_INVALID_CONTEXT**
947
948**void bcl_rand_reseed(**_void_**)**
949
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()**.
952
953    This procedure cannot fail.
954
955**BclNumber bcl_rand_seed2num(**_void_**)**
956
957:   Returns the current seed of the PRNG as a **BclNumber**.
958
959    This procedure requires a valid current context.
960
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:
963
964    * **BCL_ERROR_INVALID_CONTEXT**
965    * **BCL_ERROR_FATAL_ALLOC_ERR**
966
967**BclRandInt bcl_rand_int(**_void_**)**
968
969:   Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
970
971    This procedure cannot fail.
972
973**BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)**
974
975:   Returns a random integer between **0** and *bound* (exclusive). Bias is
976    removed before returning the integer.
977
978    This procedure cannot fail.
979
980## Consumption and Propagation
981
982Some functions are listed as consuming some or all of their arguments. This
983means that the arguments are freed, regardless of if there were errors or not.
984
985This is to enable compact code like the following:
986
987    BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
988
989If arguments to those functions were not consumed, memory would be leaked until
990reclaimed with **bcl_ctxt_freeNums(BclContext)**.
991
992When errors occur, they are propagated through. The result should always be
993checked with **bcl_err(BclNumber)**, so the example above should properly
994be:
995
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) {
998        // Handle the error.
999    }
1000
1001# ERRORS
1002
1003Most functions in bcl(3) return, directly or indirectly, any one of the error
1004codes defined in **BclError**. The complete list of codes is the following:
1005
1006**BCL_ERROR_NONE**
1007
1008:   Success; no error occurred.
1009
1010**BCL_ERROR_INVALID_NUM**
1011
1012:   An invalid **BclNumber** was given as a parameter.
1013
1014**BCL_ERROR_INVALID_CONTEXT**
1015
1016:   An invalid **BclContext** is being used.
1017
1018**BCL_ERROR_SIGNAL**
1019
1020:   A signal interrupted execution.
1021
1022**BCL_ERROR_MATH_NEGATIVE**
1023
1024:   A negative number was given as an argument to a parameter that cannot accept
1025    negative numbers, such as for square roots.
1026
1027**BCL_ERROR_MATH_NON_INTEGER**
1028
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()**.
1031
1032**BCL_ERROR_MATH_OVERFLOW**
1033
1034:   A number that would overflow its result was given as an argument, such as
1035    for converting a **BclNumber** to a **BclBigDig**.
1036
1037**BCL_ERROR_MATH_DIVIDE_BY_ZERO**
1038
1039:   A divide by zero occurred.
1040
1041**BCL_ERROR_PARSE_INVALID_STR**
1042
1043:   An invalid number string was passed to a parsing function.
1044
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.
1049
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
1055    exponent.
1056
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
1063    will be **0.0016**.
1064
1065**BCL_ERROR_FATAL_ALLOC_ERR**
1066
1067:   bcl(3) failed to allocate memory.
1068
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.
1073
1074    It is highly recommended that client libraries do *not* activate this
1075    behavior.
1076
1077**BCL_ERROR_FATAL_UNKNOWN_ERR**
1078
1079:   An unknown error occurred.
1080
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.
1085
1086    It is highly recommended that client libraries do *not* activate this
1087    behavior.
1088
1089# ATTRIBUTES
1090
1091When **bcl_handleSignal(**_void_**)** is used properly, bcl(3) is
1092async-signal-safe.
1093
1094bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one
1095thread.
1096
1097# PERFORMANCE
1098
1099Most bc(1) implementations use **char** types to calculate the value of **1**
1100decimal digit at a time, but that can be slow. bcl(3) does something
1101different.
1102
1103It uses large integers to calculate more than **1** decimal digit at a time. If
1104built 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
1106where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1107value (the number of decimal digits per large integer) is called
1108**BC_BASE_DIGS**.
1109
1110In addition, this bcl(3) uses an even larger integer for overflow checking. This
1111integer type depends on the value of **BC_LONG_BIT**, but is always at least
1112twice as large as the integer type used to store digits.
1113
1114# LIMITS
1115
1116The following are the limits on bcl(3):
1117
1118**BC_LONG_BIT**
1119
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).
1123
1124**BC_BASE_DIGS**
1125
1126:   The number of decimal digits per large integer (see the **PERFORMANCE**
1127    section). Depends on **BC_LONG_BIT**.
1128
1129**BC_BASE_POW**
1130
1131:   The max decimal number that each large integer can store (see
1132    **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1133
1134**BC_OVERFLOW_MAX**
1135
1136:   The max number that the overflow type (see the **PERFORMANCE** section) can
1137    hold. Depends on **BC_LONG_BIT**.
1138
1139**BC_BASE_MAX**
1140
1141:   The maximum output base. Set at **BC_BASE_POW**.
1142
1143**BC_SCALE_MAX**
1144
1145:   The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1146
1147**BC_NUM_MAX**
1148
1149:   The maximum length of a number (in decimal digits), which includes digits
1150    after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1151
1152**BC_RAND_MAX**
1153
1154:   The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
1155    Set at **2\^BC_LONG_BIT-1**.
1156
1157Exponent
1158
1159:   The maximum allowable exponent (positive or negative). Set at
1160    **BC_OVERFLOW_MAX**.
1161
1162These 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
1164become a problem. In fact, memory should be exhausted before these limits should
1165be hit.
1166
1167# SIGNAL HANDLING
1168
1169If a signal handler calls **bcl_handleSignal(**_void_**)** from the same thread
1170that there are bcl(3) functions executing in, it will cause all execution to
1171stop as soon as possible, interrupting long-running calculations, if necessary
1172and cause the function that was executing to return. If possible, the error code
1173**BC_ERROR_SIGNAL** is returned.
1174
1175If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
1176return to its caller.
1177
1178It is undefined behavior if **bcl_handleSignal(**_void_**)** is called from
1179a thread that is not executing bcl(3) functions, if bcl(3) functions are
1180executing.
1181
1182# SEE ALSO
1183
1184bc(1) and dc(1)
1185
1186# STANDARDS
1187
1188bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017
1189(“POSIX.1-2017”) specification at
1190https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html for bc(1).
1191
1192Note that the specification explicitly says that bc(1) only accepts numbers that
1193use a period (**.**) as a radix point, regardless of the value of
1194**LC_NUMERIC**. This is also true of bcl(3).
1195
1196# BUGS
1197
1198None are known. Report bugs at https://git.yzena.com/gavin/bc.
1199
1200# AUTHORS
1201
1202Gavin D. Howard <gavin@yzena.com> and contributors.
1203