3 * $Id: mptext.c,v 1.11 2001/06/16 23:42: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.11 2001/06/16 23:42:17 mdw
36 * Revision 1.10 2001/06/16 13:22:39 mdw
37 * Added fast-track code for binary output bases, and tests.
39 * Revision 1.9 2001/02/03 16:05:17 mdw
40 * Make flags be unsigned. Improve the write algorithm: recurse until the
41 * parts are one word long and use single-precision arithmetic from there.
42 * Fix off-by-one bug when breaking the number apart.
44 * Revision 1.8 2000/12/06 20:32:42 mdw
45 * Reduce binary bytes (to allow marker bits to be ignored). Fix error
46 * message string a bit. Allow leading `+' signs.
48 * Revision 1.7 2000/07/15 10:01:08 mdw
49 * Bug fix in binary input.
51 * Revision 1.6 2000/06/25 12:58:23 mdw
52 * Fix the derivation of `depth' commentary.
54 * Revision 1.5 2000/06/17 11:46:19 mdw
55 * New and much faster stack-based algorithm for reading integers. Support
56 * reading and writing binary integers in bases between 2 and 256.
58 * Revision 1.4 1999/12/22 15:56:56 mdw
59 * Use clever recursive algorithm for writing numbers out.
61 * Revision 1.3 1999/12/10 23:23:26 mdw
62 * Allocate slightly less memory.
64 * Revision 1.2 1999/11/20 22:24:15 mdw
65 * Use function versions of MPX_UMULN and MPX_UADDN.
67 * Revision 1.1 1999/11/17 18:02:16 mdw
68 * New multiprecision integer arithmetic suite.
72 /*----- Header files ------------------------------------------------------*/
82 /*----- Magical numbers ---------------------------------------------------*/
84 /* --- Maximum recursion depth --- *
86 * This is the number of bits in a @size_t@ object. Why?
88 * To see this, let %$b = \textit{MPW\_MAX} + 1$% and let %$Z$% be the
89 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
90 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
91 * squares the radix at each step, the highest number reached by the
92 * recursion is %$d$%, where:
96 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
97 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
99 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
100 * overestimate, since a @size_t@ representation may contain `holes'.
101 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
102 * for `some time to come'.
105 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
107 /*----- Main code ---------------------------------------------------------*/
109 /* --- @mp_read@ --- *
111 * Arguments: @mp *m@ = destination multiprecision number
112 * @int radix@ = base to assume for data (or zero to guess)
113 * @const mptext_ops *ops@ = pointer to operations block
114 * @void *p@ = data for the operations block
116 * Returns: The integer read, or zero if it didn't work.
118 * Use: Reads an integer from some source. If the @radix@ is
119 * specified, the number is assumed to be given in that radix,
120 * with the letters `a' (either upper- or lower-case) upwards
121 * standing for digits greater than 9. Otherwise, base 10 is
122 * assumed unless the number starts with `0' (octal), `0x' (hex)
123 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
124 * before the number is ignored.
127 /* --- About the algorithm --- *
129 * The algorithm here is rather aggressive. I maintain an array of
130 * successive squarings of the radix, and a stack of partial results, each
131 * with a counter attached indicating which radix square to multiply by.
132 * Once the item at the top of the stack reaches the same counter level as
133 * the next item down, they are combined together and the result is given a
134 * counter level one higher than either of the results.
136 * Gluing the results together at the end is slightly tricky. Pay attention
139 * This is more complicated because of the need to handle the slightly
143 mp
*mp_read(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
145 int ch
; /* Current char being considered */
146 unsigned f
= 0; /* Flags about the current number */
147 int r
; /* Radix to switch over to */
148 mpw rd
; /* Radix as an @mp@ digit */
149 mp rr
; /* The @mp@ for the radix */
150 unsigned nf
= m ? m
->f
& MP_BURN
: 0; /* New @mp@ flags */
154 mp
*pow
[DEPTH
]; /* List of powers */
155 unsigned pows
; /* Next index to fill */
156 struct { unsigned i
; mp
*m
; } s
[DEPTH
]; /* Main stack */
157 unsigned sp
; /* Current stack pointer */
165 /* --- Initialize the stacks --- */
167 mp_build(&rr
, &rd
, &rd
+ 1);
173 /* --- Initialize the destination number --- */
178 /* --- Read an initial character --- */
184 /* --- Handle an initial sign --- */
186 if (radix
>= 0 && (ch
== '-' || ch
== '+')) {
189 do ch
= ops
->get(p
); while isspace(ch
);
192 /* --- If the radix is zero, look for leading zeros --- */
195 assert(((void)"ascii radix must be <= 36", radix
<= 36));
198 } else if (radix
< 0) {
200 assert(((void)"binary radix must fit in a byte", rd
< UCHAR_MAX
));
202 } else if (ch
!= '0') {
217 /* --- Use fast algorithm for binary radix --- *
219 * This is the restart point after having parsed a radix number from the
220 * input. We check whether the radix is binary, and if so use a fast
221 * algorithm which just stacks the bits up in the right order.
228 case 2: bit
= 1; goto bin
;
229 case 4: bit
= 2; goto bin
;
230 case 8: bit
= 3; goto bin
;
231 case 16: bit
= 4; goto bin
;
232 case 32: bit
= 5; goto bin
;
233 case 64: bit
= 6; goto bin
;
234 case 128: bit
= 7; goto bin
;
238 /* --- The fast binary algorithm --- *
240 * We stack bits up starting at the top end of a word. When one word is
241 * full, we write it to the integer, and start another with the left-over
242 * bits. When the array in the integer is full, we resize using low-level
243 * calls and copy the current data to the top end. Finally, we do a single
244 * bit-shift when we know where the end of the number is.
249 unsigned b
= MPW_BITS
;
253 m
= mp_dest(MP_NEW
, 1, nf
);
257 for (;; ch
= ops
->get(p
)) {
263 /* --- Check that the character is a digit and in range --- */
270 if (ch
>= '0' && ch
<= '9')
274 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
283 /* --- Feed the digit into the accumulator --- */
286 if (!x
&& !(f
& f_start
))
293 a
|= MPW(x
) >> (bit
- b
);
300 v
= mpalloc(m
->a
, len
);
301 memcpy(v
+ n
, m
->v
, MPWS(n
));
306 a
= (b
< MPW_BITS
) ?
MPW(x
) << b
: 0;
310 /* --- Finish up --- */
321 m
= mp_lsr(m
, m
, (unsigned long)n
* MPW_BITS
+ b
);
326 /* --- Time to start --- */
328 for (;; ch
= ops
->get(p
)) {
334 /* --- An underscore indicates a numbered base --- */
336 if (ch
== '_' && r
> 0 && r
<= 36) {
339 /* --- Clear out the stacks --- */
341 for (i
= 1; i
< pows
; i
++)
344 for (i
= 0; i
< sp
; i
++)
348 /* --- Restart the search --- */
357 /* --- Check that the character is a digit and in range --- */
364 if (ch
>= '0' && ch
<= '9')
368 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
375 /* --- Sort out what to do with the character --- */
377 if (x
>= 10 && r
>= 0)
385 /* --- Stick the character on the end of my integer --- */
387 assert(((void)"Number is too unimaginably huge", sp
< DEPTH
));
388 s
[sp
].m
= m
= mp_new(1, nf
);
392 /* --- Now grind through the stack --- */
394 while (sp
> 0 && s
[sp
- 1].i
== s
[sp
].i
) {
396 /* --- Combine the top two items --- */
400 m
= mp_mul(m
, m
, pow
[s
[sp
].i
]);
401 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
403 MP_DROP(s
[sp
+ 1].m
);
406 /* --- Make a new radix power if necessary --- */
408 if (s
[sp
].i
>= pows
) {
409 assert(((void)"Number is too unimaginably huge", pows
< DEPTH
));
410 pow
[pows
] = mp_sqr(MP_NEW
, pow
[pows
- 1]);
420 /* --- If we're done, compute the rest of the number --- */
431 /* --- Combine the top two items --- */
435 z
= mp_mul(z
, z
, pow
[s
[sp
+ 1].i
]);
437 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
439 MP_DROP(s
[sp
+ 1].m
);
441 /* --- Make a new radix power if necessary --- */
443 if (s
[sp
].i
>= pows
) {
444 assert(((void)"Number is too unimaginably huge", pows
< DEPTH
));
445 pow
[pows
] = mp_sqr(MP_NEW
, pow
[pows
- 1]);
454 for (i
= 0; i
< sp
; i
++)
458 /* --- Clear the radix power list --- */
462 for (i
= 1; i
< pows
; i
++)
466 /* --- Bail out if the number was bad --- */
472 /* --- Set the sign and return --- */
483 /* --- @mp_write@ --- *
485 * Arguments: @mp *m@ = pointer to a multi-precision integer
486 * @int radix@ = radix to use when writing the number out
487 * @const mptext_ops *ops@ = pointer to an operations block
488 * @void *p@ = data for the operations block
490 * Returns: Zero if it worked, nonzero otherwise.
492 * Use: Writes a large integer in textual form.
495 /* --- Simple case --- *
497 * Use a fixed-sized buffer and single-precision arithmetic to pick off
498 * low-order digits. Put each digit in a buffer, working backwards from the
499 * end. If the buffer becomes full, recurse to get another one. Ensure that
500 * there are at least @z@ digits by writing leading zeroes if there aren't
501 * enough real digits.
504 static int simple(mpw n
, int radix
, unsigned z
,
505 const mptext_ops
*ops
, void *p
)
509 unsigned i
= sizeof(buf
);
510 int rd
= radix
> 0 ? radix
: -radix
;
530 rc
= simple(n
, radix
, z
, ops
, p
);
533 memset(zbuf
, (radix
< 0) ?
0 : '0', sizeof(zbuf
));
534 while (!rc
&& z
>= sizeof(zbuf
)) {
535 rc
= ops
->put(zbuf
, sizeof(zbuf
), p
);
539 rc
= ops
->put(zbuf
, z
, p
);
542 rc
= ops
->put(buf
+ i
, sizeof(buf
) - i
, p
);
547 /* --- Complicated case --- *
549 * If the number is small, fall back to the simple case above. Otherwise
550 * divide and take remainder by current large power of the radix, and emit
551 * each separately. Don't emit a zero quotient. Be very careful about
552 * leading zeroes on the remainder part, because they're deeply significant.
555 static int complicated(mp
*m
, int radix
, mp
**pr
, unsigned i
, unsigned z
,
556 const mptext_ops
*ops
, void *p
)
563 return (simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, z
, ops
, p
));
566 mp_div(&q
, &m
, m
, pr
[i
]);
574 rc
= complicated(q
, radix
, pr
, i
- 1, z
, ops
, p
);
577 rc
= complicated(m
, radix
, pr
, i
- 1, d
, ops
, p
);
582 /* --- Binary case --- *
584 * Special case for binary output. Goes much faster.
587 static int binary(mp
*m
, int bit
, int radix
, const mptext_ops
*ops
, void *p
)
602 /* --- Work out where to start --- */
605 n
+= bit
- (n
% bit
);
616 mask
= (1 << bit
) - 1;
619 /* --- Main code --- */
635 if (!x
&& !(f
& f_out
))
645 if (q
>= buf
+ sizeof(buf
)) {
646 if ((rc
= ops
->put(buf
, sizeof(buf
), p
)) != 0)
661 rc
= ops
->put(buf
, q
- buf
, p
);
670 /* --- Main driver code --- */
672 int mp_write(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
676 /* --- Set various things up --- */
681 /* --- Check the radix for sensibleness --- */
684 assert(((void)"ascii radix must be <= 36", radix
<= 36));
686 assert(((void)"binary radix must fit in a byte", -radix
< UCHAR_MAX
));
688 assert(((void)"radix can't be zero in mp_write", 0));
690 /* --- If the number is negative, sort that out --- */
693 if (ops
->put("-", 1, p
))
698 /* --- Handle binary radix --- */
701 case 2: case -2: return (binary(m
, 1, radix
, ops
, p
));
702 case 4: case -4: return (binary(m
, 2, radix
, ops
, p
));
703 case 8: case -8: return (binary(m
, 3, radix
, ops
, p
));
704 case 16: case -16: return (binary(m
, 4, radix
, ops
, p
));
705 case 32: case -32: return (binary(m
, 5, radix
, ops
, p
));
706 case -64: return (binary(m
, 6, radix
, ops
, p
));
707 case -128: return (binary(m
, 7, radix
, ops
, p
));
710 /* --- If the number is small, do it the easy way --- */
713 rc
= simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, 0, ops
, p
);
715 /* --- Use a clever algorithm --- *
717 * Square the radix repeatedly, remembering old results, until I get
718 * something more than half the size of the number @m@. Use this to divide
719 * the number: the quotient and remainder will be approximately the same
720 * size, and I'll have split them on a digit boundary, so I can just emit
721 * the quotient and remainder recursively, in order.
726 size_t target
= (MP_LEN(m
) + 1) / 2;
728 mp
*z
= mp_new(1, 0);
730 /* --- Set up the exponent table --- */
732 z
->v
[0] = (radix
> 0 ? radix
: -radix
);
735 assert(((void)"Number is too unimaginably huge", i
< DEPTH
));
737 if (MP_LEN(z
) > target
)
739 z
= mp_sqr(MP_NEW
, z
);
742 /* --- Write out the answer --- */
744 rc
= complicated(m
, radix
, pr
, i
- 1, 0, ops
, p
);
746 /* --- Tidy away the array --- */
752 /* --- Tidying up code --- */
758 /*----- Test rig ----------------------------------------------------------*/
762 #include <mLib/testrig.h>
764 static int verify(dstr
*v
)
767 int ib
= *(int *)v
[0].buf
, ob
= *(int *)v
[2].buf
;
769 mp
*m
= mp_readdstr(MP_NEW
, &v
[1], 0, ib
);
772 fprintf(stderr
, "*** unexpected successful parse\n"
773 "*** input [%2i] = ", ib
);
775 type_hex
.dump(&v
[1], stderr
);
777 fputs(v
[1].buf
, stderr
);
778 mp_writedstr(m
, &d
, 10);
779 fprintf(stderr
, "\n*** (value = %s)\n", d
.buf
);
782 mp_writedstr(m
, &d
, ob
);
783 if (d
.len
!= v
[3].len
|| memcmp(d
.buf
, v
[3].buf
, d
.len
) != 0) {
784 fprintf(stderr
, "*** failed read or write\n"
785 "*** input [%2i] = ", ib
);
787 type_hex
.dump(&v
[1], stderr
);
789 fputs(v
[1].buf
, stderr
);
790 fprintf(stderr
, "\n*** output [%2i] = ", ob
);
792 type_hex
.dump(&d
, stderr
);
794 fputs(d
.buf
, stderr
);
795 fprintf(stderr
, "\n*** expected [%2i] = ", ob
);
797 type_hex
.dump(&v
[3], stderr
);
799 fputs(v
[3].buf
, stderr
);
807 fprintf(stderr
, "*** unexpected parse failure\n"
808 "*** input [%i] = ", ib
);
810 type_hex
.dump(&v
[1], stderr
);
812 fputs(v
[1].buf
, stderr
);
813 fprintf(stderr
, "\n*** expected [%i] = ", ob
);
815 type_hex
.dump(&v
[3], stderr
);
817 fputs(v
[3].buf
, stderr
);
824 assert(mparena_count(MPARENA_GLOBAL
) == 0);
828 static test_chunk tests
[] = {
829 { "mptext-ascii", verify
,
830 { &type_int
, &type_string
, &type_int
, &type_string
, 0 } },
831 { "mptext-bin-in", verify
,
832 { &type_int
, &type_hex
, &type_int
, &type_string
, 0 } },
833 { "mptext-bin-out", verify
,
834 { &type_int
, &type_string
, &type_int
, &type_hex
, 0 } },
838 int main(int argc
, char *argv
[])
841 test_run(argc
, argv
, tests
, SRCDIR
"/tests/mptext");
847 /*----- That's all, folks -------------------------------------------------*/