Reduce binary bytes (to allow marker bits to be ignored). Fix error
[u/mdw/catacomb] / mptext.c
1 /* -*-c-*-
2 *
3 * $Id: mptext.c,v 1.8 2000/12/06 20:32:42 mdw Exp $
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 $
33 * Revision 1.8 2000/12/06 20:32:42 mdw
34 * Reduce binary bytes (to allow marker bits to be ignored). Fix error
35 * message string a bit. Allow leading `+' signs.
36 *
37 * Revision 1.7 2000/07/15 10:01:08 mdw
38 * Bug fix in binary input.
39 *
40 * Revision 1.6 2000/06/25 12:58:23 mdw
41 * Fix the derivation of `depth' commentary.
42 *
43 * Revision 1.5 2000/06/17 11:46:19 mdw
44 * New and much faster stack-based algorithm for reading integers. Support
45 * reading and writing binary integers in bases between 2 and 256.
46 *
47 * Revision 1.4 1999/12/22 15:56:56 mdw
48 * Use clever recursive algorithm for writing numbers out.
49 *
50 * Revision 1.3 1999/12/10 23:23:26 mdw
51 * Allocate slightly less memory.
52 *
53 * Revision 1.2 1999/11/20 22:24:15 mdw
54 * Use function versions of MPX_UMULN and MPX_UADDN.
55 *
56 * Revision 1.1 1999/11/17 18:02:16 mdw
57 * New multiprecision integer arithmetic suite.
58 *
59 */
60
61 /*----- Header files ------------------------------------------------------*/
62
63 #include <ctype.h>
64 #include <limits.h>
65 #include <stdio.h>
66
67 #include "mp.h"
68 #include "mptext.h"
69 #include "paranoia.h"
70
71 /*----- Magical numbers ---------------------------------------------------*/
72
73 /* --- Maximum recursion depth --- *
74 *
75 * This is the number of bits in a @size_t@ object. Why?
76 *
77 * To see this, let %$b = \mathit{MPW\_MAX} + 1$% and let %$Z$% be the
78 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
79 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
80 * squares the radix at each step, the highest number reached by the
81 * recursion is %$d$%, where:
82 *
83 * %$r^{2^d} = b^Z$%.
84 *
85 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
86 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
87 *
88 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
89 * overestimate, since a @size_t@ representation may contain `holes'.
90 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
91 * for `some time to come'.
92 */
93
94 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
95
96 /*----- Main code ---------------------------------------------------------*/
97
98 /* --- @mp_read@ --- *
99 *
100 * Arguments: @mp *m@ = destination multiprecision number
101 * @int radix@ = base to assume for data (or zero to guess)
102 * @const mptext_ops *ops@ = pointer to operations block
103 * @void *p@ = data for the operations block
104 *
105 * Returns: The integer read, or zero if it didn't work.
106 *
107 * Use: Reads an integer from some source. If the @radix@ is
108 * specified, the number is assumed to be given in that radix,
109 * with the letters `a' (either upper- or lower-case) upwards
110 * standing for digits greater than 9. Otherwise, base 10 is
111 * assumed unless the number starts with `0' (octal), `0x' (hex)
112 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
113 * before the number is ignored.
114 */
115
116 /* --- About the algorithm --- *
117 *
118 * The algorithm here is rather aggressive. I maintain an array of
119 * successive squarings of the radix, and a stack of partial results, each
120 * with a counter attached indicating which radix square to multiply by.
121 * Once the item at the top of the stack reaches the same counter level as
122 * the next item down, they are combined together and the result is given a
123 * counter level one higher than either of the results.
124 *
125 * Gluing the results together at the end is slightly tricky. Pay attention
126 * to the code.
127 *
128 * This is more complicated because of the need to handle the slightly
129 * bizarre syntax.
130 */
131
132 mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p)
133 {
134 int ch; /* Current char being considered */
135 unsigned f = 0; /* Flags about the current number */
136 int r; /* Radix to switch over to */
137 mpw rd; /* Radix as an @mp@ digit */
138 mp rr; /* The @mp@ for the radix */
139 unsigned nf = m ? m->f & MP_BURN : 0; /* New @mp@ flags */
140
141 /* --- Stacks --- */
142
143 mp *pow[DEPTH]; /* List of powers */
144 unsigned pows; /* Next index to fill */
145 struct { unsigned i; mp *m; } s[DEPTH]; /* Main stack */
146 unsigned sp; /* Current stack pointer */
147
148 /* --- Flags --- */
149
150 enum {
151 f_neg = 1u,
152 f_ok = 2u
153 };
154
155 /* --- Initialize the stacks --- */
156
157 mp_build(&rr, &rd, &rd + 1);
158 pow[0] = &rr;
159 pows = 1;
160
161 sp = 0;
162
163 /* --- Initialize the destination number --- */
164
165 if (m)
166 MP_DROP(m);
167
168 /* --- Read an initial character --- */
169
170 ch = ops->get(p);
171 while (isspace(ch))
172 ch = ops->get(p);
173
174 /* --- Handle an initial sign --- */
175
176 if (radix >= 0 && (ch == '-' || ch == '+')) {
177 if (ch == '-')
178 f |= f_neg;
179 do ch = ops->get(p); while isspace(ch);
180 }
181
182 /* --- If the radix is zero, look for leading zeros --- */
183
184 if (radix > 0) {
185 assert(((void)"ascii radix must be <= 36", radix <= 36));
186 rd = radix;
187 r = -1;
188 } else if (radix < 0) {
189 rd = -radix;
190 assert(((void)"binary radix must fit in a byte", rd < UCHAR_MAX));
191 r = -1;
192 } else if (ch != '0') {
193 rd = 10;
194 r = 0;
195 } else {
196 ch = ops->get(p);
197 if (ch == 'x') {
198 ch = ops->get(p);
199 rd = 16;
200 } else {
201 rd = 8;
202 f |= f_ok;
203 }
204 r = -1;
205 }
206
207 /* --- Time to start --- */
208
209 for (;; ch = ops->get(p)) {
210 int x;
211
212 if (ch < 0)
213 break;
214
215 /* --- An underscore indicates a numbered base --- */
216
217 if (ch == '_' && r > 0 && r <= 36) {
218 unsigned i;
219
220 /* --- Clear out the stacks --- */
221
222 for (i = 1; i < pows; i++)
223 MP_DROP(pow[i]);
224 pows = 1;
225 for (i = 0; i < sp; i++)
226 MP_DROP(s[i].m);
227 sp = 0;
228
229 /* --- Restart the search --- */
230
231 rd = r;
232 r = -1;
233 f &= ~f_ok;
234 continue;
235 }
236
237 /* --- Check that the character is a digit and in range --- */
238
239 if (radix < 0)
240 x = ch % rd;
241 else {
242 if (!isalnum(ch))
243 break;
244 if (ch >= '0' && ch <= '9')
245 x = ch - '0';
246 else {
247 ch = tolower(ch);
248 if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */
249 x = ch - 'a' + 10;
250 else
251 break;
252 }
253 }
254
255 /* --- Sort out what to do with the character --- */
256
257 if (x >= 10 && r >= 0)
258 r = -1;
259 if (x >= rd)
260 break;
261
262 if (r >= 0)
263 r = r * 10 + x;
264
265 /* --- Stick the character on the end of my integer --- */
266
267 assert(((void)"Number is too unimaginably huge", sp < DEPTH));
268 s[sp].m = m = mp_new(1, nf);
269 m->v[0] = x;
270 s[sp].i = 0;
271
272 /* --- Now grind through the stack --- */
273
274 while (sp > 0 && s[sp - 1].i == s[sp].i) {
275
276 /* --- Combine the top two items --- */
277
278 sp--;
279 m = s[sp].m;
280 m = mp_mul(m, m, pow[s[sp].i]);
281 m = mp_add(m, m, s[sp + 1].m);
282 s[sp].m = m;
283 MP_DROP(s[sp + 1].m);
284 s[sp].i++;
285
286 /* --- Make a new radix power if necessary --- */
287
288 if (s[sp].i >= pows) {
289 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
290 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
291 pows++;
292 }
293 }
294 f |= f_ok;
295 sp++;
296 }
297
298 ops->unget(ch, p);
299
300 /* --- If we're done, compute the rest of the number --- */
301
302 if (f & f_ok) {
303 if (!sp)
304 return (MP_ZERO);
305 else {
306 mp *z = MP_ONE;
307 sp--;
308
309 while (sp > 0) {
310
311 /* --- Combine the top two items --- */
312
313 sp--;
314 m = s[sp].m;
315 z = mp_mul(z, z, pow[s[sp + 1].i]);
316 m = mp_mul(m, m, z);
317 m = mp_add(m, m, s[sp + 1].m);
318 s[sp].m = m;
319 MP_DROP(s[sp + 1].m);
320
321 /* --- Make a new radix power if necessary --- */
322
323 if (s[sp].i >= pows) {
324 assert(((void)"Number is too unimaginably huge", pows < DEPTH));
325 pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]);
326 pows++;
327 }
328 }
329 MP_DROP(z);
330 m = s[0].m;
331 }
332 } else {
333 unsigned i;
334 for (i = 0; i < sp; i++)
335 MP_DROP(s[i].m);
336 }
337
338 /* --- Clear the radix power list --- */
339
340 {
341 unsigned i;
342 for (i = 1; i < pows; i++)
343 MP_DROP(pow[i]);
344 }
345
346 /* --- Bail out if the number was bad --- */
347
348 if (!(f & f_ok))
349 return (0);
350
351 /* --- Set the sign and return --- */
352
353 if (f & f_neg)
354 m->f |= MP_NEG;
355 return (m);
356 }
357
358 /* --- @mp_write@ --- *
359 *
360 * Arguments: @mp *m@ = pointer to a multi-precision integer
361 * @int radix@ = radix to use when writing the number out
362 * @const mptext_ops *ops@ = pointer to an operations block
363 * @void *p@ = data for the operations block
364 *
365 * Returns: Zero if it worked, nonzero otherwise.
366 *
367 * Use: Writes a large integer in textual form.
368 */
369
370 /* --- Simple case --- *
371 *
372 * Use a fixed-sized buffer and the simple single-precision division
373 * algorithm to pick off low-order digits. Put each digit in a buffer,
374 * working backwards from the end. If the buffer becomes full, recurse to
375 * get another one. Ensure that there are at least @z@ digits by writing
376 * leading zeroes if there aren't enough real digits.
377 */
378
379 static int simple(mp *m, int radix, unsigned z,
380 const mptext_ops *ops, void *p)
381 {
382 int rc = 0;
383 char buf[64];
384 unsigned i = sizeof(buf);
385 int rd = radix > 0 ? radix : -radix;
386
387 do {
388 int ch;
389 mpw x;
390
391 x = mpx_udivn(m->v, m->vl, m->v, m->vl, rd);
392 MP_SHRINK(m);
393 if (radix < 0)
394 ch = x;
395 else {
396 if (x < 10)
397 ch = '0' + x;
398 else
399 ch = 'a' + x - 10;
400 }
401 buf[--i] = ch;
402 if (z)
403 z--;
404 } while (i && MP_LEN(m));
405
406 if (MP_LEN(m))
407 rc = simple(m, radix, z, ops, p);
408 else {
409 static const char zero[32] = "00000000000000000000000000000000";
410 while (!rc && z >= sizeof(zero)) {
411 rc = ops->put(zero, sizeof(zero), p);
412 z -= sizeof(zero);
413 }
414 if (!rc && z)
415 rc = ops->put(zero, z, p);
416 }
417 if (!rc)
418 ops->put(buf + i, sizeof(buf) - i, p);
419 if (m->f & MP_BURN)
420 BURN(buf);
421 return (rc);
422 }
423
424 /* --- Complicated case --- *
425 *
426 * If the number is small, fall back to the simple case above. Otherwise
427 * divide and take remainder by current large power of the radix, and emit
428 * each separately. Don't emit a zero quotient. Be very careful about
429 * leading zeroes on the remainder part, because they're deeply significant.
430 */
431
432 static int complicated(mp *m, int radix, mp **pr, unsigned i, unsigned z,
433 const mptext_ops *ops, void *p)
434 {
435 int rc = 0;
436 mp *q = MP_NEW;
437 unsigned d = 1 << i;
438
439 if (MP_LEN(m) < 8)
440 return (simple(m, radix, z, ops, p));
441
442 mp_div(&q, &m, m, pr[i]);
443 if (!MP_LEN(q))
444 d = z;
445 else {
446 if (z > d)
447 z -= d;
448 else
449 z = 0;
450 rc = complicated(q, radix, pr, i - 1, z, ops, p);
451 }
452 if (!rc)
453 rc = complicated(m, radix, pr, i - 1, d, ops, p);
454 mp_drop(q);
455 return (rc);
456 }
457
458 /* --- Main driver code --- */
459
460 int mp_write(mp *m, int radix, const mptext_ops *ops, void *p)
461 {
462 int rc;
463
464 /* --- Set various things up --- */
465
466 m = MP_COPY(m);
467 MP_SPLIT(m);
468
469 /* --- Check the radix for sensibleness --- */
470
471 if (radix > 0)
472 assert(((void)"ascii radix must be <= 36", radix <= 36));
473 else if (radix < 0)
474 assert(((void)"binary radix must fit in a byte", -radix < UCHAR_MAX));
475 else
476 assert(((void)"radix can't be zero in mp_write", 0));
477
478 /* --- If the number is negative, sort that out --- */
479
480 if (m->f & MP_NEG) {
481 if (ops->put("-", 1, p))
482 return (EOF);
483 m->f &= ~MP_NEG;
484 }
485
486 /* --- If the number is small, do it the easy way --- */
487
488 if (MP_LEN(m) < 8)
489 rc = simple(m, radix, 0, ops, p);
490
491 /* --- Use a clever algorithm --- *
492 *
493 * Square the radix repeatedly, remembering old results, until I get
494 * something more than half the size of the number @m@. Use this to divide
495 * the number: the quotient and remainder will be approximately the same
496 * size, and I'll have split them on a digit boundary, so I can just emit
497 * the quotient and remainder recursively, in order.
498 */
499
500 else {
501 mp *pr[DEPTH];
502 size_t target = MP_LEN(m) / 2;
503 unsigned i = 0;
504 mp *z = mp_new(1, 0);
505
506 /* --- Set up the exponent table --- */
507
508 z->v[0] = (radix > 0 ? radix : -radix);
509 z->f = 0;
510 for (;;) {
511 assert(((void)"Number is too unimaginably huge", i < DEPTH));
512 pr[i++] = z;
513 if (MP_LEN(z) > target)
514 break;
515 z = mp_sqr(MP_NEW, z);
516 }
517
518 /* --- Write out the answer --- */
519
520 rc = complicated(m, radix, pr, i - 1, 0, ops, p);
521
522 /* --- Tidy away the array --- */
523
524 while (i > 0)
525 mp_drop(pr[--i]);
526 }
527
528 /* --- Tidying up code --- */
529
530 MP_DROP(m);
531 return (rc);
532 }
533
534 /*----- Test rig ----------------------------------------------------------*/
535
536 #ifdef TEST_RIG
537
538 #include <mLib/testrig.h>
539
540 static int verify(dstr *v)
541 {
542 int ok = 1;
543 int ib = *(int *)v[0].buf, ob = *(int *)v[2].buf;
544 dstr d = DSTR_INIT;
545 mp *m = mp_readdstr(MP_NEW, &v[1], 0, ib);
546 if (m) {
547 if (!ob) {
548 fprintf(stderr, "*** unexpected successful parse\n"
549 "*** input [%i] = ", ib);
550 if (ib < 0)
551 type_hex.dump(&v[1], stderr);
552 else
553 fputs(v[1].buf, stderr);
554 mp_writedstr(m, &d, 10);
555 fprintf(stderr, "\n*** (value = %s)\n", d.buf);
556 ok = 0;
557 } else {
558 mp_writedstr(m, &d, ob);
559 if (d.len != v[3].len || memcmp(d.buf, v[3].buf, d.len) != 0) {
560 fprintf(stderr, "*** failed read or write\n"
561 "*** input [%i] = ", ib);
562 if (ib < 0)
563 type_hex.dump(&v[1], stderr);
564 else
565 fputs(v[1].buf, stderr);
566 fprintf(stderr, "\n*** output [%i] = ", ob);
567 if (ob < 0)
568 type_hex.dump(&d, stderr);
569 else
570 fputs(d.buf, stderr);
571 fprintf(stderr, "\n*** expected [%i] = ", ob);
572 if (ob < 0)
573 type_hex.dump(&v[3], stderr);
574 else
575 fputs(v[3].buf, stderr);
576 fputc('\n', stderr);
577 ok = 0;
578 }
579 }
580 mp_drop(m);
581 } else {
582 if (ob) {
583 fprintf(stderr, "*** unexpected parse failure\n"
584 "*** input [%i] = ", ib);
585 if (ib < 0)
586 type_hex.dump(&v[1], stderr);
587 else
588 fputs(v[1].buf, stderr);
589 fprintf(stderr, "\n*** expected [%i] = ", ob);
590 if (ob < 0)
591 type_hex.dump(&v[3], stderr);
592 else
593 fputs(v[3].buf, stderr);
594 fputc('\n', stderr);
595 ok = 0;
596 }
597 }
598
599 dstr_destroy(&d);
600 assert(mparena_count(MPARENA_GLOBAL) == 0);
601 return (ok);
602 }
603
604 static test_chunk tests[] = {
605 { "mptext-ascii", verify,
606 { &type_int, &type_string, &type_int, &type_string, 0 } },
607 { "mptext-bin-in", verify,
608 { &type_int, &type_hex, &type_int, &type_string, 0 } },
609 { "mptext-bin-out", verify,
610 { &type_int, &type_string, &type_int, &type_hex, 0 } },
611 { 0, 0, { 0 } }
612 };
613
614 int main(int argc, char *argv[])
615 {
616 sub_init();
617 test_run(argc, argv, tests, SRCDIR "/tests/mptext");
618 return (0);
619 }
620
621 #endif
622
623 /*----- That's all, folks -------------------------------------------------*/