Merge branch '2.5.x'
[catacomb] / math / mptext.c
CommitLineData
d3409d5e 1/* -*-c-*-
2 *
d3409d5e 3 * Textual representation of multiprecision numbers
4 *
5 * (c) 1999 Straylight/Edgeware
6 */
7
45c0fd36 8/*----- Licensing notice --------------------------------------------------*
d3409d5e 9 *
10 * This file is part of Catacomb.
11 *
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
45c0fd36 16 *
d3409d5e 17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
45c0fd36 21 *
d3409d5e 22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * MA 02111-1307, USA.
26 */
27
d3409d5e 28/*----- Header files ------------------------------------------------------*/
29
30#include <ctype.h>
2b26f2d7 31#include <limits.h>
d3409d5e 32#include <stdio.h>
33
d3409d5e 34#include "mp.h"
35#include "mptext.h"
e360a4f2 36#include "paranoia.h"
d3409d5e 37
2b26f2d7 38/*----- Magical numbers ---------------------------------------------------*/
39
40/* --- Maximum recursion depth --- *
41 *
45c0fd36 42 * This is the number of bits in a @size_t@ object. Why?
2b26f2d7 43 *
eaa515d8 44 * To see this, let %$b = \textit{MPW\_MAX} + 1$% and let %$Z$% be the
dd9199f0 45 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
46 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
47 * squares the radix at each step, the highest number reached by the
48 * recursion is %$d$%, where:
2b26f2d7 49 *
dd9199f0 50 * %$r^{2^d} = b^Z$%.
2b26f2d7 51 *
52 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
53 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
54 *
55 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
56 * overestimate, since a @size_t@ representation may contain `holes'.
57 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
58 * for `some time to come'.
59 */
60
61#define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
62
626cd971 63/*----- Input -------------------------------------------------------------*/
d3409d5e 64
65/* --- @mp_read@ --- *
66 *
67 * Arguments: @mp *m@ = destination multiprecision number
68 * @int radix@ = base to assume for data (or zero to guess)
69 * @const mptext_ops *ops@ = pointer to operations block
70 * @void *p@ = data for the operations block
71 *
72 * Returns: The integer read, or zero if it didn't work.
73 *
74 * Use: Reads an integer from some source. If the @radix@ is
75 * specified, the number is assumed to be given in that radix,
76 * with the letters `a' (either upper- or lower-case) upwards
77 * standing for digits greater than 9. Otherwise, base 10 is
78 * assumed unless the number starts with `0' (octal), `0x' (hex)
79 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
80 * before the number is ignored.
81 */
82
2b26f2d7 83/* --- About the algorithm --- *
84 *
85 * The algorithm here is rather aggressive. I maintain an array of
86 * successive squarings of the radix, and a stack of partial results, each
87 * with a counter attached indicating which radix square to multiply by.
88 * Once the item at the top of the stack reaches the same counter level as
89 * the next item down, they are combined together and the result is given a
90 * counter level one higher than either of the results.
91 *
92 * Gluing the results together at the end is slightly tricky. Pay attention
93 * to the code.
94 *
95 * This is more complicated because of the need to handle the slightly
96 * bizarre syntax.
97 */
98
a6b6ae6b 99static int char_digit(int ch, int radix)
d3409d5e 100{
a6b6ae6b
MW
101 int r = radix < 0 ? -radix : radix;
102 int d;
103
104 if (ch < 0) return (-1);
105 if (radix < 0) d = ch;
106 else if ('0' <= ch && ch <= '9') d = ch - '0';
107 else if ('a' <= ch && ch <= 'z') d = ch - 'a' + 10;
108 else if ('A' <= ch && ch <= 'Z') d = ch - 'A' + (radix > 36 ? 36 : 10);
109 else return (-1);
110 if (d >= r) return (-1);
111 return (d);
112}
a951033d 113
a6b6ae6b
MW
114static mp *read_binary(int radix, unsigned bit, unsigned nf,
115 const mptext_ops *ops, void *p)
116{
117 mpw a = 0;
118 unsigned b = MPW_BITS;
119 int any = 0, nz = 0;
120 int ch, d;
121 size_t len, n;
122 mpw *v;
123 mp *m;
a951033d 124
125 /* --- The fast binary algorithm --- *
126 *
127 * We stack bits up starting at the top end of a word. When one word is
128 * full, we write it to the integer, and start another with the left-over
129 * bits. When the array in the integer is full, we resize using low-level
130 * calls and copy the current data to the top end. Finally, we do a single
131 * bit-shift when we know where the end of the number is.
132 */
133
a6b6ae6b
MW
134 m = mp_dest(MP_NEW, 1, nf);
135 len = n = m->sz;
136 n = len;
137 v = m->v + n;
a951033d 138
a6b6ae6b
MW
139 for (;;) {
140 ch = ops->get(p);
141 if ((d = char_digit(ch, radix)) < 0) break;
a951033d 142
a6b6ae6b 143 /* --- Ignore leading zeroes, but notice that the number is valid --- */
a951033d 144
a6b6ae6b
MW
145 any = 1;
146 if (!d && !nz) continue;
147 nz = 1;
a951033d 148
a6b6ae6b 149 /* --- Feed the digit into the accumulator --- */
a951033d 150
a6b6ae6b
MW
151 if (b > bit) {
152 b -= bit;
153 a |= MPW(d) << b;
a951033d 154 } else {
a6b6ae6b
MW
155 a |= MPW(d) >> (bit - b);
156 b += MPW_BITS - bit;
157 *--v = MPW(a); n--;
158 if (!n) {
159 n = len; len <<= 1;
160 v = mpalloc(m->a, len);
161 memcpy(v + n, m->v, MPWS(n));
162 mpfree(m->a, m->v);
163 m->v = v; v = m->v + n;
164 }
165 a = (b < MPW_BITS) ? MPW(d) << b : 0;
a951033d 166 }
a6b6ae6b 167 }
a951033d 168
a6b6ae6b 169 /* --- Finish up --- */
d3409d5e 170
a6b6ae6b
MW
171 ops->unget(ch, p);
172 if (!any) { mp_drop(m); return (0); }
d3409d5e 173
a6b6ae6b
MW
174 *--v = MPW(a); n--;
175 m->sz = len;
176 m->vl = m->v + len;
177 m->f &= ~MP_UNDEF;
178 m = mp_lsr(m, m, (unsigned long)n * MPW_BITS + b);
7d45ed6c 179
a6b6ae6b
MW
180 return (m);
181}
d3409d5e 182
a6b6ae6b 183struct readstate {
2b26f2d7 184
a6b6ae6b
MW
185 /* --- State for the general-base reader --- *
186 *
187 * There are two arrays. The @pow@ array is set so that @pow[i]@ contains
188 * %$R^{2^i}$% for @i < pows@. The stack @s@ contains partial results:
189 * each entry contains a value @m@ corresponding to %$2^i$% digits.
190 * Inductively, an empty stack represents zero; if a stack represents %$x$%
191 * then pushing a new entry on the top causes the stack to represent
192 * %$R^{2^i} x + m$%.
193 *
194 * It is an invariant that each entry has a strictly smaller @i@ than the
195 * items beneath it. This is achieved by coaslescing entries at the top if
196 * they have equal %$i$% values: if the top items are %$(m, i)$%, and
197 * %$(M', i)$%, and the rest of the stack represents the integer %$x$%,
198 * then %$R^{2^i} (R^{2^i} x + M) + m = R^{2^{i+1}} x + (R^{2^i} M + m)$%,
199 * so we replace the top two items by %$((R^{2^i} M + m), i + 1)$%, and
200 * repeat if necessary.
201 */
2b26f2d7 202
a6b6ae6b
MW
203 unsigned pows, sp;
204 struct { unsigned i; mp *m; } s[DEPTH];
205 mp *pow[DEPTH];
206};
2b26f2d7 207
a6b6ae6b
MW
208static void ensure_power(struct readstate *rs)
209{
210 /* --- Make sure we have the necessary %$R^{2^i}$% computed --- */
2b26f2d7 211
a6b6ae6b
MW
212 if (rs->s[rs->sp].i >= rs->pows) {
213 assert(rs->pows < DEPTH);
214 rs->pow[rs->pows] = mp_sqr(MP_NEW, rs->pow[rs->pows - 1]);
215 rs->pows++;
216 }
217}
d3409d5e 218
a6b6ae6b
MW
219static void read_digit(struct readstate *rs, unsigned nf, int d)
220{
221 mp *m = mp_new(1, nf);
222 m->v[0] = d;
d3409d5e 223
a6b6ae6b 224 /* --- Put the new digit on top --- */
d3409d5e 225
a6b6ae6b
MW
226 assert(rs->sp < DEPTH);
227 rs->s[rs->sp].m = m;
228 rs->s[rs->sp].i = 0;
d3409d5e 229
a6b6ae6b 230 /* --- Restore the stack invariant --- */
d3409d5e 231
a6b6ae6b
MW
232 while (rs->sp && rs->s[rs->sp - 1].i <= rs->s[rs->sp].i) {
233 assert(rs->sp > 0);
234 ensure_power(rs);
235 rs->sp--;
d3409d5e 236
a6b6ae6b
MW
237 m = rs->s[rs->sp].m;
238 m = mp_mul(m, m, rs->pow[rs->s[rs->sp + 1].i]);
239 m = mp_add(m, m, rs->s[rs->sp + 1].m);
240 MP_DROP(rs->s[rs->sp + 1].m);
241 rs->s[rs->sp].m = m;
242 rs->s[rs->sp].i++;
243 }
d3409d5e 244
a6b6ae6b 245 /* --- Leave the stack pointer at an empty item --- */
2b26f2d7 246
a6b6ae6b
MW
247 rs->sp++;
248}
2b26f2d7 249
a6b6ae6b
MW
250static mp *read_general(int radix, unsigned t, unsigned nf,
251 const mptext_ops *ops, void *p)
252{
253 struct readstate rs;
254 unsigned char v[4];
255 unsigned i;
256 mpw r;
257 int any = 0;
258 int ch, d;
259 mp rr;
260 mp *m, *z, *n;
261
262 /* --- Prepare the stack --- */
263
264 r = radix < 0 ? -radix : radix;
265 mp_build(&rr, &r, &r + 1);
266 rs.pow[0] = &rr;
267 rs.pows = 1;
268 rs.sp = 0;
269
270 /* --- If we've partially parsed some input then feed it in --- *
271 *
272 * Unfortunately, what we've got is backwards. Fortunately there's a
273 * fairly tight upper bound on how many digits @t@ might be, since we
274 * aborted that loop once it got too large.
275 */
276
277 if (t) {
278 i = 0;
279 while (t) { assert(i < sizeof(v)); v[i++] = t%r; t /= r; }
280 while (i) read_digit(&rs, nf, v[--i]);
281 any = 1;
282 }
2b26f2d7 283
a6b6ae6b 284 /* --- Read more stuff --- */
2b26f2d7 285
a6b6ae6b
MW
286 for (;;) {
287 ch = ops->get(p);
288 if ((d = char_digit(ch, radix)) < 0) break;
289 read_digit(&rs, nf, d); any = 1;
290 }
291 ops->unget(ch, p);
2b26f2d7 292
a6b6ae6b
MW
293 /* --- Stitch all of the numbers together --- *
294 *
295 * This is not the same code as @read_digit@. In particular, here we must
296 * cope with the partial result being some inconvenient power of %$R$%,
297 * rather than %$R^{2^i}$%.
298 */
2b26f2d7 299
a6b6ae6b
MW
300 if (!any) return (0);
301 m = MP_ZERO; z = MP_ONE;
302 while (rs.sp) {
303 rs.sp--;
304 ensure_power(&rs);
305 n = rs.s[rs.sp].m;
306 n = mp_mul(n, n, z);
307 m = mp_add(m, m, n);
308 z = mp_mul(z, z, rs.pow[rs.s[rs.sp].i]);
309 MP_DROP(n);
d3409d5e 310 }
a6b6ae6b
MW
311 for (i = 0; i < rs.pows; i++) MP_DROP(rs.pow[i]);
312 MP_DROP(z);
313 return (m);
314}
d3409d5e 315
a6b6ae6b
MW
316mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p)
317{
318 unsigned t = 0;
319 unsigned nf = 0;
320 int ch, d, rd;
321
322 unsigned f = 0;
323#define f_neg 1u
324#define f_ok 2u
d3409d5e 325
a6b6ae6b
MW
326 /* --- We don't actually need a destination so throw it away --- *
327 *
328 * But note the flags before we lose it entirely.
329 */
2b26f2d7 330
a6b6ae6b
MW
331 if (m) {
332 nf = m->f & MP_BURN;
333 MP_DROP(m);
334 }
2b26f2d7 335
a6b6ae6b 336 /* --- Maintain a lookahead character --- */
2b26f2d7 337
a6b6ae6b 338 ch = ops->get(p);
2b26f2d7 339
a6b6ae6b 340 /* --- If we're reading text, skip leading space, and maybe a sign --- */
2b26f2d7 341
a6b6ae6b
MW
342 if (radix >= 0) {
343 while (isspace(ch)) ch = ops->get(p);
344 switch (ch) {
345 case '-': f |= f_neg; /* and on */
346 case '+': do ch = ops->get(p); while (isspace(ch));
347 }
348 }
349
350 /* --- If we don't have a fixed radix, then parse one from the input --- *
351 *
352 * This is moderately easy if the input starts with `0x' or similar. If it
353 * starts with `0' and something else, then it might be octal, or just a
354 * plain old zero. Finally, it might start with a leading `NN_', in which
355 * case we carefully collect the decimal number until we're sure it's
356 * either a radix prefix (in which case we accept it and start over) or it
357 * isn't (in which case it's actually the start of a large number we need
358 * to read).
359 */
2b26f2d7 360
a6b6ae6b
MW
361 if (radix == 0) {
362 if (ch == '0') {
363 ch = ops->get(p);
364 switch (ch) {
365 case 'x': case 'X': radix = 16; goto fetch;
366 case 'o': case 'O': radix = 8; goto fetch;
367 case 'b': case 'B': radix = 2; goto fetch;
368 fetch: ch = ops->get(p); break;
369 default: radix = 8; f |= f_ok; break;
370 }
371 } else {
372 if ((d = char_digit(ch, 10)) < 0) { ops->unget(ch, p); return (0); }
373 for (;;) {
374 t = 10*t + d;
375 ch = ops->get(p);
376 if (t > 52) break;
377 if ((d = char_digit(ch, 10)) < 0) break;
378 }
379 if (ch != '_' || t > 52) radix = 10;
380 else {
381 radix = t; t = 0;
382 ch = ops->get(p);
2b26f2d7 383 }
2b26f2d7 384 }
2b26f2d7 385 }
386
a6b6ae6b
MW
387 /* --- We're now ready to dispatch to the correct handler --- */
388
389 rd = radix < 0 ? -radix : radix;
390 ops->unget(ch, p);
391 switch (rd) {
392 case 2: m = read_binary(radix, 1, nf, ops, p); break;
393 case 4: m = read_binary(radix, 2, nf, ops, p); break;
394 case 8: m = read_binary(radix, 3, nf, ops, p); break;
395 case 16: m = read_binary(radix, 4, nf, ops, p); break;
396 case 32: m = read_binary(radix, 5, nf, ops, p); break;
397 case 64: m = read_binary(radix, 6, nf, ops, p); break;
398 case 128: m = read_binary(radix, 7, nf, ops, p); break;
399 default: m = read_general(radix, t, nf, ops, p); break;
400 }
401
402 /* --- That didn't work --- *
403 *
404 * If we've already read something then return that. Otherwise it's an
405 * error.
406 */
2b26f2d7 407
a6b6ae6b
MW
408 if (!m) {
409 if (f & f_ok) return (MP_ZERO);
410 else return (0);
2b26f2d7 411 }
412
a6b6ae6b 413 /* --- Negate the result if we should do that --- */
d3409d5e 414
a6b6ae6b 415 if (f & f_neg) m = mp_neg(m, m);
d3409d5e 416
a6b6ae6b 417 /* --- And we're all done --- */
d3409d5e 418
d3409d5e 419 return (m);
3bc9cb53 420
421#undef f_neg
422#undef f_ok
d3409d5e 423}
424
626cd971
MW
425/*----- Output ------------------------------------------------------------*/
426
d3409d5e 427/* --- @mp_write@ --- *
428 *
429 * Arguments: @mp *m@ = pointer to a multi-precision integer
430 * @int radix@ = radix to use when writing the number out
431 * @const mptext_ops *ops@ = pointer to an operations block
432 * @void *p@ = data for the operations block
433 *
434 * Returns: Zero if it worked, nonzero otherwise.
435 *
436 * Use: Writes a large integer in textual form.
437 */
438
626cd971
MW
439static int digit_char(int d, int radix)
440{
441 if (radix < 0) return (d);
442 else if (d < 10) return (d + '0');
443 else if (d < 26) return (d - 10 + 'a');
444 else return (d - 36 + 'A');
445}
446
e360a4f2 447/* --- Simple case --- *
448 *
3bc9cb53 449 * Use a fixed-sized buffer and single-precision arithmetic to pick off
450 * low-order digits. Put each digit in a buffer, working backwards from the
451 * end. If the buffer becomes full, recurse to get another one. Ensure that
452 * there are at least @z@ digits by writing leading zeroes if there aren't
453 * enough real digits.
e360a4f2 454 */
455
626cd971
MW
456static int write_simple(mpw n, int radix, unsigned z,
457 const mptext_ops *ops, void *p)
e360a4f2 458{
459 int rc = 0;
460 char buf[64];
461 unsigned i = sizeof(buf);
2b26f2d7 462 int rd = radix > 0 ? radix : -radix;
626cd971 463 mpw x;
e360a4f2 464
465 do {
626cd971
MW
466 x = n % rd; n /= rd;
467 buf[--i] = digit_char(x, radix);
468 if (z) z--;
3bc9cb53 469 } while (i && n);
e360a4f2 470
3bc9cb53 471 if (n)
626cd971 472 rc = write_simple(n, radix, z, ops, p);
e360a4f2 473 else {
a951033d 474 char zbuf[32];
475 memset(zbuf, (radix < 0) ? 0 : '0', sizeof(zbuf));
476 while (!rc && z >= sizeof(zbuf)) {
477 rc = ops->put(zbuf, sizeof(zbuf), p);
478 z -= sizeof(zbuf);
e360a4f2 479 }
626cd971 480 if (!rc && z) rc = ops->put(zbuf, z, p);
e360a4f2 481 }
626cd971 482 if (!rc) rc = ops->put(buf + i, sizeof(buf) - i, p);
3bc9cb53 483 BURN(buf);
e360a4f2 484 return (rc);
485}
486
487/* --- Complicated case --- *
488 *
489 * If the number is small, fall back to the simple case above. Otherwise
490 * divide and take remainder by current large power of the radix, and emit
491 * each separately. Don't emit a zero quotient. Be very careful about
492 * leading zeroes on the remainder part, because they're deeply significant.
493 */
494
626cd971
MW
495static int write_complicated(mp *m, int radix, mp **pr,
496 unsigned i, unsigned z,
497 const mptext_ops *ops, void *p)
e360a4f2 498{
499 int rc = 0;
500 mp *q = MP_NEW;
501 unsigned d = 1 << i;
502
3bc9cb53 503 if (MP_LEN(m) < 2)
626cd971 504 return (write_simple(MP_LEN(m) ? m->v[0] : 0, radix, z, ops, p));
e360a4f2 505
3bc9cb53 506 assert(i);
e360a4f2 507 mp_div(&q, &m, m, pr[i]);
626cd971 508 if (MP_ZEROP(q)) d = z;
e360a4f2 509 else {
626cd971
MW
510 if (z > d) z -= d;
511 else z = 0;
512 rc = write_complicated(q, radix, pr, i - 1, z, ops, p);
e360a4f2 513 }
626cd971 514 if (!rc) rc = write_complicated(m, radix, pr, i - 1, d, ops, p);
e360a4f2 515 mp_drop(q);
516 return (rc);
517}
518
a951033d 519/* --- Binary case --- *
520 *
521 * Special case for binary output. Goes much faster.
522 */
523
626cd971
MW
524static int write_binary(mp *m, int bit, int radix,
525 const mptext_ops *ops, void *p)
a951033d 526{
527 mpw *v;
528 mpw a;
529 int rc = 0;
530 unsigned b;
531 unsigned mask;
532 unsigned long n;
533 unsigned f = 0;
534 char buf[8], *q;
535 unsigned x;
a951033d 536
537#define f_out 1u
538
539 /* --- Work out where to start --- */
540
541 n = mp_bits(m);
626cd971 542 if (n % bit) n += bit - (n % bit);
a951033d 543 b = n % MPW_BITS;
544 n /= MPW_BITS;
afd054c1 545
546 if (n >= MP_LEN(m)) {
a951033d 547 n--;
548 b += MPW_BITS;
549 }
550
551 v = m->v + n;
552 a = *v;
553 mask = (1 << bit) - 1;
554 q = buf;
555
556 /* --- Main code --- */
557
558 for (;;) {
559 if (b > bit) {
560 b -= bit;
561 x = a >> b;
562 } else {
563 x = a << (bit - b);
564 b += MPW_BITS - bit;
626cd971 565 if (v == m->v) break;
a951033d 566 a = *--v;
626cd971 567 if (b < MPW_BITS) x |= a >> b;
a951033d 568 }
569 x &= mask;
626cd971 570 if (!x && !(f & f_out)) continue;
a951033d 571
626cd971 572 *q++ = digit_char(x, radix);
a951033d 573 if (q >= buf + sizeof(buf)) {
626cd971 574 if ((rc = ops->put(buf, sizeof(buf), p)) != 0) goto done;
a951033d 575 q = buf;
576 }
577 f |= f_out;
578 }
579
580 x &= mask;
626cd971 581 *q++ = digit_char(x, radix);
a951033d 582 rc = ops->put(buf, q - buf, p);
583
584done:
585 mp_drop(m);
586 return (rc);
587
588#undef f_out
589}
590
e360a4f2 591/* --- Main driver code --- */
592
d3409d5e 593int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
594{
e360a4f2 595 int rc;
626cd971
MW
596 mp *pr[DEPTH];
597 size_t target;
598 unsigned i = 0;
599 mp *z;
d3409d5e 600
afd054c1 601 if (MP_EQ(m, MP_ZERO))
572b324a 602 return (ops->put(radix > 0 ? "0" : "\0", 1, p));
afd054c1 603
d3409d5e 604 /* --- Set various things up --- */
605
606 m = MP_COPY(m);
e360a4f2 607 MP_SPLIT(m);
d3409d5e 608
2b26f2d7 609 /* --- Check the radix for sensibleness --- */
610
611 if (radix > 0)
631673a1 612 assert(((void)"ascii radix must be <= 62", radix <= 62));
2b26f2d7 613 else if (radix < 0)
25b5e686 614 assert(((void)"binary radix must fit in a byte", -radix <= UCHAR_MAX));
2b26f2d7 615 else
616 assert(((void)"radix can't be zero in mp_write", 0));
617
d3409d5e 618 /* --- If the number is negative, sort that out --- */
619
a69a3efd 620 if (MP_NEGP(m)) {
572b324a 621 assert(radix > 0);
626cd971 622 if (ops->put("-", 1, p)) return (EOF);
2b26f2d7 623 m->f &= ~MP_NEG;
d3409d5e 624 }
625
a951033d 626 /* --- Handle binary radix --- */
627
628 switch (radix) {
626cd971
MW
629 case 2: case -2: return (write_binary(m, 1, radix, ops, p));
630 case 4: case -4: return (write_binary(m, 2, radix, ops, p));
631 case 8: case -8: return (write_binary(m, 3, radix, ops, p));
632 case 16: case -16: return (write_binary(m, 4, radix, ops, p));
633 case 32: case -32: return (write_binary(m, 5, radix, ops, p));
634 case -64: return (write_binary(m, 6, radix, ops, p));
635 case -128: return (write_binary(m, 7, radix, ops, p));
a951033d 636 }
637
e360a4f2 638 /* --- If the number is small, do it the easy way --- */
639
3bc9cb53 640 if (MP_LEN(m) < 2)
626cd971 641 rc = write_simple(MP_LEN(m) ? m->v[0] : 0, radix, 0, ops, p);
e360a4f2 642
643 /* --- Use a clever algorithm --- *
644 *
645 * Square the radix repeatedly, remembering old results, until I get
646 * something more than half the size of the number @m@. Use this to divide
647 * the number: the quotient and remainder will be approximately the same
648 * size, and I'll have split them on a digit boundary, so I can just emit
649 * the quotient and remainder recursively, in order.
e360a4f2 650 */
651
652 else {
626cd971
MW
653 target = (MP_LEN(m) + 1) / 2;
654 z = mp_new(1, 0);
e360a4f2 655
656 /* --- Set up the exponent table --- */
657
2b26f2d7 658 z->v[0] = (radix > 0 ? radix : -radix);
e360a4f2 659 z->f = 0;
660 for (;;) {
2b26f2d7 661 assert(((void)"Number is too unimaginably huge", i < DEPTH));
e360a4f2 662 pr[i++] = z;
626cd971 663 if (MP_LEN(z) > target) break;
e360a4f2 664 z = mp_sqr(MP_NEW, z);
665 }
d3409d5e 666
e360a4f2 667 /* --- Write out the answer --- */
d3409d5e 668
626cd971 669 rc = write_complicated(m, radix, pr, i - 1, 0, ops, p);
d3409d5e 670
e360a4f2 671 /* --- Tidy away the array --- */
d3409d5e 672
626cd971 673 while (i > 0) mp_drop(pr[--i]);
d3409d5e 674 }
e360a4f2 675
676 /* --- Tidying up code --- */
677
678 MP_DROP(m);
679 return (rc);
d3409d5e 680}
681
682/*----- Test rig ----------------------------------------------------------*/
683
684#ifdef TEST_RIG
685
686#include <mLib/testrig.h>
687
688static int verify(dstr *v)
689{
690 int ok = 1;
691 int ib = *(int *)v[0].buf, ob = *(int *)v[2].buf;
692 dstr d = DSTR_INIT;
50bea2af 693 size_t off = 0;
694 mp *m = mp_readdstr(MP_NEW, &v[1], &off, ib);
d3409d5e 695 if (m) {
696 if (!ob) {
697 fprintf(stderr, "*** unexpected successful parse\n"
45c0fd36 698 "*** input [%2i] = ", ib);
2b26f2d7 699 if (ib < 0)
700 type_hex.dump(&v[1], stderr);
701 else
702 fputs(v[1].buf, stderr);
d3409d5e 703 mp_writedstr(m, &d, 10);
2b26f2d7 704 fprintf(stderr, "\n*** (value = %s)\n", d.buf);
d3409d5e 705 ok = 0;
706 } else {
707 mp_writedstr(m, &d, ob);
708 if (d.len != v[3].len || memcmp(d.buf, v[3].buf, d.len) != 0) {
709 fprintf(stderr, "*** failed read or write\n"
45c0fd36 710 "*** input [%2i] = ", ib);
2b26f2d7 711 if (ib < 0)
712 type_hex.dump(&v[1], stderr);
713 else
714 fputs(v[1].buf, stderr);
45c0fd36 715 fprintf(stderr, "\n*** output [%2i] = ", ob);
2b26f2d7 716 if (ob < 0)
717 type_hex.dump(&d, stderr);
718 else
719 fputs(d.buf, stderr);
45c0fd36 720 fprintf(stderr, "\n*** expected [%2i] = ", ob);
2b26f2d7 721 if (ob < 0)
722 type_hex.dump(&v[3], stderr);
723 else
724 fputs(v[3].buf, stderr);
725 fputc('\n', stderr);
d3409d5e 726 ok = 0;
727 }
728 }
729 mp_drop(m);
730 } else {
731 if (ob) {
732 fprintf(stderr, "*** unexpected parse failure\n"
45c0fd36 733 "*** input [%2i] = ", ib);
2b26f2d7 734 if (ib < 0)
735 type_hex.dump(&v[1], stderr);
736 else
737 fputs(v[1].buf, stderr);
50bea2af 738 fprintf(stderr, "\n*** expected [%2i] = ", ob);
2b26f2d7 739 if (ob < 0)
740 type_hex.dump(&v[3], stderr);
741 else
742 fputs(v[3].buf, stderr);
743 fputc('\n', stderr);
d3409d5e 744 ok = 0;
745 }
746 }
747
50bea2af 748 if (v[1].len - off != v[4].len ||
749 memcmp(v[1].buf + off, v[4].buf, v[4].len) != 0) {
750 fprintf(stderr, "*** leftovers incorrect\n"
45c0fd36 751 "*** input [%2i] = ", ib);
50bea2af 752 if (ib < 0)
753 type_hex.dump(&v[1], stderr);
754 else
755 fputs(v[1].buf, stderr);
756 fprintf(stderr, "\n*** expected `%s'\n"
45c0fd36 757 "*** found `%s'\n",
50bea2af 758 v[4].buf, v[1].buf + off);
759 ok = 0;
760 }
45c0fd36 761
d3409d5e 762 dstr_destroy(&d);
9c3df6c0 763 assert(mparena_count(MPARENA_GLOBAL) == 0);
d3409d5e 764 return (ok);
765}
766
767static test_chunk tests[] = {
2b26f2d7 768 { "mptext-ascii", verify,
50bea2af 769 { &type_int, &type_string, &type_int, &type_string, &type_string, 0 } },
2b26f2d7 770 { "mptext-bin-in", verify,
50bea2af 771 { &type_int, &type_hex, &type_int, &type_string, &type_string, 0 } },
2b26f2d7 772 { "mptext-bin-out", verify,
50bea2af 773 { &type_int, &type_string, &type_int, &type_hex, &type_string, 0 } },
d3409d5e 774 { 0, 0, { 0 } }
775};
776
777int main(int argc, char *argv[])
778{
779 sub_init();
0f00dc4c 780 test_run(argc, argv, tests, SRCDIR "/t/mptext");
d3409d5e 781 return (0);
782}
783
784#endif
785
786/*----- That's all, folks -------------------------------------------------*/