84056e65901d5b90cd89ed4604f5108acf8243bb
3 * $Id: mptext.c,v 1.13 2002/10/09 00:21:06 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.13 2002/10/09 00:21:06 mdw
34 * Allow user-specified `r_xx' bases to be up to 62.
36 * Revision 1.12 2002/01/13 19:51:18 mdw
37 * Extend the textual format to bases up to 62 by distinguishing case.
39 * Revision 1.11 2001/06/16 23:42:17 mdw
42 * Revision 1.10 2001/06/16 13:22:39 mdw
43 * Added fast-track code for binary output bases, and tests.
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.
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.
54 * Revision 1.7 2000/07/15 10:01:08 mdw
55 * Bug fix in binary input.
57 * Revision 1.6 2000/06/25 12:58:23 mdw
58 * Fix the derivation of `depth' commentary.
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.
64 * Revision 1.4 1999/12/22 15:56:56 mdw
65 * Use clever recursive algorithm for writing numbers out.
67 * Revision 1.3 1999/12/10 23:23:26 mdw
68 * Allocate slightly less memory.
70 * Revision 1.2 1999/11/20 22:24:15 mdw
71 * Use function versions of MPX_UMULN and MPX_UADDN.
73 * Revision 1.1 1999/11/17 18:02:16 mdw
74 * New multiprecision integer arithmetic suite.
78 /*----- Header files ------------------------------------------------------*/
88 /*----- Magical numbers ---------------------------------------------------*/
90 /* --- Maximum recursion depth --- *
92 * This is the number of bits in a @size_t@ object. Why?
94 * To see this, let %$b = \textit{MPW\_MAX} + 1$% and let %$Z$% be the
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:
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$%.
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'.
111 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
113 /*----- Main code ---------------------------------------------------------*/
115 /* --- @mp_read@ --- *
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
122 * Returns: The integer read, or zero if it didn't work.
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.
133 /* --- About the algorithm --- *
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.
142 * Gluing the results together at the end is slightly tricky. Pay attention
145 * This is more complicated because of the need to handle the slightly
149 mp
*mp_read(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
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 */
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 */
171 /* --- Initialize the stacks --- */
173 mp_build(&rr
, &rd
, &rd
+ 1);
179 /* --- Initialize the destination number --- */
184 /* --- Read an initial character --- */
190 /* --- Handle an initial sign --- */
192 if (radix
>= 0 && (ch
== '-' || ch
== '+')) {
195 do ch
= ops
->get(p
); while isspace(ch
);
198 /* --- If the radix is zero, look for leading zeros --- */
201 assert(((void)"ascii radix must be <= 62", radix
<= 62));
204 } else if (radix
< 0) {
206 assert(((void)"binary radix must fit in a byte", rd
< UCHAR_MAX
));
208 } else if (ch
!= '0') {
223 /* --- Use fast algorithm for binary radix --- *
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.
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
;
244 /* --- The fast binary algorithm --- *
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.
255 unsigned b
= MPW_BITS
;
259 m
= mp_dest(MP_NEW
, 1, nf
);
263 for (;; ch
= ops
->get(p
)) {
269 /* --- Check that the character is a digit and in range --- */
276 if (ch
>= '0' && ch
<= '9')
281 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
283 else if (ch
>= 'A' && ch
<= 'Z')
292 /* --- Feed the digit into the accumulator --- */
295 if (!x
&& !(f
& f_start
))
302 a
|= MPW(x
) >> (bit
- b
);
309 v
= mpalloc(m
->a
, len
);
310 memcpy(v
+ n
, m
->v
, MPWS(n
));
315 a
= (b
< MPW_BITS
) ?
MPW(x
) << b
: 0;
319 /* --- Finish up --- */
330 m
= mp_lsr(m
, m
, (unsigned long)n
* MPW_BITS
+ b
);
335 /* --- Time to start --- */
337 for (;; ch
= ops
->get(p
)) {
343 /* --- An underscore indicates a numbered base --- */
345 if (ch
== '_' && r
> 0 && r
<= 62) {
348 /* --- Clear out the stacks --- */
350 for (i
= 1; i
< pows
; i
++)
353 for (i
= 0; i
< sp
; i
++)
357 /* --- Restart the search --- */
366 /* --- Check that the character is a digit and in range --- */
373 if (ch
>= '0' && ch
<= '9')
378 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
380 else if (ch
>= 'A' && ch
<= 'Z')
387 /* --- Sort out what to do with the character --- */
389 if (x
>= 10 && r
>= 0)
397 /* --- Stick the character on the end of my integer --- */
399 assert(((void)"Number is too unimaginably huge", sp
< DEPTH
));
400 s
[sp
].m
= m
= mp_new(1, nf
);
404 /* --- Now grind through the stack --- */
406 while (sp
> 0 && s
[sp
- 1].i
== s
[sp
].i
) {
408 /* --- Combine the top two items --- */
412 m
= mp_mul(m
, m
, pow
[s
[sp
].i
]);
413 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
415 MP_DROP(s
[sp
+ 1].m
);
418 /* --- Make a new radix power if necessary --- */
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]);
432 /* --- If we're done, compute the rest of the number --- */
443 /* --- Combine the top two items --- */
447 z
= mp_mul(z
, z
, pow
[s
[sp
+ 1].i
]);
449 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
451 MP_DROP(s
[sp
+ 1].m
);
453 /* --- Make a new radix power if necessary --- */
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]);
466 for (i
= 0; i
< sp
; i
++)
470 /* --- Clear the radix power list --- */
474 for (i
= 1; i
< pows
; i
++)
478 /* --- Bail out if the number was bad --- */
484 /* --- Set the sign and return --- */
495 /* --- @mp_write@ --- *
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
502 * Returns: Zero if it worked, nonzero otherwise.
504 * Use: Writes a large integer in textual form.
507 /* --- Simple case --- *
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.
516 static int simple(mpw n
, int radix
, unsigned z
,
517 const mptext_ops
*ops
, void *p
)
521 unsigned i
= sizeof(buf
);
522 int rd
= radix
> 0 ? radix
: -radix
;
534 else if (x
< 36) /* Ascii specific */
544 rc
= simple(n
, radix
, z
, ops
, p
);
547 memset(zbuf
, (radix
< 0) ?
0 : '0', sizeof(zbuf
));
548 while (!rc
&& z
>= sizeof(zbuf
)) {
549 rc
= ops
->put(zbuf
, sizeof(zbuf
), p
);
553 rc
= ops
->put(zbuf
, z
, p
);
556 rc
= ops
->put(buf
+ i
, sizeof(buf
) - i
, p
);
561 /* --- Complicated case --- *
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.
569 static int complicated(mp
*m
, int radix
, mp
**pr
, unsigned i
, unsigned z
,
570 const mptext_ops
*ops
, void *p
)
577 return (simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, z
, ops
, p
));
580 mp_div(&q
, &m
, m
, pr
[i
]);
588 rc
= complicated(q
, radix
, pr
, i
- 1, z
, ops
, p
);
591 rc
= complicated(m
, radix
, pr
, i
- 1, d
, ops
, p
);
596 /* --- Binary case --- *
598 * Special case for binary output. Goes much faster.
601 static int binary(mp
*m
, int bit
, int radix
, const mptext_ops
*ops
, void *p
)
616 /* --- Work out where to start --- */
619 n
+= bit
- (n
% bit
);
630 mask
= (1 << bit
) - 1;
633 /* --- Main code --- */
649 if (!x
&& !(f
& f_out
))
657 ch
= 'a' + x
- 10; /* Ascii specific */
661 if (q
>= buf
+ sizeof(buf
)) {
662 if ((rc
= ops
->put(buf
, sizeof(buf
), p
)) != 0)
675 ch
= 'a' + x
- 10; /* Ascii specific */
679 rc
= ops
->put(buf
, q
- buf
, p
);
688 /* --- Main driver code --- */
690 int mp_write(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
694 /* --- Set various things up --- */
699 /* --- Check the radix for sensibleness --- */
702 assert(((void)"ascii radix must be <= 62", radix
<= 62));
704 assert(((void)"binary radix must fit in a byte", -radix
< UCHAR_MAX
));
706 assert(((void)"radix can't be zero in mp_write", 0));
708 /* --- If the number is negative, sort that out --- */
711 if (ops
->put("-", 1, p
))
716 /* --- Handle binary 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
));
728 /* --- If the number is small, do it the easy way --- */
731 rc
= simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, 0, ops
, p
);
733 /* --- Use a clever algorithm --- *
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.
744 size_t target
= (MP_LEN(m
) + 1) / 2;
746 mp
*z
= mp_new(1, 0);
748 /* --- Set up the exponent table --- */
750 z
->v
[0] = (radix
> 0 ? radix
: -radix
);
753 assert(((void)"Number is too unimaginably huge", i
< DEPTH
));
755 if (MP_LEN(z
) > target
)
757 z
= mp_sqr(MP_NEW
, z
);
760 /* --- Write out the answer --- */
762 rc
= complicated(m
, radix
, pr
, i
- 1, 0, ops
, p
);
764 /* --- Tidy away the array --- */
770 /* --- Tidying up code --- */
776 /*----- Test rig ----------------------------------------------------------*/
780 #include <mLib/testrig.h>
782 static int verify(dstr
*v
)
785 int ib
= *(int *)v
[0].buf
, ob
= *(int *)v
[2].buf
;
787 mp
*m
= mp_readdstr(MP_NEW
, &v
[1], 0, ib
);
790 fprintf(stderr
, "*** unexpected successful parse\n"
791 "*** input [%2i] = ", ib
);
793 type_hex
.dump(&v
[1], stderr
);
795 fputs(v
[1].buf
, stderr
);
796 mp_writedstr(m
, &d
, 10);
797 fprintf(stderr
, "\n*** (value = %s)\n", d
.buf
);
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"
803 "*** input [%2i] = ", ib
);
805 type_hex
.dump(&v
[1], stderr
);
807 fputs(v
[1].buf
, stderr
);
808 fprintf(stderr
, "\n*** output [%2i] = ", ob
);
810 type_hex
.dump(&d
, stderr
);
812 fputs(d
.buf
, stderr
);
813 fprintf(stderr
, "\n*** expected [%2i] = ", ob
);
815 type_hex
.dump(&v
[3], stderr
);
817 fputs(v
[3].buf
, stderr
);
825 fprintf(stderr
, "*** unexpected parse failure\n"
826 "*** input [%i] = ", ib
);
828 type_hex
.dump(&v
[1], stderr
);
830 fputs(v
[1].buf
, stderr
);
831 fprintf(stderr
, "\n*** expected [%i] = ", ob
);
833 type_hex
.dump(&v
[3], stderr
);
835 fputs(v
[3].buf
, stderr
);
842 assert(mparena_count(MPARENA_GLOBAL
) == 0);
846 static test_chunk tests
[] = {
847 { "mptext-ascii", verify
,
848 { &type_int
, &type_string
, &type_int
, &type_string
, 0 } },
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 } },
856 int main(int argc
, char *argv
[])
859 test_run(argc
, argv
, tests
, SRCDIR
"/tests/mptext");
865 /*----- That's all, folks -------------------------------------------------*/