Debian Codegraph @

terps/tads/tads3/vmbignumlib.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /* Copyright (c) 2012 by Michael J. Roberts. All Rights Reserved. */
7 /*
8 Name
9 vmbignumlib.cpp - BigNumber numerics library
10 Function
11 This module contains the low-level numerics library for the BigNumber
12 object. The routines here operate on the internal byte-array
13 representation of a BigNumber value, without the CVmObjBigNum wrapper
14 object, so this module can be used as a library for high-precision
15 arithmetic without dragging in the whole TADS 3 VM.
16 Notes
17
18 Modified
19 06/20/12 MJRoberts - Creation
20 */
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <assert.h>
25 #include <limits.h>
26 #include <stdarg.h>
27 #include <math.h>
28 #include <float.h>
29
30 #include "t3std.h"
31 #include "utf8.h"
32 #include "vmtype.h"
33 #include "vmbignum.h"
34
35
36 /* ------------------------------------------------------------------------ */
37 /*
38 * convert to a string, storing the result in the given buffer
39 */
40 const char *CVmObjBigNum::cvt_to_string_buf(
41 char *buf, size_t buflen,
42 int max_digits, int whole_places, int frac_digits, int exp_digits,
43 ulong flags)
44 {
45 /* convert to a string into our buffer */
46 CBigNumStringBufFixed alo(buf, buflen);
47 return cvt_to_string_gen(&alo, ext_, max_digits, whole_places,
48 frac_digits, exp_digits, flags, 0, 0);
49 }
50
51 /*
52 * Convert to a string, storign the result in the given buffer
53 */
54 const char *CVmObjBigNum::cvt_to_string_buf(
55 char *buf, size_t buflen, const char *ext,
56 int max_digits, int whole_places, int frac_digits, int exp_digits,
57 ulong flags, const char *lead_fill, size_t lead_fill_len)
58 {
59 /* convert to a string into our buffer */
60 CBigNumStringBufFixed alo(buf, buflen);
61 return cvt_to_string_gen(&alo, ext, max_digits, whole_places,
62 frac_digits, exp_digits, flags,
63 lead_fill, lead_fill_len);
64 }
65
66 /*
67 * Convert an integer value to a string, storing the result in the buffer.
68 * This can be used to apply the whole set of floating-point formatting
69 * options to an ordinary integer value, without going to the trouble of
70 * creating a BigNumber object.
71 */
72 const char *CVmObjBigNum::cvt_int_to_string_buf(
73 char *buf, size_t buflen, int32_t intval,
74 int max_digits, int whole_places, int frac_digits, int exp_digits,
75 ulong flags)
76 {
77 /*
78 * Set up a stack register with the number. Allow 20 digits of
79 * precision so that this can extend to 64-bit ints in the future.
80 */
81 char tmp[5 + 20] = { 20, 0, 0, 0, 0 };
82 set_int_val(tmp, intval);
83
84 /*
85 * set the actual precision to equal the exponent, since zeros after
86 * the decimal point aren't significant for an integer source
87 */
88 set_prec(tmp, get_exp(tmp));
89
90 /* convert to a string into our buffer */
91 CBigNumStringBufFixed alo(buf, buflen);
92 return cvt_to_string_gen(&alo, tmp, max_digits, whole_places,
93 frac_digits, exp_digits, flags, 0, 0);
94 }
95
96
97 /*
98 * Common routine to create a string representation. If buf is null,
99 * we'll allocate a new string object, filling in new_str with the
100 * object reference; otherwise, we'll format into the given buffer.
101 */
102 const char *CVmObjBigNum::cvt_to_string_gen(
103 IBigNumStringBuf *bufalo, const char *ext,
104 int max_digits, int whole_places, int frac_digits, int exp_digits,
105 ulong flags, const char *lead_fill, size_t lead_fill_len)
106 {
107 char plus_sign = '\0';
108 int always_sign_exp = ((flags & VMBN_FORMAT_EXP_SIGN) != 0);
109 int always_exp = ((flags & VMBN_FORMAT_EXP) != 0);
110 int lead_zero = ((flags & VMBN_FORMAT_LEADING_ZERO) != 0);
111 int always_show_pt = ((flags & VMBN_FORMAT_POINT) != 0);
112 int exp_caps = ((flags & VMBN_FORMAT_EXP_CAP) != 0);
113 int pos_lead_space = ((flags & VMBN_FORMAT_POS_SPACE) != 0);
114 int commas = ((flags & VMBN_FORMAT_COMMAS) != 0);
115 int euro = ((flags & VMBN_FORMAT_EUROSTYLE) != 0);
116 size_t req_chars;
117 int prec = (int)get_prec(ext);
118 int exp = get_exp(ext);
119 int dig_before_pt;
120 int dig_after_pt;
121 int idx;
122 unsigned int dig;
123 char *p;
124 int exp_carry;
125 int show_pt;
126 int whole_padding;
127 int non_sci_digs;
128 char decpt_char = (euro ? ',' : '.');
129 char comma_char = (euro ? '.' : ',');
130 char *tmp_ext = 0;
131 uint tmp_hdl;
132 int max_sig = ((flags & VMBN_FORMAT_MAXSIG) != 0);
133 int all_out_cnt, sig_out_cnt;
134
135 /* we haven't written out any digits yet */
136 all_out_cnt = sig_out_cnt = 0;
137
138 /* note the sign character to use for positive numbers, if any */
139 if (pos_lead_space)
140 plus_sign = ' ';
141 else if ((flags & VMBN_FORMAT_SIGN) != 0)
142 plus_sign = '+';
143
144 /*
145 * If we're not required to use exponential notation, but we don't
146 * have enough max_digits places for the part before the decimal
147 * point, use exponential anyway. (The number of digits before the
148 * decimal point is simply the exponent if it's greater than zero,
149 * or zero otherwise.)
150 */
151 if (max_digits >= 0 && exp > max_digits)
152 always_exp = TRUE;
153
154
155 /*
156 * If we're not required to use exponential notation, but our
157 * absolute value is so small that we wouldn't show anything
158 * "0.00000..." (i.e., we'd have too many zeros after the decimal
159 * point to show any actual digits of our number), use exponential
160 * notation. If our exponent is negative, its absolute value is the
161 * number of zeros we'd show after the decimal point before the
162 * first non-zero digit.
163 */
164 if (max_digits >= 0
165 && exp < 0
166 && (-exp > max_digits
167 || (frac_digits != -1 && -exp > frac_digits)))
168 always_exp = TRUE;
169
170 /*
171 * If we're the "compact" mode flag is set, use scientific notation if
172 * the displayed decimal exponent is less than -4 or greater than the
173 * number of digits after the decimal point. (The displayed exponent
174 * is one lower than the internal exponent, since the normalized format
175 * has no digits before the decimal point but the displayed scientific
176 * notation format shows one whole-part digit.)
177 */
178 if ((flags & VMBN_FORMAT_COMPACT) != 0
179 && (exp < -3 || (max_digits >= 0 && exp - 1 > max_digits)))
180 always_exp = TRUE;
181
182 /* calculate how many digits we'd need in non-scientific notation */
183 if (exp < 0)
184 {
185 /* we have leading zeros before the first significant digit */
186 non_sci_digs = -exp + prec;
187 }
188 else if (exp > prec)
189 {
190 /* we have trailing zeros after the last significant digit */
191 non_sci_digs = exp + prec;
192 }
193 else
194 {
195 /*
196 * we have no leading or trailing zeros to represent - only the
197 * digits actually stored need to be displayed
198 */
199 non_sci_digs = prec;
200 }
201
202 /*
203 * Figure out how much space we need for our string. Start with the
204 * length of the basic digit string, which is the smaller of max_digits
205 * or the actual space we need for non-scientific notation.
206 */
207 if (max_digits >= 0 && max_digits < non_sci_digs)
208 {
209 /* max_digits limits the number of characters we can show */
210 req_chars = max_digits;
211
212 /*
213 *. ..but if it only counts significant digits, and the exponent
214 * is negative, we might also have to show all those leading zeros
215 * over and above the max_digits limit
216 */
217 if (max_sig && exp < 0)
218 req_chars += -exp;
219 }
220 else
221 {
222 /* there's no cap on digits, so we could have to show them all */
223 req_chars = non_sci_digs;
224 }
225
226 /*
227 * Now add overhead space for the sign symbol, a leading zero, a
228 * decimal point, an 'E' for the exponent, an exponent sign, and up to
229 * five digits for the exponent (16-bit integer -> -32768 to 32767).
230 * Also allow an extra character in case we need to add a digit due to
231 * rounding.
232 */
233 req_chars += 11;
234
235 /*
236 * Make sure we leave enough room for the lead fill string - if they
237 * specified a number of whole places, and we're not using
238 * exponential format, we'll insert lead fill characters before the
239 * first non-zero whole digit.
240 */
241 if (!always_exp && whole_places != -1 && exp < whole_places)
242 {
243 int extra;
244 int char_size;
245
246 /*
247 * if the exponent is negative, we'll pad by the full amount;
248 * otherwise, we'll just pad by the difference between the
249 * number of places needed and the exponent
250 */
251 extra = whole_places;
252 if (exp > 0)
253 extra -= exp;
254
255 /*
256 * Add the extra bytes: one byte per character if we're using
257 * the default space padding, or up to three bytes per character
258 * if a lead string was specified (each unicode character can
259 * take up to three bytes)
260 */
261 char_size = (lead_fill != 0 ? 3 : 1);
262 req_chars += extra * char_size;
263
264 /*
265 * add space for each padding character we could insert into a
266 * comma position (there's at most one comma per three fill
267 * characters)
268 */
269 if (commas)
270 req_chars += ((extra + 2)/3) * char_size;
271 }
272
273 /*
274 * If we're using commas, and we're not using scientific notation,
275 * add space for a comma for each three digits before the decimal
276 * point
277 */
278 if (commas && !always_exp)
279 {
280 /* add space for the commas */
281 req_chars += ((exp + 2) / 3);
282 }
283
284 /*
285 * if they requested a specific minimum number of exponent digits,
286 * and that number is greater than the allowance of 5 we already
287 * provided, add the extra space needed
288 */
289 if (exp_digits > 5)
290 req_chars += (exp_digits - 5);
291
292 /*
293 * If they requested a specific number of digits after the decimal
294 * point, make sure we have room for those digits.
295 */
296 if (frac_digits != -1)
297 req_chars += frac_digits;
298
299 /* now that we know how much space we need, get the output buffer */
300 char *buf = bufalo->get_buf(req_chars + VMB_LEN);
301
302 /* if that failed, return failure */
303 if (buf == 0)
304 return 0;
305
306 /* check for special values */
307 switch(get_type(ext))
308 {
309 case VMBN_T_NUM:
310 /* normal number - proceed */
311 break;
312
313 case VMBN_T_NAN:
314 /* not a number - show "1.#NAN" */
315 strcpy(buf + VMB_LEN, "1.#NAN");
316 vmb_put_len(buf, 6);
317 return buf;
318
319 case VMBN_T_INF:
320 /* positive or negative infinity */
321 if (get_neg(ext))
322 {
323 memcpy(buf + VMB_LEN, "-1.#INF", 7);
324 vmb_put_len(buf, 7);
325 }
326 else
327 {
328 memcpy(buf + VMB_LEN, "1.#INF", 6);
329 vmb_put_len(buf, 6);
330 }
331 return buf;
332
333 default:
334 /* other values are not valid */
335 memcpy(buf + VMB_LEN, "1.#???", 6);
336 vmb_put_len(buf, 6);
337 return buf;
338 }
339
340 /*
341 * Allocate a temporary buffer to contain a copy of the number. At
342 * most, we'll have to show max_digits of the number, or the current
343 * precision, whichever is lower.
344 */
345 {
346 int new_prec;
347
348 /*
349 * limit the new precision to the maximum digits to be shown, or
350 * our existing precision, whichever is lower
351 */
352 if (max_digits < 0)
353 new_prec = prec;
354 else
355 {
356 new_prec = max_digits;
357 if (prec < new_prec)
358 new_prec = prec;
359 }
360
361 /* allocate the space */
362 alloc_temp_regs((size_t)new_prec, 1, &tmp_ext, &tmp_hdl);
363
364 /* copy the value to the temp register, rounding the value */
365 copy_val(tmp_ext, ext, TRUE);
366
367 /* note the new precision */
368 prec = new_prec;
369
370 /* forget the original number and use the rounded version */
371 ext = tmp_ext;
372 }
373
374 start_over:
375 /*
376 * note the exponent, in case we rounded or otherwise adjusted the
377 * temporary number
378 */
379 exp = get_exp(ext);
380
381 /* presume we won't carry into the exponent */
382 exp_carry = FALSE;
383
384 /* no whole-part padding yet */
385 whole_padding = 0;
386
387 /*
388 * Figure out where the decimal point goes in the display. If we're
389 * displaying in exponential format, we'll always display exactly
390 * one digit before the decimal point. Otherwise, we'll display the
391 * number given by our exponent if it's positive, or zero or one
392 * (depending on lead_zero) if it's negative or zero.
393 */
394 if (always_exp)
395 dig_before_pt = 1;
396 else if (exp > 0)
397 dig_before_pt = exp;
398 else
399 dig_before_pt = 0;
400
401 /*
402 * if the digits before the decimal point exceed our maximum number
403 * of digits allowed, we'll need to use exponential format
404 */
405 if (max_digits >= 0 && dig_before_pt > max_digits)
406 {
407 always_exp = TRUE;
408 goto start_over;
409 }
410
411 /*
412 * Limit digits after the decimal point according to the maximum digits
413 * allowed and the number we'll show before the decimal point. If we
414 * have an explicit number of fractional digits to show, that overrides
415 * the limit.
416 */
417 if (max_digits >= 0)
418 dig_after_pt = max_digits - dig_before_pt;
419 else if (frac_digits >= 0)
420 dig_after_pt = frac_digits;
421 else if (prec > dig_before_pt)
422 dig_after_pt = prec - dig_before_pt;
423 else
424 dig_after_pt = 0;
425
426 /* start writing after the buffer length prefix */
427 p = buf + VMB_LEN;
428
429 /*
430 * if we're not in exponential mode, add leading spaces for the
431 * unused whole places
432 */
433 if (!always_exp && dig_before_pt < whole_places)
434 {
435 int cnt;
436 size_t src_rem;
437 utf8_ptr src;
438 utf8_ptr dst;
439 int idx;
440
441 /* start with the excess whole places */
442 cnt = whole_places - dig_before_pt;
443
444 /* if we're going to add a leading zero, that's one less space */
445 if (dig_before_pt == 0 && lead_zero)
446 --cnt;
447
448 /*
449 * Increase the count by the number of comma positions in the
450 * padding area.
451 */
452 if (commas)
453 {
454 /* scan over the positions to fill and count commas */
455 for (idx = dig_before_pt ; idx < whole_places ; ++idx)
456 {
457 /* if this is a comma position, note it */
458 if ((idx % 3) == 0)
459 ++cnt;
460 }
461 }
462
463 /* set up our read and write pointers */
464 src.set((char *)lead_fill);
465 src_rem = lead_fill_len;
466 dst.set(p);
467
468 /* add (and count) the leading spaces */
469 for ( ; cnt != 0 ; --cnt, ++whole_padding)
470 {
471 wchar_t ch;
472
473 /*
474 * if we have a lead fill string, read from it; otherwise,
475 * just use a space
476 */
477 if (lead_fill != 0)
478 {
479 /* if we've exhausted the string, start over */
480 if (src_rem == 0)
481 {
482 src.set((char *)lead_fill);
483 src_rem = lead_fill_len;
484 }
485
486 /* get the next character */
487 ch = src.getch();
488
489 /* skip this character */
490 src.inc(&src_rem);
491 }
492 else
493 {
494 /* no lead fill string - insert a space by default */
495 ch = ' ';
496 }
497
498 /* write this character */
499 dst.setch(ch);
500 }
501
502 /* resynchronize from our utf8 pointer */
503 p = dst.getptr();
504 }
505
506 /*
507 * if the number is negative, or we're always showing a sign, add
508 * the sign; if we're not adding a sign, but we're showing a leading
509 * space for positive numbers, add the leading space
510 */
511 if (get_neg(ext))
512 *p++ = '-';
513 else if (plus_sign != '\0')
514 *p++ = plus_sign;
515
516 /*
517 * if we have no digits before the decimal, and we're adding a
518 * leading zero, add it now
519 */
520 if (dig_before_pt == 0 && lead_zero)
521 {
522 /* add the leading zero */
523 *p++ = '0';
524
525 /*
526 * If we have a total digit limit, reduce the limit on the digits
527 * after the decimal point, since this leading zero comes out of
528 * our overall digit budget. This doesn't apply if max_digits is
529 * the number of significant digits.
530 */
531 if (max_digits >= 0 && !max_sig)
532 --dig_after_pt;
533
534 /* count it in the output counter for all digits */
535 all_out_cnt++;
536 }
537
538 /*
539 * If we have limited the number of digits that we'll allow after the
540 * decimal point, due to the limit on the total number of digits and
541 * the number of digits we need to display before the decimal, start
542 * over in exponential format to ensure we get the after-decimal
543 * display we want.
544 *
545 * Note that we won't bother going into exponential format if the
546 * number of digits before the decimal point is zero or one, because
547 * exponential format won't give us any more room - in such cases we
548 * simply have an impossible request.
549 */
550 if (max_digits >=0 && !always_exp
551 && frac_digits != -1
552 && dig_after_pt < frac_digits
553 && dig_before_pt > 1)
554 {
555 /* switch to exponential format and start over */
556 always_exp = TRUE;
557 goto start_over;
558 }
559
560 /* display the digits before the decimal point */
561 for (idx = 0 ; idx < dig_before_pt && idx < prec ; ++idx)
562 {
563 /*
564 * if this isn't the first digit, and we're adding commas, and
565 * an even multiple of three more digits follow, insert a comma
566 */
567 if (idx != 0 && commas && !always_exp
568 && ((dig_before_pt - idx) % 3) == 0)
569 *p++ = comma_char;
570
571 /* get this digit */
572 dig = get_dig(ext, idx);
573
574 /* add it to the string */
575 *p++ = (dig + '0');
576
577 /* count it */
578 all_out_cnt++;
579 if (dig != 0 || sig_out_cnt != 0)
580 sig_out_cnt++;
581 }
582
583 /* if we ran out of precision, add zeros */
584 for ( ; idx < dig_before_pt ; ++idx)
585 {
586 /* add the zero */
587 *p++ = '0';
588
589 /* count it */
590 all_out_cnt++;
591 if (sig_out_cnt != 0)
592 sig_out_cnt++;
593 }
594
595 /*
596 * Add the decimal point. Show the decimal point unless
597 * always_show_pt is false, and either frac_digits is zero, or
598 * frac_digits is -1 and we have no fractional part.
599 */
600 if (always_show_pt)
601 {
602 /* always showing the point */
603 show_pt = TRUE;
604 }
605 else
606 {
607 if (frac_digits > 0)
608 {
609 /* we're showing fractional digits - always show a point */
610 show_pt = TRUE;
611 }
612 else if (frac_digits == 0)
613 {
614 /* we're showing no fractional digits, so suppress the point */
615 show_pt = FALSE;
616 }
617 else
618 {
619 /*
620 * for now assume we'll show the point; we'll take it back
621 * out if we don't encounter anything but zeros
622 */
623 show_pt = TRUE;
624 }
625 }
626
627 /* if we're showing the fractional part, show it */
628 if (show_pt)
629 {
630 int frac_len;
631 int frac_lim;
632 char *last_non_zero;
633
634 /*
635 * remember the current position as the last trailing non-zero -
636 * if we don't find anything but zeros and decide to remove the
637 * trailing zeros, we'll also remove the decimal point by
638 * coming back here
639 */
640 last_non_zero = p;
641
642 /* add the point */
643 *p++ = decpt_char;
644
645 /* if we're always showing a decimal point, we can't remove it */
646 if (always_show_pt)
647 last_non_zero = p;
648
649 /* if frac_digits is -1, there's no limit */
650 if (frac_digits == -1)
651 frac_lim = dig_after_pt;
652 else
653 frac_lim = frac_digits;
654
655 /*
656 * further limit the fractional digits according to the maximum
657 * digit allowance
658 */
659 if (frac_lim > dig_after_pt)
660 frac_lim = dig_after_pt;
661
662 /* no fractional digits output yet */
663 frac_len = 0;
664
665 /*
666 * if we haven't yet reached the first non-zero digit, display
667 * as many zeros as necessary
668 */
669 if (idx == 0 && exp < 0)
670 {
671 int cnt;
672
673 /*
674 * display leading zeros based no the exponent: if exp is
675 * zero, we don't need any; if exp is -1, we need one; if
676 * exp is -2, we need two, and so on
677 */
678 for (cnt = exp ; cnt != 0 && frac_len < frac_lim ; ++cnt)
679 {
680 /* add a zero */
681 *p++ = '0';
682
683 /*
684 * if we're counting all digits (not just significant
685 * digits), count this digit against the total
686 */
687 if (!max_sig)
688 ++frac_len;
689
690 /* count it in the total digits out */
691 all_out_cnt++;
692 }
693 }
694
695 /* add the fractional digits */
696 for ( ; idx < prec && frac_len < frac_lim ; ++idx, ++frac_len)
697 {
698 /* get this digit */
699 dig = get_dig(ext, idx);
700
701 /* add it */
702 *p++ = (dig + '0');
703
704 /*
705 * if it's not a zero, note the location - if we decide to
706 * trim trailing zeros, we'll want to keep at least this
707 * much, since this is a significant trailing digit
708 */
709 if (dig != 0)
710 last_non_zero = p;
711
712 /* count it */
713 all_out_cnt++;
714 if (dig != 0 || sig_out_cnt != 0)
715 sig_out_cnt++;
716 }
717
718 /*
719 * If the "keep trailing zeros" flag is set, and there's a
720 * max_digits quota that we haven't filled, add trailing zeros as
721 * needed.
722 */
723 if ((flags & VMBN_FORMAT_TRAILING_ZEROS) != 0 && max_digits >= 0)
724 {
725 /*
726 * fill out the request: if max_digits is stated in significant
727 * digits, count the number of significant digits we've written
728 * so far, otherwise count all digits written so far
729 */
730 for (int i = max_sig ? sig_out_cnt : all_out_cnt ;
731 i < max_digits ; ++i)
732 {
733 /* add a digit */
734 *p++ = '0';
735
736 /* count it */
737 all_out_cnt++;
738 if (sig_out_cnt != 0)
739 sig_out_cnt++;
740 }
741 }
742
743 /*
744 * add the trailing zeros if we ran out of precision before we
745 * filled the requested number of places
746 */
747 if (frac_digits != -1)
748 {
749 /* fill out the remaining request length with zeros */
750 for ( ; frac_len < frac_lim ; ++frac_len)
751 {
752 /* add a zero */
753 *p++ = '0';
754
755 /* count it */
756 all_out_cnt++;
757 if (sig_out_cnt != 0)
758 sig_out_cnt++;
759 }
760 }
761 else if (!(flags & VMBN_FORMAT_TRAILING_ZEROS))
762 {
763 char *p1;
764
765 /*
766 * if we're removing the decimal point, we're not showing a
767 * fractional part after all - so note
768 */
769 if (last_non_zero < p && *last_non_zero == decpt_char)
770 show_pt = FALSE;
771
772 /*
773 * We can use whatever length we like, so remove meaningless
774 * trailing zeros. Before we do this, though, make sure we
775 * aren't rounding up the last trailing zero - if we need to
776 * round the last digit up, the final zero is really a 1.
777 */
778 if (p > last_non_zero && get_round_dir(ext, idx))
779 {
780 /*
781 * That last zero is significant after all, since we're
782 * going to round it up to a 1 for display. Don't actually
783 * do the rounding now; simply note that the last zero is
784 * significant so that we don't drop the digits leading up
785 * to it.
786 */
787 last_non_zero = p;
788 }
789
790 /*
791 * We've checked for rounding in the last digit, so we can now
792 * safely remove meaningless trailing zeros. If this leaves a
793 * completely empty buffer, not counting a sign and/or a
794 * decimal point, it means that we have a fractional number
795 * that we're showing without an exponent, and the number of
796 * digits we had for display was insufficient to reach the
797 * first non-zero fractional digit. In this case, simply show
798 * '0' (or '0.', if a decimal point is required) as the result.
799 * To find out, scan for digits.
800 */
801 p = last_non_zero;
802 for (p1 = buf + VMB_LEN ; p1 < p && !is_digit(*p1) ; ++p1) ;
803
804 /* if we didn't find any digits, add/insert a '0' */
805 if (p1 == p)
806 {
807 /*
808 * if there's a decimal point, insert the '0' before it;
809 * otherwise, just append the zero
810 */
811 if (p > buf + VMB_LEN && *(p-1) == decpt_char)
812 {
813 *(p-1) = '0';
814 *p++ = decpt_char;
815 }
816 else
817 *p++ = '0';
818 }
819 }
820 }
821
822 /* if necessary, round up at the last digit */
823 if (get_round_dir(ext, idx))
824 {
825 char *rp;
826 int need_carry;
827 int found_pt;
828 int dig_cnt;
829
830 /*
831 * go back through the number and add one to the last digit,
832 * carrying as needed
833 */
834 for (dig_cnt = 0, found_pt = FALSE, need_carry = TRUE, rp = p - 1 ;
835 rp >= buf + VMB_LEN ; rp = utf8_ptr::s_dec(rp))
836 {
837 /* if this is a digit, bump it up */
838 if (is_digit(*rp))
839 {
840 /* count it */
841 ++dig_cnt;
842
843 /* if it's 9, we'll have to carry; otherwise it's easy */
844 if (*rp == '9')
845 {
846 /* set it to zero and keep going to do the carry */
847 *rp = '0';
848
849 /*
850 * if we haven't found the decimal point yet, and
851 * we're not required to show a certain number of
852 * fractional digits, we can simply remove this
853 * trailing zero
854 */
855 if (show_pt && !found_pt && frac_digits == -1)
856 {
857 /* remove the trailing zero */
858 p = utf8_ptr::s_dec(p);
859
860 /* remove it from the digit count */
861 --dig_cnt;
862 }
863 }
864 else
865 {
866 /* bump it up one */
867 ++(*rp);
868
869 /* no more carrying is needed */
870 need_carry = FALSE;
871
872 /* we don't need to look any further */
873 break;
874 }
875 }
876 else if (*rp == decpt_char)
877 {
878 /* note that we found the decimal point */
879 found_pt = TRUE;
880 }
881 }
882
883 /*
884 * If we got to the start of the number and we still need a
885 * carry, we must have had all 9's. In this case, we need to
886 * redo the entire number, since all of the layout (commas,
887 * leading spaces, etc) can change - it's way too much work to
888 * try to back-patch all of this stuff, so we'll just bump the
889 * number up and reformat it from scratch.
890 */
891 if (need_carry)
892 {
893 /* truncate at this digit, and round up what we're keeping */
894 set_dig(tmp_ext, idx, 0);
895 round_up_abs(tmp_ext, idx);
896
897 /*
898 * if this pushes us over the maximum digit range, switch to
899 * scientific notation
900 */
901 if (max_digits >= 0 && dig_cnt + 1 > max_digits)
902 always_exp = TRUE;
903
904 /* go back and start over */
905 goto start_over;
906 }
907 }
908
909 /* add the exponent */
910 if (always_exp)
911 {
912 int disp_exp;
913
914 /* add the 'E' */
915 *p++ = (exp_caps ? 'E' : 'e');
916
917 /*
918 * calculate the display exponent - it's one less than the
919 * actual exponent, because we put the point after one digit
920 */
921 disp_exp = exp - 1;
922
923 /*
924 * if we carried into the exponent due to rounding, increase the
925 * exponent by one
926 */
927 if (exp_carry)
928 ++disp_exp;
929
930 /* add the sign */
931 if (disp_exp < 0)
932 {
933 *p++ = '-';
934 disp_exp = -disp_exp;
935 }
936 else if (always_sign_exp)
937 *p++ = '+';
938
939 /*
940 * if the exponent is zero, just put zero (unless a more
941 * specific format was requested)
942 */
943 if (disp_exp == 0 && exp_digits == -1)
944 {
945 /* add the zero exponent */
946 *p++ = '0';
947 }
948 else
949 {
950 char expbuf[20];
951 char *ep;
952 int dig_cnt;
953
954 /* build the exponent in reverse */
955 for (dig_cnt = 0, ep = expbuf + sizeof(expbuf) ; disp_exp != 0 ;
956 disp_exp /= 10, ++dig_cnt)
957 {
958 /* move back one character */
959 --ep;
960
961 /* add one digit */
962 *ep = (disp_exp % 10) + '0';
963 }
964
965 /* if necessary, add leading zeros to the exponent */
966 if (exp_digits != -1 && exp_digits > dig_cnt)
967 {
968 for ( ; dig_cnt < exp_digits ; ++dig_cnt)
969 *p++ = '0';
970 }
971
972 /* copy the exponent into the output */
973 for ( ; ep < expbuf + sizeof(expbuf) ; ++ep)
974 *p++ = *ep;
975 }
976 }
977
978 /* if we allocated a temporary register, free it */
979 if (tmp_ext != 0)
980 release_temp_regs(1, tmp_hdl);
981
982 /* set the string length and return the buffer */
983 vmb_put_len(buf, p - buf - VMB_LEN);
984 return buf;
985 }
986
987 /* ------------------------------------------------------------------------ */
988 /*
989 * Parse a string into an allocated buffer.
990 */
991 char *CVmObjBigNum::parse_str_alo(size_t &buflen,
992 const char *str, size_t len, int radix)
993 {
994 /* figure the precision */
995 int prec = precision_from_string(str, len, radix);
996
997 /* allocate a buffer */
998 char *ext = new char[buflen = calc_alloc(prec)];
999 set_prec(ext, prec);
1000
1001 /* parse the number */
1002 parse_str_into(ext, str, len, radix);
1003
1004 /* return the new buffer */
1005 return ext;
1006 }
1007
1008 /* ------------------------------------------------------------------------ */
1009 /*
1010 * Parse a string with the given radix.
1011 */
1012 void CVmObjBigNum::parse_str_into(char *ext, const char *str, size_t len,
1013 int radix)
1014 {
1015 /* if the radix is 0, infer the radix from the string */
1016 int inferred_radix = 0;
1017 if (radix == 0)
1018 radix = inferred_radix = radix_from_string(str, len);
1019
1020 /* if it's decimal, parse as a floating point value */
1021 if (radix == 10)
1022 {
1023 parse_str_into(ext, str, len);
1024 return;
1025 }
1026
1027 /* get the precision */
1028 size_t prec = get_prec(ext);
1029
1030 /* set the initial value to zero */
1031 set_type(ext, VMBN_T_NUM);
1032 memset(ext + VMBN_MANT, 0, (prec + 1)/2);
1033
1034 /* set up to scan the string */
1035 utf8_ptr p((char *)str);
1036 size_t rem = len;
1037
1038 /* skip leading spaces */
1039 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1040
1041 /* check for a sign */
1042 int neg = FALSE;
1043 if (rem != 0 && p.getch() == '+')
1044 {
1045 /* skip the sign */
1046 p.inc(&rem);
1047 }
1048 else if (rem != 0 && p.getch() == '-')
1049 {
1050 /* note the sign and skip it */
1051 neg = TRUE;
1052 p.inc(&rem);
1053 }
1054
1055 /* skip spaces after the sign */
1056 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1057
1058 /* if we inferred the radix as hax, skip any '0x' marker */
1059 if (inferred_radix == 16
1060 && rem != 0
1061 && p.getch() == '0'
1062 && (p.getch_at(1) == 'x' || p.getch_at(1) == 'X'))
1063 {
1064 /* skip the '0x' prefix */
1065 p.inc(&rem);
1066 p.inc(&rem);
1067 }
1068
1069 /* allocate a temporary register for swapping with the accumulator */
1070 uint thdl;
1071 char *tmp = alloc_temp_reg(prec, &thdl);
1072 char *t1 = ext, *t2 = tmp;
1073
1074 /* parse the digits */
1075 int significant = FALSE;
1076 for ( ; rem != 0 ; p.inc(&rem))
1077 {
1078 /* get the next character */
1079 wchar_t ch = p.getch();
1080
1081 /* get the digit value of this character */
1082 int d;
1083 if (ch >= '0' && ch <= '9')
1084 d = ch - '0';
1085 else if (ch >= 'A' && ch <= 'Z')
1086 d = ch - 'A' + 10;
1087 else if (ch >= 'a' && ch <= 'z')
1088 d = ch - 'a' + 10;
1089 else
1090 break;
1091
1092 /* if the digit isn't within the radix, it's not a digit after all */
1093 if (d >= radix)
1094 break;
1095
1096 /* if it's not a leading zero, it's significant */
1097 if (ch != '0')
1098 significant = TRUE;
1099
1100 /* if it's a significant digit, add it to the accumulator */
1101 if (significant)
1102 {
1103 /*
1104 * Set up a stack register with the digit value. The radix can
1105 * be up to 36, so the digit value can be up to 35, so we need
1106 * up to two decimal digits to represent the digit value.
1107 */
1108 char dreg[5 + 2] = { 2, 0, 0, 0, 0 };
1109 set_uint_val(dreg, d);
1110
1111 /* shift the accumulator and add the digit */
1112 mul_by_long(t1, radix);
1113 compute_abs_sum_into(t2, t1, dreg);
1114
1115 /* swap the accumulators */
1116 char *tt = t1;
1117 t1 = t2;
1118 t2 = tt;
1119 }
1120 }
1121
1122 /* if we ended up with the value in 'tmp', copy it into our result */
1123 if (t1 != ext)
1124 copy_val(ext, t1, FALSE);
1125
1126 /* free our temporary register */
1127 release_temp_reg(thdl);
1128
1129 /* set the sign */
1130 set_neg(ext, neg);
1131 }
1132
1133 /* ------------------------------------------------------------------------ */
1134 /*
1135 * Parse a string value into an extension
1136 */
1137 void CVmObjBigNum::parse_str_into(char *ext, const char *str, size_t len)
1138 {
1139 /* get the precision */
1140 size_t prec = get_prec(ext);
1141
1142 /* set the type to number */
1143 set_type(ext, VMBN_T_NUM);
1144
1145 /* initially zero the mantissa */
1146 memset(ext + VMBN_MANT, 0, (prec + 1)/2);
1147
1148 /* set up to scan the string */
1149 utf8_ptr p((char *)str);
1150 size_t rem = len;
1151
1152 /* initialize the exponent to zero */
1153 int exp = 0;
1154
1155 /* presume it will be positive */
1156 int neg = FALSE;
1157
1158 /* skip leading spaces */
1159 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1160
1161 /* check for a sign */
1162 if (rem != 0 && p.getch() == '+')
1163 {
1164 /* skip the sign */
1165 p.inc(&rem);
1166 }
1167 else if (rem != 0 && p.getch() == '-')
1168 {
1169 /* note the sign and skip it */
1170 neg = TRUE;
1171 p.inc(&rem);
1172 }
1173
1174 /* set the sign */
1175 set_neg(ext, neg);
1176
1177 /* skip spaces after the sign */
1178 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1179
1180 /* we haven't yet found a significant digit */
1181 int significant = FALSE;
1182
1183 /* shift the digits into the value */
1184 int pt = FALSE;
1185 for (size_t idx = 0 ; rem != 0 ; p.inc(&rem))
1186 {
1187 wchar_t ch;
1188
1189 /* get this character */
1190 ch = p.getch();
1191
1192 /* check for a digit */
1193 if (is_digit(ch))
1194 {
1195 /*
1196 * if it's not a zero, we're definitely into the significant
1197 * part of the number
1198 */
1199 if (ch != '0')
1200 significant = TRUE;
1201
1202 /*
1203 * if it's significant, add it to the number - skip leading
1204 * zeros, since they add no information to the number
1205 */
1206 if (significant)
1207 {
1208 /* if we're not out of precision, add the digit */
1209 if (idx < prec)
1210 {
1211 /* set the next digit */
1212 set_dig(ext, idx, value_of_digit(ch));
1213
1214 /* move on to the next digit position */
1215 ++idx;
1216 }
1217
1218 /*
1219 * that's another factor of 10 if we haven't found the
1220 * decimal point (whether or not we're out of precision to
1221 * actually store the digit, count the increase in the
1222 * exponent)
1223 */
1224 if (!pt)
1225 ++exp;
1226 }
1227 else if (pt)
1228 {
1229 /*
1230 * we haven't yet found a significant digit, so this is a
1231 * leading zero, but we have found the decimal point - this
1232 * reduces the exponent by one
1233 */
1234 --exp;
1235 }
1236 }
1237 else if (ch == '.' && !pt)
1238 {
1239 /*
1240 * this is the decimal point - note it; from now on, we won't
1241 * increase the exponent as we add digits
1242 */
1243 pt = TRUE;
1244 }
1245 else if (ch == 'e' || ch == 'E')
1246 {
1247 int acc;
1248 int exp_neg = FALSE;
1249
1250 /* exponent - skip the 'e' */
1251 p.inc(&rem);
1252
1253 /* check for a sign */
1254 if (rem != 0 && p.getch() == '+')
1255 {
1256 /* skip the sign */
1257 p.inc(&rem);
1258 }
1259 else if (rem != 0 && p.getch() == '-')
1260 {
1261 /* skip it and note it */
1262 p.inc(&rem);
1263 exp_neg = TRUE;
1264 }
1265
1266 /* parse the exponent */
1267 for (acc = 0 ; rem != 0 ; p.inc(&rem))
1268 {
1269 wchar_t ch;
1270
1271 /* if this is a digit, add it to the exponent */
1272 ch = p.getch();
1273 if (is_digit(ch))
1274 {
1275 /* accumulate the digit */
1276 acc *= 10;
1277 acc += value_of_digit(ch);
1278 }
1279 else
1280 {
1281 /* that's it for the exponent */
1282 break;
1283 }
1284 }
1285
1286 /* if it's negative, apply the sign */
1287 if (exp_neg)
1288 acc = -acc;
1289
1290 /* add the exponent to the one we've calculated */
1291 exp += acc;
1292
1293 /* after the exponent, we're done with the whole number */
1294 break;
1295 }
1296 else
1297 {
1298 /* it looks like we've reached the end of the number */
1299 break;
1300 }
1301 }
1302
1303 /* set the exponent */
1304 set_exp(ext, exp);
1305
1306 /* normalize the number */
1307 normalize(ext);
1308 }
1309
1310 /* ------------------------------------------------------------------------ */
1311 /*
1312 * Parse a string to determine the radix. If it has a '0x' prefix, it's in
1313 * hex. If it has a '0' prefix and no decimal point, 'E', or '8' or '9',
1314 * it's octal. Otherwise it's decimal.
1315 */
1316 int CVmObjBigNum::radix_from_string(const char *str, size_t len)
1317 {
1318 /* set up to scan the string */
1319 utf8_ptr p((char *)str);
1320 size_t rem = len;
1321
1322 /* skip leading spaces */
1323 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1324
1325 /* skip the sign if present */
1326 if (rem != 0 && (p.getch() == '-' || p.getch() == '+'))
1327 p.inc(&rem);
1328
1329 /* skip more spaces after the sign */
1330 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1331
1332 /* check for a radix indicator */
1333 if (rem != 0 && p.getch() == '0')
1334 {
1335 /*
1336 * There's a leading zero, so it could be hex or octal. If there's
1337 * an 'x', it's definitely hex. Otherwise, it's octal as long as
1338 * it's in purely integer format - that is, no decimal point or 'E'
1339 * exponent marker.
1340 */
1341 p.inc(&rem);
1342 if (rem != 0 && (p.getch() == 'x' || p.getch() == 'X'))
1343 {
1344 /* 0x prefix, so it's definitely hex */
1345 return 16;
1346 }
1347
1348 /*
1349 * There's a leading 0 but no 'x', so it could be octal or decimal,
1350 * depending on what's in the rest of the string.
1351 */
1352 for ( ; rem != 0 ; p.inc(&rem))
1353 {
1354 switch (p.getch())
1355 {
1356 case '0':
1357 case '1':
1358 case '2':
1359 case '3':
1360 case '4':
1361 case '5':
1362 case '6':
1363 case '7':
1364 /* octal digit, so we can't rule anything out yet */
1365 continue;
1366
1367 case '.':
1368 case 'e':
1369 case 'E':
1370 /*
1371 * decimal point or exponent marker, so it's a floating
1372 * point value, which can only be decimal
1373 */
1374 return 10;
1375
1376 case '8':
1377 case '9':
1378 /* an 8 or a 9 can only appear in a decimal number */
1379 return 10;
1380
1381 default:
1382 /*
1383 * Anything else is invalid within a number, whether octal
1384 * integer or floating point, so we've reached the end of
1385 * the number. Since we didn't encounter anything that
1386 * makes the number a floating point value or decimal
1387 * integer, we have an octal integer.
1388 */
1389 return 8;
1390 }
1391 }
1392
1393 /*
1394 * we reached the end of the number without finding anything that
1395 * would rule out treating it as an octal integer, so that's what
1396 * it is
1397 */
1398 return 8;
1399 }
1400 else
1401 {
1402 /* no leading '0', so it's decimal */
1403 return 10;
1404 }
1405 }
1406
1407
1408 /* ------------------------------------------------------------------------ */
1409 /*
1410 * Parse a string representation of a number in the given radix to
1411 * determine the precision required to hold the value. If 'radix' is 0, we
1412 * infer the radix from the string: if it has a '0' prefix and no decimal
1413 * point or 'E', it's an octal integer; if it has a '0x' prefix, it's a hex
1414 * integer; otherwise it's decimal and can be an integer or a floating
1415 * point value.
1416 */
1417 int CVmObjBigNum::precision_from_string(const char *str, size_t len, int radix)
1418 {
1419 /* if the radix is zero, infer the radix from the string */
1420 int inferred_radix = 0;
1421 if (radix == 0)
1422 radix = inferred_radix = radix_from_string(str, len);
1423
1424 /* for decimal values, parse the full floating point format */
1425 if (radix == 10)
1426 return precision_from_string(str, len);
1427
1428 /* set up to scan the string */
1429 utf8_ptr p((char *)str);
1430 size_t rem = len;
1431
1432 /* skip leading spaces */
1433 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1434
1435 /* skip the sign if present */
1436 if (rem != 0 && (p.getch() == '-' || p.getch() == '+'))
1437 p.inc(&rem);
1438
1439 /* skip more spaces after the sign */
1440 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1441
1442 /* if we inferred the radix as hax, skip any '0x' marker */
1443 if (inferred_radix == 16
1444 && rem != 0
1445 && p.getch() == '0'
1446 && (p.getch_at(1) == 'x' || p.getch_at(1) == 'X'))
1447 {
1448 /* skip the '0x' prefix */
1449 p.inc(&rem);
1450 p.inc(&rem);
1451 }
1452
1453 /* scan digits */
1454 int prec, significant = FALSE;
1455 for (prec = 0 ; rem != 0 ; p.inc(&rem))
1456 {
1457 /* get this character */
1458 wchar_t ch = p.getch();
1459
1460 /* get the digit value of this character */
1461 int d;
1462 if (ch >= '0' && ch <= '9')
1463 d = ch - '0';
1464 else if (ch >= 'A' && ch <= 'Z')
1465 d = ch - 'A' + 10;
1466 else if (ch >= 'a' && ch <= 'z')
1467 d = ch - 'a' + 10;
1468 else
1469 break;
1470
1471 /* if the digit isn't within the radix, it's not a digit after all */
1472 if (d >= radix)
1473 break;
1474
1475 /* it's significant if it's not a leading zero */
1476 if (ch != '0')
1477 significant = TRUE;
1478
1479 /*
1480 * if we have found a significant digit so far, count this one - do
1481 * not count leading zeros, whether they occur before or after the
1482 * decimal point
1483 */
1484 if (significant)
1485 ++prec;
1486 }
1487
1488 /*
1489 * Figure the decimal precision required to hold a number in the given
1490 * radix. This is a simple linear conversion: N base-R digits require
1491 * log(R)/log(10) decimal digits. Using log10 as our canonical log
1492 * base means that log(R)/log(10) == log(R)/1 == log(R). We of course
1493 * have to round up for any fractional digits.
1494 */
1495 return (int)ceil(prec * log10((double)radix));
1496 }
1497
1498 /*
1499 * Parse a string representation of a number to determine the precision
1500 * required to hold the value.
1501 */
1502 int CVmObjBigNum::precision_from_string(const char *str, size_t len)
1503 {
1504 /* set up to scan the string */
1505 utf8_ptr p((char *)str);
1506 size_t rem = len;
1507
1508 /* skip leading spaces */
1509 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1510
1511 /* skip the sign if present */
1512 if (rem != 0 && (p.getch() == '-' || p.getch() == '+'))
1513 p.inc(&rem);
1514
1515 /* skip more spaces after the sign */
1516 for ( ; rem != 0 && is_space(p.getch()) ; p.inc(&rem)) ;
1517
1518 /* we haven't yet found a significant leading digit */
1519 int significant = FALSE;
1520
1521 /* scan digits */
1522 size_t prec;
1523 int pt;
1524 int digcnt;
1525 for (prec = 0, digcnt = 0, pt = FALSE ; rem != 0 ; p.inc(&rem))
1526 {
1527 /* get this character */
1528 wchar_t ch = p.getch();
1529
1530 /* see what we have */
1531 if (is_digit(ch))
1532 {
1533 /*
1534 * if it's not a zero, note that we've found a significant
1535 * digit
1536 */
1537 if (ch != '0')
1538 significant = TRUE;
1539
1540 /*
1541 * if we have found a significant digit so far, count this one
1542 * - do not count leading zeros, whether they occur before or
1543 * after the decimal point
1544 */
1545 if (significant)
1546 ++prec;
1547
1548 /* count the digit in any case */
1549 ++digcnt;
1550 }
1551 else if (ch == '.' && !pt)
1552 {
1553 /* decimal point - note it and keep going */
1554 pt = TRUE;
1555 }
1556 else if (ch == 'e' || ch == 'E')
1557 {
1558 /* exponent - that's the end of the mantissa */
1559 break;
1560 }
1561 else
1562 {
1563 /* we've reached the end of the number */
1564 break;
1565 }
1566 }
1567
1568 /*
1569 * if the precision is zero, the number must be zero - use the actual
1570 * number of digits for the default precision, so that a value
1571 * specified as "0.0000000" has eight digits of precision
1572 */
1573 if (prec == 0)
1574 prec = digcnt;
1575
1576 /* return the precision necessary to store the entire string */
1577 return prec;
1578 }
1579
1580 /* ------------------------------------------------------------------------ */
1581 /*
1582 * Set my value to the given double
1583 */
1584 void CVmObjBigNum::set_double_val(char *ext, double val)
1585 {
1586 /* get the precision */
1587 size_t prec = get_prec(ext);
1588
1589 /* set the type to number */
1590 set_type(ext, VMBN_T_NUM);
1591
1592 /* set the sign bit */
1593 if (val < 0)
1594 {
1595 set_neg(ext, TRUE);
1596 val = -val;
1597 }
1598 else
1599 set_neg(ext, FALSE);
1600
1601 /* zero the mantissa */
1602 memset(ext + VMBN_MANT, 0, (prec + 1)/2);
1603
1604 /*
1605 * Initialize our exponent 'exp' to the integer portion of log10(val).
1606 * If val is a power of 10, exp == log10(val) is an integer, and val is
1607 * exactly one times 10^exp (e.g., if val is 1000, log10(val) == 3.0,
1608 * and val == 1*10^3). If val isn't a power of 10, 10^exp is the
1609 * nearest power of 10 below val. For example, log10(1500) == 3.176,
1610 * so exp == int(log10(1500)) == 3, so val = 1.5*10^3. In other words,
1611 * the value can be represented as some number between 1 and 10 times
1612 * 10^exp. Our storage format is close to this: we store the mantissa
1613 * as a value between 0 and 1. So what we *really* want for the
1614 * exponent is log10(val)+1 - this will give us an exponent that we can
1615 * multiply by some number between 0 and 1 to recreate 'val'.
1616 */
1617 int exp = (int)log10(val) + 1;
1618 set_exp(ext, exp);
1619
1620 /*
1621 * We know that val divided by 10^exp is between 0 and 1. So the most
1622 * significant digit of val is val/10^(exp-1). We can then divide the
1623 * remainder of that calculation by 10^(exp-2) to get the next digit,
1624 * and the remainder of that by 10^(exp-3) for the next digit, and so
1625 * on. Keep going until we've filled out our digits.
1626 */
1627 double base = pow(10.0, exp - 1);
1628 for (size_t i = 0 ; i < prec ; ++i, base /= 10.0)
1629 {
1630 /*
1631 * get the most significant remaining digit by dividing by the
1632 * log10 exponent of the current value
1633 */
1634 int dig = (int)(val / base);
1635 set_dig(ext, i, dig);
1636
1637 /* get the remainder */
1638 val -= dig*base;
1639 }
1640
1641 /* normalize the number */
1642 normalize(ext);
1643 }
1644
1645
1646 /* ------------------------------------------------------------------------ */
1647 /*
1648 * Set my value to a given integer value
1649 */
1650 void CVmObjBigNum::set_int_val(char *ext, long val)
1651 {
1652 if (val < 0)
1653 {
1654 set_uint_val(ext, -val);
1655 set_neg(ext, TRUE);
1656 }
1657 else
1658 {
1659 set_uint_val(ext, val);
1660 }
1661 }
1662
1663 void CVmObjBigNum::set_uint_val(char *ext, ulong val)
1664 {
1665 size_t prec;
1666 int exp;
1667
1668 /* get the precision */
1669 prec = get_prec(ext);
1670
1671 /* set the type to number */
1672 ext[VMBN_FLAGS] = 0;
1673 set_type(ext, VMBN_T_NUM);
1674
1675 /* the value is unsigned, so it's non-negative */
1676 set_neg(ext, FALSE);
1677
1678 /* initially zero the mantissa */
1679 memset(ext + VMBN_MANT, 0, (prec + 1)/2);
1680
1681 /* initialize the exponent to zero */
1682 exp = 0;
1683
1684 /* shift the integer value into the value */
1685 while (val != 0)
1686 {
1687 unsigned int dig;
1688
1689 /* get the low-order digit of the value */
1690 dig = (unsigned int)(val % 10);
1691
1692 /* shift the value one place */
1693 val /= 10;
1694
1695 /*
1696 * shift our number one place right to accommodate this next
1697 * higher-order digit
1698 */
1699 shift_right(ext, 1);
1700
1701 /* set the new most significant digit */
1702 set_dig(ext, 0, dig);
1703
1704 /* that's another factor of 10 */
1705 ++exp;
1706 }
1707
1708 /* set the exponent */
1709 set_exp(ext, exp);
1710
1711 /* normalize the number */
1712 normalize(ext);
1713 }
1714
1715 /* ------------------------------------------------------------------------ */
1716 /*
1717 * compare extensions
1718 */
1719 int CVmObjBigNum::compare_ext(const char *a, const char *b)
1720 {
1721 /* if either one is not a number, they can't be compared */
1722 if (is_nan(a) || is_nan(b))
1723 err_throw(VMERR_INVALID_COMPARISON);
1724
1725 /* if the signs differ, the positive one is greater */
1726 if (get_neg(a) != get_neg(b))
1727 {
1728 /*
1729 * if a is negative, it's the lesser number; otherwise it's the
1730 * greater number
1731 */
1732 return (get_neg(a) ? -1 : 1);
1733 }
1734
1735 /* the signs are the same - compare the absolute values */
1736 int ret = compare_abs(a, b);
1737
1738 /*
1739 * If the numbers are negative, and abs(a) > abs(b), a is actually the
1740 * lesser number; if they're negative and abs(a) < abs(b), a is the
1741 * greater number. So, if a is negative, invert the sense of the
1742 * result. Otherwise, both numbers are positive, so the sense of the
1743 * absolute value comparison is the same as the sense of the actual
1744 * comparison, so just return the result directly.
1745 */
1746 return (get_neg(a) ? -ret : ret);
1747 }
1748
1749 /* ------------------------------------------------------------------------ */
1750 /*
1751 * Compare the absolute values of two numbers
1752 */
1753 int CVmObjBigNum::compare_abs(const char *ext1, const char *ext2)
1754 {
1755 size_t idx;
1756 int zero1 = is_zero(ext1);
1757 int zero2 = is_zero(ext2);
1758 size_t prec1 = get_prec(ext1);
1759 size_t prec2 = get_prec(ext2);
1760 size_t max_prec;
1761 size_t min_prec;
1762 const char *max_ext;
1763 int result;
1764
1765 /*
1766 * if one is zero and the other is not, the one that's not zero has a
1767 * larger absolute value
1768 */
1769 if (zero1)
1770 return (zero2 ? 0 : -1);
1771 if (zero2)
1772 return (zero1 ? 0 : 1);
1773
1774 /*
1775 * if the exponents differ, the one with the larger exponent is the
1776 * larger number (this is necessarily true because we keep all numbers
1777 * normalized)
1778 */
1779 if (get_exp(ext1) > get_exp(ext2))
1780 return 1;
1781 else if (get_exp(ext1) < get_exp(ext2))
1782 return -1;
1783
1784 /*
1785 * The exponents are equal, so we must compare the mantissas digit by
1786 * digit
1787 */
1788
1789 /* get the larger of the two precisions */
1790 min_prec = prec2;
1791 max_prec = prec1;
1792 max_ext = ext1;
1793 if (prec2 > max_prec)
1794 {
1795 min_prec = prec1;
1796 max_prec = prec2;
1797 max_ext = ext2;
1798 }
1799
1800 /*
1801 * The digits are in order from most significant to least significant,
1802 * which means we can use memcmp to compare the common parts. However,
1803 * we can only compare an even number of digits this way, so round down
1804 * the common precision if it's odd.
1805 */
1806 if (min_prec > 1
1807 && (result = memcmp(ext1 + VMBN_MANT, ext2 + VMBN_MANT,
1808 min_prec/2)) != 0)
1809 {
1810 /*
1811 * they're different in the common memcmp-able parts, so return the
1812 * memcmp result
1813 */
1814 return result;
1815 }
1816
1817 /* if the common precision is odd, compare the final common digit */
1818 if ((min_prec & 1) != 0
1819 && (result = ((int)get_dig(ext1, min_prec-1)
1820 - (int)get_dig(ext2, min_prec-1))) != 0)
1821 return result;
1822
1823 /*
1824 * the common parts of the mantissas are identical; check each
1825 * remaining digit of the longer one to see if any are non-zero
1826 */
1827 for (idx = min_prec ; idx < max_prec ; ++idx)
1828 {
1829 /*
1830 * if this digit is non-zero, the longer one is greater, because
1831 * the shorter one has an implied zero in this position
1832 */
1833 if (get_dig(max_ext, idx) != 0)
1834 return (int)prec1 - (int)prec2;
1835 }
1836
1837 /* they're identical */
1838 return 0;
1839 }
1840
1841 /* ------------------------------------------------------------------------ */
1842 /*
1843 * Compute a sum into the given buffer
1844 */
1845 void CVmObjBigNum::compute_sum_into(char *new_ext,
1846 const char *ext1, const char *ext2)
1847 {
1848 /* check to see if the numbers have the same sign */
1849 if (get_neg(ext1) == get_neg(ext2))
1850 {
1851 /*
1852 * the two numbers have the same sign, so the sum has the same sign
1853 * as the two values, and the magnitude is the sum of the absolute
1854 * values of the operands
1855 */
1856
1857 /* compute the sum of the absolute values */
1858 compute_abs_sum_into(new_ext, ext1, ext2);
1859
1860 /* set the sign to match that of the operand */
1861 set_neg(new_ext, get_neg(ext1));
1862 }
1863 else
1864 {
1865 /*
1866 * one is positive and the other is negative - subtract the
1867 * absolute value of the negative one from the absolute value of
1868 * the positive one; the sign will be set correctly by the
1869 * differencing
1870 */
1871 if (get_neg(ext1))
1872 compute_abs_diff_into(new_ext, ext2, ext1);
1873 else
1874 compute_abs_diff_into(new_ext, ext1, ext2);
1875 }
1876 }
1877
1878 /* ------------------------------------------------------------------------ */
1879 /*
1880 * Compute the sum of two absolute values into the given buffer.
1881 */
1882 void CVmObjBigNum::compute_abs_sum_into(char *new_ext,
1883 const char *ext1, const char *ext2)
1884 {
1885 int exp1 = get_exp(ext1), exp2 = get_exp(ext2), new_exp;
1886 int prec1 = get_prec(ext1), prec2 = get_prec(ext2);
1887 int new_prec = get_prec(new_ext);
1888
1889 /* if one or the other is identically zero, return the other value */
1890 if (is_zero(ext1))
1891 {
1892 /* ext1 is zero - return ext2 */
1893 copy_val(new_ext, ext2, TRUE);
1894 return;
1895 }
1896 else if (is_zero(ext2))
1897 {
1898 /* ext2 is zero - return ext1 */
1899 copy_val(new_ext, ext1, TRUE);
1900 return;
1901 }
1902
1903 /*
1904 * start the new value with the larger of the two exponents - this
1905 * will have the desired effect of dropping the least significant
1906 * digits if any digits must be dropped
1907 */
1908 new_exp = exp1;
1909 if (exp2 > new_exp)
1910 new_exp = exp2;
1911 set_exp(new_ext, new_exp);
1912
1913 /* compute the digit positions at the bounds of each of our values */
1914 int hi1 = exp1 - 1;
1915 int lo1 = exp1 - prec1;
1916
1917 int hi2 = exp2 - 1;
1918 int lo2 = exp2 - prec2;
1919
1920 int hi3 = new_exp - 1;
1921 int lo3 = new_exp - new_prec;
1922
1923 /*
1924 * If one of the values provides a digit one past the end of our
1925 * result, remember that as the trailing digit that we're going to
1926 * drop. We'll check this when we're done to see if we need to
1927 * round the number. Since the result has precision at least as
1928 * large as the larger of the two inputs, we can only be dropping
1929 * significant digits from one of the two inputs - we can't be
1930 * cutting off both inputs.
1931 */
1932 int trail_dig = 0, trail_val = 0;
1933 if (lo3 - 1 >= lo1 && lo3 - 1 <= hi1)
1934 {
1935 /* remember the digit */
1936 trail_dig = get_dig(ext1, exp1 - (lo3-1) - 1);
1937 trail_val = get_ORdigs(ext1, exp1 - (lo3-1));
1938 }
1939 else if (lo3 - 1 >= lo2 && lo3 - 1 <= hi2)
1940 {
1941 /* remember the digit */
1942 trail_dig = get_dig(ext2, exp2 - (lo3-1) - 1);
1943 trail_val = get_ORdigs(ext2, exp2 - (lo3-1));
1944 }
1945
1946 /* no carry yet */
1947 int carry = 0;
1948
1949 /* add the digits */
1950 for (int pos = lo3 ; pos <= hi3 ; ++pos)
1951 {
1952 /* start with the carry */
1953 int acc = carry;
1954
1955 /* add the first value digit if it's in range */
1956 if (pos >= lo1 && pos <= hi1)
1957 acc += get_dig(ext1, exp1 - pos - 1);
1958
1959 /* add the second value digit if it's in range */
1960 if (pos >= lo2 && pos <= hi2)
1961 acc += get_dig(ext2, exp2 - pos - 1);
1962
1963 /* check for carry */
1964 if (acc > 9)
1965 {
1966 /* reduce the accumulator and set the carry */
1967 acc -= 10;
1968 carry = 1;
1969 }
1970 else
1971 {
1972 /* no carry */
1973 carry = 0;
1974 }
1975
1976 /* set the digit in the result */
1977 set_dig(new_ext, new_exp - pos - 1, acc);
1978 }
1979
1980 /*
1981 * If we have a carry at the end, we must carry it out to a new
1982 * digit. In order to do this, we must shift the whole number right
1983 * one place, then insert the one.
1984 */
1985 if (carry)
1986 {
1987 /*
1988 * remember the last digit of the result, which we won't have
1989 * space to store after the shift
1990 */
1991 trail_val |= trail_dig;
1992 trail_dig = get_dig(new_ext, new_prec - 1);
1993
1994 /* shift the result right */
1995 shift_right(new_ext, 1);
1996
1997 /* increase the exponent to compensate for the shift */
1998 set_exp(new_ext, get_exp(new_ext) + 1);
1999
2000 /* set the leading 1 */
2001 set_dig(new_ext, 0, 1);
2002 }
2003
2004 /* the sum of two absolute values is always positive */
2005 set_neg(new_ext, FALSE);
2006
2007 /*
2008 * round up if the trailing digits are >5000..., or exactly 5000...
2009 * and the last digit is odd
2010 */
2011 round_for_dropped_digits(new_ext, trail_dig, trail_val);
2012
2013 /* normalize the number */
2014 normalize(new_ext);
2015 }
2016
2017 /* ------------------------------------------------------------------------ */
2018 /*
2019 * Compute a difference into a buffer
2020 */
2021 void CVmObjBigNum::compute_diff_into(char *result,
2022 const char *ext1, const char *ext2)
2023 {
2024 /* check to see if the numbers have the same sign */
2025 if (get_neg(ext1) == get_neg(ext2))
2026 {
2027 /*
2028 * The two numbers have the same sign, so the difference is the
2029 * difference in the magnitudes, and has a sign depending on the
2030 * order of the difference and the signs of the original values.
2031 * If both values are positive, the difference is negative if the
2032 * second value is larger than the first. If both values are
2033 * negative, the difference is negative if the second value has
2034 * larger absolute value than the first.
2035 */
2036
2037 /* compute the difference in magnitudes */
2038 compute_abs_diff_into(result, ext1, ext2);
2039
2040 /*
2041 * if the original values were negative, then the sign of the
2042 * result is the opposite of the sign of the difference of the
2043 * absolute values; otherwise, it's the same as the sign of the
2044 * difference of the absolute values
2045 */
2046 if (get_neg(ext1))
2047 negate(result);
2048 }
2049 else
2050 {
2051 /*
2052 * one is positive and the other is negative - the result has the
2053 * sign of the first operand, and has magnitude equal to the sum of
2054 * the absolute values
2055 */
2056
2057 /* compute the sum of the absolute values */
2058 compute_abs_sum_into(result, ext1, ext2);
2059
2060 /* set the sign of the result to that of the first operand */
2061 if (!is_zero(result))
2062 set_neg(result, get_neg(ext1));
2063 }
2064 }
2065
2066 /* ------------------------------------------------------------------------ */
2067 /*
2068 * Compute the difference of two absolute values into the given buffer
2069 */
2070 void CVmObjBigNum::compute_abs_diff_into(char *new_ext,
2071 const char *ext1, const char *ext2)
2072 {
2073 int max_exp;
2074 int lo1, hi1;
2075 int lo2, hi2;
2076 int lo3, hi3;
2077 int pos;
2078 int result_neg = FALSE;
2079 int borrow;
2080
2081 /* if we're subtracting zero or from zero, it's easy */
2082 if (is_zero(ext2))
2083 {
2084 /*
2085 * we're subtracting zero from another value - the result is
2086 * simply the first value
2087 */
2088 copy_val(new_ext, ext1, TRUE);
2089 return;
2090 }
2091 else if (is_zero(ext1))
2092 {
2093 /*
2094 * We're subtracting a value from zero - we know the value we're
2095 * subtracting is non-zero (we already checked for that case
2096 * above), and we're only considering the absolute values, so
2097 * simply return the negative of the absolute value of the
2098 * second operand.
2099 */
2100 copy_val(new_ext, ext2, TRUE);
2101 set_neg(new_ext, TRUE);
2102 return;
2103 }
2104
2105 /*
2106 * Compare the absolute values of the two operands. If the first
2107 * value is larger than the second, subtract them in the given
2108 * order. Otherwise, reverse the order and note that the result is
2109 * negative.
2110 */
2111 if (compare_abs(ext1, ext2) < 0)
2112 {
2113 const char *tmp;
2114
2115 /* the result will be negative */
2116 result_neg = TRUE;
2117
2118 /* swap the order of the subtraction */
2119 tmp = ext1;
2120 ext1 = ext2;
2121 ext2 = tmp;
2122 }
2123
2124 /*
2125 * start the new value with the larger of the two exponents - this
2126 * will have the desired effect of dropping the least significant
2127 * digits if any digits must be dropped
2128 */
2129 max_exp = get_exp(ext1);
2130 if (get_exp(ext2) > max_exp)
2131 max_exp = get_exp(ext2);
2132 set_exp(new_ext, max_exp);
2133
2134 /* compute the digit positions at the bounds of each of our values */
2135 hi1 = get_exp(ext1) - 1;
2136 lo1 = get_exp(ext1) - get_prec(ext1);
2137
2138 hi2 = get_exp(ext2) - 1;
2139 lo2 = get_exp(ext2) - get_prec(ext2);
2140
2141 hi3 = get_exp(new_ext) - 1;
2142 lo3 = get_exp(new_ext) - get_prec(new_ext);
2143
2144 /* start off with no borrow */
2145 borrow = 0;
2146
2147 /*
2148 * Check for borrowing from before the least significant digit
2149 * position in common to both numbers
2150 */
2151 if (lo3-1 >= lo1 && lo3-1 <= hi1)
2152 {
2153 /*
2154 * In this case, we would be dropping precision from the end of
2155 * the top number. This case should never happen - the only way
2156 * it could happen is for the bottom number to extend to the
2157 * left of the top number at the most significant end. This
2158 * cannot happen because the bottom number always has small
2159 * magnitude by this point (we guarantee this above). So, we
2160 * should never get here.
2161 */
2162 assert(FALSE);
2163 }
2164 else if (lo3-1 >= lo2 && lo3-1 <= hi2)
2165 {
2166 size_t idx;
2167
2168 /*
2169 * We're dropping precision from the bottom number, so we want
2170 * to borrow into the subtraction if the rest of the number is
2171 * greater than 5xxxx. If it's exactly 5000..., do not borrow,
2172 * since the result would end in 5 and we'd round up.
2173 *
2174 * If the next digit is 6 or greater, we know for a fact we'll
2175 * have to borrow. If the next digit is 4 or less, we know for
2176 * a fact we won't have to borrow. If the next digit is 5,
2177 * though, we must look at the rest of the number to see if
2178 * there's anything but trailing zeros.
2179 */
2180 idx = (size_t)(get_exp(ext2) - (lo3-1) - 1);
2181 if (get_dig(ext2, idx) >= 6)
2182 {
2183 /* definitely borrow */
2184 borrow = 1;
2185 }
2186 else if (get_dig(ext2, idx) == 5)
2187 {
2188 /* borrow only if we have something non-zero following */
2189 for (++idx ; idx < get_prec(ext2) ; ++idx)
2190 {
2191 /* if it's non-zero, we must borrow */
2192 if (get_dig(ext2, idx) != 0)
2193 {
2194 /* note the borrow */
2195 borrow = 1;
2196
2197 /* no need to keep scanning */
2198 break;
2199 }
2200 }
2201 }
2202 }
2203
2204 /* subtract the digits from least to most significant */
2205 for (pos = lo3 ; pos <= hi3 ; ++pos)
2206 {
2207 int acc;
2208
2209 /* start with zero in the accumulator */
2210 acc = 0;
2211
2212 /* start with the top-line value if it's represented here */
2213 if (pos >= lo1 && pos <= hi1)
2214 acc = get_dig(ext1, get_exp(ext1) - pos - 1);
2215
2216 /* subtract the second value digit if it's represented here */
2217 if (pos >= lo2 && pos <= hi2)
2218 acc -= get_dig(ext2, get_exp(ext2) - pos - 1);
2219
2220 /* subtract the borrow */
2221 acc -= borrow;
2222
2223 /* check for borrow */
2224 if (acc < 0)
2225 {
2226 /* increase the accumulator */
2227 acc += 10;
2228
2229 /* we must borrow from the next digit up */
2230 borrow = 1;
2231 }
2232 else
2233 {
2234 /* we're in range - no need to borrow */
2235 borrow = 0;
2236 }
2237
2238 /* set the digit in the result */
2239 set_dig(new_ext, get_exp(new_ext) - pos - 1, acc);
2240 }
2241
2242 /* set the sign of the result as calculated earlier */
2243 set_neg(new_ext, result_neg);
2244
2245 /* normalize the number */
2246 normalize(new_ext);
2247 }
2248
2249 /* ------------------------------------------------------------------------ */
2250 /*
2251 * Compute the product of the values into the given buffer
2252 */
2253 void CVmObjBigNum::compute_prod_into(char *new_ext,
2254 const char *ext1, const char *ext2)
2255 {
2256 size_t prec1 = get_prec(ext1);
2257 size_t prec2 = get_prec(ext2);
2258 size_t new_prec = get_prec(new_ext);
2259 size_t idx1;
2260 size_t idx2;
2261 size_t out_idx;
2262 size_t start_idx;
2263 int out_exp;
2264
2265 /* start out with zero in the accumulator */
2266 memset(new_ext + VMBN_MANT, 0, (new_prec + 1)/2);
2267
2268 /*
2269 * Initially write output in the same 'column' where the top number
2270 * ends, so we start out with the same scale as the top number.
2271 */
2272 start_idx = get_prec(ext1);
2273
2274 /*
2275 * initial result exponent is the sum of the exponents, minus the
2276 * number of digits in the bottom number (effectively, this lets us
2277 * treat the bottom number as a whole number by scaling it enough to
2278 * make it whole, soaking up the factors of ten into decimal point
2279 * relocation)
2280 */
2281 out_exp = get_exp(ext1) + get_exp(ext2) - prec2;
2282
2283 /* there's no trailing accumulator digit yet */
2284 int trail_dig = 0, trail_val = 0;
2285
2286 /*
2287 * Loop over digits in the bottom number, from least significant to
2288 * most significant - we'll multiply each digit of the bottom number
2289 * by the top number and add the result into the accumulator.
2290 */
2291 for (idx2 = prec2 ; idx2 != 0 ; )
2292 {
2293 int carry;
2294 int dig;
2295 int ext2_dig;
2296
2297 /* no carry yet on this round */
2298 carry = 0;
2299
2300 /* start writing this round at the output start index */
2301 out_idx = start_idx;
2302
2303 /* move to the next digit */
2304 --idx2;
2305
2306 /* get this digit of ext2 */
2307 ext2_dig = get_dig(ext2, idx2);
2308
2309 /*
2310 * if this digit of ext2 is non-zero, multiply the digits of
2311 * ext1 by the digit (obviously if the digit is zero, there's no
2312 * need to iterate over the digits of ext1)
2313 */
2314 if (ext2_dig != 0)
2315 {
2316 /*
2317 * loop over digits in the top number, from least to most
2318 * significant
2319 */
2320 for (idx1 = prec1 ; idx1 != 0 ; )
2321 {
2322 /* move to the next digit of the top number */
2323 --idx1;
2324
2325 /* move to the next digit of the accumulator */
2326 --out_idx;
2327
2328 /*
2329 * compute the product of the current digits, and add in
2330 * the carry from the last digit, then add in the
2331 * current accumulator digit in this position
2332 */
2333 dig = (get_dig(ext1, idx1) * ext2_dig)
2334 + carry
2335 + get_dig(new_ext, out_idx);
2336
2337 /* figure the carry to the next digit */
2338 carry = (dig / 10);
2339 dig = dig % 10;
2340
2341 /* store the new digit */
2342 set_dig(new_ext, out_idx, dig);
2343 }
2344 }
2345
2346 /*
2347 * Shift the result accumulator right in preparation for the
2348 * next round. One exception: if this is the last (most
2349 * significant) digit of the bottom number, and there's no
2350 * carry, there's no need to shift the number, since we'd just
2351 * normalize away the leading zero anyway
2352 */
2353 if (idx2 != 0 || carry != 0)
2354 {
2355 /* remember the trailing digit that we're going to drop */
2356 trail_val |= trail_dig;
2357 trail_dig = get_dig(new_ext, new_prec - 1);
2358
2359 /* shift the accumulator */
2360 shift_right(new_ext, 1);
2361
2362 /* increase the output exponent */
2363 ++out_exp;
2364
2365 /* insert the carry as the lead digit */
2366 set_dig(new_ext, 0, carry);
2367 }
2368 }
2369
2370 /* set the result exponent */
2371 set_exp(new_ext, out_exp);
2372
2373 /*
2374 * set the sign - if both inputs have the same sign, the output is
2375 * positive, otherwise it's negative
2376 */
2377 set_neg(new_ext, get_neg(ext1) != get_neg(ext2));
2378
2379 /* if the trailing digit is 5 or greater, round up */
2380 round_for_dropped_digits(new_ext, trail_dig, trail_val);
2381
2382 /* normalize the number */
2383 normalize(new_ext);
2384 }
2385
2386 /* ------------------------------------------------------------------------ */
2387 /*
2388 * Compute a quotient into the given buffer. If new_rem_ext is
2389 * non-null, we'll save the remainder into this buffer. We calculate
2390 * the remainder only to the precision of the quotient.
2391 */
2392 void CVmObjBigNum::compute_quotient_into(char *new_ext,
2393 char *new_rem_ext,
2394 const char *ext1, const char *ext2)
2395 {
2396 char *rem_ext;
2397 uint rem_hdl;
2398 char *rem_ext2;
2399 uint rem_hdl2;
2400 int quo_exp;
2401 size_t quo_idx;
2402 size_t quo_prec = get_prec(new_ext);
2403 size_t dvd_prec = get_prec(ext1);
2404 size_t dvs_prec = get_prec(ext2);
2405 char *dvs_ext;
2406 uint dvs_hdl;
2407 char *dvs_ext2;
2408 uint dvs_hdl2;
2409 int lead_dig_set;
2410 int zero_remainder;
2411 int acc;
2412 size_t rem_prec;
2413
2414 /* if the divisor is zero, throw an error */
2415 if (is_zero(ext2))
2416 err_throw(VMERR_DIVIDE_BY_ZERO);
2417
2418 /* if the dividend is zero, the result is zero */
2419 if (is_zero(ext1))
2420 {
2421 /* set the result to zero */
2422 set_zero(new_ext);
2423
2424 /* if they want the remainder, it's zero also */
2425 if (new_rem_ext != 0)
2426 set_zero(new_rem_ext);
2427
2428 /* we're done */
2429 return;
2430 }
2431
2432 /*
2433 * Calculate the precision we need for the running remainder. We
2434 * must retain enough precision in the remainder to calculate exact
2435 * differences, so we need the greater of the precisions of the
2436 * dividend and the divisor, plus enough extra digits for the
2437 * maximum relative shifting. We'll have to shift at most one
2438 * extra digit, but use two to be extra safe.
2439 */
2440 rem_prec = dvd_prec;
2441 if (rem_prec < dvs_prec)
2442 rem_prec = dvs_prec;
2443 rem_prec += 2;
2444
2445 /*
2446 * Make sure the precision is at least three, since it simplifies
2447 * our digit approximation calculation.
2448 */
2449 if (rem_prec < 3)
2450 rem_prec = 3;
2451
2452 /*
2453 * Allocate two temporary registers for the running remainder, and
2454 * one more for the multiplied divisor. Note that we allocate the
2455 * multiplied divisor at our higher precision so that we don't lose
2456 * digits in our multiplier calculations.
2457 */
2458 alloc_temp_regs(rem_prec, 3,
2459 &rem_ext, &rem_hdl, &rem_ext2, &rem_hdl2,
2460 &dvs_ext2, &dvs_hdl2);
2461
2462 /*
2463 * Allocate another temp register for the shifted divisor. Note
2464 * that we need a different precision here, which is why we must
2465 * make a separate allocation call
2466 */
2467 err_try
2468 {
2469 /* make the additional allocation */
2470 alloc_temp_regs(dvs_prec, 1, &dvs_ext, &dvs_hdl);
2471 }
2472 err_catch_disc
2473 {
2474 /* delete the first group of registers we allocated */
2475 release_temp_regs(3, rem_hdl, rem_hdl2, dvs_hdl2);
2476
2477 /* re-throw the exception */
2478 err_rethrow();
2479 }
2480 err_end;
2481
2482 /* the dividend is the initial value of the running remainder */
2483 copy_val(rem_ext, ext1, TRUE);
2484
2485 /* copy the initial divisor into our temp register */
2486 copy_val(dvs_ext, ext2, TRUE);
2487
2488 /* we haven't set a non-zero leading digit yet */
2489 lead_dig_set = FALSE;
2490
2491 /*
2492 * scale the divisor so that the divisor and dividend have the same
2493 * exponent, and absorb the multiplier in the quotient
2494 */
2495 quo_exp = get_exp(ext1) - get_exp(ext2) + 1;
2496 set_exp(dvs_ext, get_exp(ext1));
2497
2498 /* we don't have a zero remainder yet */
2499 zero_remainder = FALSE;
2500
2501 /*
2502 * if the result of the floating point division is entirely fractional,
2503 * the dividend is the remainder, and the quotient is zero
2504 */
2505 if (new_rem_ext != 0 && quo_exp <= 0)
2506 {
2507 /* copy the initial remainder into the output remainder */
2508 copy_val(new_rem_ext, rem_ext, TRUE);
2509
2510 /* set the quotient to zero */
2511 set_zero(new_ext);
2512
2513 /* we have the result - no need to do any more work */
2514 goto done;
2515 }
2516
2517 /*
2518 * Loop over each digit of precision of the quotient.
2519 */
2520 for (quo_idx = 0 ; ; )
2521 {
2522 int rem_approx, dvs_approx;
2523 int dig_approx;
2524 char *tmp;
2525 int exp_diff;
2526
2527 /* start out with 0 in our digit accumulator */
2528 acc = 0;
2529
2530 /*
2531 * Get the first few digits of the remainder, and the first few
2532 * digits of the divisor, rounding up the divisor and rounding
2533 * down the remainder. Compute the quotient - this will give us
2534 * a rough guess and a lower bound for the current digit's
2535 * value.
2536 */
2537 rem_approx = (get_dig(rem_ext, 0)*100
2538 + get_dig(rem_ext, 1)*10
2539 + get_dig(rem_ext, 2));
2540 dvs_approx = (get_dig(dvs_ext, 0)*100
2541 + (dvs_prec >= 2 ? get_dig(dvs_ext, 1) : 0)*10
2542 + (dvs_prec >= 3 ? get_dig(dvs_ext, 2) : 0)
2543 + 1);
2544
2545 /* adjust for differences in the scale */
2546 exp_diff = get_exp(rem_ext) - get_exp(dvs_ext);
2547 if (exp_diff > 0)
2548 {
2549 /* the remainder is larger - scale it up */
2550 for ( ; exp_diff > 0 ; --exp_diff)
2551 rem_approx *= 10;
2552 }
2553 else if (exp_diff <= -3)
2554 {
2555 /*
2556 * The divisor is larger by more than 10^3, which means that
2557 * the result of our integer division is definitely going to
2558 * be zero, so there's no point in actually doing the
2559 * calculation. This is only a special case because, for
2560 * sufficiently large negative differences, we'd have to
2561 * multiply our divisor approximation by 10 so many times
2562 * that we'd overflow a native int type, at which point we'd
2563 * get 0 in the divisor, which would result in a
2564 * divide-by-zero. To avoid this, just put 1000 in our
2565 * divisor, which is definitely larger than anything we can
2566 * have in rem_ext at this point (since it was just three
2567 * decimal digits, after all).
2568 */
2569 dvs_approx = 1000;
2570 }
2571 else if (exp_diff < 0)
2572 {
2573 /* the divisor is larger - scale it up */
2574 for ( ; exp_diff < 0 ; ++exp_diff)
2575 dvs_approx *= 10;
2576 }
2577
2578 /* calculate our initial guess for this digit */
2579 dig_approx = rem_approx / dvs_approx;
2580
2581 /*
2582 * If this digit is above 2, it'll save us a lot of work to
2583 * subtract digit*divisor once, rather than iteratively
2584 * deducting the divisor one time per iteration. (It costs us a
2585 * little to calculate the digit*divisor product, so we don't
2586 * want to do this for very small digit values.)
2587 */
2588 if (dig_approx > 2)
2589 {
2590 /* put the approximate digit in the accumulator */
2591 acc = dig_approx;
2592
2593 /* make a copy of the divisor */
2594 copy_val(dvs_ext2, dvs_ext, FALSE);
2595
2596 /*
2597 * multiply it by the guess for the digit - we know this
2598 * will always be less than or equal to the real value
2599 * because of the way we did the rounding
2600 */
2601 mul_by_long(dvs_ext2, (ulong)dig_approx);
2602
2603 /* subtract it from the running remainder */
2604 compute_abs_diff_into(rem_ext2, rem_ext, dvs_ext2);
2605
2606 /* if that leaves zero in the remainder, note it */
2607 if (is_zero(rem_ext2))
2608 {
2609 zero_remainder = TRUE;
2610 break;
2611 }
2612
2613 /*
2614 * swap the remainder registers, since rem_ext2 is now the
2615 * new running remainder value
2616 */
2617 tmp = rem_ext;
2618 rem_ext = rem_ext2;
2619 rem_ext2 = tmp;
2620
2621 /*
2622 * Now we'll finish up the job by subtracting the divisor
2623 * from the remainder as many more times as necessary for
2624 * the remainder to fall below the divisor. We can't be
2625 * exact at this step because we're not considering all of
2626 * the digits, but we should only have one more subtraction
2627 * remaining at this point.
2628 */
2629 }
2630
2631 /*
2632 * subtract the divisor from the running remainder as many times
2633 * as we can
2634 */
2635 for ( ; ; ++acc)
2636 {
2637 int comp_res;
2638
2639 /* compare the running remainder to the divisor */
2640 comp_res = compare_abs(rem_ext, dvs_ext);
2641 if (comp_res < 0)
2642 {
2643 /*
2644 * the remainder is smaller than the divisor - we have
2645 * our result for this digit
2646 */
2647 break;
2648 }
2649 else if (comp_res == 0)
2650 {
2651 /* note that we have a zero remainder */
2652 zero_remainder = TRUE;
2653
2654 /* count one more subtraction */
2655 ++acc;
2656
2657 /* we have our result for this digit */
2658 break;
2659 }
2660
2661 /* subtract it */
2662 compute_abs_diff_into(rem_ext2, rem_ext, dvs_ext);
2663
2664 /*
2665 * swap the remainder registers, since rem_ext2 is now the
2666 * new running remainder value
2667 */
2668 tmp = rem_ext;
2669 rem_ext = rem_ext2;
2670 rem_ext2 = tmp;
2671 }
2672
2673 /* store this digit of the quotient */
2674 if (quo_idx < quo_prec)
2675 {
2676 /* store the digit */
2677 set_dig(new_ext, quo_idx, acc);
2678 }
2679 else if (quo_idx == quo_prec)
2680 {
2681 /* set the quotient's exponent */
2682 set_exp(new_ext, quo_exp);
2683
2684 /*
2685 * This is the last digit, which we calculated for rounding
2686 * purposes only. If it's greater than 5, round up. If it's
2687 * exactly 5 and we have a non-zero remainder, round up. If
2688 * it's exactly 5 and we have a zero remainder, round up if the
2689 * last digit is odd.
2690 */
2691 round_for_dropped_digits(new_ext, acc, !zero_remainder);
2692
2693 /* we've reached the rounding digit - we can stop now */
2694 break;
2695 }
2696
2697 /*
2698 * if this is a non-zero digit, we've found a significant
2699 * leading digit
2700 */
2701 if (acc != 0)
2702 lead_dig_set = TRUE;
2703
2704 /*
2705 * if we've found a significant leading digit, move to the next
2706 * digit of the quotient; if not, adjust the quotient exponent
2707 * down one, and keep preparing to write the first digit at the
2708 * first "column" of the quotient
2709 */
2710 if (lead_dig_set)
2711 ++quo_idx;
2712 else
2713 --quo_exp;
2714
2715 /*
2716 * If we have an exact result (a zero remainder), we're done.
2717 *
2718 * Similarly, if we've reached the units digit, and the caller
2719 * wants the remainder, stop now - the caller wants an integer
2720 * result for the quotient, which we now have.
2721 *
2722 * Similarly, if we've reached the rounding digit, and the
2723 * caller wants the remainder, skip the rounding step - the
2724 * caller wants an unrounded result for the quotient so that the
2725 * quotient times the divisor plus the remainder equals the
2726 * dividend.
2727 */
2728 if (zero_remainder
2729 || (new_rem_ext != 0
2730 && ((int)quo_idx == quo_exp || quo_idx == quo_prec)))
2731 {
2732 /* zero any remaining digits of the quotient */
2733 for ( ; quo_idx < quo_prec ; ++quo_idx)
2734 set_dig(new_ext, quo_idx, 0);
2735
2736 /* set the quotient's exponent */
2737 set_exp(new_ext, quo_exp);
2738
2739 /* that's it */
2740 break;
2741 }
2742
2743 /* divide the divisor by ten */
2744 set_exp(dvs_ext, get_exp(dvs_ext) - 1);
2745 }
2746
2747 /* store the remainder if the caller wants the value */
2748 if (new_rem_ext != 0)
2749 {
2750 /* save the remainder into the caller's buffer */
2751 if (zero_remainder)
2752 {
2753 /* the remainder is exactly zero */
2754 set_zero(new_rem_ext);
2755 }
2756 else
2757 {
2758 /* copy the running remainder */
2759 copy_val(new_rem_ext, rem_ext, TRUE);
2760
2761 /* the remainder has the same sign as the dividend */
2762 set_neg(new_rem_ext, get_neg(ext1));
2763
2764 /* normalize the remainder */
2765 normalize(new_rem_ext);
2766 }
2767 }
2768
2769 /*
2770 * the quotient is positive if both the divisor and dividend have
2771 * the same sign, negative if they're different
2772 */
2773 set_neg(new_ext, get_neg(ext1) != get_neg(ext2));
2774
2775 /* normalize the quotient */
2776 normalize(new_ext);
2777
2778 done:
2779 /* release the temporary registers */
2780 release_temp_regs(4, rem_hdl, rem_hdl2, dvs_hdl, dvs_hdl2);
2781 }
2782
2783 /* ------------------------------------------------------------------------ */
2784 /*
2785 * The BigNumber cache is implemented as an ordinary static. This can be
2786 * shared among VM instances (since it stores mathematical constants and
2787 * provides some simple memory management facilities), so it's not
2788 * necessary to use the VM global scheme (which is only needed for data
2789 * that must be isolated per VM instance). This simplifies interfaces to
2790 * many of the low-level routines by letting us omit the VMG_ parameter,
2791 * and allows many BigNumber features to be accessed without having to link
2792 * in the whole VM global subsystem. This last bit lets us use BigNumber
2793 * calculations in the compiler, for example, which is useful for constant
2794 * folding.
2795 */
2796 CVmBigNumCache *S_bignum_cache = 0;
2797
2798 /* number of references to the cache */
2799 static int S_bignum_cache_refs = 0;
2800
2801
2802 /* ------------------------------------------------------------------------ */
2803 /*
2804 * Cache creation/deletion
2805 */
2806
2807 void CVmObjBigNum::init_cache()
2808 {
2809 if (S_bignum_cache_refs++ == 0)
2810 S_bignum_cache = new CVmBigNumCache(32);
2811 }
2812
2813 void CVmObjBigNum::term_cache()
2814 {
2815 if (--S_bignum_cache_refs == 0)
2816 {
2817 delete S_bignum_cache;
2818 S_bignum_cache = 0;
2819 }
2820 }
2821
2822 /* ------------------------------------------------------------------------ */
2823 /*
2824 * Allocate a temporary register
2825 */
2826 char *CVmObjBigNum::alloc_temp_reg(size_t prec, uint *hdl)
2827 {
2828 /* allocate a register with enough space for the desired precision */
2829 char *p = S_bignum_cache->alloc_reg(calc_alloc(prec), hdl);
2830
2831 /* if that succeeded, initialize the memory */
2832 if (p != 0)
2833 {
2834 /* set the desired precision */
2835 set_prec(p, prec);
2836
2837 /* initialize the flags */
2838 p[VMBN_FLAGS] = 0;
2839 }
2840
2841 /* return the register memory */
2842 return p;
2843 }
2844
2845 /* ------------------------------------------------------------------------ */
2846 /*
2847 * release a temporary register
2848 */
2849 void CVmObjBigNum::release_temp_reg(uint hdl)
2850 {
2851 /* release the register to the cache */
2852 S_bignum_cache->release_reg(hdl);
2853 }
2854
2855 /* ------------------------------------------------------------------------ */
2856 /*
2857 * Allocate a group of temporary registers
2858 */
2859 void CVmObjBigNum::alloc_temp_regs(size_t prec, size_t cnt, ...)
2860 {
2861 va_list marker;
2862 size_t i;
2863 int failed;
2864 char **ext_ptr;
2865 uint *hdl_ptr;
2866
2867 /* set up to read varargs */
2868 va_start(marker, cnt);
2869
2870 /* no failures yet */
2871 failed = FALSE;
2872
2873 /* scan the varargs list */
2874 for (i = 0 ; i < cnt ; ++i)
2875 {
2876 /* get the next argument */
2877 ext_ptr = va_arg(marker, char **);
2878 hdl_ptr = va_arg(marker, uint *);
2879
2880 /* allocate a register */
2881 *ext_ptr = alloc_temp_reg(prec, hdl_ptr);
2882
2883 /* if this allocation failed, note it, but keep going for now */
2884 if (*ext_ptr == 0)
2885 failed = TRUE;
2886 }
2887
2888 /* done reading argument */
2889 va_end(marker);
2890
2891 /* if we had any failures, free all of the registers we allocated */
2892 if (failed)
2893 {
2894 /* restart reading the varargs */
2895 va_start(marker, cnt);
2896
2897 /* scan the varargs and free the successfully allocated registers */
2898 for (i = 0 ; i < cnt ; ++i)
2899 {
2900 /* get the next argument */
2901 ext_ptr = va_arg(marker, char **);
2902 hdl_ptr = va_arg(marker, uint *);
2903
2904 /* free this register if we successfully allocated it */
2905 if (*ext_ptr != 0)
2906 release_temp_reg(*hdl_ptr);
2907 }
2908
2909 /* done reading varargs */
2910 va_end(marker);
2911
2912 /* throw the error */
2913 err_throw(VMERR_BIGNUM_NO_REGS);
2914 }
2915 }
2916
2917 /* ------------------------------------------------------------------------ */
2918 /*
2919 * Release a block of temporary registers
2920 */
2921 void CVmObjBigNum::release_temp_regs(size_t cnt, ...)
2922 {
2923 /* start reading the varargs */
2924 va_list marker;
2925 va_start(marker, cnt);
2926
2927 /* scan the varargs and free the listed registers */
2928 for (size_t i = 0 ; i < cnt ; ++i)
2929 {
2930 uint hdl;
2931
2932 /* get the next handle */
2933 hdl = va_arg(marker, uint);
2934
2935 /* free this register */
2936 release_temp_reg(hdl);
2937 }
2938
2939 /* done reading varargs */
2940 va_end(marker);
2941 }
2942
2943 /* ------------------------------------------------------------------------ */
2944 /*
2945 * Round the extension to the nearest integer
2946 */
2947 void CVmObjBigNum::round_to_int(char *ext)
2948 {
2949 /*
2950 * the exponent is equal to the number of digits before the decimal
2951 * point, so that's the number of digits we want to keep
2952 */
2953 round_to(ext, get_exp(ext));
2954 }
2955
2956 /*
2957 * Round the extension to the given number of digits
2958 */
2959 void CVmObjBigNum::round_to(char *ext, int digits)
2960 {
2961 /* if we're dropping digits, and we need to round up, round up */
2962 int prec = get_prec(ext);
2963 if (digits < prec)
2964 {
2965 /* note if we need to round up */
2966 int r = get_round_dir(ext, digits);
2967
2968 /* zero the digits beyond the last one we're keeping */
2969 for (int i = digits ; i < prec ; ++i)
2970 set_dig(ext, i, 0);
2971
2972 /* round up if necessary */
2973 if (r)
2974 round_up_abs(ext, digits);
2975 }
2976 }
2977
2978 /*
2979 * get the OR sum of digits from the given starting place to least
2980 * significant
2981 */
2982 int CVmObjBigNum::get_ORdigs(const char *ext, int d)
2983 {
2984 int sum, prec = get_prec(ext);
2985 for (sum = 0 ; d < prec ; sum |= get_dig(ext, d++)) ;
2986 return sum;
2987 }
2988
2989 /*
2990 * Determine the direction to round a value to the given number of digits.
2991 * Returns 1 to round up, 0 to round down - this is effectively the value
2992 * to add at the last digit we're keeping.
2993 */
2994 int CVmObjBigNum::get_round_dir(const char *ext, int digits)
2995 {
2996 /* if the dropped digit is beyond the precision, there's no rounding */
2997 int prec = get_prec(ext);
2998 if (digits >= prec)
2999 return 0;
3000
3001 /* we can't round to negative digits */
3002 if (digits < 0)
3003 digits = 0;
3004
3005 /*
3006 * if the first dropped digit is greater than 5, round up; if it's less
3007 * than 5, round down; otherwise we have to break the tie
3008 */
3009 int d = get_dig(ext, digits);
3010 if (d > 5)
3011 return 1;
3012 if (d < 5)
3013 return 0;
3014
3015 /*
3016 * it's a 5 - if there are any non-zero digits after this point, the
3017 * value is greater than 5, so round up
3018 */
3019 for (int i = digits + 1 ; i < prec ; ++i)
3020 {
3021 /* if it's a non-zero digit, round up */
3022 if (get_dig(ext, i) != 0)
3023 return 1;
3024 }
3025
3026 /*
3027 * It's exactly 5000...., so we need to break the tie by rounding to
3028 * the nearest even digit in the last digit we're keeping. Get that
3029 * last digit.
3030 */
3031 d = (digits > 0 ? get_dig(ext, digits - 1) : 0);
3032
3033 /*
3034 * If the digit is already even, round down (return 0) to stay at that
3035 * even value. If it's odd, round up (return 1) to get to the next
3036 * even digit. (d & 1) happens to be 1 if it's odd, 0 if it's even.
3037 */
3038 return d & 1;
3039 }
3040
3041 /*
3042 * Round a number based on dropped digits lost during a calculation.
3043 * 'trail_dig' is the most significant dropped digit, and 'trail_val' is
3044 * the "|" sum of all of the less significant dropped digits.
3045 */
3046 void CVmObjBigNum::round_for_dropped_digits(
3047 char *ext, int trail_dig, int trail_val)
3048 {
3049 if (trail_dig > 5
3050 || (trail_dig == 5 && trail_val > 0)
3051 || (trail_dig == 5 && trail_val == 0
3052 && (get_dig(ext, get_prec(ext)-1) & 1) != 0))
3053 round_up_abs(ext);
3054 }
3055
3056 /*
3057 * Round a number up. This adds 1 starting at the least significant digit
3058 * of the number.
3059 */
3060 void CVmObjBigNum::round_up_abs(char *ext)
3061 {
3062 round_up_abs(ext, get_prec(ext));
3063 }
3064
3065 /*
3066 * Round a number up. This adds 1 starting at the least significant digit
3067 * we're keeping.
3068 */
3069 void CVmObjBigNum::round_up_abs(char *ext, int keep_digits)
3070 {
3071 /* start with a "carry" into the least significant digit */
3072 int carry = TRUE;
3073
3074 /* propagate the carry through the number's digits */
3075 for (int idx = keep_digits ; idx != 0 ; )
3076 {
3077 /* move to the next more significant digit */
3078 --idx;
3079
3080 /* add the carry */
3081 int d = get_dig(ext, idx);
3082 if (d < 9)
3083 {
3084 /* bump it up */
3085 set_dig(ext, idx, d + 1);
3086
3087 /* no carrying required, so we can stop now */
3088 carry = FALSE;
3089 break;
3090 }
3091 else
3092 {
3093 /* it's a '9', so bump it up to '0' and carry to the next digit */
3094 set_dig(ext, idx, 0);
3095 }
3096 }
3097
3098 /*
3099 * If we carried out of the top digit, we must have had all nines, in
3100 * which case we now have all zeros. Put a 1 in the first digit and
3101 * increase the exponent to renormalize.
3102 */
3103 if (carry)
3104 {
3105 /* shift the mantissa */
3106 shift_right(ext, 1);
3107
3108 /* increase the exponent */
3109 set_exp(ext, get_exp(ext) + 1);
3110
3111 /* set the lead digit to 1 */
3112 set_dig(ext, 0, 1);
3113 }
3114
3115 /* we know the value is non-zero now */
3116 ext[VMBN_FLAGS] &= ~VMBN_F_ZERO;
3117 }
3118
3119 /* ------------------------------------------------------------------------ */
3120 /*
3121 * Copy a value, extending with zeros if expanding, or truncating or
3122 * rounding, as desired, if the precision changes
3123 */
3124 void CVmObjBigNum::copy_val(char *dst, const char *src, int round)
3125 {
3126 size_t src_prec = get_prec(src);
3127 size_t dst_prec = get_prec(dst);
3128
3129 /* check to see if we're growing or shrinking */
3130 if (dst_prec > src_prec)
3131 {
3132 /*
3133 * it's growing - copy the entire old mantissa, plus the flags,
3134 * sign, and exponent
3135 */
3136 memcpy(dst + VMBN_EXP, src + VMBN_EXP,
3137 (VMBN_MANT - VMBN_EXP) + (src_prec + 1)/2);
3138
3139 /* clear the balance of the mantissa */
3140 memset(dst + VMBN_MANT + (src_prec + 1)/2,
3141 0, (dst_prec + 1)/2 - (src_prec + 1)/2);
3142
3143 /*
3144 * clear the digit just after the last digit we copied - we might
3145 * have missed this with the memset, since it only deals with
3146 * even-numbered pairs of digits
3147 */
3148 set_dig(dst, src_prec, 0);
3149 }
3150 else
3151 {
3152 /* it's shrinking - truncate the mantissa to the new length */
3153 memcpy(dst + VMBN_EXP, src + VMBN_EXP,
3154 (VMBN_MANT - VMBN_EXP) + (dst_prec + 1)/2);
3155
3156 /* check for rounding */
3157 if (round && get_round_dir(src, dst_prec))
3158 round_up_abs(dst);
3159 }
3160 }
3161
3162 /* ------------------------------------------------------------------------ */
3163 /*
3164 * Multiply by an integer constant value
3165 */
3166 void CVmObjBigNum::mul_by_long(char *ext, unsigned long val)
3167 {
3168 size_t idx;
3169 size_t prec = get_prec(ext);
3170 unsigned long carry = 0;
3171
3172 /*
3173 * start at the least significant digit and work up through the digits
3174 */
3175 for (idx = prec ; idx != 0 ; )
3176 {
3177 unsigned long prod;
3178
3179 /* move to the next digit */
3180 --idx;
3181
3182 /*
3183 * compute the product of this digit and the given value, and add
3184 * in the carry from the last digit
3185 */
3186 prod = (val * get_dig(ext, idx)) + carry;
3187
3188 /* set this digit to the residue mod 10 */
3189 set_dig(ext, idx, prod % 10);
3190
3191 /* carry the rest */
3192 carry = prod / 10;
3193 }
3194
3195 /* if we have a carry left over, shift it in */
3196 int dropped_dig = 0, dropped_val = 0;
3197 while (carry != 0)
3198 {
3199 /*
3200 * Note if the previous dropped digit is non-zero, then note the
3201 * newly dropped digit. dropped_val tells us if there's anything
3202 * non-zero after the last digit, in case the last digit turns out
3203 * to be a 5.
3204 */
3205 dropped_val |= dropped_dig;
3206 dropped_dig = get_dig(ext, prec - 1);
3207
3208 /* shift the number and adjust the exponent */
3209 shift_right(ext, 1);
3210 set_exp(ext, get_exp(ext) + 1);
3211
3212 /* shift in this digit of the carry */
3213 set_dig(ext, 0, carry % 10);
3214
3215 /* take it out of the carry */
3216 carry /= 10;
3217 }
3218
3219 /*
3220 * round up if the dropped digits are >5000..., or they're exactly
3221 * 5000... and the last digit we're keeping is odd
3222 */
3223 round_for_dropped_digits(ext, dropped_dig, dropped_val);
3224
3225 /* normalize the result */
3226 normalize(ext);
3227 }
3228
3229 /*
3230 * Divide the magnitude of the number by 2^32. This is a special case of
3231 * div_by_long() for splitting a number into 32-bit chunks. Returns with
3232 * the quotient in 'ext', and the remainder in 'remp'.
3233 */
3234 void CVmObjBigNum::div_by_2e32(char *ext, uint32_t *remp)
3235 {
3236 size_t in_idx;
3237 size_t out_idx;
3238 int sig;
3239 size_t prec = get_prec(ext);
3240 unsigned long rem = 0;
3241 int exp = get_exp(ext);
3242
3243 /* if it's entirely fractional, the result is 0 with remainder 0 */
3244 if (exp <= 0)
3245 {
3246 *remp = 0;
3247 set_zero(ext);
3248 return;
3249 }
3250
3251 /* start at the most significant digit and work down */
3252 for (rem = 0, sig = FALSE, in_idx = out_idx = 0 ;
3253 out_idx < prec ; ++in_idx)
3254 {
3255 /*
3256 * Multiply the remainder by 10. 10 == (2+8), so this is the sum
3257 * of rem<<1 and rem<<3. This is handy because it makes it
3258 * relatively easy to calculate the overflow from the 32-bit
3259 * accumulator on 32-bit platforms: the overflow is the sum of the
3260 * high bit and the high three bits, plus the carry from the low
3261 * part. The low part has a carry of 1 if rem<<1 + rem<<3 exceeds
3262 * 0xffffffff, which we can calculate in 32 bits as rem<<1 >
3263 * 0xffffffff - rem<<3.
3264 */
3265 ulong rem1 = (rem << 1) & 0xffffffff;
3266 ulong rem3 = (rem << 3) & 0xffffffff;
3267 ulong hi = ((rem >> 31) & 0x00000001)
3268 + ((rem >> 29) & 0x00000007)
3269 + (rem1 > 0xffffffff - rem3 ? 1 : 0);
3270 rem = (rem1 + rem3) & 0xffffffff;
3271
3272 /*
3273 * Add the current digit into the remainder. We again need to
3274 * carry the overflow into the high part.
3275 */
3276 ulong dig = (in_idx < prec ? get_dig(ext, in_idx) : 0);
3277 hi += dig > 0xffffffff - rem ? 1 : 0;
3278 rem = (rem + dig) & 0xffffffff;
3279
3280 /*
3281 * We now have the quotient of rem/2^32 in 'hi', and the remainder
3282 * in 'rem'.
3283 */
3284 int quo = (int)hi;
3285
3286 /* if the quotient is non-zero, we've found a significant digit */
3287 if (quo != 0)
3288 sig = TRUE;
3289
3290 /*
3291 * if we've found a significant digit, store it; otherwise, just
3292 * reduce the exponent to account for an implied leading zero that
3293 * we won't actually store
3294 */
3295 if (sig)
3296 {
3297 /* store the digit */
3298 set_dig(ext, out_idx++, quo);
3299
3300 /*
3301 * if we've reached the decimal place, stop here, since we're
3302 * doing integer division
3303 */
3304 if ((int)out_idx == exp)
3305 break;
3306 }
3307 else
3308 {
3309 /* all leading zeros so far - adjust the exponent */
3310 set_exp(ext, --exp);
3311
3312 /* if this leaves us with a fractional result, we're done */
3313 if (exp == 0)
3314 break;
3315 }
3316
3317 /*
3318 * If we've reached the last input digit and the remainder is zero,
3319 * we're done - fill out the rest of the number with trailing zeros
3320 * and stop looping. If we've reached the decimal point in the
3321 * output, stop here, since we're doing an integer division.
3322 */
3323 if (rem == 0 && in_idx >= prec)
3324 {
3325 /* if we don't have any significant digits, we have a zero */
3326 if (!sig)
3327 {
3328 set_zero(ext);
3329 out_idx = prec;
3330 }
3331
3332 /* we have our result */
3333 break;
3334 }
3335 }
3336
3337 /* fill out the rest of the number with zeros */
3338 for ( ; out_idx < prec ; ++out_idx)
3339 set_dig(ext, out_idx, 0);
3340
3341 /* normalize the result */
3342 normalize(ext);
3343
3344 /* pass back the remainder */
3345 *remp = rem;
3346 }
3347
3348 /*
3349 * Divide by an integer constant value. Note that 'val' must not exceed
3350 * ULONG_MAX/10, because we have to be able to compute intermediate integer
3351 * dividend values up to 10*val.
3352 */
3353 void CVmObjBigNum::div_by_long(char *ext, unsigned long val,
3354 unsigned long *remp)
3355 {
3356 size_t in_idx;
3357 size_t out_idx;
3358 int sig;
3359 size_t prec = get_prec(ext);
3360 unsigned long rem = 0;
3361 int exp = get_exp(ext);
3362
3363 /*
3364 * if we're doing integer division, and the dividend is entirely
3365 * fractional, the result is 0 with remainder 0
3366 */
3367 if (remp != 0 && exp <= 0)
3368 {
3369 *remp = 0;
3370 set_zero(ext);
3371 return;
3372 }
3373
3374 /* start at the most significant digit and work down */
3375 for (rem = 0, sig = FALSE, in_idx = out_idx = 0 ;
3376 out_idx < prec ; ++in_idx)
3377 {
3378 /*
3379 * shift this digit into the remainder - if we're past the end of
3380 * the number, shift in an implied trailing zero
3381 */
3382 rem *= 10;
3383 rem += (in_idx < prec ? get_dig(ext, in_idx) : 0);
3384
3385 /* calculate the quotient and the next remainder */
3386 long quo = rem / val;
3387 rem %= val;
3388
3389 /* if the quotient is non-zero, we've found a significant digit */
3390 if (quo != 0)
3391 sig = TRUE;
3392
3393 /*
3394 * if we've found a significant digit, store it; otherwise, just
3395 * reduce the exponent to account for an implied leading zero that
3396 * we won't actually store
3397 */
3398 if (sig)
3399 {
3400 /* store the digit */
3401 set_dig(ext, out_idx++, (int)quo);
3402
3403 /*
3404 * if we've reached the decimal place, and the caller wants the
3405 * remainder, stop here - the caller wants the integer quotient
3406 * and remainder rather than the full quotient
3407 */
3408 if (remp != 0 && (int)out_idx == exp)
3409 break;
3410 }
3411 else
3412 {
3413 /* all leading zeros so far - adjust the exponent */
3414 set_exp(ext, --exp);
3415
3416 /*
3417 * if we're doing integer division, and this leaves us with a
3418 * fractional result, we're done
3419 */
3420 if (remp != 0 && exp == 0)
3421 break;
3422 }
3423
3424 /*
3425 * if we've reached the last input digit and the remainder is zero,
3426 * we're done - fill out the rest of the number with trailing zeros
3427 * and stop looping
3428 */
3429 if (rem == 0 && in_idx >= prec)
3430 {
3431 /* check to see if we have any significant digits */
3432 if (!sig)
3433 {
3434 /* no significant digits - the result is zero */
3435 set_zero(ext);
3436 out_idx = prec;
3437 }
3438
3439 /* we have our result */
3440 break;
3441 }
3442 }
3443
3444 /* fill out any remaining output digits with zeros */
3445 for ( ; out_idx < prec ; ++out_idx)
3446 set_dig(ext, out_idx, 0);
3447
3448 /* pass back the remainder if desired */
3449 if (remp != 0)
3450 {
3451 /* hand back the integer remainder */
3452 *remp = rem;
3453 }
3454 else
3455 {
3456 /*
3457 * We're computing the full-precision quotient, not the quotient
3458 * and remainder. Round up if the remainder is more than half the
3459 * divisor, or it's exactly half the divisor and the last digit is
3460 * odd.
3461 *
3462 * (This is effectively testing to see if the next digits are
3463 * 5000... or higher. The next digit is the whole part of
3464 * remainder*10/val, so it's >=5 if remainder/val >= 0.5, which is
3465 * to say remainder >= val/2, or remainder*2 >= val.)
3466 */
3467 if (rem*2 > val || (rem*2 == val && (get_dig(ext, prec-1) & 1)))
3468 round_up_abs(ext);
3469 }
3470
3471 /* normalize the result */
3472 normalize(ext);
3473 }
3474
3475 /* ------------------------------------------------------------------------ */
3476 /*
3477 * Normalize a number - shift it so that the first digit is non-zero. If
3478 * the number is zero, set the exponent to zero and clear the sign bit.
3479 */
3480 void CVmObjBigNum::normalize(char *ext)
3481 {
3482 int idx;
3483 int prec = get_prec(ext);
3484 int all_zero;
3485 int nonzero_idx = 0;
3486
3487 /* no work is necessary for anything but ordinary numbers */
3488 if (is_nan(ext))
3489 return;
3490
3491 /* check for an all-zero mantissa */
3492 for (all_zero = TRUE, idx = 0 ; idx < prec ; ++idx)
3493 {
3494 /* check this digit */
3495 if (get_dig(ext, idx) != 0)
3496 {
3497 /* note the location of the first non-zero digit */
3498 nonzero_idx = idx;
3499
3500 /* note that the number isn't all zeros */
3501 all_zero = FALSE;
3502
3503 /* no need to keep searching */
3504 break;
3505 }
3506 }
3507
3508 /* if it's zero or underflows, set the canonical zero format */
3509 if (all_zero || get_exp(ext) - nonzero_idx < -32768)
3510 {
3511 /* set the value to zero */
3512 set_zero(ext);
3513 }
3514 else
3515 {
3516 /* clear the zero flag */
3517 ext[VMBN_FLAGS] &= ~VMBN_F_ZERO;
3518
3519 /* shift the mantissa left to make the first digit non-zero */
3520 if (nonzero_idx != 0)
3521 shift_left(ext, nonzero_idx);
3522
3523 /* decrease the exponent to account for the mantissa shift */
3524 set_exp(ext, get_exp(ext) - nonzero_idx);
3525 }
3526 }
3527
3528 /* ------------------------------------------------------------------------ */
3529 /* ------------------------------------------------------------------------ */
3530 /*
3531 * Shift the value left (multiply by 10^shift)
3532 */
3533 void CVmObjBigNum::shift_left(char *ext, unsigned int shift)
3534 {
3535 size_t prec = get_prec(ext);
3536 size_t i;
3537
3538 /* do nothing with a zero shift */
3539 if (shift == 0)
3540 return;
3541
3542 /* if it's an even shift, it's especially easy */
3543 if ((shift & 1) == 0)
3544 {
3545 /* simply move the bytes left by the required amount */
3546 for (i = 0 ; i + shift/2 < (prec+1)/2 ; ++i)
3547 ext[VMBN_MANT + i] = ext[VMBN_MANT + i + shift/2];
3548
3549 /* zero the remaining digits */
3550 for ( ; i < (prec+1)/2 ; ++i)
3551 ext[VMBN_MANT + i] = 0;
3552
3553 /*
3554 * be sure to zero the last digit - if we have an odd precision, we
3555 * will have copied the garbage digit from the final half-byte
3556 */
3557 set_dig(ext, prec - shift, 0);
3558 }
3559 else
3560 {
3561 /* apply the shift to each digit */
3562 for (i = 0 ; i + shift < prec ; ++i)
3563 {
3564 unsigned int dig;
3565
3566 /* get this source digit */
3567 dig = get_dig(ext, i + shift);
3568
3569 /* set this destination digit */
3570 set_dig(ext, i, dig);
3571 }
3572
3573 /* zero the remaining digits */
3574 for ( ; i < prec ; ++i)
3575 set_dig(ext, i, 0);
3576 }
3577 }
3578
3579 /*
3580 * Shift the value right (divide by 10^shift)
3581 */
3582 void CVmObjBigNum::shift_right(char *ext, unsigned int shift)
3583 {
3584 size_t prec = get_prec(ext);
3585 size_t i;
3586
3587 /* if it's an even shift, it's especially easy */
3588 if ((shift & 1) == 0)
3589 {
3590 /* simply move the bytes left by the required amount */
3591 for (i = (prec+1)/2 ; i > shift/2 ; --i)
3592 ext[VMBN_MANT + i-1] = ext[VMBN_MANT + i-1 - shift/2];
3593
3594 /* zero the leading digits */
3595 for ( ; i > 0 ; --i)
3596 ext[VMBN_MANT + i-1] = 0;
3597 }
3598 else
3599 {
3600 /* apply the shift to each digit */
3601 for (i = prec ; i > shift ; --i)
3602 {
3603 unsigned int dig;
3604
3605 /* get this source digit */
3606 dig = get_dig(ext, i-1 - shift);
3607
3608 /* set this destination digit */
3609 set_dig(ext, i-1, dig);
3610 }
3611
3612 /* zero the remaining digits */
3613 for ( ; i >0 ; --i)
3614 set_dig(ext, i-1, 0);
3615 }
3616 }
3617
3618 /*
3619 * Increment a number
3620 */
3621 void CVmObjBigNum::increment_abs(char *ext)
3622 {
3623 size_t idx;
3624 int exp = get_exp(ext);
3625 int carry;
3626
3627 /* start at the one's place, if represented */
3628 idx = (exp <= 0 ? 0 : (size_t)exp);
3629
3630 /*
3631 * if the units digit is to the right of the number (i.e., the number's
3632 * scale is large), there's nothing to do
3633 */
3634 if (idx > get_prec(ext))
3635 return;
3636
3637 /* increment digits */
3638 for (carry = TRUE ; idx != 0 ; )
3639 {
3640 int dig;
3641
3642 /* move to the next digit */
3643 --idx;
3644
3645 /* get the digit value */
3646 dig = get_dig(ext, idx);
3647
3648 /* increment it, checking for carry */
3649 if (dig == 9)
3650 {
3651 /* increment it to zero and keep going to carry */
3652 set_dig(ext, idx, 0);
3653 }
3654 else
3655 {
3656 /* increment this digit */
3657 set_dig(ext, idx, dig + 1);
3658
3659 /* there's no carry out */
3660 carry = FALSE;
3661
3662 /* done */
3663 break;
3664 }
3665 }
3666
3667 /* if we carried past the end of the number, insert the leading 1 */
3668 if (carry)
3669 {
3670 /*
3671 * if we still haven't reached the units position, shift right
3672 * until we do
3673 */
3674 while (get_exp(ext) < 0)
3675 {
3676 /* shift it right and adjust the exponent */
3677 shift_right(ext, 1);
3678 set_exp(ext, get_exp(ext) + 1);
3679 }
3680
3681 /* shift the number right and adjust the exponent */
3682 shift_right(ext, 1);
3683 set_exp(ext, get_exp(ext) + 1);
3684
3685 /* insert the leading 1 */
3686 set_dig(ext, 0, 1);
3687 }
3688
3689 /* we know the value is now non-zero */
3690 ext[VMBN_FLAGS] &= ~VMBN_F_ZERO;
3691 }
3692
3693 /*
3694 * Determine if the fractional part is zero
3695 */
3696 int CVmObjBigNum::is_frac_zero(const char *ext)
3697 {
3698 size_t idx;
3699 int exp = get_exp(ext);
3700 size_t prec = get_prec(ext);
3701
3702 /* start at the first fractional digit, if represented */
3703 idx = (exp <= 0 ? 0 : (size_t)exp);
3704
3705 /* scan the digits for a non-zero digit */
3706 for ( ; idx < prec ; ++idx)
3707 {
3708 /* if this digit is non-zero, the fraction is non-zero */
3709 if (get_dig(ext, idx) != 0)
3710 return FALSE;
3711 }
3712
3713 /* we didn't find any non-zero fractional digits */
3714 return TRUE;
3715 }
3716
3717 /* ------------------------------------------------------------------------ */
3718 /*
3719 * Convert to an integer value
3720 */
3721 int32_t CVmObjBigNum::ext_to_int(const char *ext, int &ov)
3722 {
3723 /* get the magnitude */
3724 ov = FALSE;
3725 uint32_t m = convert_to_int_base(ext, ov);
3726
3727 /* apply the sign and check limits */
3728 if (get_neg(ext))
3729 {
3730 /*
3731 * a T3 VM int is a 32-bit signed value (irrespective of the local
3732 * platform int size), so the magnitude of a negative value can't
3733 * exceed 2147483648
3734 */
3735 if (m > 2147483648U)
3736 ov = TRUE;
3737
3738 /* negate the number and return it */
3739 return -(long)m;
3740 }
3741 else
3742 {
3743 /*
3744 * a T3 VM positive int value can't exceed 2147483647L (regardless
3745 * of the local platform int size)
3746 */
3747 if (m > 2147483647U)
3748 ov = TRUE;
3749
3750 /* return the value */
3751 return (long)m;
3752 }
3753 }
3754
3755 /*
3756 * Convert to unsigned int
3757 */
3758 uint32_t CVmObjBigNum::convert_to_uint(int &ov) const
3759 {
3760 /* negative numbers can't be converted to unsigned */
3761 ov = get_neg(ext_);
3762
3763 /* return the magnitude */
3764 return convert_to_int_base(ext_, ov);
3765 }
3766
3767 /*
3768 * Get the magnitude of an integer value, ignoring the sign
3769 */
3770 uint32_t CVmObjBigNum::convert_to_int_base(const char *ext, int &ov)
3771 {
3772 size_t prec = get_prec(ext);
3773 int exp = get_exp(ext);
3774 size_t idx;
3775 size_t stop_idx;
3776 int round_inc;
3777
3778 /* start the accumulator at zero */
3779 uint32_t acc = 0;
3780
3781 /*
3782 * if the exponent is negative, it means that the first non-zero digit
3783 * is in the second position after the decimal point, so even after
3784 * rounding, the result will always be zero
3785 */
3786 if (exp < 0)
3787 return 0;
3788
3789 /* get the rounding direction for truncating at the decimal point */
3790 round_inc = get_round_dir(ext, exp);
3791
3792 /* stop at the first fractional digit */
3793 if (exp <= 0)
3794 {
3795 /* all digits are fractional */
3796 stop_idx = 0;
3797 }
3798 else if ((size_t)exp < prec)
3799 {
3800 /* stop at the first fractional digit */
3801 stop_idx = (size_t)exp;
3802 }
3803 else
3804 {
3805 /* all of the digits are in the whole part */
3806 stop_idx = prec;
3807 }
3808
3809 /* convert the integer part digit by digit */
3810 if (stop_idx > 0)
3811 {
3812 /* loop over digits */
3813 for (idx = 0 ; idx < stop_idx ; ++idx)
3814 {
3815 /* get this digit */
3816 int dig = get_dig(ext, idx);
3817
3818 /* make sure that shifting the accumulator won't overflow */
3819 ov |= (acc > UINT32MAXVAL/10);
3820
3821 /* shift the accumulator */
3822 acc *= 10;
3823
3824 /* make sure this digit won't overflow the 32-bit VM int type */
3825 ov |= (acc > (UINT32MAXVAL - dig));
3826
3827 /* add the digit */
3828 acc += dig;
3829 }
3830 }
3831
3832 /* make sure rounding won't overflow */
3833 ov |= (acc > UINT32MAXVAL - round_inc);
3834
3835 /* return the result adjusted for rounding */
3836 return acc + round_inc;
3837 }
3838
3839 /*
3840 * Convert to a 64-bit portable representation, signed
3841 */
3842 void CVmObjBigNum::wp8s(char *buf, int &ov) const
3843 {
3844 /* note if the value is negative */
3845 int neg = get_neg(ext_);
3846
3847 /* generate the absolute value */
3848 wp8abs(buf, ov);
3849
3850 /* if it's negative, compute the 2's complement of the buffer */
3851 if (neg)
3852 {
3853 /* take the 2's complement */
3854 twos_complement_p8((unsigned char *)buf);
3855
3856 /* if it didn't come out negative, we have an overflow */
3857 ov |= ((buf[7] & 0x80) == 0);
3858 }
3859 else
3860 {
3861 /* positive - the sign bit is set, we overflowed */
3862 ov |= (buf[7] & 0x80);
3863 }
3864 }
3865
3866 /*
3867 * Convert to a 64-bit portable representation, unsigned
3868 */
3869 void CVmObjBigNum::wp8(char *buf, int &ov) const
3870 {
3871 /* generate the absolute value */
3872 wp8abs(buf, ov);
3873
3874 /*
3875 * if the value is negative, we can't represent it as unsigned; take
3876 * the two's complement in case they want the truncated version of the
3877 * value, and set the overflow flag
3878 */
3879 if (get_neg(ext_))
3880 {
3881 ov = TRUE;
3882 twos_complement_p8((unsigned char *)buf);
3883 }
3884 }
3885
3886 /*
3887 * generate the portable 64-bit integer representation of the absolute
3888 * value of the number
3889 */
3890 void CVmObjBigNum::wp8abs(char *buf, int &ov) const
3891 {
3892 /*
3893 * as a rough cut, if the number is greater than 10^30, it's definitely
3894 * too big for a 64-bit integer buffer
3895 */
3896 ov = (get_exp(ext_) > 30);
3897
3898 /*
3899 * Make a local copy of the value - we need at most 20 digits of
3900 * precision, since we only want the integer part.
3901 */
3902 char tmp[5 + 20] = { 20, 0, 0, 0, 0 };
3903 copy_val(tmp, ext_, TRUE);
3904
3905 /*
3906 * Divide the value by 2^32. This splits the value into two 32-bit
3907 * halves for us, which are then easy to arrange into the buffer with
3908 * integer arithmetic.
3909 */
3910 uint32_t lo, hi;
3911 div_by_2e32(tmp, &lo);
3912 hi = convert_to_int_base(tmp, ov);
3913
3914 /*
3915 * store the low part in the first four bytes, the high part in the
3916 * next four bytes
3917 */
3918 oswp4(buf, lo);
3919 oswp4(buf + 4, hi);
3920 }
3921
3922 /*
3923 * Encode the integer portion of the number as a BER compressed integer.
3924 */
3925 void CVmObjBigNum::encode_ber(char *buf, size_t buflen, size_t &outlen,
3926 int &ov)
3927 {
3928 /* BER can only store unsigned integers */
3929 ov = get_neg(ext_);
3930
3931 /* clear the output buffer */
3932 outlen = 0;
3933
3934 /* make a temporary copy of the value in a temp register */
3935 uint thdl;
3936 char *tmp = alloc_temp_reg(get_prec(ext_), &thdl);
3937 copy_val(tmp, ext_, FALSE);
3938
3939 /* keep going until the number is zero or we run out of space */
3940 int z;
3941 while (!(z = is_zero(tmp)) && outlen < buflen)
3942 {
3943 /* get the low-order 7 bits by getting the remainder mod 128 */
3944 ulong rem;
3945 div_by_long(tmp, 128, &rem);
3946
3947 /* store it */
3948 buf[outlen++] = (char)rem;
3949 }
3950
3951 /* release the temporary register */
3952 release_temp_reg(thdl);
3953
3954 /* if we ran out of buffer before we ran out of digits, we overflowed */
3955 ov |= (!z);
3956
3957 /* if we wrote nothing, write a trivial zero value */
3958 if (outlen == 0)
3959 buf[outlen++] = 0;
3960
3961 /*
3962 * We stored the bytes from least significant to most significant, but
3963 * the standard format is the other way around. Reverse the bytes.
3964 */
3965 int i, j;
3966 for (i = 0, j = (int)outlen - 1 ; i < j ; ++i, --j)
3967 {
3968 char tmpc = buf[i];
3969 buf[i] = buf[j];
3970 buf[j] = tmpc;
3971 }
3972
3973 /* set the high bit in every byte except the last one */
3974 for (i = 0 ; i < (int)outlen - 1 ; ++i)
3975 buf[i] |= 0x80;
3976 }
3977
3978 /*
3979 * Calculate the 2's complement of a portable 8-byte integer buffer
3980 */
3981 void CVmObjBigNum::twos_complement_p8(unsigned char *p)
3982 {
3983 size_t i;
3984 int carry;
3985 for (i = 0, carry = 1 ; i < 8 ; ++i)
3986 {
3987 p[i] = (~p[i] + carry) & 0xff;
3988 carry &= (p[i] == 0);
3989 }
3990 }
3991
3992 /*
3993 * Convert to double
3994 */
3995 double CVmObjBigNum::ext_to_double(const char *ext)
3996 {
3997 /* note the precision and sign */
3998 size_t prec = get_prec(ext);
3999 int is_neg = get_neg(ext);
4000
4001 /* if we're not a number (INF, NAN), it's an error */
4002 if (get_type(ext) != VMBN_T_NUM)
4003 err_throw(VMERR_NO_DOUBLE_CONV);
4004
4005 /*
4006 * if our absolute value is too large to store in a double, throw an
4007 * overflow error
4008 */
4009 if (compare_abs(ext, cache_dbl_max()) > 1)
4010 err_throw(VMERR_NUM_OVERFLOW);
4011
4012 /*
4013 * Our value is represented as .abcdef * 10^exp, where a is our first
4014 * digit, b is our second digit, etc. Start off the accumulator with
4015 * our most significant digit, a. The actual numeric value of this
4016 * digit is a*10^(exp-1) - one less than the exponent, because of the
4017 * implied decimal point at the start of the mantissa.
4018 */
4019 double base = pow(10.0, get_exp(ext) - 1);
4020 double acc = get_dig(ext, 0) * base;
4021
4022 /*
4023 * Now add in the remaining digits, starting from the second most
4024 * significant.
4025 *
4026 * We might have more precision than a double can hold. Digits added
4027 * beyond the precision of the double will have no effect on the double
4028 * value, since a double will naturally drop digits at the less
4029 * significant end when we exceed its precision. There's no point in
4030 * adding digits beyond that point. The maximum number of digits a
4031 * native double can hold is given by the float.h constant DBL_DIG; go
4032 * a couple of digits beyond this anyway, since many float packages
4033 * perform intermediate calculations at slightly higher precision and
4034 * can thus benefit from an extra digit or two for rounding purposes.
4035 */
4036 size_t max_digits = (prec > DBL_DIG + 2 ? DBL_DIG + 2 : prec);
4037 for (size_t idx = 1 ; idx < max_digits ; ++idx)
4038 {
4039 /* get this digit */
4040 int dig = get_dig(ext, idx);
4041
4042 /* adjust the exponent base for this digit */
4043 base /= 10.0;
4044
4045 /* add the digit */
4046 acc += dig * base;
4047 }
4048
4049 /* apply the sign */
4050 if (is_neg)
4051 acc = -acc;
4052
4053 /* return the result */
4054 return acc;
4055 }
4056
4057 /* ------------------------------------------------------------------------ */
4058 /*
4059 * Cache DBL_MAX
4060 */
4061 const char *CVmObjBigNum::cache_dbl_max()
4062 {
4063 /* get the cache register; use the platform precision for a double */
4064 size_t prec = DBL_DIG;
4065 int expanded;
4066 char *ext = S_bignum_cache->get_dbl_max_reg(calc_alloc(prec), &expanded);
4067
4068 /* if that failed, throw an error */
4069 if (ext == 0)
4070 err_throw(VMERR_OUT_OF_MEMORY);
4071
4072 /* if we got a previously cached value, return it */
4073 if (!expanded && get_prec(ext) >= prec)
4074 return ext;
4075
4076 /* we allocated or reallocated the register, so set the new precision */
4077 set_prec(ext, prec);
4078
4079 /* store DBL_MAX in the register */
4080 set_double_val(ext, DBL_MAX);
4081
4082 /* return the register */
4083 return ext;
4084 }
4085
4086 /*
4087 * Cache DBL_MIN
4088 */
4089 const char *CVmObjBigNum::cache_dbl_min()
4090 {
4091 /* get the cache register; use the platform precision for a double */
4092 size_t prec = DBL_DIG;
4093 int expanded;
4094 char *ext = S_bignum_cache->get_dbl_min_reg(calc_alloc(prec), &expanded);
4095
4096 /* if that failed, throw an error */
4097 if (ext == 0)
4098 err_throw(VMERR_OUT_OF_MEMORY);
4099
4100 /* if we got a previously cached value, return it */
4101 if (!expanded && get_prec(ext) >= prec)
4102 return ext;
4103
4104 /* we allocated or reallocated the register, so set the new precision */
4105 set_prec(ext, prec);
4106
4107 /* store DBL_MIN in the register */
4108 set_double_val(ext, DBL_MIN);
4109
4110 /* return the register */
4111 return ext;
4112 }
4113
4114
4115 /* ------------------------------------------------------------------------ */
4116 /*
4117 * Internal cache. The cache stores frequently used constants (pi, e,
4118 * DBL_MAX), and also provides memory for temporary registers for
4119 * intermediate values in calculations.
4120 */
4121
4122 /*
4123 * initialize
4124 */
4125 CVmBigNumCache::CVmBigNumCache(size_t max_regs)
4126 {
4127 CVmBigNumCacheReg *p;
4128 size_t i;
4129
4130 /* allocate our register array */
4131 reg_ = (CVmBigNumCacheReg *)t3malloc(max_regs * sizeof(reg_[0]));
4132
4133 /* remember the number of registers */
4134 max_regs_ = max_regs;
4135
4136 /* clear the list heads */
4137 free_reg_ = 0;
4138 unalloc_reg_ = 0;
4139
4140 /* we haven't actually allocated any registers yet - clear them out */
4141 for (p = reg_, i = max_regs ; i != 0 ; ++p, --i)
4142 {
4143 /* clear this register descriptor */
4144 p->clear();
4145
4146 /* link it into the unallocated list */
4147 p->nxt_ = unalloc_reg_;
4148 unalloc_reg_ = p;
4149 }
4150
4151 /* we haven't allocated the constants registers yet */
4152 ln10_.clear();
4153 ln2_.clear();
4154 pi_.clear();
4155 e_.clear();
4156 dbl_max_.clear();
4157 dbl_min_.clear();
4158 }
4159
4160 /*
4161 * delete
4162 */
4163 CVmBigNumCache::~CVmBigNumCache()
4164 {
4165 CVmBigNumCacheReg *p;
4166 size_t i;
4167
4168 /* delete each of our allocated registers */
4169 for (p = reg_, i = max_regs_ ; i != 0 ; ++p, --i)
4170 p->free_mem();
4171
4172 /* free the register list array */
4173 t3free(reg_);
4174
4175 /* free the constant value registers */
4176 ln10_.free_mem();
4177 ln2_.free_mem();
4178 pi_.free_mem();
4179 e_.free_mem();
4180 dbl_max_.free_mem();
4181 dbl_min_.free_mem();
4182 }
4183
4184 /*
4185 * Allocate a register
4186 */
4187 char *CVmBigNumCache::alloc_reg(size_t siz, uint *hdl)
4188 {
4189 CVmBigNumCacheReg *p;
4190 CVmBigNumCacheReg *prv;
4191
4192 /*
4193 * search the free list for an available register satisfying the size
4194 * requirements
4195 */
4196 for (p = free_reg_, prv = 0 ; p != 0 ; prv = p, p = p->nxt_)
4197 {
4198 /* if it satisfies the size requirements, return it */
4199 if (p->siz_ >= siz)
4200 {
4201 /* unlink it from the free list */
4202 if (prv == 0)
4203 free_reg_ = p->nxt_;
4204 else
4205 prv->nxt_ = p->nxt_;
4206
4207 /* it's no longer in the free list */
4208 p->nxt_ = 0;
4209
4210 /* return it */
4211 *hdl = (uint)(p - reg_);
4212 return p->buf_;
4213 }
4214 }
4215
4216 /*
4217 * if there's an unallocated register, allocate it and use it;
4218 * otherwise, reallocate the smallest free register
4219 */
4220 if (unalloc_reg_ != 0)
4221 {
4222 /* use the first unallocated register */
4223 p = unalloc_reg_;
4224
4225 /* unlink it from the list */
4226 unalloc_reg_ = unalloc_reg_->nxt_;
4227 }
4228 else if (free_reg_ != 0)
4229 {
4230 CVmBigNumCacheReg *min_free_p;
4231 CVmBigNumCacheReg *min_free_prv = 0;
4232
4233 /* search for the smallest free register */
4234 for (min_free_p = 0, p = free_reg_, prv = 0 ; p != 0 ;
4235 prv = p, p = p->nxt_)
4236 {
4237 /* if it's the smallest so far, remember it */
4238 if (min_free_p == 0 || p->siz_ < min_free_p->siz_)
4239 {
4240 /* remember it */
4241 min_free_p = p;
4242 min_free_prv = prv;
4243 }
4244 }
4245
4246 /* use the smallest register we found */
4247 p = min_free_p;
4248
4249 /* unlink it from the list */
4250 if (min_free_prv == 0)
4251 free_reg_ = p->nxt_;
4252 else
4253 min_free_prv->nxt_ = p->nxt_;
4254 }
4255 else
4256 {
4257 /* there are no free registers - return failure */
4258 return 0;
4259 }
4260
4261 /*
4262 * we found a register that was either previously unallocated, or was
4263 * previously allocated but was too small - allocate or reallocate the
4264 * register at the new size
4265 */
4266 p->alloc_mem(siz);
4267
4268 /* return the new register */
4269 *hdl = (uint)(p - reg_);
4270 return p->buf_;
4271 }
4272
4273 /*
4274 * Release a register
4275 */
4276 void CVmBigNumCache::release_reg(uint hdl)
4277 {
4278 CVmBigNumCacheReg *p = &reg_[hdl];
4279
4280 /* add the register to the free list */
4281 p->nxt_ = free_reg_;
4282 free_reg_ = p;
4283 }
4284
4285 /*
4286 * Release all registers
4287 */
4288 void CVmBigNumCache::release_all()
4289 {
4290 size_t i;
4291
4292 /* mark each of our registers as not in use */
4293 for (i = 0 ; i < max_regs_ ; ++i)
4294 release_reg(i);
4295 }
4296
4297