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