Allow user-specified `r_xx' bases to be up to 62.
[u/mdw/catacomb] / mptext.c
CommitLineData
d3409d5e 1/* -*-c-*-
2 *
6ea6fe51 3 * $Id: mptext.c,v 1.13 2002/10/09 00:21:06 mdw Exp $
d3409d5e 4 *
5 * Textual representation of multiprecision numbers
6 *
7 * (c) 1999 Straylight/Edgeware
8 */
9
10/*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Catacomb.
13 *
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.
18 *
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.
23 *
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,
27 * MA 02111-1307, USA.
28 */
29
30/*----- Revision history --------------------------------------------------*
31 *
32 * $Log: mptext.c,v $
6ea6fe51 33 * Revision 1.13 2002/10/09 00:21:06 mdw
34 * Allow user-specified `r_xx' bases to be up to 62.
35 *
631673a1 36 * Revision 1.12 2002/01/13 19:51:18 mdw
37 * Extend the textual format to bases up to 62 by distinguishing case.
38 *
eaa515d8 39 * Revision 1.11 2001/06/16 23:42:17 mdw
40 * Typesetting fixes.
41 *
a951033d 42 * Revision 1.10 2001/06/16 13:22:39 mdw
43 * Added fast-track code for binary output bases, and tests.
44 *
3bc9cb53 45 * Revision 1.9 2001/02/03 16:05:17 mdw
46 * Make flags be unsigned. Improve the write algorithm: recurse until the
47 * parts are one word long and use single-precision arithmetic from there.
48 * Fix off-by-one bug when breaking the number apart.
49 *
9d3838a0 50 * Revision 1.8 2000/12/06 20:32:42 mdw
51 * Reduce binary bytes (to allow marker bits to be ignored). Fix error
52 * message string a bit. Allow leading `+' signs.
53 *
7d45ed6c 54 * Revision 1.7 2000/07/15 10:01:08 mdw
55 * Bug fix in binary input.
56 *
dd9199f0 57 * Revision 1.6 2000/06/25 12:58:23 mdw
58 * Fix the derivation of `depth' commentary.
59 *
2b26f2d7 60 * Revision 1.5 2000/06/17 11:46:19 mdw
61 * New and much faster stack-based algorithm for reading integers. Support
62 * reading and writing binary integers in bases between 2 and 256.
63 *
e360a4f2 64 * Revision 1.4 1999/12/22 15:56:56 mdw
65 * Use clever recursive algorithm for writing numbers out.
66 *
9c3df6c0 67 * Revision 1.3 1999/12/10 23:23:26 mdw
68 * Allocate slightly less memory.
69 *
90b6f0be 70 * Revision 1.2 1999/11/20 22:24:15 mdw
71 * Use function versions of MPX_UMULN and MPX_UADDN.
72 *
d3409d5e 73 * Revision 1.1 1999/11/17 18:02:16 mdw
74 * New multiprecision integer arithmetic suite.
75 *
76 */
77
78/*----- Header files ------------------------------------------------------*/
79
80#include <ctype.h>
2b26f2d7 81#include <limits.h>
d3409d5e 82#include <stdio.h>
83
d3409d5e 84#include "mp.h"
85#include "mptext.h"
e360a4f2 86#include "paranoia.h"
d3409d5e 87
2b26f2d7 88/*----- Magical numbers ---------------------------------------------------*/
89
90/* --- Maximum recursion depth --- *
91 *
92 * This is the number of bits in a @size_t@ object. Why?
93 *
eaa515d8 94 * To see this, let %$b = \textit{MPW\_MAX} + 1$% and let %$Z$% be the
dd9199f0 95 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
96 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
97 * squares the radix at each step, the highest number reached by the
98 * recursion is %$d$%, where:
2b26f2d7 99 *
dd9199f0 100 * %$r^{2^d} = b^Z$%.
2b26f2d7 101 *
102 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
103 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
104 *
105 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
106 * overestimate, since a @size_t@ representation may contain `holes'.
107 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
108 * for `some time to come'.
109 */
110
111#define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
112
d3409d5e 113/*----- Main code ---------------------------------------------------------*/
114
115/* --- @mp_read@ --- *
116 *
117 * Arguments: @mp *m@ = destination multiprecision number
118 * @int radix@ = base to assume for data (or zero to guess)
119 * @const mptext_ops *ops@ = pointer to operations block
120 * @void *p@ = data for the operations block
121 *
122 * Returns: The integer read, or zero if it didn't work.
123 *
124 * Use: Reads an integer from some source. If the @radix@ is
125 * specified, the number is assumed to be given in that radix,
126 * with the letters `a' (either upper- or lower-case) upwards
127 * standing for digits greater than 9. Otherwise, base 10 is
128 * assumed unless the number starts with `0' (octal), `0x' (hex)
129 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
130 * before the number is ignored.
131 */
132
2b26f2d7 133/* --- About the algorithm --- *
134 *
135 * The algorithm here is rather aggressive. I maintain an array of
136 * successive squarings of the radix, and a stack of partial results, each
137 * with a counter attached indicating which radix square to multiply by.
138 * Once the item at the top of the stack reaches the same counter level as
139 * the next item down, they are combined together and the result is given a
140 * counter level one higher than either of the results.
141 *
142 * Gluing the results together at the end is slightly tricky. Pay attention
143 * to the code.
144 *
145 * This is more complicated because of the need to handle the slightly
146 * bizarre syntax.
147 */
148
d3409d5e 149mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p)
150{
2b26f2d7 151 int ch; /* Current char being considered */
152 unsigned f = 0; /* Flags about the current number */
153 int r; /* Radix to switch over to */
154 mpw rd; /* Radix as an @mp@ digit */
155 mp rr; /* The @mp@ for the radix */
156 unsigned nf = m ? m->f & MP_BURN : 0; /* New @mp@ flags */
157
158 /* --- Stacks --- */
159
160 mp *pow[DEPTH]; /* List of powers */
161 unsigned pows; /* Next index to fill */
162 struct { unsigned i; mp *m; } s[DEPTH]; /* Main stack */
163 unsigned sp; /* Current stack pointer */
164
165 /* --- Flags --- */
d3409d5e 166
3bc9cb53 167#define f_neg 1u
168#define f_ok 2u
a951033d 169#define f_start 4u
d3409d5e 170
2b26f2d7 171 /* --- Initialize the stacks --- */
172
173 mp_build(&rr, &rd, &rd + 1);
174 pow[0] = &rr;
175 pows = 1;
176
177 sp = 0;
178
d3409d5e 179 /* --- Initialize the destination number --- */
180
2b26f2d7 181 if (m)
182 MP_DROP(m);
d3409d5e 183
184 /* --- Read an initial character --- */
185
186 ch = ops->get(p);
187 while (isspace(ch))
188 ch = ops->get(p);
189
190 /* --- Handle an initial sign --- */
191
9d3838a0 192 if (radix >= 0 && (ch == '-' || ch == '+')) {
193 if (ch == '-')
194 f |= f_neg;
195 do ch = ops->get(p); while isspace(ch);
d3409d5e 196 }
197
198 /* --- If the radix is zero, look for leading zeros --- */
199
2b26f2d7 200 if (radix > 0) {
631673a1 201 assert(((void)"ascii radix must be <= 62", radix <= 62));
2b26f2d7 202 rd = radix;
203 r = -1;
204 } else if (radix < 0) {
205 rd = -radix;
9d3838a0 206 assert(((void)"binary radix must fit in a byte", rd < UCHAR_MAX));
d3409d5e 207 r = -1;
2b26f2d7 208 } else if (ch != '0') {
209 rd = 10;
d3409d5e 210 r = 0;
211 } else {
212 ch = ops->get(p);
213 if (ch == 'x') {
214 ch = ops->get(p);
2b26f2d7 215 rd = 16;
d3409d5e 216 } else {
2b26f2d7 217 rd = 8;
d3409d5e 218 f |= f_ok;
219 }
220 r = -1;
221 }
222
a951033d 223 /* --- Use fast algorithm for binary radix --- *
224 *
225 * This is the restart point after having parsed a radix number from the
226 * input. We check whether the radix is binary, and if so use a fast
227 * algorithm which just stacks the bits up in the right order.
228 */
229
230restart:
231 switch (rd) {
232 unsigned bit;
233
234 case 2: bit = 1; goto bin;
235 case 4: bit = 2; goto bin;
236 case 8: bit = 3; goto bin;
237 case 16: bit = 4; goto bin;
238 case 32: bit = 5; goto bin;
239 case 64: bit = 6; goto bin;
240 case 128: bit = 7; goto bin;
241 default:
242 break;
243
244 /* --- The fast binary algorithm --- *
245 *
246 * We stack bits up starting at the top end of a word. When one word is
247 * full, we write it to the integer, and start another with the left-over
248 * bits. When the array in the integer is full, we resize using low-level
249 * calls and copy the current data to the top end. Finally, we do a single
250 * bit-shift when we know where the end of the number is.
251 */
252
253 bin: {
254 mpw a = 0;
255 unsigned b = MPW_BITS;
256 size_t len, n;
257 mpw *v;
258
259 m = mp_dest(MP_NEW, 1, nf);
260 len = n = m->sz;
261 n = len;
262 v = m->v + n;
263 for (;; ch = ops->get(p)) {
264 unsigned x;
265
266 if (ch < 0)
267 break;
268
269 /* --- Check that the character is a digit and in range --- */
270
271 if (radix < 0)
272 x = ch % rd;
273 else {
274 if (!isalnum(ch))
275 break;
276 if (ch >= '0' && ch <= '9')
277 x = ch - '0';
278 else {
631673a1 279 if (rd <= 36)
280 ch = tolower(ch);
a951033d 281 if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */
282 x = ch - 'a' + 10;
631673a1 283 else if (ch >= 'A' && ch <= 'Z')
284 x = ch - 'A' + 36;
a951033d 285 else
286 break;
287 }
288 }
289 if (x >= rd)
290 break;
291
292 /* --- Feed the digit into the accumulator --- */
293
294 f |= f_ok;
295 if (!x && !(f & f_start))
296 continue;
297 f |= f_start;
298 if (b > bit) {
299 b -= bit;
300 a |= MPW(x) << b;
301 } else {
302 a |= MPW(x) >> (bit - b);
303 b += MPW_BITS - bit;
304 *--v = MPW(a);
305 n--;
306 if (!n) {
307 n = len;
308 len <<= 1;
309 v = mpalloc(m->a, len);
310 memcpy(v + n, m->v, MPWS(n));
311 mpfree(m->a, m->v);
312 m->v = v;
313 v = m->v + n;
314 }
315 a = (b < MPW_BITS) ? MPW(x) << b : 0;
316 }
317 }
318
319 /* --- Finish up --- */
320
321 if (!(f & f_ok)) {
322 mp_drop(m);
323 m = 0;
324 } else {
325 *--v = MPW(a);
326 n--;
327 m->sz = len;
328 m->vl = m->v + len;
329 m->f &= ~MP_UNDEF;
330 m = mp_lsr(m, m, (unsigned long)n * MPW_BITS + b);
331 }
332 goto done;
333 }}
334
d3409d5e 335 /* --- Time to start --- */
336
337 for (;; ch = ops->get(p)) {
a951033d 338 unsigned x;
d3409d5e 339
7d45ed6c 340 if (ch < 0)
341 break;
342
d3409d5e 343 /* --- An underscore indicates a numbered base --- */
344
6ea6fe51 345 if (ch == '_' && r > 0 && r <= 62) {
2b26f2d7 346 unsigned i;
347
348 /* --- Clear out the stacks --- */
349
350 for (i = 1; i < pows; i++)
351 MP_DROP(pow[i]);
352 pows = 1;
353 for (i = 0; i < sp; i++)
354 MP_DROP(s[i].m);
355 sp = 0;
356
357 /* --- Restart the search --- */
358
359 rd = r;
d3409d5e 360 r = -1;
361 f &= ~f_ok;
a951033d 362 ch = ops->get(p);
363 goto restart;
d3409d5e 364 }
365
366 /* --- Check that the character is a digit and in range --- */
367
2b26f2d7 368 if (radix < 0)
9d3838a0 369 x = ch % rd;
d3409d5e 370 else {
2b26f2d7 371 if (!isalnum(ch))
d3409d5e 372 break;
2b26f2d7 373 if (ch >= '0' && ch <= '9')
374 x = ch - '0';
375 else {
631673a1 376 if (rd <= 36)
377 ch = tolower(ch);
2b26f2d7 378 if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */
379 x = ch - 'a' + 10;
631673a1 380 else if (ch >= 'A' && ch <= 'Z')
381 x = ch - 'A' + 36;
2b26f2d7 382 else
383 break;
384 }
d3409d5e 385 }
386
387 /* --- Sort out what to do with the character --- */
388
389 if (x >= 10 && r >= 0)
390 r = -1;
2b26f2d7 391 if (x >= rd)
d3409d5e 392 break;
393
394 if (r >= 0)
395 r = r * 10 + x;
396
397 /* --- Stick the character on the end of my integer --- */
398
2b26f2d7 399 assert(((void)"Number is too unimaginably huge", sp < DEPTH));
400 s[sp].m = m = mp_new(1, nf);
401 m->v[0] = x;
402 s[sp].i = 0;
403
404 /* --- Now grind through the stack --- */
405
406 while (sp > 0 && s[sp - 1].i == s[sp].i) {
407
408 /* --- Combine the top two items --- */
409
410 sp--;
411 m = s[sp].m;
412 m = mp_mul(m, m, pow[s[sp].i]);
413 m = mp_add(m, m, s[sp + 1].m);
414 s[sp].m = m;
415 MP_DROP(s[sp + 1].m);
416 s[sp].i++;
417
418 /* --- Make a new radix power if necessary --- */
419
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]);
423 pows++;
424 }
425 }
d3409d5e 426 f |= f_ok;
2b26f2d7 427 sp++;
d3409d5e 428 }
429
430 ops->unget(ch, p);
431
2b26f2d7 432 /* --- If we're done, compute the rest of the number --- */
433
434 if (f & f_ok) {
435 if (!sp)
436 return (MP_ZERO);
437 else {
438 mp *z = MP_ONE;
439 sp--;
440
441 while (sp > 0) {
442
443 /* --- Combine the top two items --- */
444
445 sp--;
446 m = s[sp].m;
447 z = mp_mul(z, z, pow[s[sp + 1].i]);
448 m = mp_mul(m, m, z);
449 m = mp_add(m, m, s[sp + 1].m);
450 s[sp].m = m;
451 MP_DROP(s[sp + 1].m);
452
453 /* --- Make a new radix power if necessary --- */
454
455 if (s[sp].i >= pows) {
456 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
457 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
458 pows++;
459 }
460 }
461 MP_DROP(z);
462 m = s[0].m;
463 }
464 } else {
465 unsigned i;
466 for (i = 0; i < sp; i++)
467 MP_DROP(s[i].m);
468 }
469
470 /* --- Clear the radix power list --- */
471
472 {
473 unsigned i;
474 for (i = 1; i < pows; i++)
475 MP_DROP(pow[i]);
476 }
477
d3409d5e 478 /* --- Bail out if the number was bad --- */
479
a951033d 480done:
2b26f2d7 481 if (!(f & f_ok))
d3409d5e 482 return (0);
d3409d5e 483
484 /* --- Set the sign and return --- */
485
d3409d5e 486 if (f & f_neg)
487 m->f |= MP_NEG;
488 return (m);
3bc9cb53 489
a951033d 490#undef f_start
3bc9cb53 491#undef f_neg
492#undef f_ok
d3409d5e 493}
494
495/* --- @mp_write@ --- *
496 *
497 * Arguments: @mp *m@ = pointer to a multi-precision integer
498 * @int radix@ = radix to use when writing the number out
499 * @const mptext_ops *ops@ = pointer to an operations block
500 * @void *p@ = data for the operations block
501 *
502 * Returns: Zero if it worked, nonzero otherwise.
503 *
504 * Use: Writes a large integer in textual form.
505 */
506
e360a4f2 507/* --- Simple case --- *
508 *
3bc9cb53 509 * Use a fixed-sized buffer and single-precision arithmetic to pick off
510 * low-order digits. Put each digit in a buffer, working backwards from the
511 * end. If the buffer becomes full, recurse to get another one. Ensure that
512 * there are at least @z@ digits by writing leading zeroes if there aren't
513 * enough real digits.
e360a4f2 514 */
515
3bc9cb53 516static int simple(mpw n, int radix, unsigned z,
e360a4f2 517 const mptext_ops *ops, void *p)
518{
519 int rc = 0;
520 char buf[64];
521 unsigned i = sizeof(buf);
2b26f2d7 522 int rd = radix > 0 ? radix : -radix;
e360a4f2 523
524 do {
525 int ch;
526 mpw x;
527
3bc9cb53 528 x = n % rd;
529 n /= rd;
2b26f2d7 530 if (radix < 0)
531 ch = x;
3bc9cb53 532 else if (x < 10)
533 ch = '0' + x;
631673a1 534 else if (x < 36) /* Ascii specific */
3bc9cb53 535 ch = 'a' + x - 10;
631673a1 536 else
537 ch = 'A' + x - 36;
e360a4f2 538 buf[--i] = ch;
539 if (z)
540 z--;
3bc9cb53 541 } while (i && n);
e360a4f2 542
3bc9cb53 543 if (n)
544 rc = simple(n, radix, z, ops, p);
e360a4f2 545 else {
a951033d 546 char zbuf[32];
547 memset(zbuf, (radix < 0) ? 0 : '0', sizeof(zbuf));
548 while (!rc && z >= sizeof(zbuf)) {
549 rc = ops->put(zbuf, sizeof(zbuf), p);
550 z -= sizeof(zbuf);
e360a4f2 551 }
552 if (!rc && z)
a951033d 553 rc = ops->put(zbuf, z, p);
e360a4f2 554 }
555 if (!rc)
3bc9cb53 556 rc = ops->put(buf + i, sizeof(buf) - i, p);
557 BURN(buf);
e360a4f2 558 return (rc);
559}
560
561/* --- Complicated case --- *
562 *
563 * If the number is small, fall back to the simple case above. Otherwise
564 * divide and take remainder by current large power of the radix, and emit
565 * each separately. Don't emit a zero quotient. Be very careful about
566 * leading zeroes on the remainder part, because they're deeply significant.
567 */
568
569static int complicated(mp *m, int radix, mp **pr, unsigned i, unsigned z,
570 const mptext_ops *ops, void *p)
571{
572 int rc = 0;
573 mp *q = MP_NEW;
574 unsigned d = 1 << i;
575
3bc9cb53 576 if (MP_LEN(m) < 2)
577 return (simple(MP_LEN(m) ? m->v[0] : 0, radix, z, ops, p));
e360a4f2 578
3bc9cb53 579 assert(i);
e360a4f2 580 mp_div(&q, &m, m, pr[i]);
581 if (!MP_LEN(q))
582 d = z;
583 else {
584 if (z > d)
585 z -= d;
586 else
587 z = 0;
588 rc = complicated(q, radix, pr, i - 1, z, ops, p);
589 }
590 if (!rc)
591 rc = complicated(m, radix, pr, i - 1, d, ops, p);
592 mp_drop(q);
593 return (rc);
594}
595
a951033d 596/* --- Binary case --- *
597 *
598 * Special case for binary output. Goes much faster.
599 */
600
601static int binary(mp *m, int bit, int radix, const mptext_ops *ops, void *p)
602{
603 mpw *v;
604 mpw a;
605 int rc = 0;
606 unsigned b;
607 unsigned mask;
608 unsigned long n;
609 unsigned f = 0;
610 char buf[8], *q;
611 unsigned x;
612 int ch;
613
614#define f_out 1u
615
616 /* --- Work out where to start --- */
617
618 n = mp_bits(m);
619 n += bit - (n % bit);
620 b = n % MPW_BITS;
621 n /= MPW_BITS;
622
623 if (n > MP_LEN(m)) {
624 n--;
625 b += MPW_BITS;
626 }
627
628 v = m->v + n;
629 a = *v;
630 mask = (1 << bit) - 1;
631 q = buf;
632
633 /* --- Main code --- */
634
635 for (;;) {
636 if (b > bit) {
637 b -= bit;
638 x = a >> b;
639 } else {
640 x = a << (bit - b);
641 b += MPW_BITS - bit;
642 if (v == m->v)
643 break;
644 a = *--v;
645 if (b < MPW_BITS)
646 x |= a >> b;
647 }
648 x &= mask;
649 if (!x && !(f & f_out))
650 continue;
651
652 if (radix < 0)
653 ch = x;
654 else if (x < 10)
655 ch = '0' + x;
631673a1 656 else if (x < 36)
657 ch = 'a' + x - 10; /* Ascii specific */
a951033d 658 else
631673a1 659 ch = 'A' + x - 36;
a951033d 660 *q++ = ch;
661 if (q >= buf + sizeof(buf)) {
662 if ((rc = ops->put(buf, sizeof(buf), p)) != 0)
663 goto done;
664 q = buf;
665 }
666 f |= f_out;
667 }
668
669 x &= mask;
670 if (radix < 0)
671 ch = x;
672 else if (x < 10)
673 ch = '0' + x;
631673a1 674 else if (x < 36)
675 ch = 'a' + x - 10; /* Ascii specific */
a951033d 676 else
631673a1 677 ch = 'A' + x - 36;
a951033d 678 *q++ = ch;
679 rc = ops->put(buf, q - buf, p);
680
681done:
682 mp_drop(m);
683 return (rc);
684
685#undef f_out
686}
687
e360a4f2 688/* --- Main driver code --- */
689
d3409d5e 690int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
691{
e360a4f2 692 int rc;
d3409d5e 693
694 /* --- Set various things up --- */
695
696 m = MP_COPY(m);
e360a4f2 697 MP_SPLIT(m);
d3409d5e 698
2b26f2d7 699 /* --- Check the radix for sensibleness --- */
700
701 if (radix > 0)
631673a1 702 assert(((void)"ascii radix must be <= 62", radix <= 62));
2b26f2d7 703 else if (radix < 0)
704 assert(((void)"binary radix must fit in a byte", -radix < UCHAR_MAX));
705 else
706 assert(((void)"radix can't be zero in mp_write", 0));
707
d3409d5e 708 /* --- If the number is negative, sort that out --- */
709
710 if (m->f & MP_NEG) {
711 if (ops->put("-", 1, p))
712 return (EOF);
2b26f2d7 713 m->f &= ~MP_NEG;
d3409d5e 714 }
715
a951033d 716 /* --- Handle binary radix --- */
717
718 switch (radix) {
719 case 2: case -2: return (binary(m, 1, radix, ops, p));
720 case 4: case -4: return (binary(m, 2, radix, ops, p));
721 case 8: case -8: return (binary(m, 3, radix, ops, p));
722 case 16: case -16: return (binary(m, 4, radix, ops, p));
723 case 32: case -32: return (binary(m, 5, radix, ops, p));
724 case -64: return (binary(m, 6, radix, ops, p));
725 case -128: return (binary(m, 7, radix, ops, p));
726 }
727
e360a4f2 728 /* --- If the number is small, do it the easy way --- */
729
3bc9cb53 730 if (MP_LEN(m) < 2)
731 rc = simple(MP_LEN(m) ? m->v[0] : 0, radix, 0, ops, p);
e360a4f2 732
733 /* --- Use a clever algorithm --- *
734 *
735 * Square the radix repeatedly, remembering old results, until I get
736 * something more than half the size of the number @m@. Use this to divide
737 * the number: the quotient and remainder will be approximately the same
738 * size, and I'll have split them on a digit boundary, so I can just emit
739 * the quotient and remainder recursively, in order.
e360a4f2 740 */
741
742 else {
2b26f2d7 743 mp *pr[DEPTH];
3bc9cb53 744 size_t target = (MP_LEN(m) + 1) / 2;
e360a4f2 745 unsigned i = 0;
2b26f2d7 746 mp *z = mp_new(1, 0);
e360a4f2 747
748 /* --- Set up the exponent table --- */
749
2b26f2d7 750 z->v[0] = (radix > 0 ? radix : -radix);
e360a4f2 751 z->f = 0;
752 for (;;) {
2b26f2d7 753 assert(((void)"Number is too unimaginably huge", i < DEPTH));
e360a4f2 754 pr[i++] = z;
755 if (MP_LEN(z) > target)
756 break;
757 z = mp_sqr(MP_NEW, z);
758 }
d3409d5e 759
e360a4f2 760 /* --- Write out the answer --- */
d3409d5e 761
e360a4f2 762 rc = complicated(m, radix, pr, i - 1, 0, ops, p);
d3409d5e 763
e360a4f2 764 /* --- Tidy away the array --- */
d3409d5e 765
e360a4f2 766 while (i > 0)
767 mp_drop(pr[--i]);
d3409d5e 768 }
e360a4f2 769
770 /* --- Tidying up code --- */
771
772 MP_DROP(m);
773 return (rc);
d3409d5e 774}
775
776/*----- Test rig ----------------------------------------------------------*/
777
778#ifdef TEST_RIG
779
780#include <mLib/testrig.h>
781
782static int verify(dstr *v)
783{
784 int ok = 1;
785 int ib = *(int *)v[0].buf, ob = *(int *)v[2].buf;
786 dstr d = DSTR_INIT;
787 mp *m = mp_readdstr(MP_NEW, &v[1], 0, ib);
788 if (m) {
789 if (!ob) {
790 fprintf(stderr, "*** unexpected successful parse\n"
a951033d 791 "*** input [%2i] = ", ib);
2b26f2d7 792 if (ib < 0)
793 type_hex.dump(&v[1], stderr);
794 else
795 fputs(v[1].buf, stderr);
d3409d5e 796 mp_writedstr(m, &d, 10);
2b26f2d7 797 fprintf(stderr, "\n*** (value = %s)\n", d.buf);
d3409d5e 798 ok = 0;
799 } else {
800 mp_writedstr(m, &d, ob);
801 if (d.len != v[3].len || memcmp(d.buf, v[3].buf, d.len) != 0) {
802 fprintf(stderr, "*** failed read or write\n"
a951033d 803 "*** input [%2i] = ", ib);
2b26f2d7 804 if (ib < 0)
805 type_hex.dump(&v[1], stderr);
806 else
807 fputs(v[1].buf, stderr);
a951033d 808 fprintf(stderr, "\n*** output [%2i] = ", ob);
2b26f2d7 809 if (ob < 0)
810 type_hex.dump(&d, stderr);
811 else
812 fputs(d.buf, stderr);
a951033d 813 fprintf(stderr, "\n*** expected [%2i] = ", ob);
2b26f2d7 814 if (ob < 0)
815 type_hex.dump(&v[3], stderr);
816 else
817 fputs(v[3].buf, stderr);
818 fputc('\n', stderr);
d3409d5e 819 ok = 0;
820 }
821 }
822 mp_drop(m);
823 } else {
824 if (ob) {
825 fprintf(stderr, "*** unexpected parse failure\n"
2b26f2d7 826 "*** input [%i] = ", ib);
827 if (ib < 0)
828 type_hex.dump(&v[1], stderr);
829 else
830 fputs(v[1].buf, stderr);
831 fprintf(stderr, "\n*** expected [%i] = ", ob);
832 if (ob < 0)
833 type_hex.dump(&v[3], stderr);
834 else
835 fputs(v[3].buf, stderr);
836 fputc('\n', stderr);
d3409d5e 837 ok = 0;
838 }
839 }
840
841 dstr_destroy(&d);
9c3df6c0 842 assert(mparena_count(MPARENA_GLOBAL) == 0);
d3409d5e 843 return (ok);
844}
845
846static test_chunk tests[] = {
2b26f2d7 847 { "mptext-ascii", verify,
d3409d5e 848 { &type_int, &type_string, &type_int, &type_string, 0 } },
2b26f2d7 849 { "mptext-bin-in", verify,
850 { &type_int, &type_hex, &type_int, &type_string, 0 } },
851 { "mptext-bin-out", verify,
852 { &type_int, &type_string, &type_int, &type_hex, 0 } },
d3409d5e 853 { 0, 0, { 0 } }
854};
855
856int main(int argc, char *argv[])
857{
858 sub_init();
859 test_run(argc, argv, tests, SRCDIR "/tests/mptext");
860 return (0);
861}
862
863#endif
864
865/*----- That's all, folks -------------------------------------------------*/