xref: /freebsd/contrib/bc/manuals/bcl.3.md (revision d7d962ead0b6e5e8a39202d0590022082bf5bfb6)
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**void bcl_gc(**_void_**);**
65
66## Contexts
67
68These items will allow clients to handle contexts, which are isolated from each
69other. This allows more than one client to use bcl(3) in the same program.
70
71**struct BclCtxt;**
72
73**typedef struct BclCtxt\* BclContext;**
74
75**BclContext bcl_ctxt_create(**_void_**);**
76
77**void bcl_ctxt_free(BclContext** _ctxt_**);**
78
79**BclError bcl_pushContext(BclContext** _ctxt_**);**
80
81**void bcl_popContext(**_void_**);**
82
83**BclContext bcl_context(**_void_**);**
84
85**void bcl_ctxt_freeNums(BclContext** _ctxt_**);**
86
87**size_t bcl_ctxt_scale(BclContext** _ctxt_**);**
88
89**void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);**
90
91**size_t bcl_ctxt_ibase(BclContext** _ctxt_**);**
92
93**void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);**
94
95**size_t bcl_ctxt_obase(BclContext** _ctxt_**);**
96
97**void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);**
98
99## Errors
100
101These items allow clients to handle errors.
102
103**typedef enum BclError BclError;**
104
105**BclError bcl_err(BclNumber** _n_**);**
106
107## Numbers
108
109These items allow clients to manipulate and query the arbitrary-precision
110numbers managed by bcl(3).
111
112**typedef struct { size_t i; } BclNumber;**
113
114**BclNumber bcl_num_create(**_void_**);**
115
116**void bcl_num_free(BclNumber** _n_**);**
117
118**bool bcl_num_neg(BclNumber** _n_**);**
119
120**void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);**
121
122**size_t bcl_num_scale(BclNumber** _n_**);**
123
124**BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);**
125
126**size_t bcl_num_len(BclNumber** _n_**);**
127
128## Conversion
129
130These items allow clients to convert numbers into and from strings and integers.
131
132**BclNumber bcl_parse(const char \*restrict** _val_**);**
133
134**char\* bcl_string(BclNumber** _n_**);**
135
136**BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);**
137
138**BclNumber bcl_bigdig2num(BclBigDig** _val_**);**
139
140## Math
141
142These items allow clients to run math on numbers.
143
144**BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);**
145
146**BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);**
147
148**BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);**
149
150**BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);**
151
152**BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);**
153
154**BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);**
155
156**BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);**
157
158**BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);**
159
160**BclNumber bcl_sqrt(BclNumber** _a_**);**
161
162**BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);**
163
164**BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);**
165
166## Miscellaneous
167
168These items are miscellaneous.
169
170**void bcl_zero(BclNumber** _n_**);**
171
172**void bcl_one(BclNumber** _n_**);**
173
174**ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);**
175
176**BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);**
177
178**BclNumber bcl_dup(BclNumber** _s_**);**
179
180## Pseudo-Random Number Generator
181
182These items allow clients to manipulate the seeded pseudo-random number
183generator in bcl(3).
184
185**#define BCL_SEED_ULONGS**
186
187**#define BCL_SEED_SIZE**
188
189**typedef unsigned long BclBigDig;**
190
191**typedef unsigned long BclRandInt;**
192
193**BclNumber bcl_irand(BclNumber** _a_**);**
194
195**BclNumber bcl_frand(size_t** _places_**);**
196
197**BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);**
198
199**BclError bcl_rand_seedWithNum(BclNumber** _n_**);**
200
201**BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);**
202
203**void bcl_rand_reseed(**_void_**);**
204
205**BclNumber bcl_rand_seed2num(**_void_**);**
206
207**BclRandInt bcl_rand_int(**_void_**);**
208
209**BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);**
210
211# DESCRIPTION
212
213bcl(3) is a library that implements arbitrary-precision decimal math, as
214[standardized by POSIX][1] in bc(1).
215
216bcl(3) is async-signal-safe if **bcl_handleSignal(**_void_**)** is used
217properly. (See the **SIGNAL HANDLING** section.)
218
219bcl(3) assumes that it is allowed to use the **bcl_** and **bc_** prefixes for
220symbol names without collision.
221
222All of the items in its interface are described below. See the documentation for
223each function for what each function can return.
224
225## Signals
226
227**void bcl_handleSignal(**_void_**)**
228
229:   An async-signal-safe function that can be called from a signal handler. If
230    called from a signal handler on the same thread as any executing bcl(3)
231    functions, it will interrupt the functions and force them to return early.
232    It is undefined behavior if this function is called from a thread that is
233    *not* executing any bcl(3) functions while any bcl(3) functions are
234    executing.
235
236    If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
237    return to its caller.
238
239    See the **SIGNAL HANDLING** section.
240
241**bool bcl_running(**_void_**)**
242
243:   An async-signal-safe function that can be called from a signal handler. It
244    will return **true** if any bcl(3) procedures are running, which means it is
245    safe to call **bcl_handleSignal(**_void_**)**. Otherwise, it returns
246    **false**.
247
248    See the **SIGNAL HANDLING** section.
249
250## Setup
251
252**BclError bcl_init(**_void_**)**
253
254:   Initializes this library. This function can be called multiple times, but
255    each call must be matched by a call to **bcl_free(**_void_**)**. This is to
256    make it possible for multiple libraries and applications to initialize
257    bcl(3) without problem.
258
259    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
260    function can return:
261
262    * **BCL_ERROR_FATAL_ALLOC_ERR**
263
264    This function must be the first one clients call. Calling any other
265    function without calling this one first is undefined behavior.
266
267**void bcl_free(**_void_**)**
268
269:   Decrements bcl(3)'s reference count and frees the data associated with it if
270    the reference count is **0**.
271
272    This function must be the last one clients call. Calling this function
273    before calling any other function is undefined behavior.
274
275**bool bcl_abortOnFatalError(**_void_**)**
276
277:   Queries and returns the current state of calling **abort()** on fatal
278    errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal
279    error occurs.
280
281    If activated, clients do not need to check for fatal errors.
282
283**void bcl_setAbortOnFatalError(bool** _abrt_**)**
284
285:   Sets the state of calling **abort()** on fatal errors. If *abrt* is
286    **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the
287    call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors
288    after the call.
289
290    If activated, clients do not need to check for fatal errors.
291
292**void bcl_gc(**_void_**)**
293
294:   Garbage collects cached instances of arbitrary-precision numbers. This only
295    frees the memory of numbers that are *not* in use, so it is safe to call at
296    any time.
297
298## Contexts
299
300All procedures that take a **BclContext** parameter a require a valid context as
301an argument.
302
303**struct BclCtxt**
304
305:   A forward declaration for a hidden **struct** type. Clients cannot access
306    the internals of the **struct** type directly. All interactions with the
307    type are done through pointers. See **BclContext** below.
308
309**BclContext**
310
311:   A typedef to a pointer of **struct BclCtxt**. This is the only handle
312    clients can get to **struct BclCtxt**.
313
314    A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
315    well as a list of numbers.
316
317    **scale** is a value used to control how many decimal places calculations
318    should use. A value of **0** means that calculations are done on integers
319    only, where applicable, and a value of 20, for example, means that all
320    applicable calculations return results with 20 decimal places. The default
321    is **0**.
322
323    **ibase** is a value used to control the input base. The minimum **ibase**
324    is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are
325    parsed as though they are in binary, and any digits larger than **1** are
326    clamped. Likewise, a value of **10** means that numbers are parsed as though
327    they are decimal, and any larger digits are clamped. The default is **10**.
328
329    **obase** is a value used to control the output base. The minimum **obase**
330    is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section).
331
332    Numbers created in one context are not valid in another context. It is
333    undefined behavior to use a number created in a different context. Contexts
334    are meant to isolate the numbers used by different clients in the same
335    application.
336
337**BclContext bcl_ctxt_create(**_void_**)**
338
339:   Creates a context and returns it. Returns **NULL** if there was an error.
340
341**void bcl_ctxt_free(BclContext** _ctxt_**)**
342
343:   Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
344    attempt to use an invalid context.
345
346**BclError bcl_pushContext(BclContext** _ctxt_**)**
347
348:   Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
349    with **bcl_ctxt_create(**_void_**)**.
350
351    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
352    function can return:
353
354    * **BCL_ERROR_FATAL_ALLOC_ERR**
355
356    There *must* be a valid context to do any arithmetic.
357
358**void bcl_popContext(**_void_**)**
359
360:   Pops the current context off of the stack, if one exists.
361
362**BclContext bcl_context(**_void_**)**
363
364:   Returns the current context, or **NULL** if no context exists.
365
366**void bcl_ctxt_freeNums(BclContext** _ctxt_**)**
367
368:   Frees all numbers in use that are associated with *ctxt*. It is undefined
369    behavior to attempt to use a number associated with *ctxt* after calling
370    this procedure unless such numbers have been created with
371    **bcl_num_create(**_void_**)** after calling this procedure.
372
373**size_t bcl_ctxt_scale(BclContext** _ctxt_**)**
374
375:   Returns the **scale** for given context.
376
377**void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)**
378
379:   Sets the **scale** for the given context to the argument *scale*.
380
381**size_t bcl_ctxt_ibase(BclContext** _ctxt_**)**
382
383:   Returns the **ibase** for the given context.
384
385**void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)**
386
387:   Sets the **ibase** for the given context to the argument *ibase*. If the
388    argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is
389    clamped to **2**, and any values above **36** are clamped to **36**.
390
391**size_t bcl_ctxt_obase(BclContext** _ctxt_**)**
392
393:   Returns the **obase** for the given context.
394
395**void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)**
396
397:   Sets the **obase** for the given context to the argument *obase*.
398
399## Errors
400
401**BclError**
402
403:   An **enum** of possible error codes. See the **ERRORS** section for a
404    complete listing the codes.
405
406**BclError bcl_err(BclNumber** _n_**)**
407
408:   Checks for errors in a **BclNumber**. All functions that can return a
409    **BclNumber** can encode an error in the number, and this function will
410    return the error, if any. If there was no error, it will return
411    **BCL_ERROR_NONE**.
412
413    There must be a valid current context.
414
415## Numbers
416
417All procedures in this section require a valid current context.
418
419**BclNumber**
420
421:   A handle to an arbitrary-precision number. The actual number type is not
422    exposed; the **BclNumber** handle is the only way clients can refer to
423    instances of arbitrary-precision numbers.
424
425**BclNumber bcl_num_create(**_void_**)**
426
427:   Creates and returns a **BclNumber**.
428
429    bcl(3) will encode an error in the return value, if there was one. The error
430    can be queried with **bcl_err(BclNumber)**. Possible errors include:
431
432    * **BCL_ERROR_INVALID_CONTEXT**
433    * **BCL_ERROR_FATAL_ALLOC_ERR**
434
435**void bcl_num_free(BclNumber** _n_**)**
436
437:   Frees *n*. It is undefined behavior to use *n* after calling this function.
438
439**bool bcl_num_neg(BclNumber** _n_**)**
440
441:   Returns **true** if *n* is negative, **false** otherwise.
442
443**void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)**
444
445:   Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
446    positive.
447
448**size_t bcl_num_scale(BclNumber** _n_**)**
449
450:   Returns the *scale* of *n*.
451
452    The *scale* of a number is the number of decimal places it has after the
453    radix (decimal point).
454
455**BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)**
456
457:   Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is
458    greater than the *scale* of *n*, *n* is extended. If the argument *scale* is
459    less than the *scale* of *n*, *n* is truncated.
460
461    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
462    function can return:
463
464    * **BCL_ERROR_INVALID_NUM**
465    * **BCL_ERROR_INVALID_CONTEXT**
466    * **BCL_ERROR_FATAL_ALLOC_ERR**
467
468**size_t bcl_num_len(BclNumber** _n_**)**
469
470:   Returns the number of *significant decimal digits* in *n*.
471
472## Conversion
473
474All procedures in this section require a valid current context.
475
476All procedures in this section consume the given **BclNumber** arguments that
477are not given to pointer arguments. See the **Consumption and Propagation**
478subsection below.
479
480**BclNumber bcl_parse(const char \*restrict** _val_**)**
481
482:   Parses a number string according to the current context's **ibase** and
483    returns the resulting number.
484
485    *val* must be non-**NULL** and a valid string. See
486    **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
487    information.
488
489    bcl(3) will encode an error in the return value, if there was one. The error
490    can be queried with **bcl_err(BclNumber)**. Possible errors include:
491
492    * **BCL_ERROR_INVALID_NUM**
493    * **BCL_ERROR_INVALID_CONTEXT**
494    * **BCL_ERROR_PARSE_INVALID_STR**
495    * **BCL_ERROR_FATAL_ALLOC_ERR**
496
497**char\* bcl_string(BclNumber** _n_**)**
498
499:   Returns a string representation of *n* according the the current context's
500    **ibase**. The string is dynamically allocated and must be freed by the
501    caller.
502
503    *n* is consumed; it cannot be used after the call. See the
504    **Consumption and Propagation** subsection below.
505
506**BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)**
507
508:   Converts *n* into a **BclBigDig** and returns the result in the space
509    pointed to by *result*.
510
511    *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
512
513    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
514    function can return:
515
516    * **BCL_ERROR_INVALID_NUM**
517    * **BCL_ERROR_INVALID_CONTEXT**
518    * **BCL_ERROR_MATH_OVERFLOW**
519
520    *n* is consumed; it cannot be used after the call. See the
521    **Consumption and Propagation** subsection below.
522
523**BclNumber bcl_bigdig2num(BclBigDig** _val_**)**
524
525:   Creates a **BclNumber** from *val*.
526
527    bcl(3) will encode an error in the return value, if there was one. The error
528    can be queried with **bcl_err(BclNumber)**. Possible errors include:
529
530    * **BCL_ERROR_INVALID_CONTEXT**
531    * **BCL_ERROR_FATAL_ALLOC_ERR**
532
533## Math
534
535All procedures in this section require a valid current context.
536
537All procedures in this section can return the following errors:
538
539* **BCL_ERROR_INVALID_NUM**
540* **BCL_ERROR_INVALID_CONTEXT**
541* **BCL_ERROR_FATAL_ALLOC_ERR**
542
543**BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)**
544
545:   Adds *a* and *b* and returns the result. The *scale* of the result is the
546    max of the *scale*s of *a* and *b*.
547
548    *a* and *b* are consumed; they cannot be used after the call. See the
549    **Consumption and Propagation** subsection below.
550
551    *a* and *b* can be the same number.
552
553    bcl(3) will encode an error in the return value, if there was one. The error
554    can be queried with **bcl_err(BclNumber)**. Possible errors include:
555
556    * **BCL_ERROR_INVALID_NUM**
557    * **BCL_ERROR_INVALID_CONTEXT**
558    * **BCL_ERROR_FATAL_ALLOC_ERR**
559
560**BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)**
561
562:   Subtracts *b* from *a* and returns the result. The *scale* of the result is
563    the max of the *scale*s of *a* and *b*.
564
565    *a* and *b* are consumed; they cannot be used after the call. See the
566    **Consumption and Propagation** subsection below.
567
568    *a* and *b* can be the same number.
569
570    bcl(3) will encode an error in the return value, if there was one. The error
571    can be queried with **bcl_err(BclNumber)**. Possible errors include:
572
573    * **BCL_ERROR_INVALID_NUM**
574    * **BCL_ERROR_INVALID_CONTEXT**
575    * **BCL_ERROR_FATAL_ALLOC_ERR**
576
577**BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)**
578
579:   Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of
580    *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal
581    to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and
582    **max()** return the obvious values.
583
584    *a* and *b* are consumed; they cannot be used after the call. See the
585    **Consumption and Propagation** subsection below.
586
587    *a* and *b* can be the same number.
588
589    bcl(3) will encode an error in the return value, if there was one. The error
590    can be queried with **bcl_err(BclNumber)**. Possible errors include:
591
592    * **BCL_ERROR_INVALID_NUM**
593    * **BCL_ERROR_INVALID_CONTEXT**
594    * **BCL_ERROR_FATAL_ALLOC_ERR**
595
596**BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)**
597
598:   Divides *a* by *b* and returns the result. The *scale* of the result is the
599    *scale* of the current context.
600
601    *b* cannot be **0**.
602
603    *a* and *b* are consumed; they cannot be used after the call. See the
604    **Consumption and Propagation** subsection below.
605
606    *a* and *b* can be the same number.
607
608    bcl(3) will encode an error in the return value, if there was one. The error
609    can be queried with **bcl_err(BclNumber)**. Possible errors include:
610
611    * **BCL_ERROR_INVALID_NUM**
612    * **BCL_ERROR_INVALID_CONTEXT**
613    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
614    * **BCL_ERROR_FATAL_ALLOC_ERR**
615
616**BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)**
617
618:   Divides *a* by *b* to the *scale* of the current context, computes the
619    modulus **a-(a/b)\*b**, and returns the modulus.
620
621    *b* cannot be **0**.
622
623    *a* and *b* are consumed; they cannot be used after the call. See the
624    **Consumption and Propagation** subsection below.
625
626    *a* and *b* can be the same number.
627
628    bcl(3) will encode an error in the return value, if there was one. The error
629    can be queried with **bcl_err(BclNumber)**. Possible errors include:
630
631    * **BCL_ERROR_INVALID_NUM**
632    * **BCL_ERROR_INVALID_CONTEXT**
633    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
634    * **BCL_ERROR_FATAL_ALLOC_ERR**
635
636**BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)**
637
638:   Calculates *a* to the power of *b* to the *scale* of the current context.
639    *b* must be an integer, but can be negative. If it is negative, *a* must
640    be non-zero.
641
642    *b* must be an integer. If *b* is negative, *a* must not be **0**.
643
644    *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
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_NON_INTEGER**
657    * **BCL_ERROR_MATH_OVERFLOW**
658    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
659    * **BCL_ERROR_FATAL_ALLOC_ERR**
660
661**BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)**
662
663:   Shifts *a* left (moves the radix right) by *b* places and returns the
664    result. This is done in decimal. *b* must be an integer.
665
666    *b* must be an integer.
667
668    *a* and *b* are consumed; they cannot be used after the call. See the
669    **Consumption and Propagation** subsection below.
670
671    *a* and *b* can be the same number.
672
673    bcl(3) will encode an error in the return value, if there was one. The error
674    can be queried with **bcl_err(BclNumber)**. Possible errors include:
675
676    * **BCL_ERROR_INVALID_NUM**
677    * **BCL_ERROR_INVALID_CONTEXT**
678    * **BCL_ERROR_MATH_NON_INTEGER**
679    * **BCL_ERROR_FATAL_ALLOC_ERR**
680
681**BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)**
682
683:   Shifts *a* right (moves the radix left) by *b* places and returns the
684    result. This is done in decimal. *b* must be an integer.
685
686    *b* must be an integer.
687
688    *a* and *b* are consumed; they cannot be used after the call. See the
689    **Consumption and Propagation** subsection below.
690
691    *a* and *b* can be the same number.
692
693    bcl(3) will encode an error in the return value, if there was one. The error
694    can be queried with **bcl_err(BclNumber)**. Possible errors include:
695
696    * **BCL_ERROR_INVALID_NUM**
697    * **BCL_ERROR_INVALID_CONTEXT**
698    * **BCL_ERROR_MATH_NON_INTEGER**
699    * **BCL_ERROR_FATAL_ALLOC_ERR**
700
701**BclNumber bcl_sqrt(BclNumber** _a_**)**
702
703:   Calculates the square root of *a* and returns the result. The *scale* of the
704    result is equal to the **scale** of the current context.
705
706    *a* cannot be negative.
707
708    *a* is consumed; it cannot be used after the call. See the
709    **Consumption and Propagation** subsection below.
710
711    bcl(3) will encode an error in the return value, if there was one. The error
712    can be queried with **bcl_err(BclNumber)**. Possible errors include:
713
714    * **BCL_ERROR_INVALID_NUM**
715    * **BCL_ERROR_INVALID_CONTEXT**
716    * **BCL_ERROR_MATH_NEGATIVE**
717    * **BCL_ERROR_FATAL_ALLOC_ERR**
718
719**BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)**
720
721:   Divides *a* by *b* and returns the quotient in a new number which is put
722    into the space pointed to by *c*, and puts the modulus in a new number which
723    is put into the space pointed to by *d*.
724
725    *b* cannot be **0**.
726
727    *a* and *b* are consumed; they cannot be used after the call. See the
728    **Consumption and Propagation** subsection below.
729
730    *c* and *d* cannot point to the same place, nor can they point to the space
731    occupied by *a* or *b*.
732
733    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
734    function can return:
735
736    * **BCL_ERROR_INVALID_NUM**
737    * **BCL_ERROR_INVALID_CONTEXT**
738    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
739    * **BCL_ERROR_FATAL_ALLOC_ERR**
740
741**BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)**
742
743:   Computes a modular exponentiation where *a* is the base, *b* is the
744    exponent, and *c* is the modulus, and returns the result. The *scale* of the
745    result is equal to the **scale** of the current context.
746
747    *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
748    negative.
749
750    *a*, *b*, and *c* are consumed; they cannot be used after the call. See the
751    **Consumption and Propagation** subsection below.
752
753    bcl(3) will encode an error in the return value, if there was one. The error
754    can be queried with **bcl_err(BclNumber)**. Possible errors include:
755
756    * **BCL_ERROR_INVALID_NUM**
757    * **BCL_ERROR_INVALID_CONTEXT**
758    * **BCL_ERROR_MATH_NEGATIVE**
759    * **BCL_ERROR_MATH_NON_INTEGER**
760    * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
761    * **BCL_ERROR_FATAL_ALLOC_ERR**
762
763## Miscellaneous
764
765**void bcl_zero(BclNumber** _n_**)**
766
767:   Sets *n* to **0**.
768
769**void bcl_one(BclNumber** _n_**)**
770
771:   Sets *n* to **1**.
772
773**ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)**
774
775:   Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if
776    *a* is less than *b*, and **>0** if *a* is greater than *b*.
777
778**BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)**
779
780:   Copies *s* into *d*.
781
782    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
783    function can return:
784
785    * **BCL_ERROR_INVALID_NUM**
786    * **BCL_ERROR_INVALID_CONTEXT**
787    * **BCL_ERROR_FATAL_ALLOC_ERR**
788
789**BclNumber bcl_dup(BclNumber** _s_**)**
790
791:   Creates and returns a new **BclNumber** that is a copy of *s*.
792
793    bcl(3) will encode an error in the return value, if there was one. The error
794    can be queried with **bcl_err(BclNumber)**. Possible errors include:
795
796    * **BCL_ERROR_INVALID_NUM**
797    * **BCL_ERROR_INVALID_CONTEXT**
798    * **BCL_ERROR_FATAL_ALLOC_ERR**
799
800## Pseudo-Random Number Generator
801
802The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
803seed twice, it will produce the same sequence of pseudo-random numbers twice.
804
805By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
806that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
807then calling **rand()** for each byte, since **rand()** is only guaranteed to
808return **15** bits.
809
810This should provide fairly good seeding in the standard case while also
811remaining fairly portable.
812
813If necessary, the PRNG can be reseeded with one of the following functions:
814
815* **bcl_rand_seedWithNum(BclNumber)**
816* **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])**
817* **bcl_rand_reseed(**_void_**)**
818
819The following items allow clients to use the pseudo-random number generator. All
820procedures require a valid current context.
821
822**BCL_SEED_ULONGS**
823
824:   The number of **unsigned long**'s in a seed for bcl(3)'s random number
825    generator.
826
827**BCL_SEED_SIZE**
828
829:   The size, in **char**'s, of a seed for bcl(3)'s random number generator.
830
831**BclBigDig**
832
833:   bcl(3)'s overflow type (see the **PERFORMANCE** section).
834
835**BclRandInt**
836
837:   An unsigned integer type returned by bcl(3)'s random number generator.
838
839**BclNumber bcl_irand(BclNumber** _a_**)**
840
841:   Returns a random number that is not larger than *a* in a new number. If *a*
842    is **0** or **1**, the new number is equal to **0**. The bound is unlimited,
843    so it is not bound to the size of **BclRandInt**. This is done by generating
844    as many random numbers as necessary, multiplying them by certain exponents,
845    and adding them all together.
846
847    *a* must be an integer and non-negative.
848
849    *a* is consumed; it cannot be used after the call. See the
850    **Consumption and Propagation** subsection below.
851
852    This procedure requires a valid current context.
853
854    bcl(3) will encode an error in the return value, if there was one. The error
855    can be queried with **bcl_err(BclNumber)**. Possible errors include:
856
857    * **BCL_ERROR_INVALID_NUM**
858    * **BCL_ERROR_INVALID_CONTEXT**
859    * **BCL_ERROR_MATH_NEGATIVE**
860    * **BCL_ERROR_MATH_NON_INTEGER**
861    * **BCL_ERROR_FATAL_ALLOC_ERR**
862
863**BclNumber bcl_frand(size_t** _places_**)**
864
865:   Returns a random number between **0** (inclusive) and **1** (exclusive) that
866    has *places* decimal digits after the radix (decimal point). There are no
867    limits on *places*.
868
869    This procedure requires a valid current context.
870
871    bcl(3) will encode an error in the return value, if there was one. The error
872    can be queried with **bcl_err(BclNumber)**. Possible errors include:
873
874    * **BCL_ERROR_INVALID_CONTEXT**
875    * **BCL_ERROR_FATAL_ALLOC_ERR**
876
877**BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)**
878
879:   Returns a random number less than *a* with *places* decimal digits after the
880    radix (decimal point). There are no limits on *a* or *places*.
881
882    *a* must be an integer and non-negative.
883
884    *a* is consumed; it cannot be used after the call. See the
885    **Consumption and Propagation** subsection below.
886
887    This procedure requires a valid current context.
888
889    bcl(3) will encode an error in the return value, if there was one. The error
890    can be queried with **bcl_err(BclNumber)**. Possible errors include:
891
892    * **BCL_ERROR_INVALID_NUM**
893    * **BCL_ERROR_INVALID_CONTEXT**
894    * **BCL_ERROR_MATH_NEGATIVE**
895    * **BCL_ERROR_MATH_NON_INTEGER**
896    * **BCL_ERROR_FATAL_ALLOC_ERR**
897
898**BclError bcl_rand_seedWithNum(BclNumber** _n_**)**
899
900:   Seeds the PRNG with *n*.
901
902    *n* is *not* consumed.
903
904    This procedure requires a valid current context.
905
906    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
907    function can return:
908
909    * **BCL_ERROR_INVALID_NUM**
910    * **BCL_ERROR_INVALID_CONTEXT**
911
912    Note that if **bcl_rand_seed2num(**_void_**)** or
913    **bcl_rand_seed2num_err(BclNumber)** are called right after this function,
914    they are not guaranteed to return a number equal to *n*.
915
916**BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])**
917
918:   Seeds the PRNG with the bytes in *seed*.
919
920    If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
921    function can return:
922
923    * **BCL_ERROR_INVALID_CONTEXT**
924
925**void bcl_rand_reseed(**_void_**)**
926
927:   Reseeds the PRNG with the default reseeding behavior. First, it attempts to
928    read data from **/dev/urandom** and falls back to **libc**'s **rand()**.
929
930    This procedure cannot fail.
931
932**BclNumber bcl_rand_seed2num(**_void_**)**
933
934:   Returns the current seed of the PRNG as a **BclNumber**.
935
936    This procedure requires a valid current context.
937
938    bcl(3) will encode an error in the return value, if there was one. The error
939    can be queried with **bcl_err(BclNumber)**. Possible errors include:
940
941    * **BCL_ERROR_INVALID_CONTEXT**
942    * **BCL_ERROR_FATAL_ALLOC_ERR**
943
944**BclRandInt bcl_rand_int(**_void_**)**
945
946:   Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
947
948    This procedure cannot fail.
949
950**BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)**
951
952:   Returns a random integer between **0** and *bound* (exclusive). Bias is
953    removed before returning the integer.
954
955    This procedure cannot fail.
956
957## Consumption and Propagation
958
959Some functions are listed as consuming some or all of their arguments. This
960means that the arguments are freed, regardless of if there were errors or not.
961
962This is to enable compact code like the following:
963
964    BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
965
966If arguments to those functions were not consumed, memory would be leaked until
967reclaimed with **bcl_ctxt_freeNums(BclContext)**.
968
969When errors occur, they are propagated through. The result should always be
970checked with **bcl_err(BclNumber)**, so the example above should properly
971be:
972
973    BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
974    if (bc_num_err(n) != BCL_ERROR_NONE) {
975        // Handle the error.
976    }
977
978# ERRORS
979
980Most functions in bcl(3) return, directly or indirectly, any one of the error
981codes defined in **BclError**. The complete list of codes is the following:
982
983**BCL_ERROR_NONE**
984
985:   Success; no error occurred.
986
987**BCL_ERROR_INVALID_NUM**
988
989:   An invalid **BclNumber** was given as a parameter.
990
991**BCL_ERROR_INVALID_CONTEXT**
992
993:   An invalid **BclContext** is being used.
994
995**BCL_ERROR_SIGNAL**
996
997:   A signal interrupted execution.
998
999**BCL_ERROR_MATH_NEGATIVE**
1000
1001:   A negative number was given as an argument to a parameter that cannot accept
1002    negative numbers, such as for square roots.
1003
1004**BCL_ERROR_MATH_NON_INTEGER**
1005
1006:   A non-integer was given as an argument to a parameter that cannot accept
1007    non-integer numbers, such as for the second parameter of **bcl_num_pow()**.
1008
1009**BCL_ERROR_MATH_OVERFLOW**
1010
1011:   A number that would overflow its result was given as an argument, such as
1012    for converting a **BclNumber** to a **BclBigDig**.
1013
1014**BCL_ERROR_MATH_DIVIDE_BY_ZERO**
1015
1016:   A divide by zero occurred.
1017
1018**BCL_ERROR_PARSE_INVALID_STR**
1019
1020:   An invalid number string was passed to a parsing function.
1021
1022    A valid number string can only be one radix (period). In addition, any
1023    lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is
1024    allowed for the first character to be a dash. In that case, the number is
1025    considered to be negative.
1026
1027    There is one exception to the above: one lowercase **e** is allowed in the
1028    number, after the radix, if it exists. If the letter **e** exists, the
1029    number is considered to be in scientific notation, where the part before the
1030    **e** is the number, and the part after, which must be an integer, is the
1031    exponent. There can be a dash right after the **e** to indicate a negative
1032    exponent.
1033
1034    **WARNING**: Both the number and the exponent in scientific notation are
1035    interpreted according to the current **ibase**, but the number is still
1036    multiplied by **10\^exponent** regardless of the current **ibase**. For
1037    example, if **ibase** is **16** and bcl(3) is given the number string
1038    **FFeA**, the resulting decimal number will be **2550000000000**, and if
1039    bcl(3) is given the number string **10e-4**, the resulting decimal number
1040    will be **0.0016**.
1041
1042**BCL_ERROR_FATAL_ALLOC_ERR**
1043
1044:   bcl(3) failed to allocate memory.
1045
1046    If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1047    this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1048    be turned off later by calling that same function with a **false** argument.
1049    By default, this behavior is off.
1050
1051    It is highly recommended that client libraries do *not* activate this
1052    behavior.
1053
1054**BCL_ERROR_FATAL_UNKNOWN_ERR**
1055
1056:   An unknown error occurred.
1057
1058    If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1059    this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1060    be turned off later by calling that same function with a **false** argument.
1061    By default, this behavior is off.
1062
1063    It is highly recommended that client libraries do *not* activate this
1064    behavior.
1065
1066# ATTRIBUTES
1067
1068When **bcl_handleSignal(**_void_**)** is used properly, bcl(3) is
1069async-signal-safe.
1070
1071bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one
1072thread.
1073
1074# PERFORMANCE
1075
1076Most bc(1) implementations use **char** types to calculate the value of **1**
1077decimal digit at a time, but that can be slow. bcl(3) does something
1078different.
1079
1080It uses large integers to calculate more than **1** decimal digit at a time. If
1081built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1082**64**, then each integer has **9** decimal digits. If built in an environment
1083where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1084value (the number of decimal digits per large integer) is called
1085**BC_BASE_DIGS**.
1086
1087In addition, this bcl(3) uses an even larger integer for overflow checking. This
1088integer type depends on the value of **BC_LONG_BIT**, but is always at least
1089twice as large as the integer type used to store digits.
1090
1091# LIMITS
1092
1093The following are the limits on bcl(3):
1094
1095**BC_LONG_BIT**
1096
1097:   The number of bits in the **long** type in the environment where bcl(3) was
1098    built. This determines how many decimal digits can be stored in a single
1099    large integer (see the **PERFORMANCE** section).
1100
1101**BC_BASE_DIGS**
1102
1103:   The number of decimal digits per large integer (see the **PERFORMANCE**
1104    section). Depends on **BC_LONG_BIT**.
1105
1106**BC_BASE_POW**
1107
1108:   The max decimal number that each large integer can store (see
1109    **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1110
1111**BC_OVERFLOW_MAX**
1112
1113:   The max number that the overflow type (see the **PERFORMANCE** section) can
1114    hold. Depends on **BC_LONG_BIT**.
1115
1116**BC_BASE_MAX**
1117
1118:   The maximum output base. Set at **BC_BASE_POW**.
1119
1120**BC_SCALE_MAX**
1121
1122:   The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1123
1124**BC_NUM_MAX**
1125
1126:   The maximum length of a number (in decimal digits), which includes digits
1127    after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1128
1129**BC_RAND_MAX**
1130
1131:   The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
1132    Set at **2\^BC_LONG_BIT-1**.
1133
1134Exponent
1135
1136:   The maximum allowable exponent (positive or negative). Set at
1137    **BC_OVERFLOW_MAX**.
1138
1139These limits are meant to be effectively non-existent; the limits are so large
1140(at least on 64-bit machines) that there should not be any point at which they
1141become a problem. In fact, memory should be exhausted before these limits should
1142be hit.
1143
1144# SIGNAL HANDLING
1145
1146If a signal handler calls **bcl_handleSignal(**_void_**)** from the same thread
1147that there are bcl(3) functions executing in, it will cause all execution to
1148stop as soon as possible, interrupting long-running calculations, if necessary
1149and cause the function that was executing to return. If possible, the error code
1150**BC_ERROR_SIGNAL** is returned.
1151
1152If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
1153return to its caller.
1154
1155It is undefined behavior if **bcl_handleSignal(**_void_**)** is called from
1156a thread that is not executing bcl(3) functions, if bcl(3) functions are
1157executing.
1158
1159# SEE ALSO
1160
1161bc(1) and dc(1)
1162
1163# STANDARDS
1164
1165bcl(3) is compliant with the arithmetic defined in the
1166[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification for bc(1).
1167
1168Note that the specification explicitly says that bc(1) only accepts numbers that
1169use a period (**.**) as a radix point, regardless of the value of
1170**LC_NUMERIC**. This is also true of bcl(3).
1171
1172# BUGS
1173
1174None are known. Report bugs at https://git.yzena.com/gavin/bc.
1175
1176# AUTHORS
1177
1178Gavin D. Howard <gavin@yzena.com> and contributors.
1179
1180[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
1181