3 * $Id: mptext.c,v 1.6 2000/06/25 12:58:23 mdw Exp $
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 /*----- Revision history --------------------------------------------------*
33 * Revision 1.6 2000/06/25 12:58:23 mdw
34 * Fix the derivation of `depth' commentary.
36 * Revision 1.5 2000/06/17 11:46:19 mdw
37 * New and much faster stack-based algorithm for reading integers. Support
38 * reading and writing binary integers in bases between 2 and 256.
40 * Revision 1.4 1999/12/22 15:56:56 mdw
41 * Use clever recursive algorithm for writing numbers out.
43 * Revision 1.3 1999/12/10 23:23:26 mdw
44 * Allocate slightly less memory.
46 * Revision 1.2 1999/11/20 22:24:15 mdw
47 * Use function versions of MPX_UMULN and MPX_UADDN.
49 * Revision 1.1 1999/11/17 18:02:16 mdw
50 * New multiprecision integer arithmetic suite.
54 /*----- Header files ------------------------------------------------------*/
64 /*----- Magical numbers ---------------------------------------------------*/
66 /* --- Maximum recursion depth --- *
68 * This is the number of bits in a @size_t@ object. Why?
70 * To see this, let %$b = \mathit{MPW\_MAX} + 1$% and let %$Z$% be the
71 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
72 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
73 * squares the radix at each step, the highest number reached by the
74 * recursion is %$d$%, where:
78 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
79 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
81 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
82 * overestimate, since a @size_t@ representation may contain `holes'.
83 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
84 * for `some time to come'.
87 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
89 /*----- Main code ---------------------------------------------------------*/
91 /* --- @mp_read@ --- *
93 * Arguments: @mp *m@ = destination multiprecision number
94 * @int radix@ = base to assume for data (or zero to guess)
95 * @const mptext_ops *ops@ = pointer to operations block
96 * @void *p@ = data for the operations block
98 * Returns: The integer read, or zero if it didn't work.
100 * Use: Reads an integer from some source. If the @radix@ is
101 * specified, the number is assumed to be given in that radix,
102 * with the letters `a' (either upper- or lower-case) upwards
103 * standing for digits greater than 9. Otherwise, base 10 is
104 * assumed unless the number starts with `0' (octal), `0x' (hex)
105 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
106 * before the number is ignored.
109 /* --- About the algorithm --- *
111 * The algorithm here is rather aggressive. I maintain an array of
112 * successive squarings of the radix, and a stack of partial results, each
113 * with a counter attached indicating which radix square to multiply by.
114 * Once the item at the top of the stack reaches the same counter level as
115 * the next item down, they are combined together and the result is given a
116 * counter level one higher than either of the results.
118 * Gluing the results together at the end is slightly tricky. Pay attention
121 * This is more complicated because of the need to handle the slightly
125 mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p)
127 int ch; /* Current char being considered */
128 unsigned f = 0; /* Flags about the current number */
129 int r; /* Radix to switch over to */
130 mpw rd; /* Radix as an @mp@ digit */
131 mp rr; /* The @mp@ for the radix */
132 unsigned nf = m ? m->f & MP_BURN : 0; /* New @mp@ flags */
136 mp *pow[DEPTH]; /* List of powers */
137 unsigned pows; /* Next index to fill */
138 struct { unsigned i; mp *m; } s[DEPTH]; /* Main stack */
139 unsigned sp; /* Current stack pointer */
148 /* --- Initialize the stacks --- */
150 mp_build(&rr, &rd, &rd + 1);
156 /* --- Initialize the destination number --- */
161 /* --- Read an initial character --- */
167 /* --- Handle an initial sign --- */
176 /* --- If the radix is zero, look for leading zeros --- */
179 assert(((void)"ascii radix must be <= 36", radix <= 36));
182 } else if (radix < 0) {
184 assert(((void)"binary radix must fit in a byte ", rd < UCHAR_MAX));
186 } else if (ch != '0') {
201 /* --- Time to start --- */
203 for (;; ch = ops->get(p)) {
206 /* --- An underscore indicates a numbered base --- */
208 if (ch == '_' && r > 0 && r <= 36) {
211 /* --- Clear out the stacks --- */
213 for (i = 1; i < pows; i++)
216 for (i = 0; i < sp; i++)
220 /* --- Restart the search --- */
228 /* --- Check that the character is a digit and in range --- */
235 if (ch >= '0' && ch <= '9')
239 if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */
246 /* --- Sort out what to do with the character --- */
248 if (x >= 10 && r >= 0)
256 /* --- Stick the character on the end of my integer --- */
258 assert(((void)"Number is too unimaginably huge", sp < DEPTH));
259 s[sp].m = m = mp_new(1, nf);
263 /* --- Now grind through the stack --- */
265 while (sp > 0 && s[sp - 1].i == s[sp].i) {
267 /* --- Combine the top two items --- */
271 m = mp_mul(m, m, pow[s[sp].i]);
272 m = mp_add(m, m, s[sp + 1].m);
274 MP_DROP(s[sp + 1].m);
277 /* --- Make a new radix power if necessary --- */
279 if (s[sp].i >= pows) {
280 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
281 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
291 /* --- If we're done, compute the rest of the number --- */
302 /* --- Combine the top two items --- */
306 z = mp_mul(z, z, pow[s[sp + 1].i]);
308 m = mp_add(m, m, s[sp + 1].m);
310 MP_DROP(s[sp + 1].m);
312 /* --- Make a new radix power if necessary --- */
314 if (s[sp].i >= pows) {
315 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
316 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
325 for (i = 0; i < sp; i++)
329 /* --- Clear the radix power list --- */
333 for (i = 1; i < pows; i++)
337 /* --- Bail out if the number was bad --- */
342 /* --- Set the sign and return --- */
349 /* --- @mp_write@ --- *
351 * Arguments: @mp *m@ = pointer to a multi-precision integer
352 * @int radix@ = radix to use when writing the number out
353 * @const mptext_ops *ops@ = pointer to an operations block
354 * @void *p@ = data for the operations block
356 * Returns: Zero if it worked, nonzero otherwise.
358 * Use: Writes a large integer in textual form.
361 /* --- Simple case --- *
363 * Use a fixed-sized buffer and the simple single-precision division
364 * algorithm to pick off low-order digits. Put each digit in a buffer,
365 * working backwards from the end. If the buffer becomes full, recurse to
366 * get another one. Ensure that there are at least @z@ digits by writing
367 * leading zeroes if there aren't enough real digits.
370 static int simple(mp *m, int radix, unsigned z,
371 const mptext_ops *ops, void *p)
375 unsigned i = sizeof(buf);
376 int rd = radix > 0 ? radix : -radix;
382 x = mpx_udivn(m->v, m->vl, m->v, m->vl, rd);
395 } while (i && MP_LEN(m));
398 rc = simple(m, radix, z, ops, p);
400 static const char zero[32] = "00000000000000000000000000000000";
401 while (!rc && z >= sizeof(zero)) {
402 rc = ops->put(zero, sizeof(zero), p);
406 rc = ops->put(zero, z, p);
409 ops->put(buf + i, sizeof(buf) - i, p);
415 /* --- Complicated case --- *
417 * If the number is small, fall back to the simple case above. Otherwise
418 * divide and take remainder by current large power of the radix, and emit
419 * each separately. Don't emit a zero quotient. Be very careful about
420 * leading zeroes on the remainder part, because they're deeply significant.
423 static int complicated(mp *m, int radix, mp **pr, unsigned i, unsigned z,
424 const mptext_ops *ops, void *p)
431 return (simple(m, radix, z, ops, p));
433 mp_div(&q, &m, m, pr[i]);
441 rc = complicated(q, radix, pr, i - 1, z, ops, p);
444 rc = complicated(m, radix, pr, i - 1, d, ops, p);
449 /* --- Main driver code --- */
451 int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
455 /* --- Set various things up --- */
460 /* --- Check the radix for sensibleness --- */
463 assert(((void)"ascii radix must be <= 36", radix <= 36));
465 assert(((void)"binary radix must fit in a byte", -radix < UCHAR_MAX));
467 assert(((void)"radix can't be zero in mp_write", 0));
469 /* --- If the number is negative, sort that out --- */
472 if (ops->put("-", 1, p))
477 /* --- If the number is small, do it the easy way --- */
480 rc = simple(m, radix, 0, ops, p);
482 /* --- Use a clever algorithm --- *
484 * Square the radix repeatedly, remembering old results, until I get
485 * something more than half the size of the number @m@. Use this to divide
486 * the number: the quotient and remainder will be approximately the same
487 * size, and I'll have split them on a digit boundary, so I can just emit
488 * the quotient and remainder recursively, in order.
493 size_t target = MP_LEN(m) / 2;
495 mp *z = mp_new(1, 0);
497 /* --- Set up the exponent table --- */
499 z->v[0] = (radix > 0 ? radix : -radix);
502 assert(((void)"Number is too unimaginably huge", i < DEPTH));
504 if (MP_LEN(z) > target)
506 z = mp_sqr(MP_NEW, z);
509 /* --- Write out the answer --- */
511 rc = complicated(m, radix, pr, i - 1, 0, ops, p);
513 /* --- Tidy away the array --- */
519 /* --- Tidying up code --- */
525 /*----- Test rig ----------------------------------------------------------*/
529 #include <mLib/testrig.h>
531 static int verify(dstr *v)
534 int ib = *(int *)v[0].buf, ob = *(int *)v[2].buf;
536 mp *m = mp_readdstr(MP_NEW, &v[1], 0, ib);
539 fprintf(stderr, "*** unexpected successful parse\n"
540 "*** input [%i] = ", ib);
542 type_hex.dump(&v[1], stderr);
544 fputs(v[1].buf, stderr);
545 mp_writedstr(m, &d, 10);
546 fprintf(stderr, "\n*** (value = %s)\n", d.buf);
549 mp_writedstr(m, &d, ob);
550 if (d.len != v[3].len || memcmp(d.buf, v[3].buf, d.len) != 0) {
551 fprintf(stderr, "*** failed read or write\n"
552 "*** input [%i] = ", ib);
554 type_hex.dump(&v[1], stderr);
556 fputs(v[1].buf, stderr);
557 fprintf(stderr, "\n*** output [%i] = ", ob);
559 type_hex.dump(&d, stderr);
561 fputs(d.buf, stderr);
562 fprintf(stderr, "\n*** expected [%i] = ", ob);
564 type_hex.dump(&v[3], stderr);
566 fputs(v[3].buf, stderr);
574 fprintf(stderr, "*** unexpected parse failure\n"
575 "*** input [%i] = ", ib);
577 type_hex.dump(&v[1], stderr);
579 fputs(v[1].buf, stderr);
580 fprintf(stderr, "\n*** expected [%i] = ", ob);
582 type_hex.dump(&v[3], stderr);
584 fputs(v[3].buf, stderr);
591 assert(mparena_count(MPARENA_GLOBAL) == 0);
595 static test_chunk tests[] = {
596 { "mptext-ascii", verify,
597 { &type_int, &type_string, &type_int, &type_string, 0 } },
598 { "mptext-bin-in", verify,
599 { &type_int, &type_hex, &type_int, &type_string, 0 } },
600 { "mptext-bin-out", verify,
601 { &type_int, &type_string, &type_int, &type_hex, 0 } },
605 int main(int argc, char *argv[])
608 test_run(argc, argv, tests, SRCDIR "/tests/mptext");
614 /*----- That's all, folks -------------------------------------------------*/