3 * $Id: mptext.c,v 1.9 2001/02/03 16:05:17 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.9 2001/02/03 16:05:17 mdw
34 * Make flags be unsigned. Improve the write algorithm: recurse until the
35 * parts are one word long and use single-precision arithmetic from there.
36 * Fix off-by-one bug when breaking the number apart.
38 * Revision 1.8 2000/12/06 20:32:42 mdw
39 * Reduce binary bytes (to allow marker bits to be ignored). Fix error
40 * message string a bit. Allow leading `+' signs.
42 * Revision 1.7 2000/07/15 10:01:08 mdw
43 * Bug fix in binary input.
45 * Revision 1.6 2000/06/25 12:58:23 mdw
46 * Fix the derivation of `depth' commentary.
48 * Revision 1.5 2000/06/17 11:46:19 mdw
49 * New and much faster stack-based algorithm for reading integers. Support
50 * reading and writing binary integers in bases between 2 and 256.
52 * Revision 1.4 1999/12/22 15:56:56 mdw
53 * Use clever recursive algorithm for writing numbers out.
55 * Revision 1.3 1999/12/10 23:23:26 mdw
56 * Allocate slightly less memory.
58 * Revision 1.2 1999/11/20 22:24:15 mdw
59 * Use function versions of MPX_UMULN and MPX_UADDN.
61 * Revision 1.1 1999/11/17 18:02:16 mdw
62 * New multiprecision integer arithmetic suite.
66 /*----- Header files ------------------------------------------------------*/
76 /*----- Magical numbers ---------------------------------------------------*/
78 /* --- Maximum recursion depth --- *
80 * This is the number of bits in a @size_t@ object. Why?
82 * To see this, let %$b = \mathit{MPW\_MAX} + 1$% and let %$Z$% be the
83 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
84 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
85 * squares the radix at each step, the highest number reached by the
86 * recursion is %$d$%, where:
90 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
91 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
93 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
94 * overestimate, since a @size_t@ representation may contain `holes'.
95 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
96 * for `some time to come'.
99 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
101 /*----- Main code ---------------------------------------------------------*/
103 /* --- @mp_read@ --- *
105 * Arguments: @mp *m@ = destination multiprecision number
106 * @int radix@ = base to assume for data (or zero to guess)
107 * @const mptext_ops *ops@ = pointer to operations block
108 * @void *p@ = data for the operations block
110 * Returns: The integer read, or zero if it didn't work.
112 * Use: Reads an integer from some source. If the @radix@ is
113 * specified, the number is assumed to be given in that radix,
114 * with the letters `a' (either upper- or lower-case) upwards
115 * standing for digits greater than 9. Otherwise, base 10 is
116 * assumed unless the number starts with `0' (octal), `0x' (hex)
117 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
118 * before the number is ignored.
121 /* --- About the algorithm --- *
123 * The algorithm here is rather aggressive. I maintain an array of
124 * successive squarings of the radix, and a stack of partial results, each
125 * with a counter attached indicating which radix square to multiply by.
126 * Once the item at the top of the stack reaches the same counter level as
127 * the next item down, they are combined together and the result is given a
128 * counter level one higher than either of the results.
130 * Gluing the results together at the end is slightly tricky. Pay attention
133 * This is more complicated because of the need to handle the slightly
137 mp
*mp_read(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
139 int ch
; /* Current char being considered */
140 unsigned f
= 0; /* Flags about the current number */
141 int r
; /* Radix to switch over to */
142 mpw rd
; /* Radix as an @mp@ digit */
143 mp rr
; /* The @mp@ for the radix */
144 unsigned nf
= m ? m
->f
& MP_BURN
: 0; /* New @mp@ flags */
148 mp
*pow
[DEPTH
]; /* List of powers */
149 unsigned pows
; /* Next index to fill */
150 struct { unsigned i
; mp
*m
; } s
[DEPTH
]; /* Main stack */
151 unsigned sp
; /* Current stack pointer */
158 /* --- Initialize the stacks --- */
160 mp_build(&rr
, &rd
, &rd
+ 1);
166 /* --- Initialize the destination number --- */
171 /* --- Read an initial character --- */
177 /* --- Handle an initial sign --- */
179 if (radix
>= 0 && (ch
== '-' || ch
== '+')) {
182 do ch
= ops
->get(p
); while isspace(ch
);
185 /* --- If the radix is zero, look for leading zeros --- */
188 assert(((void)"ascii radix must be <= 36", radix
<= 36));
191 } else if (radix
< 0) {
193 assert(((void)"binary radix must fit in a byte", rd
< UCHAR_MAX
));
195 } else if (ch
!= '0') {
210 /* --- Time to start --- */
212 for (;; ch
= ops
->get(p
)) {
218 /* --- An underscore indicates a numbered base --- */
220 if (ch
== '_' && r
> 0 && r
<= 36) {
223 /* --- Clear out the stacks --- */
225 for (i
= 1; i
< pows
; i
++)
228 for (i
= 0; i
< sp
; i
++)
232 /* --- Restart the search --- */
240 /* --- Check that the character is a digit and in range --- */
247 if (ch
>= '0' && ch
<= '9')
251 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
258 /* --- Sort out what to do with the character --- */
260 if (x
>= 10 && r
>= 0)
268 /* --- Stick the character on the end of my integer --- */
270 assert(((void)"Number is too unimaginably huge", sp
< DEPTH
));
271 s
[sp
].m
= m
= mp_new(1, nf
);
275 /* --- Now grind through the stack --- */
277 while (sp
> 0 && s
[sp
- 1].i
== s
[sp
].i
) {
279 /* --- Combine the top two items --- */
283 m
= mp_mul(m
, m
, pow
[s
[sp
].i
]);
284 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
286 MP_DROP(s
[sp
+ 1].m
);
289 /* --- Make a new radix power if necessary --- */
291 if (s
[sp
].i
>= pows
) {
292 assert(((void)"Number is too unimaginably huge", pows
< DEPTH
));
293 pow
[pows
] = mp_sqr(MP_NEW
, pow
[pows
- 1]);
303 /* --- If we're done, compute the rest of the number --- */
314 /* --- Combine the top two items --- */
318 z
= mp_mul(z
, z
, pow
[s
[sp
+ 1].i
]);
320 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
322 MP_DROP(s
[sp
+ 1].m
);
324 /* --- Make a new radix power if necessary --- */
326 if (s
[sp
].i
>= pows
) {
327 assert(((void)"Number is too unimaginably huge", pows
< DEPTH
));
328 pow
[pows
] = mp_sqr(MP_NEW
, pow
[pows
- 1]);
337 for (i
= 0; i
< sp
; i
++)
341 /* --- Clear the radix power list --- */
345 for (i
= 1; i
< pows
; i
++)
349 /* --- Bail out if the number was bad --- */
354 /* --- Set the sign and return --- */
364 /* --- @mp_write@ --- *
366 * Arguments: @mp *m@ = pointer to a multi-precision integer
367 * @int radix@ = radix to use when writing the number out
368 * @const mptext_ops *ops@ = pointer to an operations block
369 * @void *p@ = data for the operations block
371 * Returns: Zero if it worked, nonzero otherwise.
373 * Use: Writes a large integer in textual form.
376 /* --- Simple case --- *
378 * Use a fixed-sized buffer and single-precision arithmetic to pick off
379 * low-order digits. Put each digit in a buffer, working backwards from the
380 * end. If the buffer becomes full, recurse to get another one. Ensure that
381 * there are at least @z@ digits by writing leading zeroes if there aren't
382 * enough real digits.
385 static int simple(mpw n
, int radix
, unsigned z
,
386 const mptext_ops
*ops
, void *p
)
390 unsigned i
= sizeof(buf
);
391 int rd
= radix
> 0 ? radix
: -radix
;
411 rc
= simple(n
, radix
, z
, ops
, p
);
413 static const char zero
[32] = "00000000000000000000000000000000";
414 while (!rc
&& z
>= sizeof(zero
)) {
415 rc
= ops
->put(zero
, sizeof(zero
), p
);
419 rc
= ops
->put(zero
, z
, p
);
422 rc
= ops
->put(buf
+ i
, sizeof(buf
) - i
, p
);
427 /* --- Complicated case --- *
429 * If the number is small, fall back to the simple case above. Otherwise
430 * divide and take remainder by current large power of the radix, and emit
431 * each separately. Don't emit a zero quotient. Be very careful about
432 * leading zeroes on the remainder part, because they're deeply significant.
435 static int complicated(mp
*m
, int radix
, mp
**pr
, unsigned i
, unsigned z
,
436 const mptext_ops
*ops
, void *p
)
443 return (simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, z
, ops
, p
));
446 mp_div(&q
, &m
, m
, pr
[i
]);
454 rc
= complicated(q
, radix
, pr
, i
- 1, z
, ops
, p
);
457 rc
= complicated(m
, radix
, pr
, i
- 1, d
, ops
, p
);
462 /* --- Main driver code --- */
464 int mp_write(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
468 /* --- Set various things up --- */
473 /* --- Check the radix for sensibleness --- */
476 assert(((void)"ascii radix must be <= 36", radix
<= 36));
478 assert(((void)"binary radix must fit in a byte", -radix
< UCHAR_MAX
));
480 assert(((void)"radix can't be zero in mp_write", 0));
482 /* --- If the number is negative, sort that out --- */
485 if (ops
->put("-", 1, p
))
490 /* --- If the number is small, do it the easy way --- */
493 rc
= simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, 0, ops
, p
);
495 /* --- Use a clever algorithm --- *
497 * Square the radix repeatedly, remembering old results, until I get
498 * something more than half the size of the number @m@. Use this to divide
499 * the number: the quotient and remainder will be approximately the same
500 * size, and I'll have split them on a digit boundary, so I can just emit
501 * the quotient and remainder recursively, in order.
506 size_t target
= (MP_LEN(m
) + 1) / 2;
508 mp
*z
= mp_new(1, 0);
510 /* --- Set up the exponent table --- */
512 z
->v
[0] = (radix
> 0 ? radix
: -radix
);
515 assert(((void)"Number is too unimaginably huge", i
< DEPTH
));
517 if (MP_LEN(z
) > target
)
519 z
= mp_sqr(MP_NEW
, z
);
522 /* --- Write out the answer --- */
524 rc
= complicated(m
, radix
, pr
, i
- 1, 0, ops
, p
);
526 /* --- Tidy away the array --- */
532 /* --- Tidying up code --- */
538 /*----- Test rig ----------------------------------------------------------*/
542 #include <mLib/testrig.h>
544 static int verify(dstr
*v
)
547 int ib
= *(int *)v
[0].buf
, ob
= *(int *)v
[2].buf
;
549 mp
*m
= mp_readdstr(MP_NEW
, &v
[1], 0, ib
);
552 fprintf(stderr
, "*** unexpected successful parse\n"
553 "*** input [%i] = ", ib
);
555 type_hex
.dump(&v
[1], stderr
);
557 fputs(v
[1].buf
, stderr
);
558 mp_writedstr(m
, &d
, 10);
559 fprintf(stderr
, "\n*** (value = %s)\n", d
.buf
);
562 mp_writedstr(m
, &d
, ob
);
563 if (d
.len
!= v
[3].len
|| memcmp(d
.buf
, v
[3].buf
, d
.len
) != 0) {
564 fprintf(stderr
, "*** failed read or write\n"
565 "*** input [%i] = ", ib
);
567 type_hex
.dump(&v
[1], stderr
);
569 fputs(v
[1].buf
, stderr
);
570 fprintf(stderr
, "\n*** output [%i] = ", ob
);
572 type_hex
.dump(&d
, stderr
);
574 fputs(d
.buf
, stderr
);
575 fprintf(stderr
, "\n*** expected [%i] = ", ob
);
577 type_hex
.dump(&v
[3], stderr
);
579 fputs(v
[3].buf
, stderr
);
587 fprintf(stderr
, "*** unexpected parse failure\n"
588 "*** input [%i] = ", ib
);
590 type_hex
.dump(&v
[1], stderr
);
592 fputs(v
[1].buf
, stderr
);
593 fprintf(stderr
, "\n*** expected [%i] = ", ob
);
595 type_hex
.dump(&v
[3], stderr
);
597 fputs(v
[3].buf
, stderr
);
604 assert(mparena_count(MPARENA_GLOBAL
) == 0);
608 static test_chunk tests
[] = {
609 { "mptext-ascii", verify
,
610 { &type_int
, &type_string
, &type_int
, &type_string
, 0 } },
611 { "mptext-bin-in", verify
,
612 { &type_int
, &type_hex
, &type_int
, &type_string
, 0 } },
613 { "mptext-bin-out", verify
,
614 { &type_int
, &type_string
, &type_int
, &type_hex
, 0 } },
618 int main(int argc
, char *argv
[])
621 test_run(argc
, argv
, tests
, SRCDIR
"/tests/mptext");
627 /*----- That's all, folks -------------------------------------------------*/