5 * Textual representation of multiprecision numbers
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of Catacomb.
14 * Catacomb is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
19 * Catacomb is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
24 * You should have received a copy of the GNU Library General Public
25 * License along with Catacomb; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
30 /*----- Header files ------------------------------------------------------*/
40 /*----- Magical numbers ---------------------------------------------------*/
42 /* --- Maximum recursion depth --- *
44 * This is the number of bits in a @size_t@ object. Why?
46 * To see this, let %$b = \textit{MPW\_MAX} + 1$% and let %$Z$% be the
47 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
48 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
49 * squares the radix at each step, the highest number reached by the
50 * recursion is %$d$%, where:
54 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
55 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
57 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
58 * overestimate, since a @size_t@ representation may contain `holes'.
59 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
60 * for `some time to come'.
63 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
65 /*----- Main code ---------------------------------------------------------*/
67 /* --- @mp_read@ --- *
69 * Arguments: @mp *m@ = destination multiprecision number
70 * @int radix@ = base to assume for data (or zero to guess)
71 * @const mptext_ops *ops@ = pointer to operations block
72 * @void *p@ = data for the operations block
74 * Returns: The integer read, or zero if it didn't work.
76 * Use: Reads an integer from some source. If the @radix@ is
77 * specified, the number is assumed to be given in that radix,
78 * with the letters `a' (either upper- or lower-case) upwards
79 * standing for digits greater than 9. Otherwise, base 10 is
80 * assumed unless the number starts with `0' (octal), `0x' (hex)
81 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
82 * before the number is ignored.
85 /* --- About the algorithm --- *
87 * The algorithm here is rather aggressive. I maintain an array of
88 * successive squarings of the radix, and a stack of partial results, each
89 * with a counter attached indicating which radix square to multiply by.
90 * Once the item at the top of the stack reaches the same counter level as
91 * the next item down, they are combined together and the result is given a
92 * counter level one higher than either of the results.
94 * Gluing the results together at the end is slightly tricky. Pay attention
97 * This is more complicated because of the need to handle the slightly
101 mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p)
103 int ch; /* Current char being considered */
104 unsigned f = 0; /* Flags about the current number */
105 int r; /* Radix to switch over to */
106 mpw rd; /* Radix as an @mp@ digit */
107 mp rr; /* The @mp@ for the radix */
108 unsigned nf = m ? m->f & MP_BURN : 0; /* New @mp@ flags */
112 mp *pow[DEPTH]; /* List of powers */
113 unsigned pows; /* Next index to fill */
114 struct { unsigned i; mp *m; } s[DEPTH]; /* Main stack */
115 unsigned sp; /* Current stack pointer */
123 /* --- Initialize the stacks --- */
125 mp_build(&rr, &rd, &rd + 1);
131 /* --- Initialize the destination number --- */
136 /* --- Read an initial character --- */
144 /* --- Handle an initial sign --- */
146 if (radix >= 0 && (ch == '-' || ch == '+')) {
149 do ch = ops->get(p); while isspace(ch);
152 /* --- If the radix is zero, look for leading zeros --- */
155 assert(((void)"ascii radix must be <= 62", radix <= 62));
158 } else if (radix < 0) {
160 assert(((void)"binary radix must fit in a byte", rd <= UCHAR_MAX));
162 } else if (ch != '0') {
187 /* --- Use fast algorithm for binary radix --- *
189 * This is the restart point after having parsed a radix number from the
190 * input. We check whether the radix is binary, and if so use a fast
191 * algorithm which just stacks the bits up in the right order.
198 case 2: bit = 1; goto bin;
199 case 4: bit = 2; goto bin;
200 case 8: bit = 3; goto bin;
201 case 16: bit = 4; goto bin;
202 case 32: bit = 5; goto bin;
203 case 64: bit = 6; goto bin;
204 case 128: bit = 7; goto bin;
208 /* --- The fast binary algorithm --- *
210 * We stack bits up starting at the top end of a word. When one word is
211 * full, we write it to the integer, and start another with the left-over
212 * bits. When the array in the integer is full, we resize using low-level
213 * calls and copy the current data to the top end. Finally, we do a single
214 * bit-shift when we know where the end of the number is.
219 unsigned b = MPW_BITS;
223 m = mp_dest(MP_NEW, 1, nf);
227 for (;; ch = ops->get(p)) {
233 /* --- Check that the character is a digit and in range --- */
240 if (ch >= '0' && ch <= '9')
245 if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */
247 else if (ch >= 'A' && ch <= 'Z')
256 /* --- Feed the digit into the accumulator --- */
259 if (!x && !(f & f_start))
266 a |= MPW(x) >> (bit - b);
273 v = mpalloc(m->a, len);
274 memcpy(v + n, m->v, MPWS(n));
279 a = (b < MPW_BITS) ? MPW(x) << b : 0;
283 /* --- Finish up --- */
294 m = mp_lsr(m, m, (unsigned long)n * MPW_BITS + b);
300 /* --- Time to start --- */
302 for (;; ch = ops->get(p)) {
308 /* --- An underscore indicates a numbered base --- */
310 if (ch == '_' && r > 0 && r <= 62) {
313 /* --- Clear out the stacks --- */
315 for (i = 1; i < pows; i++)
318 for (i = 0; i < sp; i++)
322 /* --- Restart the search --- */
331 /* --- Check that the character is a digit and in range --- */
338 if (ch >= '0' && ch <= '9')
343 if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */
345 else if (ch >= 'A' && ch <= 'Z')
352 /* --- Sort out what to do with the character --- */
354 if (x >= 10 && r >= 0)
362 /* --- Stick the character on the end of my integer --- */
364 assert(((void)"Number is too unimaginably huge", sp < DEPTH));
365 s[sp].m = m = mp_new(1, nf);
369 /* --- Now grind through the stack --- */
371 while (sp > 0 && s[sp - 1].i == s[sp].i) {
373 /* --- Combine the top two items --- */
377 m = mp_mul(m, m, pow[s[sp].i]);
378 m = mp_add(m, m, s[sp + 1].m);
380 MP_DROP(s[sp + 1].m);
383 /* --- Make a new radix power if necessary --- */
385 if (s[sp].i >= pows) {
386 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
387 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
397 /* --- If we're done, compute the rest of the number --- */
408 /* --- Combine the top two items --- */
412 z = mp_mul(z, z, pow[s[sp + 1].i]);
414 m = mp_add(m, m, s[sp + 1].m);
416 MP_DROP(s[sp + 1].m);
418 /* --- Make a new radix power if necessary --- */
420 if (s[sp].i >= pows) {
421 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
422 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
431 for (i = 0; i < sp; i++)
435 /* --- Clear the radix power list --- */
439 for (i = 1; i < pows; i++)
443 /* --- Bail out if the number was bad --- */
449 /* --- Set the sign and return --- */
461 /* --- @mp_write@ --- *
463 * Arguments: @mp *m@ = pointer to a multi-precision integer
464 * @int radix@ = radix to use when writing the number out
465 * @const mptext_ops *ops@ = pointer to an operations block
466 * @void *p@ = data for the operations block
468 * Returns: Zero if it worked, nonzero otherwise.
470 * Use: Writes a large integer in textual form.
473 /* --- Simple case --- *
475 * Use a fixed-sized buffer and single-precision arithmetic to pick off
476 * low-order digits. Put each digit in a buffer, working backwards from the
477 * end. If the buffer becomes full, recurse to get another one. Ensure that
478 * there are at least @z@ digits by writing leading zeroes if there aren't
479 * enough real digits.
482 static int simple(mpw n, int radix, unsigned z,
483 const mptext_ops *ops, void *p)
487 unsigned i = sizeof(buf);
488 int rd = radix > 0 ? radix : -radix;
500 else if (x < 36) /* Ascii specific */
510 rc = simple(n, radix, z, ops, p);
513 memset(zbuf, (radix < 0) ? 0 : '0', sizeof(zbuf));
514 while (!rc && z >= sizeof(zbuf)) {
515 rc = ops->put(zbuf, sizeof(zbuf), p);
519 rc = ops->put(zbuf, z, p);
522 rc = ops->put(buf + i, sizeof(buf) - i, p);
527 /* --- Complicated case --- *
529 * If the number is small, fall back to the simple case above. Otherwise
530 * divide and take remainder by current large power of the radix, and emit
531 * each separately. Don't emit a zero quotient. Be very careful about
532 * leading zeroes on the remainder part, because they're deeply significant.
535 static int complicated(mp *m, int radix, mp **pr, unsigned i, unsigned z,
536 const mptext_ops *ops, void *p)
543 return (simple(MP_LEN(m) ? m->v[0] : 0, radix, z, ops, p));
546 mp_div(&q, &m, m, pr[i]);
554 rc = complicated(q, radix, pr, i - 1, z, ops, p);
557 rc = complicated(m, radix, pr, i - 1, d, ops, p);
562 /* --- Binary case --- *
564 * Special case for binary output. Goes much faster.
567 static int binary(mp *m, int bit, int radix, const mptext_ops *ops, void *p)
582 /* --- Work out where to start --- */
586 n += bit - (n % bit);
590 if (n >= MP_LEN(m)) {
597 mask = (1 << bit) - 1;
600 /* --- Main code --- */
616 if (!x && !(f & f_out))
624 ch = 'a' + x - 10; /* Ascii specific */
628 if (q >= buf + sizeof(buf)) {
629 if ((rc = ops->put(buf, sizeof(buf), p)) != 0)
642 ch = 'a' + x - 10; /* Ascii specific */
646 rc = ops->put(buf, q - buf, p);
655 /* --- Main driver code --- */
657 int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
661 if (MP_EQ(m, MP_ZERO))
662 return (ops->put(radix > 0 ? "0" : "\0", 1, p));
664 /* --- Set various things up --- */
669 /* --- Check the radix for sensibleness --- */
672 assert(((void)"ascii radix must be <= 62", radix <= 62));
674 assert(((void)"binary radix must fit in a byte", -radix <= UCHAR_MAX));
676 assert(((void)"radix can't be zero in mp_write", 0));
678 /* --- If the number is negative, sort that out --- */
682 if (ops->put("-", 1, p))
687 /* --- Handle binary radix --- */
690 case 2: case -2: return (binary(m, 1, radix, ops, p));
691 case 4: case -4: return (binary(m, 2, radix, ops, p));
692 case 8: case -8: return (binary(m, 3, radix, ops, p));
693 case 16: case -16: return (binary(m, 4, radix, ops, p));
694 case 32: case -32: return (binary(m, 5, radix, ops, p));
695 case -64: return (binary(m, 6, radix, ops, p));
696 case -128: return (binary(m, 7, radix, ops, p));
699 /* --- If the number is small, do it the easy way --- */
702 rc = simple(MP_LEN(m) ? m->v[0] : 0, radix, 0, ops, p);
704 /* --- Use a clever algorithm --- *
706 * Square the radix repeatedly, remembering old results, until I get
707 * something more than half the size of the number @m@. Use this to divide
708 * the number: the quotient and remainder will be approximately the same
709 * size, and I'll have split them on a digit boundary, so I can just emit
710 * the quotient and remainder recursively, in order.
715 size_t target = (MP_LEN(m) + 1) / 2;
717 mp *z = mp_new(1, 0);
719 /* --- Set up the exponent table --- */
721 z->v[0] = (radix > 0 ? radix : -radix);
724 assert(((void)"Number is too unimaginably huge", i < DEPTH));
726 if (MP_LEN(z) > target)
728 z = mp_sqr(MP_NEW, z);
731 /* --- Write out the answer --- */
733 rc = complicated(m, radix, pr, i - 1, 0, ops, p);
735 /* --- Tidy away the array --- */
741 /* --- Tidying up code --- */
747 /*----- Test rig ----------------------------------------------------------*/
751 #include <mLib/testrig.h>
753 static int verify(dstr *v)
756 int ib = *(int *)v[0].buf, ob = *(int *)v[2].buf;
759 mp *m = mp_readdstr(MP_NEW, &v[1], &off, ib);
762 fprintf(stderr, "*** unexpected successful parse\n"
763 "*** input [%2i] = ", ib);
765 type_hex.dump(&v[1], stderr);
767 fputs(v[1].buf, stderr);
768 mp_writedstr(m, &d, 10);
769 fprintf(stderr, "\n*** (value = %s)\n", d.buf);
772 mp_writedstr(m, &d, ob);
773 if (d.len != v[3].len || memcmp(d.buf, v[3].buf, d.len) != 0) {
774 fprintf(stderr, "*** failed read or write\n"
775 "*** input [%2i] = ", ib);
777 type_hex.dump(&v[1], stderr);
779 fputs(v[1].buf, stderr);
780 fprintf(stderr, "\n*** output [%2i] = ", ob);
782 type_hex.dump(&d, stderr);
784 fputs(d.buf, stderr);
785 fprintf(stderr, "\n*** expected [%2i] = ", ob);
787 type_hex.dump(&v[3], stderr);
789 fputs(v[3].buf, stderr);
797 fprintf(stderr, "*** unexpected parse failure\n"
798 "*** input [%2i] = ", ib);
800 type_hex.dump(&v[1], stderr);
802 fputs(v[1].buf, stderr);
803 fprintf(stderr, "\n*** expected [%2i] = ", ob);
805 type_hex.dump(&v[3], stderr);
807 fputs(v[3].buf, stderr);
813 if (v[1].len - off != v[4].len ||
814 memcmp(v[1].buf + off, v[4].buf, v[4].len) != 0) {
815 fprintf(stderr, "*** leftovers incorrect\n"
816 "*** input [%2i] = ", ib);
818 type_hex.dump(&v[1], stderr);
820 fputs(v[1].buf, stderr);
821 fprintf(stderr, "\n*** expected `%s'\n"
823 v[4].buf, v[1].buf + off);
828 assert(mparena_count(MPARENA_GLOBAL) == 0);
832 static test_chunk tests[] = {
833 { "mptext-ascii", verify,
834 { &type_int, &type_string, &type_int, &type_string, &type_string, 0 } },
835 { "mptext-bin-in", verify,
836 { &type_int, &type_hex, &type_int, &type_string, &type_string, 0 } },
837 { "mptext-bin-out", verify,
838 { &type_int, &type_string, &type_int, &type_hex, &type_string, 0 } },
842 int main(int argc, char *argv[])
845 test_run(argc, argv, tests, SRCDIR "/tests/mptext");
851 /*----- That's all, folks -------------------------------------------------*/