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