Debian Codegraph @

terps/tads/tads3/vmbignum.h

raw symbols SCIP
1 /* $Header$ */
2
3 /*
4 * Copyright (c) 2000, 2002 Michael J. Roberts. All Rights Reserved.
5 *
6 * Please see the accompanying license file, LICENSE.TXT, for information
7 * on using and copying this software.
8 */
9 /*
10 Name
11 vmbignum.h - big number metaclass
12 Function
13
14 Notes
15
16 Modified
17 02/18/00 MJRoberts - Creation
18 */
19
20 #ifndef VMBIGNUM_H
21 #define VMBIGNUM_H
22
23 #include <stdlib.h>
24 #include "os.h"
25 #include "vmtype.h"
26 #include "vmobj.h"
27 #include "vmglob.h"
28
29 /* ------------------------------------------------------------------------ */
30 /*
31 * Big number temporary register cache. Because big number values are
32 * of arbitrary precision, we can't know in advance how much space we'll
33 * need for temporary values. Instead, we keep this cache; each time we
34 * need a temporary register, we'll look to see if we have one available
35 * with sufficient precision, and allocate a new register if not.
36 */
37
38 /* internal register descriptor */
39 struct CVmBigNumCacheReg
40 {
41 /* clear out the register values */
42 void clear()
43 {
44 buf_ = 0;
45 siz_ = 0;
46 nxt_ = 0;
47 }
48
49 /*
50 * Allocate memory for this register. Returns true if we had to
51 * allocate memory, false if the register was already at the given
52 * size.
53 */
54 int alloc_mem(size_t siz)
55 {
56 /*
57 * if I'm already at least this large, there's no need to change
58 * anything
59 */
60 if (siz_ >= siz)
61 return FALSE;
62
63 /*
64 * round up the size a bit - this will avoid repeatedly
65 * reallocating at slightly different sizes, which could
66 * fragment the heap quite a bit; we'll use a little more memory
67 * than the caller actually asked for, but if they come back and
68 * ask for slightly more next time, an additional allocation
69 * probably won't be necessary, which will save memory in the
70 * long run
71 */
72 siz = (siz + 63) & ~63;
73
74 /* delete any existing memory */
75 free_mem();
76
77 /* remember the new size */
78 siz_ = siz;
79
80 /* allocate the memory */
81 buf_ = (char *)t3malloc(siz_);
82
83 /* indicate that we allocated memory */
84 return TRUE;
85 }
86
87 /* free the memory associated with the register, if any */
88 void free_mem()
89 {
90 /* if we have a buffer, delete it */
91 if (buf_ != 0)
92 t3free(buf_);
93 }
94
95 /* register's buffer */
96 char *buf_;
97
98 /* size of register's buffer */
99 size_t siz_;
100
101 /* next register in list */
102 CVmBigNumCacheReg *nxt_;
103 };
104
105 /*
106 * register cache
107 */
108 class CVmBigNumCache
109 {
110 public:
111 CVmBigNumCache(size_t max_regs);
112 ~CVmBigNumCache();
113
114 /*
115 * Allocate a temporary register with a minimum of the given byte
116 * size. Returns a pointer to the register's buffer, and fills in
117 * '*hdl' with the handle of the register, which must be used to
118 * release the register.
119 */
120 char *alloc_reg(size_t siz, uint *hdl);
121
122 /* release a previously-allocated register */
123 void release_reg(uint hdl);
124
125 /* release all registers */
126 void release_all();
127
128 /*
129 * Get a special dedicated constant value register, reallocating it
130 * to the required precision if it's not already available at the
131 * required precision or greater. We'll set '*expanded' to true if
132 * we had to expand the register, false if not.
133 */
134
135 /* get the constant ln(10) register */
136 char *get_ln10_reg(size_t siz, int *expanded)
137 { return alloc_reg(&ln10_, siz, expanded); }
138
139 /* get the constant ln(2) register */
140 char *get_ln2_reg(size_t siz, int *expanded)
141 { return alloc_reg(&ln2_, siz, expanded); }
142
143 /* get the constant pi register */
144 char *get_pi_reg(size_t siz, int *expanded)
145 { return alloc_reg(&pi_, siz, expanded); }
146
147 /* get the constant e register */
148 char *get_e_reg(size_t siz, int *expanded)
149 { return alloc_reg(&e_, siz, expanded); }
150
151 /* get the DBL_MAX register */
152 char *get_dbl_max_reg(size_t siz, int *expanded)
153 { return alloc_reg(&dbl_max_, siz, expanded); }
154
155 /* get the DBL_MIN register */
156 char *get_dbl_min_reg(size_t siz, int *expanded)
157 { return alloc_reg(&dbl_min_, siz, expanded); }
158
159 private:
160 /* make sure a register is allocated to a given size, and return it */
161 char *alloc_reg(CVmBigNumCacheReg *reg, size_t siz, int *expanded)
162 {
163 /* make sure the register satisfies the size requested */
164 *expanded = reg->alloc_mem(siz);
165
166 /* return the register's buffer */
167 return reg->buf_;
168 }
169
170 /* our register array */
171 CVmBigNumCacheReg *reg_;
172
173 /* head of free register list */
174 CVmBigNumCacheReg *free_reg_;
175
176 /* head of unallocated register list */
177 CVmBigNumCacheReg *unalloc_reg_;
178
179 /* constant register for ln(10) */
180 CVmBigNumCacheReg ln10_;
181
182 /* constant register for ln(2) */
183 CVmBigNumCacheReg ln2_;
184
185 /* constant register for pi */
186 CVmBigNumCacheReg pi_;
187
188 /* constant register for e */
189 CVmBigNumCacheReg e_;
190
191 /* constant registers for DBL_MAX and DBL_MIN */
192 CVmBigNumCacheReg dbl_max_;
193 CVmBigNumCacheReg dbl_min_;
194
195 /* maximum number of registers we can create */
196 size_t max_regs_;
197 };
198
199
200 /* ------------------------------------------------------------------------ */
201 /*
202 * We store a BigNumber value as a varying-length string of BCD-encoded
203 * digits; we store two digits in each byte. Our bytes are stored from
204 * most significant to least significant, and each byte has the more
205 * significant half in the high part of the byte.
206 *
207 * UINT2 number_of_digits
208 *. INT2 exponent
209 *. BYTE flags
210 *. BYTE most_significant_byte
211 *. ...
212 *. BYTE least_significant_byte
213 *
214 * Note that the number of bytes of the varying length mantissa string
215 * is equal to (number_of_digits+1)/2, because one byte stores two
216 * digits.
217 *
218 * The flags are:
219 *
220 * (flags & 0x0001) - sign bit; zero->non-negative, nonzero->negative
221 *
222 * (flags & 0x0006):
223 *. 0x0000 -> normal number
224 *. 0x0002 -> NOT A NUMBER
225 *. 0x0004 -> INFINITY (sign bit indicates sign of infinity)
226 *. 0x0006 -> reserved for future use
227 *
228 * (flags & 0x0008) - zero bit; if set, the number's value is zero
229 *
230 * All other flag bits are reserved and should be set to zero.
231 *
232 * The exponent field gives the base-10 exponent of the number. This is
233 * a signed quantity; a negative value indicates that the mantissa is to
234 * be divided by (10 ^ abs(exponent)), and a positive value indicates
235 * that the mantissa is to be multiplied by (10 ^ exponent).
236 *
237 * There is an implicit decimal point before the first byte of the
238 * mantissa.
239 */
240
241 /* byte offsets in byte string of various parts */
242 #define VMBN_PREC 0
243 #define VMBN_EXP 2
244 #define VMBN_FLAGS 4
245 #define VMBN_MANT 5
246
247 /* flags masks */
248 #define VMBN_F_NEG 0x0001 /* negative sign bit flag */
249 #define VMBN_F_TYPE_MASK 0x0006 /* number type mask */
250 #define VMBN_F_ZERO 0x0008 /* zero flag */
251
252 /* number types */
253 #define VMBN_T_NUM 0x0000 /* ordinary number */
254 #define VMBN_T_NAN 0x0002 /* NOT A NUMBER */
255 #define VMBN_T_INF 0x0004 /* INFINITY (negative or positive) */
256 #define VMBN_T_RSRVD 0x0006 /* reserved */
257
258 /* ------------------------------------------------------------------------ */
259 /*
260 * Flags for cvt_to_string
261 */
262
263 /* always show a sign, even if positive */
264 #define VMBN_FORMAT_SIGN 0x0001
265
266 /* always use exponential format */
267 #define VMBN_FORMAT_EXP 0x0002
268
269 /* always show a sign in the exponent */
270 #define VMBN_FORMAT_EXP_SIGN 0x0004
271
272 /* always show at least a zero before the decimal point */
273 #define VMBN_FORMAT_LEADING_ZERO 0x0008
274
275 /* always show a decimal point */
276 #define VMBN_FORMAT_POINT 0x0010
277
278 /* show the exponential 'e' (if any) in upper-case */
279 #define VMBN_FORMAT_EXP_CAP 0x0020
280
281 /* insert commas to denote thousands, millions, etc */
282 #define VMBN_FORMAT_COMMAS 0x0020
283
284 /* show a leading space if the number is positive */
285 #define VMBN_FORMAT_POS_SPACE 0x0040
286
287 /* use European-style formatting */
288 #define VMBN_FORMAT_EUROSTYLE 0x0080
289
290 /*
291 * Use scientific notation if it's more compact, a la C printf 'g' format.
292 * This automatically uses exponent notation if the exponent is less then
293 * -4 or greater than or equal to the number of digits after the decimal
294 * point.
295 */
296 #define VMBN_FORMAT_COMPACT 0x0100
297
298 /* max_digits counts only significant digits, not leading zeros */
299 #define VMBN_FORMAT_MAXSIG 0x0200
300
301 /* keep trailing zeros to fill out the max_digits count */
302 #define VMBN_FORMAT_TRAILING_ZEROS 0x0400
303
304
305 /* ------------------------------------------------------------------------ */
306 /*
307 * BigNumber metaclass - intrinsic function vector indices
308 */
309 enum vmobjbn_meta_fnset
310 {
311 /* undefined function */
312 VMOBJBN_UNDEF = 0,
313
314 /* format to a string */
315 VMOBJBN_FORMAT = 1,
316
317 /* equal after rounding? */
318 VMOBJBN_EQUAL_RND = 2,
319
320 /* getPrecision */
321 VMOBJBN_GET_PREC = 3,
322
323 /* setPrecision */
324 VMOBJBN_SET_PREC = 4,
325
326 /* getFraction */
327 VMOBJBN_FRAC = 5,
328
329 /* getWhole */
330 VMOBJBN_WHOLE = 6,
331
332 /* round to a given number of decimal places */
333 VMOBJBN_ROUND_DEC = 7,
334
335 /* absolute value */
336 VMOBJBN_ABS = 8,
337
338 /* ceiling */
339 VMOBJBN_CEIL = 9,
340
341 /* floor */
342 VMOBJBN_FLOOR = 10,
343
344 /* getScale */
345 VMOBJBN_GETSCALE = 11,
346
347 /* scale */
348 VMOBJBN_SCALE = 12,
349
350 /* negate */
351 VMOBJBN_NEGATE = 13,
352
353 /* copySignFrom */
354 VMOBJBN_COPYSIGN = 14,
355
356 /* isNegative */
357 VMOBJBN_ISNEG = 15,
358
359 /* getRemainder */
360 VMOBJBN_REMAINDER = 16,
361
362 /* sine */
363 VMOBJBN_SIN = 17,
364
365 /* cosine */
366 VMOBJBN_COS = 18,
367
368 /* sine */
369 VMOBJBN_TAN = 19,
370
371 /* degreesToRadians */
372 VMOBJBN_D2R = 20,
373
374 /* radiansToDegrees */
375 VMOBJBN_R2D = 21,
376
377 /* arcsine */
378 VMOBJBN_ASIN = 22,
379
380 /* arccosine */
381 VMOBJBN_ACOS = 23,
382
383 /* arctangent */
384 VMOBJBN_ATAN = 24,
385
386 /* sqrt */
387 VMOBJBN_SQRT = 25,
388
389 /* natural log */
390 VMOBJBN_LN = 26,
391
392 /* exp */
393 VMOBJBN_EXP = 27,
394
395 /* log10 */
396 VMOBJBN_LOG10 = 28,
397
398 /* power */
399 VMOBJBN_POW = 29,
400
401 /* hyperbolic sine */
402 VMOBJBN_SINH = 30,
403
404 /* hyperbolic cosine */
405 VMOBJBN_COSH = 31,
406
407 /* hyperbolic tangent */
408 VMOBJBN_TANH = 32,
409
410 /* get pi (static method) */
411 VMOBJBN_GET_PI = 33,
412
413 /* get e (static method) */
414 VMOBJBN_GET_E = 34,
415
416 /* numType */
417 VMOBJN_numType = 35
418 };
419
420
421 /* ------------------------------------------------------------------------ */
422 /*
423 * String formatter output buffer interface.
424 */
425 class IBigNumStringBuf
426 {
427 public:
428 /*
429 * Get the string buffer to use, given the required string length. If
430 * it's not possible to get a buffer of the required size, returns
431 * null, in which case the formatter will return failure as well.
432 *
433 * The formatter always fills in the first two bytes of the result
434 * buffer with a VMB_LEN length prefix, TADS-string style. The space
435 * for the two-byte prefix is included in the 'need' value passed.
436 */
437 virtual char *get_buf(size_t need) = 0;
438 };
439
440 /*
441 * Simple output buffer with a fixed, pre-allocated string.
442 */
443 class CBigNumStringBufFixed: public IBigNumStringBuf
444 {
445 public:
446 CBigNumStringBufFixed(char *buf, size_t len) : buf(buf), len(len) { }
447 char *get_buf(size_t need) { return len >= need ? buf : 0; }
448
449 char *buf;
450 size_t len;
451 };
452
453 /*
454 * Output buffer using an optional pre-allocated buffer, allocating a new
455 * CVmObjString object if the fixed buffer isn't big enough. The caller
456 * can recover the new string value from our 'strval' member after the
457 * formatting is done; this is set to nil if the fixed buffer provided is
458 * sufficient.
459 */
460 class CBigNumStringBufAlo: public CBigNumStringBufFixed
461 {
462 public:
463 /* create with no buffer - always allocates a new string */
464 CBigNumStringBufAlo(VMG_ vm_val_t *strval)
465 : CBigNumStringBufFixed(0, 0), strval(strval)
466 {
467 vmg = VMGLOB_ADDR;
468 if (strval != 0)
469 strval->set_nil();
470 }
471
472 /*
473 * create with a buffer - uses the buffer if it's big enough, otherwise
474 * allocates a new String object, storing the object in our 'strval'
475 * member
476 */
477 CBigNumStringBufAlo(VMG_ vm_val_t *strval, char *buf, size_t len)
478 : CBigNumStringBufFixed(buf, len), strval(strval)
479 {
480 vmg = VMGLOB_ADDR;
481 if (strval != 0)
482 strval->set_nil();
483 }
484
485 /* get the buffer */
486 char *get_buf(size_t need);
487
488 /* the caller's OUT variable to receive the allocated string, if needed */
489 vm_val_t *strval;
490
491 /* stashed globals */
492 vm_globals *vmg;
493 };
494
495
496 /* ------------------------------------------------------------------------ */
497 /*
498 * we have to forward-declare bignum_t, since it uses templates
499 */
500 template <int prec> class bignum_t;
501
502
503 /* ------------------------------------------------------------------------ */
504 /*
505 * Big Number metaclass
506 */
507 class CVmObjBigNum: public CVmObject
508 {
509 friend class CVmMetaclassBigNum;
510 template <int> friend class bignum_t;
511 friend class vbignum_t;
512
513 public:
514 /* metaclass registration object */
515 static class CVmMetaclass *metaclass_reg_;
516 class CVmMetaclass *get_metaclass_reg() const { return metaclass_reg_; }
517
518 /* am I of the given metaclass? */
519 virtual int is_of_metaclass(class CVmMetaclass *meta) const
520 {
521 /* try my own metaclass and my base class */
522 return (meta == metaclass_reg_
523 || CVmObject::is_of_metaclass(meta));
524 }
525
526 /* initialize/terminate the BigNumber cache */
527 static void init_cache();
528 static void term_cache();
529
530 /*
531 * write to a 'data' mode file - returns zero on success, non-zero on
532 * I/O or other error
533 */
534 int write_to_data_file(class CVmDataSource *fp);
535
536 /*
537 * Read from a 'data' mode file, creating a new BigNumber object to
538 * hold the result. Returns zero on success, non-zero on failure. On
539 * success, *retval will be filled in with the new BigNumber object.
540 */
541 static int read_from_data_file(
542 VMG_ vm_val_t *retval, class CVmDataSource *fp);
543
544 /* create dynamically using stack arguments */
545 static vm_obj_id_t create_from_stack(VMG_ const uchar **pc_ptr,
546 uint argc);
547
548 /* call a static property */
549 static int call_stat_prop(VMG_ vm_val_t *result,
550 const uchar **pc_ptr, uint *argc,
551 vm_prop_id_t prop);
552
553 /* reserve constant data */
554 virtual void reserve_const_data(VMG_ class CVmConstMapper *mapper,
555 vm_obj_id_t self);
556
557 /* convert to constant data */
558 virtual void convert_to_const_data(VMG_ class CVmConstMapper *mapper,
559 vm_obj_id_t self);
560
561 /* create with a given precision */
562 static vm_obj_id_t create(VMG_ int in_root_set, size_t digits);
563
564 /* create from a given integer value */
565 static vm_obj_id_t create(VMG_ int in_root_set, long val, size_t digits);
566
567 /* create from a given unsigned integer value */
568 static vm_obj_id_t createu(VMG_ int in_root_set, ulong val, size_t digits);
569
570 /* create from a given string value, with a given precision */
571 static vm_obj_id_t create(VMG_ int in_root_set,
572 const char *str, size_t len, size_t digits);
573
574 /* create from a double, with enough precision for a native double */
575 static vm_obj_id_t create(VMG_ int in_root_set, double val);
576
577 /* create from a double, with a given precision */
578 static vm_obj_id_t create(VMG_ int in_root_set, double val, size_t digits);
579
580 /* create from a bignum_t */
581 template <int prec> static vm_obj_id_t create(
582 VMG_ int in_root_set, const bignum_t<prec> *b)
583 {
584 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
585 new (vmg_ id) CVmObjBigNum(vmg_ prec);
586 CVmObjBigNum *n = (CVmObjBigNum *)vm_objp(vmg_ id);
587 copy_val(n->ext_, b->ext, FALSE);
588 return id;
589 }
590
591 /* create from a bignum_t */
592 template <int prec> static vm_obj_id_t create(
593 VMG_ int in_root_set, const bignum_t<prec> &b)
594 {
595 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
596 new (vmg_ id) CVmObjBigNum(vmg_ prec);
597 CVmObjBigNum *n = (CVmObjBigNum *)vm_objp(vmg_ id);
598 copy_val(n->ext_, b.ext, FALSE);
599 return id;
600 }
601
602 /*
603 * Create from a 64-bit integer in portable little-endian notation.
604 * This is the 64-bit int equivalent of osrp2(), osrp4(), etc - the
605 * name is meant to parallel those names. The buffer must be stored in
606 * our standard portable format: little-endian, two's complement.
607 * create_rp8() treats the value as unsigned, create_rp8s() treats it
608 * as signed.
609 */
610 static vm_obj_id_t create_rp8(VMG_ int in_root_set, const char *buf);
611 static vm_obj_id_t create_rp8s(VMG_ int in_root_set, const char *buf);
612
613 /*
614 * Create from a 64-bit integer expressed as two 32-bit portions. We
615 * currently only provide an unsigned version, because (a) we don't
616 * have an immediate need for signed, and (b) breaking a signed 64-bit
617 * value into two 32-bit partitions requires making assumptions about
618 * the native integer representation (2's complement, 1s' complement,
619 * etc) that we'll probably have to farm out to os_xxx code. Until we
620 * encounter a need we'll avoid the signed version. The unsigned
621 * version will work with any binary integer representation, which
622 * makes it all but universal (it won't work on a BCD machine, for
623 * example... but would anyone ever notice, or care?).
624 */
625 static vm_obj_id_t create_int64(VMG_ int in_root_set,
626 uint32_t hi, uint32_t lo);
627
628 /* create from a BER-encoded compressed unsigned integer buffer */
629 static vm_obj_id_t create_from_ber(VMG_ int in_root_set,
630 const char *buf, size_t len);
631
632 /* create from an IEEE 754-2008 binary interchange format buffer */
633 static vm_obj_id_t create_from_ieee754(
634 VMG_ int in_root_set, const char *buf, int bits);
635
636 /*
637 * create from a string value, using the precision required to hold the
638 * value in the string
639 */
640 static vm_obj_id_t create(VMG_ int in_root_set,
641 const char *str, size_t len);
642
643 /*
644 * create from a string value in a given radix, using the precision
645 * required to hold the value in the string
646 */
647 static vm_obj_id_t create_radix(VMG_ int in_root_set,
648 const char *str, size_t len, int radix);
649
650 /* determine if an object is a BigNumber */
651 static int is_bignum_obj(VMG_ vm_obj_id_t obj)
652 { return vm_objp(vmg_ obj)->is_of_metaclass(metaclass_reg_); }
653
654 /*
655 * Cast a value to a BigNumber. We can convert strings, integers, and
656 * of course BigNumber values. Fills in bnval with the BigNumber
657 * value, which will be newly allocated if the source isn't already a
658 * BigNumber (in which case bnval is just a copy of srcval).
659 */
660 static void cast_to_bignum(VMG_ vm_val_t *bnval, const vm_val_t *srcval);
661
662 /*
663 * Parse a string value into an extension buffer. If radix is 0, we
664 * infer the radix using radix_from_string() rules.
665 */
666 static void parse_str_into(char *ext, const char *str, size_t len);
667 static void parse_str_into(char *ext, const char *str, size_t len,
668 int radix);
669
670 /* parse a string, allocating a buffer with 'new char[]' */
671 static char *parse_str_alo(size_t &buflen,
672 const char *str, size_t len, int radix);
673
674 /*
675 * Get the precision required to hold the number with the given string
676 * representation. If radix is 0, we infer the radix using
677 * radix_from_string() rules.
678 */
679 static int precision_from_string(const char *str, size_t len);
680 static int precision_from_string(const char *str, size_t len, int radix);
681
682 /*
683 * Parse a string to determine its radix. If the string starts with
684 * '0x' or '0', and contains no decimal point or 'E' exponent
685 * indicator, it's a hex or octal integer, respectively. Otherwise
686 * it's a decimal integer or floating point value.
687 */
688 static int radix_from_string(const char *str, size_t len);
689
690 /* notify of deletion */
691 void notify_delete(VMG_ int in_root_set);
692
693 /* set a property */
694 void set_prop(VMG_ class CVmUndo *undo,
695 vm_obj_id_t self, vm_prop_id_t prop, const vm_val_t *val);
696
697 /* get a property */
698 int get_prop(VMG_ vm_prop_id_t prop, vm_val_t *val,
699 vm_obj_id_t self, vm_obj_id_t *source_obj, uint *argc);
700
701 /* undo operations - we are immutable and hence keep no undo */
702 void notify_new_savept() { }
703 void apply_undo(VMG_ struct CVmUndoRecord *) { }
704 void mark_undo_ref(VMG_ struct CVmUndoRecord *) { }
705 void remove_stale_undo_weak_ref(VMG_ struct CVmUndoRecord *) { }
706
707 /* mark references - we have no references so this does nothing */
708 void mark_refs(VMG_ uint) { }
709
710 /* remove weak references */
711 void remove_stale_weak_refs(VMG0_) { }
712
713 /* load from an image file */
714 void load_from_image(VMG_ vm_obj_id_t, const char *ptr, size_t)
715 { ext_ = (char *)ptr; }
716
717 /* rebuild for image file */
718 virtual ulong rebuild_image(VMG_ char *buf, ulong buflen);
719
720 /* save to a file */
721 void save_to_file(VMG_ class CVmFile *fp);
722
723 /* restore from a file */
724 void restore_from_file(VMG_ vm_obj_id_t self,
725 class CVmFile *fp, class CVmObjFixup *fixup);
726
727 /* add a value */
728 int add_val(VMG_ vm_val_t *result,
729 vm_obj_id_t self, const vm_val_t *val);
730
731 /* subtract a value */
732 int sub_val(VMG_ vm_val_t *result,
733 vm_obj_id_t self, const vm_val_t *val);
734
735 /* multiply */
736 int mul_val(VMG_ vm_val_t *result,
737 vm_obj_id_t self, const vm_val_t *val);
738
739 /* divide */
740 int div_val(VMG_ vm_val_t *result,
741 vm_obj_id_t self, const vm_val_t *val);
742
743 /* negate */
744 int neg_val(VMG_ vm_val_t *result, vm_obj_id_t self);
745
746 /* get the absolute value */
747 int abs_val(VMG_ vm_val_t *result, vm_obj_id_t self);
748
749 /* get the sgn value (-1 if negative, 0 if zero, 1 if positive) */
750 int sgn_val(VMG_ vm_val_t *result, vm_obj_id_t self);
751
752 /* check a value for equality */
753 int equals(VMG_ vm_obj_id_t self, const vm_val_t *val, int depth) const;
754
755 /* calculate a hash value for the number */
756 uint calc_hash(VMG_ vm_obj_id_t self, int depth) const;
757
758 /* compare to another value */
759 int compare_to(VMG_ vm_obj_id_t /*self*/, const vm_val_t *) const;
760
761 /*
762 * Create a string representation of the number. We'll use a
763 * default format that uses no more than a maximum number of
764 * characters to represent the string. We'll avoid exponential
765 * format if possible, but we'll fall back on exponential format if
766 * the non-exponential result would exceed our default maximum
767 * length.
768 */
769 virtual const char *cast_to_string(VMG_ vm_obj_id_t self,
770 vm_val_t *new_str) const;
771
772 /*
773 * Explicitly cast to string with a given radix
774 */
775 virtual const char *explicit_to_string(
776 VMG_ vm_obj_id_t self, vm_val_t *new_str, int radix, int flags) const;
777
778 /*
779 * Static method to convert big number data to a string. We'll create
780 * a new string object and store a reference in new_str, returning a
781 * pointer to its data buffer.
782 *
783 * max_digits is the maximum number of digits we should produce. If
784 * our precision is greater than this would allow, we'll round. If we
785 * have more digits before the decimal point than this would allow,
786 * we'll use exponential notation.
787 *
788 * If the flag VMBN_FORMAT_MAXSIG is set, max_digits is taken as the
789 * maximum number of *significant* digits to display. That is, we won't
790 * count leading zeros against the maximum.
791 *
792 * whole_places is the number of places before the decimal point that
793 * we should produce. This is a minimum; if we need more places (and
794 * we're not in exponential notation), we'll take the additional
795 * places. If, however, we don't manage to fill this quota, we'll pad
796 * with spaces to the left. We ignore whole_places in exponential
797 * format.
798 *
799 * frac_digits is the number of digits after the decimal point that we
800 * should produce. We'll round if we have more precision than this
801 * would allow, or pad with zeros if we don't have enough precision.
802 * If frac_digits is -1, we will produce as many fractional digits as
803 * we need up to the max_digits limit.
804 *
805 * If the VMBN_FORMAT_EXP flag isn't set, we'll format the number
806 * without an exponent as long as we have enough space in max_digits
807 * for the part before the decimal point, and we have enough space in
808 * max_digits and frac_digits that a number with a small absolute value
809 * wouldn't show up as all zeros.
810 *
811 * If the VMBN_FORMAT_POINT flag is set, we'll show a decimal point for
812 * all numbers. Otherwise, if frac_digits is zero, or frac_digits is
813 * -1 and the number has no fractional part, we'll suppress the decimal
814 * point. This doesn't matter when frac_digits is greater than zero,
815 * or it's -1 and there's a fractional part to display.
816 *
817 * If exp_digits is non-zero, it specifies the minimum number of digits
818 * to display in the exponent. We'll pad with zeros to make this many
819 * digits if necessary.
820 *
821 * If lead_fill is provided, it must be a string value. We'll fill the
822 * string with the characters from this string, looping to repeat the
823 * string if necessary. If this string isn't provided, we'll use
824 * leading spaces. This is only needed if the whole_places value
825 * requires us to insert filler.
826 *
827 * Note that VMG_ can be passed as VMGNULL_ (null global context) for
828 * the cvt_to_string_buf() functions IF 'new_str' and 'lead_fill' are
829 * null.
830 */
831 static const char *cvt_to_string(
832 VMG_ vm_obj_id_t self, vm_val_t *new_str, const char *ext,
833 int max_digits, int whole_places, int frac_digits, int exp_digits,
834 ulong flags, vm_val_t *lead_fill);
835
836 /* format the value into the given buffer */
837 const char *cvt_to_string_buf(
838 char *buf, size_t buflen, int max_digits,
839 int whole_places, int frac_digits, int exp_digits, ulong flags);
840
841 /* format BigNumber data (without a 'self') into the given buffer */
842 static const char *cvt_to_string_buf(
843 char *buf, size_t buflen, const char *ext,
844 int max_digits, int whole_places, int frac_digits, int exp_digits,
845 ulong flags, const char *lead_fill, size_t lead_fill_len);
846
847 /*
848 * format the value into the given buffer, or into a new String if the
849 * value overflows the buffer
850 */
851 const char *cvt_to_string_buf(
852 VMG_ vm_val_t *new_str, char *buf, size_t buflen, int max_digits,
853 int whole_places, int frac_digits, int exp_digits, ulong flags);
854
855
856 /*
857 * format a regular integer value into a buffer as though it were a
858 * BigNumber value
859 */
860 static const char *cvt_int_to_string_buf(
861 char *buf, size_t buflen, int32_t intval,
862 int max_digits, int whole_places, int frac_digits, int exp_digits,
863 ulong flags);
864
865 /* format as an integer in a given radix */
866 const char *cvt_to_string_in_radix(
867 VMG_ vm_obj_id_t self, vm_val_t *new_str, int radix) const;
868
869 /* get the fractional part/whole part */
870 static void compute_frac(char *ext);
871 static void compute_whole(char *ext);
872
873 /* compute a sum */
874 static void compute_sum(VMG_ vm_val_t *result,
875 const char *ext1, const char *ext2);
876
877 /* compute a difference */
878 static void compute_diff(VMG_ vm_val_t *result,
879 const char *ext1, const char *ext2);
880
881 /* compute a product */
882 static void compute_prod(VMG_ vm_val_t *result,
883 const char *ext1, const char *ext2);
884
885 /* compute a quotient */
886 static void compute_quotient(VMG_ vm_val_t *result,
887 const char *ext1, const char *ext2);
888
889 /* compute a remainder */
890 static void compute_rem(VMG_ vm_val_t *result,
891 const char *ext1, const char *ext2);
892
893 /* compute a natural logarithm */
894 static void compute_ln_into(char *dst, const char *src);
895
896 /* compute e^x */
897 static void compute_exp_into(char *dst, const char *src);
898
899 /* compute a hyperbolic sine or cosine */
900 static void compute_sinhcosh_into(char *dst, const char *src,
901 int is_cosh, int is_tanh);
902
903 /*
904 * Determine if two values are exactly equal. If one value has more
905 * precision than the other, we'll implicitly extend the shorter
906 * value with trailing zeros.
907 */
908 static int compute_eq_exact(const char *ext1, const char *ext2);
909
910 /*
911 * Determine if two values are equal with rounding. If one value is
912 * less precise than the other, we'll round the more precise value
913 * to the shorter precision, and compare the shorter number to the
914 * rounded longer number.
915 */
916 static int compute_eq_round(VMG_ const char *ext1, const char *ext2);
917
918 /*
919 * Create a rounded value, rounding to the given precision. If
920 * always_create is true, we'll create a new number regardless of
921 * whether rounding is required; otherwise, when the caller can
922 * simply treat the old value as truncated, we'll set new_val to nil
923 * and return the original value.
924 */
925 static const char *round_val(VMG_ vm_val_t *new_val, const char *ext,
926 size_t digits, int always_create);
927
928 /* set my value to a given integer value */
929 static void set_int_val(char *ext, long val);
930 static void set_uint_val(char *ext, ulong val);
931
932 /* set from a portable little-endian 64-bit unsigned int buffer */
933 void set_rp8(const uchar *p);
934
935 /* set my value to the given double */
936 static void set_double_val(char *ext, double val);
937
938 /* set my value to a given string */
939 void set_str_val(const char *str, size_t len);
940 void set_str_val(const char *str, size_t len, int radix);
941
942 /* get my data pointer */
943 char *get_ext() const { return ext_; }
944
945 /* BigNumber is a numeric type */
946 virtual int is_numeric() const { return TRUE; }
947
948 /* cast to integer */
949 virtual long cast_to_int(VMG0_) const
950 {
951 /* return the integer conversion */
952 return convert_to_int();
953 }
954
955 /* get my integer value */
956 virtual int get_as_int(long *val) const
957 {
958 /* return the integer conversion */
959 *val = convert_to_int();
960 return TRUE;
961 }
962
963 /* get my double value */
964 virtual int get_as_double(VMG_ double *val) const
965 {
966 *val = convert_to_double();
967 return TRUE;
968 }
969
970 /* promote an integer to a BigNumber */
971 virtual void promote_int(VMG_ vm_val_t *val) const;
972
973 /*
974 * Convert to an integer value (signed or unsigned). We set 'ov' to
975 * true if the value overflows the integer type.
976 */
977 int32_t convert_to_int(int &ov) const { return ext_to_int(ext_, ov); }
978 uint32_t convert_to_uint(int &ov) const;
979
980 /*
981 * convert to integer; sets 'ov' to true if the result doesn't fit an
982 * int32
983 */
984 static int32_t ext_to_int(const char *ext, int &ov);
985
986 /* convert to integer, throwing an error on overflow */
987 int32_t convert_to_int() const
988 {
989 int ov;
990 int32_t l = convert_to_int(ov);
991 if (ov)
992 err_throw(VMERR_NUM_OVERFLOW);
993 return l;
994 }
995 uint32_t convert_to_uint() const
996 {
997 int ov;
998 uint32_t l = convert_to_uint(ov);
999 if (ov)
1000 err_throw(VMERR_NUM_OVERFLOW);
1001 return l;
1002 }
1003
1004 /* cast to numeric */
1005 virtual void cast_to_num(VMG_ vm_val_t *val, vm_obj_id_t self) const
1006 {
1007 /* we're already numeric - just return myself unchanged */
1008 val->set_obj(self);
1009 }
1010
1011 /* convert to double */
1012 double convert_to_double() const { return ext_to_double(ext_); }
1013 static double ext_to_double(const char *ext);
1014
1015 /*
1016 * Convert to the IEEE 754-2008 binary interchange format with the
1017 * given bit size. These are a portable formats, which are not
1018 * necessarily the same as any of the local system's native floating
1019 * point types (although most modern hardware does use this format for
1020 * its native types, modulo byte order). The defined sizes are 16, 32,
1021 * 64, and 128 bits; 32 bits corresponds to the single-precision (C
1022 * "float") type, and 64 bits corresponds to the double-precision (C
1023 * "double") type. We assume that the buffer is big enough for the
1024 * requested bit size. We use the standard IEEE format, *except* that
1025 * we use little-endian byte order for consistency with the TADS
1026 * pack/unpack formats.
1027 */
1028 void convert_to_ieee754(VMG_ char *buf, int bits, int &ov);
1029
1030 /* set the value from an IEEE 754 buffer */
1031 void set_ieee754_value(VMG_ const char *buf, int bits);
1032
1033 /*
1034 * Write a 64-bit integer representation, using the standard TADS
1035 * portable integer format: 8-bit bytes, little-endian, two's
1036 * complement. These are analogous to the osifc routines oswp2(),
1037 * oswp2s(), etc., thus the names.
1038 *
1039 * (Why don't we need more osifc routines for these? Because BigNumber
1040 * internal representation is all under the control of the portable
1041 * code, and the byte buffer representation is portable as well. We
1042 * don't need osifc code for a portable-to-portable conversion. The
1043 * integer routines do need osifc code because they convert to and from
1044 * the local platform integer format, which obviously varies. Even
1045 * that could be done portably in principle, by using integer
1046 * arithmetic; but we don't do it that way, because osifc code can be
1047 * ruthlessly efficient on most platforms by directly accessing the
1048 * byte structure of the local int type rather than doing a bunch of
1049 * arithmetic. There's no such efficiency gain possible with
1050 * BigNumbers, which aren't native anywhere.)
1051 */
1052 void wp8(char *buf, int &ov) const;
1053 void wp8s(char *buf, int &ov) const;
1054
1055 /* write a BER compressed integer representation */
1056 void encode_ber(char *buf, size_t buflen, size_t &result_len, int &ov);
1057
1058 protected:
1059 /* create with no extension */
1060 CVmObjBigNum();
1061
1062 /* create with a given precision */
1063 CVmObjBigNum(VMG_ size_t digits);
1064
1065 /* create with a given precision, initializing with an integer value */
1066 CVmObjBigNum(VMG_ long val, size_t digits);
1067
1068 /* create with a given precision, initializing with a string value */
1069 CVmObjBigNum(VMG_ const char *str, size_t len, size_t digits);
1070
1071 /* create with a given precision, initializing with a double value */
1072 CVmObjBigNum(VMG_ double val, size_t digits);
1073
1074 /* convert a value to a BigNumber */
1075 int cvt_to_bignum(VMG_ vm_obj_id_t self, vm_val_t *val) const;
1076
1077 /* get the magnitude of the integer conversion, ignoring the sign bit */
1078 static uint32_t convert_to_int_base(const char *ext, int &ov);
1079
1080 /*
1081 * general string conversion routine
1082 */
1083 static const char *cvt_to_string_gen(
1084 IBigNumStringBuf *buf, const char *ext,
1085 int max_digits, int whole_places, int frac_digits, int exp_digits,
1086 ulong flags, const char *lead_fill, size_t lead_fill_len);
1087
1088 /* property evaluator - undefined property */
1089 int getp_undef(VMG_ vm_obj_id_t, vm_val_t *, uint *) { return FALSE; }
1090
1091 /* property evaluator - formatString */
1092 int getp_format(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1093
1094 /* property evaluator - equalRound */
1095 int getp_equal_rnd(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1096
1097 /* property evaluator - getPrecision */
1098 int getp_get_prec(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1099
1100 /* property evaluator - setPrecision */
1101 int getp_set_prec(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1102
1103 /* property evaluator - getFraction */
1104 int getp_frac(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1105
1106 /* property evaluator - getWhole */
1107 int getp_whole(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1108
1109 /* property evaluator - roundToDecimal */
1110 int getp_round_dec(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1111
1112 /* property evaluator - absolute value */
1113 int getp_abs(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1114
1115 /* property evaluator - ceiling */
1116 int getp_ceil(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1117
1118 /* property evaluator - floor */
1119 int getp_floor(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1120
1121 /* property evaluator - getScale */
1122 int getp_get_scale(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1123
1124 /* property evaluator - scale */
1125 int getp_scale(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1126
1127 /* property evaluator - negate */
1128 int getp_negate(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1129
1130 /* property evaluator - copySignFrom */
1131 int getp_copy_sign(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1132
1133 /* property evaluator - isNegative */
1134 int getp_is_neg(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1135
1136 /* property evaluator - remainder */
1137 int getp_remainder(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1138
1139 /* property evaluator - sine */
1140 int getp_sin(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1141
1142 /* property evaluator - cosine */
1143 int getp_cos(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1144
1145 /* property evaluator - tangent */
1146 int getp_tan(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1147
1148 /* property evaluator - radiansToDegrees */
1149 int getp_rad2deg(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1150
1151 /* property evaluator - degreesToRadians */
1152 int getp_deg2rad(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1153
1154 /* property evaluator - arcsine */
1155 int getp_asin(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1156
1157 /* property evaluator - arccosine */
1158 int getp_acos(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1159
1160 /* property evaluator - arcsine */
1161 int getp_atan(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1162
1163 /* property evaluator - square root */
1164 int getp_sqrt(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1165
1166 /* property evaluator - natural log */
1167 int getp_ln(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1168
1169 /* property evaluator - exp */
1170 int getp_exp(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1171
1172 /* property evaluator - log10 */
1173 int getp_log10(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1174
1175 /* property evaluator - power */
1176 int getp_pow(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1177
1178 /* property evaluator - hyperbolic sine */
1179 int getp_sinh(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1180
1181 /* property evaluator - hyperbolic cosine */
1182 int getp_cosh(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1183
1184 /* property evaluator - hyperbolic tangent */
1185 int getp_tanh(VMG_ vm_obj_id_t self, vm_val_t *val, uint *argc);
1186
1187 /* property evaluator - get pi */
1188 int getp_pi(VMG_ vm_obj_id_t, vm_val_t *val, uint *argc)
1189 { return s_getp_pi(vmg_ val, argc); }
1190
1191 /* property evaluator - get e */
1192 int getp_e(VMG_ vm_obj_id_t, vm_val_t *val, uint *argc)
1193 { return s_getp_e(vmg_ val, argc); }
1194
1195 /* property evaluator - get the number type */
1196 int getp_numType(VMG_ vm_obj_id_t, vm_val_t *val, uint *argc);
1197
1198 /* static property evaluator - get pi */
1199 static int s_getp_pi(VMG_ vm_val_t *val, uint *argc);
1200
1201 /* static property evaluator - get e */
1202 static int s_getp_e(VMG_ vm_val_t *val, uint *argc);
1203
1204 /* set up for a getp operation with zero arguments */
1205 int setup_getp_0(VMG_ vm_obj_id_t self, vm_val_t *retval,
1206 uint *argc, char **new_ext);
1207
1208 /* set up for a getp operation with one argument */
1209 int setup_getp_1(VMG_ vm_obj_id_t self, vm_val_t *retval,
1210 uint *argc, char **new_ext,
1211 vm_val_t *val2, const char **val2_ext,
1212 int use_self_prec);
1213
1214 /* set up a return value for a getp operation */
1215 int setup_getp_retval(VMG_ vm_obj_id_t self, vm_val_t *retval,
1216 char **new_ext, size_t prec);
1217
1218 /* common property evaluator for asin and acos */
1219 int calc_asincos(VMG_ vm_obj_id_t self,
1220 vm_val_t *retval, uint *argc, int is_acos);
1221
1222 /* common property evaluator - sinh, cosh, and tanh */
1223 int calc_sinhcosh(VMG_ vm_obj_id_t self,
1224 vm_val_t *retval, uint *argc,
1225 int is_cosh, int is_tanh);
1226
1227 /* calculate asin or acos into the given buffer */
1228 static void calc_asincos_into(char *new_ext, const char *ext,
1229 int is_acos);
1230
1231 /*
1232 * Calculate the arcsin series expansion; valid only for small
1233 * values of x (0 < x < 1/sqrt(2)). The argument value is in ext1,
1234 * and we return a pointer to the register containing the result.
1235 */
1236 static char *calc_asin_series(char *ext1, char *ext2,
1237 char *ext3, char *ext4, char *ext5);
1238
1239 /*
1240 * Compute the ln series expansion. This is valid only for small
1241 * arguments; the argument is in ext1 initially. Returns a pointer
1242 * to the register containing the result
1243 */
1244 static char *compute_ln_series_into(char *ext1, char *ext2,
1245 char *ext3, char *ext4, char *ext5);
1246
1247 /* allocate space for a given number of decimal digits of precision */
1248 void alloc_bignum(VMG_ size_t prec);
1249
1250 /* calculate how much space we need for a given precision */
1251 static size_t calc_alloc(size_t prec)
1252 { return (2 + 2 + 1) + ((prec + 1)/2); }
1253
1254 /* initialize a computation for a two-operand operator */
1255 static char *compute_init_2op(VMG_ vm_val_t *result,
1256 const char *ext1, const char *ext2);
1257
1258 /* compute a square root */
1259 static void compute_sqrt_into(char *new_ext, const char *ext);
1260
1261 /* compute the sum of two operands into the given buffer */
1262 static void compute_sum_into(char *new_ext,
1263 const char *ext1, const char *ext2);
1264
1265 /*
1266 * Compute the sum of the absolute values of the operands into the
1267 * given buffer. The result is always positive. The result buffer
1268 * must have a precision at least as large as the larger of the two
1269 * input precisions.
1270 */
1271 static void compute_abs_sum_into(char *new_ext,
1272 const char *ext1, const char *ext2);
1273
1274 /* compute the difference of two operands into the given buffer */
1275 static void compute_diff_into(char *new_ext,
1276 const char *ext1, const char *ext2);
1277
1278 /*
1279 * Compute the difference of the absolute values of the operands
1280 * into the given buffer. The result is positive if the first value
1281 * is larger than the second, negative if the first value is smaller
1282 * than the second. The result buffer must have precision at least
1283 * as large as the larger of the two input precisions.
1284 */
1285 static void compute_abs_diff_into(char *new_ext,
1286 const char *ext1, const char *ext2);
1287
1288 /*
1289 * Compute the product of the two values into the given buffer. The
1290 * result buffer must have precision at least as large as the larger
1291 * of the two input precisions.
1292 */
1293 static void compute_prod_into(char *new_ext,
1294 const char *ext1, const char *ext2);
1295
1296 /*
1297 * Compute the quotient of the two values into the given buffer. If
1298 * new_rem_ext is not null, we'll store the remainder there.
1299 */
1300 static void compute_quotient_into(char *new_ext,
1301 char *new_rem_ext,
1302 const char *ext1, const char *ext2);
1303
1304 /* compare extensions - return 0 if equal, <0 if a<b, >0 if a>b */
1305 static int compare_ext(const char *a, const char *b);
1306
1307 /*
1308 * Compare the absolute values of two numbers. If the first is
1309 * greater than the second, we'll return a positive result. If the
1310 * two are equal, we'll return zero. If the first is less than the
1311 * second, we'll return a negative result. This routine ignores NAN
1312 * and INF values, so the caller must ensure that only ordinary
1313 * numbers are passed to this routine.
1314 */
1315 static int compare_abs(const char *ext1, const char *ext2);
1316
1317 /* get/set the digit precision */
1318 static size_t get_prec(const char *ext)
1319 { return osrp2(ext + VMBN_PREC); }
1320 static void set_prec(char *ext, size_t prec)
1321 { oswp2(ext + VMBN_PREC, prec); }
1322
1323 /* get/set the exponent */
1324 static int get_exp(const char *ext)
1325 { return osrp2s(ext + VMBN_EXP); }
1326 static void set_exp(char *ext, int exp)
1327 { oswp2s(ext + VMBN_EXP, exp); }
1328
1329 /* get the negative sign flag */
1330 static int get_neg(const char *ext)
1331 { return (ext[VMBN_FLAGS] & VMBN_F_NEG) != 0; }
1332
1333 /* set/clear negative sign flag */
1334 static void set_neg(char *ext, int neg)
1335 {
1336 if (neg)
1337 ext[VMBN_FLAGS] |= VMBN_F_NEG;
1338 else
1339 ext[VMBN_FLAGS] &= ~VMBN_F_NEG;
1340 }
1341
1342 /* get the number type */
1343 static int get_type(const char *ext)
1344 { return ext[VMBN_FLAGS] & VMBN_F_TYPE_MASK; }
1345
1346 /* set the number type (to a VMBN_T_xxx value) */
1347 static void set_type(char *ext, int typ)
1348 {
1349 /* clear the old number type */
1350 ext[VMBN_FLAGS] &= ~VMBN_F_TYPE_MASK;
1351
1352 /* set the new number type */
1353 ext[VMBN_FLAGS] |= typ;
1354 }
1355
1356 /* get a digit at a particular index (0 = most significant) */
1357 static unsigned int get_dig(const char *ext, size_t i)
1358 {
1359 /* get the digit pair containing our digit */
1360 unsigned int pair = ext[VMBN_MANT + i/2];
1361
1362 /*
1363 * If it's an even index, we need the high half. Otherwise, we
1364 * need the low half.
1365 *
1366 * This is a bit tricky, all to avoid a condition branch. If
1367 * the index is even, (i & 1) will be 0, otherwise (i & 1) will
1368 * be 1. So, (1 - (i & 1)) will be 1 if even, 0 if odd. That
1369 * quantity shifted left twice will hence be 4 if the index is
1370 * even, 0 if the index is odd. Thus, we'll shift the pair
1371 * right by 4 if the index is even, yielding the high part, or
1372 * shift right by 0 if the index is odd, keeping the low part.
1373 */
1374 pair >>= ((1 - (i & 1)) << 2);
1375
1376 /* mask to one digit */
1377 return (pair & 0x0f);
1378 }
1379
1380 /* set a digit at a particular index */
1381 static void set_dig(char *ext, size_t i, unsigned int dig)
1382 {
1383 unsigned char mask;
1384
1385 /* make sure our input digit is just a digit */
1386 dig &= 0x0F;
1387
1388 /*
1389 * If it's an even index, we need to store our digit in the high
1390 * half. Otherwise, we need to store it in the low half. So,
1391 * if we're storing in an even index, shift our number left 4
1392 * bits so that it's in the high half of its low byte;
1393 * otherwise, leave the number as-is.
1394 */
1395 dig <<= ((1 - (i & 1)) << 2);
1396
1397 /*
1398 * We need a mask that we can AND the current value with to
1399 * preserve the half we're not changing, but clear the other
1400 * half. So, we need 0x0F if we're setting the high half (even
1401 * index), or 0xF0 if we're setting the low half (odd index).
1402 * Use the same trick as above, with the shift sense inverted,
1403 * so generate our mask.
1404 */
1405 mask = (0x0F << ((i & 1) << 2));
1406
1407 /* mask out our part from the pair */
1408 ext[VMBN_MANT + i/2] &= mask;
1409
1410 /* OR in our digit now that we've masked the place clear */
1411 ext[VMBN_MANT + i/2] |= (unsigned char)dig;
1412 }
1413
1414 /* shift mantissa left/right, leaving the exponent unchanged */
1415 static void shift_left(char *ext, unsigned int shift);
1416 static void shift_right(char *ext, unsigned int shift);
1417
1418 /* multiply a number by a long integer value */
1419 static void mul_by_long(char *ext, unsigned long val);
1420
1421 /*
1422 * Divide a number by a long integer value.
1423 *
1424 * Important: 'val' must not exceed ULONG_MAX/10. Our algorithm
1425 * computes integer dividends from ext's digits; these can range up to
1426 * 10*val and have to fit in a ulong, thus the ULONG_MAX/10 limit on
1427 * val.
1428 */
1429 static void div_by_long(char *ext, unsigned long val,
1430 unsigned long *remp = 0);
1431
1432 /* divide by 2^32 */
1433 static void div_by_2e32(char *ext, uint32_t *remainder);
1434
1435 /*
1436 * store the portable 64-bit integer representation of the absolute
1437 * value of this number in the given buffer
1438 */
1439 void wp8abs(char *buf, int &ov) const;
1440
1441 /* compute the 2's complement of a p8 (64-bit little-endian int) buffer */
1442 static void twos_complement_p8(unsigned char *buf);
1443
1444 /* increment a number's absolute value */
1445 static void increment_abs(char *ext);
1446
1447 /* round for digits dropped during a calculation */
1448 static void round_for_dropped_digits(
1449 char *ext, int trail_dig, int trail_val);
1450
1451 /* get the OR sum of digits from 'd' to least significant */
1452 static int get_ORdigs(const char *ext, int d);
1453
1454 /* round an extension to the nearest integer */
1455 static void round_to_int(char *ext);
1456
1457 /* round an extension to the given number of digits */
1458 static void round_to(char *ext, int digits);
1459
1460 /*
1461 * get the rounding direction for rounding to the given number of
1462 * digits: 1 means round up, 0 means round down, so you can simply add
1463 * the return value to the last digit you're keeping
1464 */
1465 static int get_round_dir(const char *ext, int digits);
1466
1467 /*
1468 * round up: add 1 to the least significant digit of the number we're
1469 * keeping (if not specified, we're keep all digits)
1470 */
1471 static void round_up_abs(char *ext);
1472 static void round_up_abs(char *ext, int keep_digits);
1473
1474 /*
1475 * copy a value - if the new value has greater precision than the
1476 * old value, we'll extend with zeros in the new least significance
1477 * digits; if the new value has smaller precision than the old
1478 * value, and 'round' is false, we'll simply truncate the value to
1479 * the new precision. If 'round' is true and we're reducing the
1480 * precision, we'll round up the value instead of truncating it.
1481 */
1482 static void copy_val(char *dst, const char *src, int round);
1483
1484 /* normalize a number */
1485 static void normalize(char *ext);
1486
1487 /* set a number to zero */
1488 static void set_zero(char *ext)
1489 {
1490 /* set the exponent to one */
1491 set_exp(ext, 1);
1492
1493 /* set the zero flag */
1494 ext[VMBN_FLAGS] |= VMBN_F_ZERO;
1495
1496 /* set the sign to non-negative */
1497 set_neg(ext, FALSE);
1498
1499 /* set the type to ordinary number */
1500 set_type(ext, VMBN_T_NUM);
1501
1502 /* set the mantissa to all zeros */
1503 memset(ext + VMBN_MANT, 0, (get_prec(ext) + 1)/2);
1504 }
1505
1506 /* determine if the number equals zero */
1507 static int is_zero(const char *ext)
1508 { return (ext[VMBN_FLAGS] & VMBN_F_ZERO) != 0; }
1509
1510 /* negate a value */
1511 static void negate(char *ext)
1512 {
1513 /* only change the sign if the value is non-zero */
1514 if (!is_zero(ext))
1515 {
1516 /* it's not zero - invert the sign */
1517 set_neg(ext, !get_neg(ext));
1518 }
1519 }
1520
1521 /* make a value negative */
1522 static void make_negative(char *ext)
1523 {
1524 /* only set the sign if the value is non-zero */
1525 if (!is_zero(ext))
1526 set_neg(ext, TRUE);
1527 }
1528
1529 /* check to see if the fractional part is zero */
1530 static int is_frac_zero(const char *ext);
1531
1532 /*
1533 * check for NAN and INF conditions - returns true if the number is
1534 * a NAN or INF, false if it's an ordinary number
1535 */
1536 static int is_nan(const char *ext)
1537 {
1538 /* if it's anything but an ordinary number, indicate NAN */
1539 return (get_type(ext) != VMBN_T_NUM);
1540 }
1541
1542 /* check for infinities */
1543 static int is_infinity(const char *ext)
1544 { return get_type(ext) == VMBN_T_INF; }
1545
1546 /* calculate a Taylor series for sin(x) */
1547 void calc_sin_series(VMG_ char *new_ext, char *ext1, char *ext2,
1548 char *ext3, char *ext4, char *ext5,
1549 char *ext6, char *ext7);
1550
1551 /* calculate a Taylor series for cos(x) */
1552 void calc_cos_series(VMG_ char *new_ext, char *ext1, char *ext2,
1553 char *ext3, char *ext4, char *ext5,
1554 char *ext6, char *ext7);
1555
1556 /*
1557 * given an object number known to refer to a CVmObjBigNum object, get
1558 * the object's extension
1559 */
1560 static char *get_objid_ext(VMG_ vm_obj_id_t obj_id)
1561 {
1562 /* get the object pointer, cast it, and get the extension */
1563 return get_objid_obj(vmg_ obj_id)->get_ext();
1564 }
1565
1566 /*
1567 * given an object number known to refer to a CVmObjBigNum object, get
1568 * the object pointer
1569 */
1570 static CVmObjBigNum *get_objid_obj(VMG_ vm_obj_id_t obj_id)
1571 {
1572 /* get the object pointer and cast it */
1573 return (CVmObjBigNum *)vm_objp(vmg_ obj_id);
1574 }
1575
1576 /* allocate a temporary register */
1577 static char *alloc_temp_reg(size_t prec, uint *hdl);
1578
1579 /*
1580 * Allocate a set of temporary registers; throws an error on
1581 * failure. For each register, there is an additional pair of
1582 * arguments: a (char **) to receive a pointer to the register
1583 * memory, and a (uint *) to receive the register handle.
1584 */
1585 static void alloc_temp_regs(size_t prec, size_t cnt, ...);
1586
1587 /*
1588 * Release a set of temporary registers. For each register, there
1589 * is a uint argument giving the handle of the register to release.
1590 */
1591 static void release_temp_regs(size_t cnt, ...);
1592
1593 /* release a temporary register */
1594 static void release_temp_reg(uint hdl);
1595
1596 /*
1597 * Get the natural logarithm of 10 to the required precision. We'll
1598 * return the cached value if available, or compute and cache the
1599 * constant to (at least) the required precision if not.
1600 */
1601 static const char *cache_ln10(size_t prec);
1602
1603 /* get ln(2) */
1604 static const char *cache_ln2(size_t prec);
1605
1606 /* cache pi to the required precision */
1607 static const char *cache_pi(size_t prec);
1608
1609 /* cache e to the required precision */
1610 static const char *cache_e(size_t prec);
1611
1612 /* get the constant value 1 */
1613 static const char *get_one() { return (const char *)one_; }
1614
1615 /* cache DBL_MAX, DBL_MIN */
1616 static const char *cache_dbl_max();
1617 static const char *cache_dbl_min();
1618
1619 /* constant value 1 */
1620 static const unsigned char one_[];
1621
1622 /* property evaluation function table */
1623 static int (CVmObjBigNum::*func_table_[])(VMG_ vm_obj_id_t self,
1624 vm_val_t *retval, uint *argc);
1625 };
1626
1627 /* ------------------------------------------------------------------------ */
1628 /*
1629 * Registration table object
1630 */
1631 class CVmMetaclassBigNum: public CVmMetaclass
1632 {
1633 public:
1634 /* get the global name */
1635 const char *get_meta_name() const { return "bignumber/030001"; }
1636
1637 /* create from image file */
1638 void create_for_image_load(VMG_ vm_obj_id_t id)
1639 {
1640 new (vmg_ id) CVmObjBigNum();
1641 G_obj_table->set_obj_gc_characteristics(id, FALSE, FALSE);
1642 }
1643
1644 /* create from restoring from saved state */
1645 void create_for_restore(VMG_ vm_obj_id_t id)
1646 {
1647 new (vmg_ id) CVmObjBigNum();
1648 G_obj_table->set_obj_gc_characteristics(id, FALSE, FALSE);
1649 }
1650
1651 /* create dynamically using stack arguments */
1652 vm_obj_id_t create_from_stack(VMG_ const uchar **pc_ptr, uint argc)
1653 { return CVmObjBigNum::create_from_stack(vmg_ pc_ptr, argc); }
1654
1655 /* call a static property */
1656 int call_stat_prop(VMG_ vm_val_t *result,
1657 const uchar **pc_ptr, uint *argc,
1658 vm_prop_id_t prop)
1659 {
1660 return CVmObjBigNum::call_stat_prop(vmg_ result, pc_ptr, argc, prop);
1661 }
1662 };
1663
1664 /* ------------------------------------------------------------------------ */
1665 /*
1666 * A C++ template class for doing BigNumber arithmetic on the stack with
1667 * fixed-precision buffers. This can be used for high-precision arithmetic
1668 * in C++ without creating any garbage-collected BigNumber objects. It's
1669 * not quite as flexible as the BigNumber class itself, but it allows C++
1670 * code to perform decimal arithmetic with higher precision than doubles
1671 * when needed.
1672 */
1673 template <int prec> class bignum_t
1674 {
1675 friend class CVmObjBigNum;
1676
1677 public:
1678 bignum_t() { init(); }
1679 bignum_t(long i) { init(); set(i); }
1680 bignum_t(double d) { init(); set(d); }
1681 bignum_t(VMG_ const vm_val_t *val) { init(); set(vmg_ val); }
1682 template <int precb> bignum_t(const bignum_t<precb> b)
1683 { init(); set(b); }
1684 template <int precb> bignum_t(const bignum_t<precb> *b)
1685 { init(); set(*b); }
1686
1687
1688 void set(long i) { CVmObjBigNum::set_int_val(ext, i); }
1689 void set(double d) { CVmObjBigNum::set_double_val(ext, d); }
1690 template <int bprec> void set(const bignum_t<bprec> &b)
1691 { CVmObjBigNum::copy_val(ext, b.ext, TRUE); }
1692
1693 void set(VMG_ const vm_val_t *val)
1694 {
1695 CVmObjBigNum *b;
1696 if (val->typ == VM_INT)
1697 CVmObjBigNum::set_int_val(ext, val->val.intval);
1698 else if ((b = vm_val_cast(CVmObjBigNum, val)) != 0)
1699 CVmObjBigNum::copy_val(ext, b->get_ext(), TRUE);
1700 else if (val->is_numeric(vmg0_))
1701 CVmObjBigNum::set_double_val(ext, val->num_to_double(vmg0_));
1702 else
1703 err_throw(VMERR_NUM_VAL_REQD);
1704 }
1705
1706 /* cast to int/double */
1707 operator int32_t()
1708 {
1709 int ov;
1710 int32_t ret = CVmObjBigNum::ext_to_int(ext, ov);
1711 if (ov)
1712 err_throw(VMERR_NUM_OVERFLOW);
1713 return ret;
1714 }
1715 operator double()
1716 {
1717 return CVmObjBigNum::ext_to_double(ext);
1718 }
1719
1720 /*
1721 * addition operators
1722 */
1723 bignum_t operator +(long l) const
1724 {
1725 bignum_t<prec> bl(l);
1726 return *this + bl;
1727 }
1728 bignum_t operator +(double d) const
1729 {
1730 bignum_t<prec> bd(d);
1731 return *this + bd;
1732 }
1733 template <int precb> bignum_t operator +(const bignum_t<precb> &b) const
1734 {
1735 bignum_t<(precb > prec ? precb : prec)> result;
1736 CVmObjBigNum::compute_sum_into(result.ext, ext, b.ext);
1737 return result;
1738 }
1739
1740 bignum_t &operator +=(long l) { set(*this + l); return *this; }
1741 bignum_t &operator +=(double d) { set(*this + d); return *this; }
1742 template <int precb> bignum_t &operator +=(bignum_t<precb> &b)
1743 { set(*this + b); return *this; }
1744 template <int precb> bignum_t &operator +=(bignum_t<precb> b)
1745 { set(*this + b); return *this; }
1746
1747 /*
1748 * subtraction operators
1749 */
1750 bignum_t operator -(long l) const
1751 {
1752 bignum_t<prec> bl(l);
1753 return *this - bl;
1754 }
1755 bignum_t operator -(double d) const
1756 {
1757 bignum_t<prec> bd(d);
1758 return *this - bd;
1759 }
1760 template <int precb> bignum_t operator -(bignum_t<precb> &b) const
1761 {
1762 bignum_t<(precb > prec ? precb : prec)> result;
1763 CVmObjBigNum::compute_diff_into(result.ext, ext, b.ext);
1764 return result;
1765 }
1766
1767 bignum_t &operator -=(long l) { set(*this - l); return *this; }
1768 bignum_t &operator -=(double d) { set(*this - d); return *this; }
1769 template <int precb> bignum_t &operator -=(bignum_t<precb> &b)
1770 { set(*this - b); return *this; }
1771 template <int precb> bignum_t &operator -=(bignum_t<precb> b)
1772 { set(*this - b); return *this; }
1773
1774 /*
1775 * Negation
1776 */
1777 bignum_t<prec> operator -()
1778 {
1779 bignum_t<prec> result(this);
1780 CVmObjBigNum::negate(result.ext);
1781 return result;
1782 }
1783
1784 /*
1785 * multiplication operators
1786 */
1787 bignum_t operator *(long l) const
1788 {
1789 bignum_t<prec> bl(l);
1790 return *this * bl;
1791 }
1792 bignum_t operator *(double d) const
1793 {
1794 bignum_t<prec> bd(d);
1795 return *this * bd;
1796 }
1797 template <int precb> bignum_t operator *(bignum_t<precb> &b) const
1798 {
1799 bignum_t<(precb > prec ? precb : prec)> result;
1800 CVmObjBigNum::compute_prod_into(result.ext, ext, b.ext);
1801 return result;
1802 }
1803
1804 bignum_t &operator *=(long l) { set(*this * l); return *this; }
1805 bignum_t &operator *=(double d) { set(*this * d); return *this; }
1806 template <int precb> bignum_t &operator *=(bignum_t<precb> &b)
1807 { set(*this * b); return *this; }
1808 template <int precb> bignum_t &operator *=(bignum_t<precb> b)
1809 { set(*this * b); return *this; }
1810
1811 /*
1812 * division operators
1813 */
1814 bignum_t operator /(long l) const
1815 {
1816 bignum_t<prec> bl(l);
1817 return *this / bl;
1818 }
1819 bignum_t operator /(double d) const
1820 {
1821 bignum_t<prec> bd(d);
1822 return *this / bd;
1823 }
1824 template <int precb> bignum_t operator /(bignum_t<precb> &b) const
1825 {
1826 bignum_t<(precb > prec ? precb : prec)> result;
1827 CVmObjBigNum::compute_quotient_into(result.ext, 0, ext, b.ext);
1828 return result;
1829 }
1830
1831 bignum_t &operator /=(long l) { set(*this / l); return *this; }
1832 bignum_t &operator /=(double d) { set(*this / d); return *this; }
1833 template <int precb> bignum_t &operator /=(bignum_t<precb> &b)
1834 { set(*this / b); return *this; }
1835 template <int precb> bignum_t &operator /=(bignum_t<precb> b)
1836 { set(*this / b); return *this; }
1837
1838 /*
1839 * modulo operators
1840 */
1841 bignum_t operator %(long l) const
1842 {
1843 bignum_t<prec> bl(l);
1844 return *this % bl;
1845 }
1846 bignum_t operator %(double d) const
1847 {
1848 bignum_t<prec> bd(d);
1849 return *this % bd;
1850 }
1851 template <int precb> bignum_t operator %(bignum_t<precb> &b) const
1852 {
1853 bignum_t<(precb > prec ? precb : prec)> quo, rem;
1854 CVmObjBigNum::compute_quotient_into(quo.ext, rem.ext, ext, b.ext);
1855 return rem;
1856 }
1857 template <int precb> bignum_t &operator %=(bignum_t<precb> &b)
1858 { set(*this % b); return *this; }
1859 template <int precb> bignum_t &operator %=(bignum_t<precb> b)
1860 { set(*this % b); return *this; }
1861
1862 /*
1863 * formatting
1864 */
1865 void format(char *buf, size_t buflen)
1866 {
1867 CVmObjBigNum::cvt_to_string_buf(
1868 buf, buflen, ext, -1, -1, -1, -1, VMBN_FORMAT_POINT, 0, 0);
1869 }
1870 void format(char *buf, size_t buflen, int maxdigits, int fracdigits)
1871 {
1872 CVmObjBigNum::cvt_to_string_buf(
1873 buf, buflen, ext, maxdigits, -1, fracdigits, -1,
1874 VMBN_FORMAT_POINT, 0, 0);
1875 }
1876
1877 protected:
1878 void init()
1879 {
1880 oswp2(ext, prec);
1881 ext[VMBN_FLAGS] = 0;
1882 }
1883 char ext[VMBN_MANT + (prec+1)/2];
1884 };
1885
1886 /*
1887 * Yet another C++ BigNumber adapter class, this time for variable
1888 * precision BigNumber values allocated on the C++ heap. This is similar
1889 * to bignum_t<int prec>, but allows the precision to be determined at
1890 * run-time. The trade-off is that this type must be allocated on the heap
1891 * due to the dynamic precision.
1892 */
1893 class vbignum_t
1894 {
1895 public:
1896 /* create from native types */
1897 vbignum_t(long l) { init(10); set(l); }
1898 vbignum_t(ulong l) { init(10); set(l); }
1899 vbignum_t(double d) { init(18); set(d); }
1900 vbignum_t(const char *str, size_t len)
1901 {
1902 init(CVmObjBigNum::precision_from_string(str, len));
1903 CVmObjBigNum::parse_str_into(ext_, str, len);
1904 }
1905 vbignum_t(const char *str, size_t len, int radix)
1906 {
1907 init(CVmObjBigNum::precision_from_string(str, len, radix));
1908 CVmObjBigNum::parse_str_into(ext_, str, len, radix);
1909 }
1910
1911 /* delete */
1912 ~vbignum_t() { delete [] ext_; }
1913
1914 /* set from native types */
1915 void set(long l) { CVmObjBigNum::set_int_val(ext_, l); }
1916 void set(ulong l) { CVmObjBigNum::set_uint_val(ext_, l); }
1917 void set(double d) { CVmObjBigNum::set_double_val(ext_, d); }
1918
1919 /* get my precision in digits */
1920 int prec() const { return CVmObjBigNum::get_prec(ext_); }
1921
1922 /* is the value zero? */
1923 int is_zero() const { return CVmObjBigNum::is_zero(ext_); }
1924
1925 /* get the value as an int32; sets 'ov' to true on overflow */
1926 int32_t to_int(int &ov) { return CVmObjBigNum::ext_to_int(ext_, ov); }
1927
1928 /* format */
1929 const char *format(IBigNumStringBuf *buf) const
1930 {
1931 return CVmObjBigNum::cvt_to_string_gen(
1932 buf, ext_, -1, -1, -1, -1, VMBN_FORMAT_POINT, 0, 0);
1933 }
1934 const char *format(IBigNumStringBuf *buf,
1935 int maxdigits, int fracdigits) const
1936 {
1937 return CVmObjBigNum::cvt_to_string_gen(
1938 buf, ext_, maxdigits, -1, fracdigits, -1,
1939 VMBN_FORMAT_POINT, 0, 0);
1940 }
1941 const char *format(char *buf, size_t buflen) const
1942 {
1943 return CVmObjBigNum::cvt_to_string_buf(
1944 buf, buflen, ext_, -1, -1, -1, -1, VMBN_FORMAT_POINT, 0, 0);
1945 }
1946 const char *format(char *buf, size_t buflen,
1947 int maxdigits, int fracdigits) const
1948 {
1949 return CVmObjBigNum::cvt_to_string_buf(
1950 buf, buflen, ext_, maxdigits, -1, fracdigits, -1,
1951 VMBN_FORMAT_POINT, 0, 0);
1952 }
1953
1954 /* cast to int/double */
1955 operator int32_t()
1956 {
1957 int ov;
1958 int32_t ret = CVmObjBigNum::ext_to_int(ext_, ov);
1959 if (ov)
1960 err_throw(VMERR_NUM_OVERFLOW);
1961 return ret;
1962 }
1963 operator double()
1964 {
1965 return CVmObjBigNum::ext_to_double(ext_);
1966 }
1967
1968 /* compare - returns 0 if equal, <0 if this<b, >0 if this>b */
1969 int compare(const vbignum_t &b) const
1970 { return CVmObjBigNum::compare_ext(ext_, b.ext_); }
1971
1972 /* addition */
1973 vbignum_t *operator +(long l) const
1974 {
1975 vbignum_t bl(l);
1976 return *this + bl;
1977 }
1978 vbignum_t *operator +(const vbignum_t &b) const
1979 {
1980 vbignum_t *sum = new vbignum_t();
1981 sum->init(maxprec(this, &b));
1982 CVmObjBigNum::compute_sum_into(sum->ext_, ext_, b.ext_);
1983 return sum;
1984 }
1985
1986 /* subtraction */
1987 vbignum_t *operator -(long l) const
1988 {
1989 vbignum_t bl(l);
1990 return *this - bl;
1991 }
1992 vbignum_t *operator -(const vbignum_t &b) const
1993 {
1994 vbignum_t *res = new vbignum_t();
1995 res->init(maxprec(this, &b));
1996 CVmObjBigNum::compute_diff_into(res->ext_, ext_, b.ext_);
1997 return res;
1998 }
1999
2000 /* multiplication */
2001 vbignum_t *operator *(long l) const
2002 {
2003 vbignum_t bl(l);
2004 return *this * bl;
2005 }
2006 vbignum_t *operator *(const vbignum_t &b) const
2007 {
2008 vbignum_t *res = new vbignum_t();
2009 res->init(maxprec(this, &b));
2010 CVmObjBigNum::compute_prod_into(res->ext_, ext_, b.ext_);
2011 return res;
2012 }
2013
2014 /* division */
2015 vbignum_t *operator /(long l) const
2016 {
2017 vbignum_t bl(l);
2018 return *this / bl;
2019 }
2020 vbignum_t *operator /(const vbignum_t &b) const
2021 {
2022 vbignum_t *res = new vbignum_t(), rem;
2023 res->init(maxprec(this, &b));
2024 rem.init(2);
2025 CVmObjBigNum::compute_quotient_into(res->ext_, rem.ext_, ext_, b.ext_);
2026 return res;
2027 }
2028
2029 /* remainder */
2030 vbignum_t *operator %(long l) const
2031 {
2032 vbignum_t bl(l);
2033 return *this % bl;
2034 }
2035 vbignum_t *operator %(const vbignum_t &b) const
2036 {
2037 vbignum_t *res = new vbignum_t(), quo;
2038 res->init(maxprec(this, &b));
2039 quo.init(2);
2040 CVmObjBigNum::compute_quotient_into(quo.ext_, res->ext_, ext_, b.ext_);
2041 return res;
2042 }
2043
2044 /* get the higher of two numbers' precisions */
2045 static int maxprec(const vbignum_t *a, const vbignum_t *b)
2046 { return a->prec() > b->prec() ? a->prec() : b->prec(); }
2047
2048 protected:
2049 /* create with no extension */
2050 vbignum_t() { ext_ = 0; }
2051
2052 /* initialize with a given precision, allocating the extension */
2053 void init(int prec)
2054 {
2055 ext_ = new char[CVmObjBigNum::calc_alloc(prec)];
2056 oswp2(ext_, prec);
2057 ext_[VMBN_FLAGS] = 0;
2058 }
2059
2060 /* extension buffer - allocated with new char[prec] */
2061 char *ext_;
2062 };
2063
2064 #endif /* VMBIGNUM_H */
2065
2066 /*
2067 * Register the class
2068 */
2069 VM_REGISTER_METACLASS(CVmObjBigNum)