3 * $Id: mptext.c,v 1.16 2002/10/15 22:57:43 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.16 2002/10/15 22:57:43 mdw
34 * Bug fix: prevent negative zero.
36 * Revision 1.15 2002/10/15 19:18:15 mdw
37 * Fix fencepost bugs in binary radix writing.
39 * Revision 1.14 2002/10/09 00:33:44 mdw
40 * Allow `0o' and `0b' prefixes for octal and binary (from Haskell)
42 * Revision 1.13 2002/10/09 00:21:06 mdw
43 * Allow user-specified `r_xx' bases to be up to 62.
45 * Revision 1.12 2002/01/13 19:51:18 mdw
46 * Extend the textual format to bases up to 62 by distinguishing case.
48 * Revision 1.11 2001/06/16 23:42:17 mdw
51 * Revision 1.10 2001/06/16 13:22:39 mdw
52 * Added fast-track code for binary output bases, and tests.
54 * Revision 1.9 2001/02/03 16:05:17 mdw
55 * Make flags be unsigned. Improve the write algorithm: recurse until the
56 * parts are one word long and use single-precision arithmetic from there.
57 * Fix off-by-one bug when breaking the number apart.
59 * Revision 1.8 2000/12/06 20:32:42 mdw
60 * Reduce binary bytes (to allow marker bits to be ignored). Fix error
61 * message string a bit. Allow leading `+' signs.
63 * Revision 1.7 2000/07/15 10:01:08 mdw
64 * Bug fix in binary input.
66 * Revision 1.6 2000/06/25 12:58:23 mdw
67 * Fix the derivation of `depth' commentary.
69 * Revision 1.5 2000/06/17 11:46:19 mdw
70 * New and much faster stack-based algorithm for reading integers. Support
71 * reading and writing binary integers in bases between 2 and 256.
73 * Revision 1.4 1999/12/22 15:56:56 mdw
74 * Use clever recursive algorithm for writing numbers out.
76 * Revision 1.3 1999/12/10 23:23:26 mdw
77 * Allocate slightly less memory.
79 * Revision 1.2 1999/11/20 22:24:15 mdw
80 * Use function versions of MPX_UMULN and MPX_UADDN.
82 * Revision 1.1 1999/11/17 18:02:16 mdw
83 * New multiprecision integer arithmetic suite.
87 /*----- Header files ------------------------------------------------------*/
97 /*----- Magical numbers ---------------------------------------------------*/
99 /* --- Maximum recursion depth --- *
101 * This is the number of bits in a @size_t@ object. Why?
103 * To see this, let %$b = \textit{MPW\_MAX} + 1$% and let %$Z$% be the
104 * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where
105 * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion
106 * squares the radix at each step, the highest number reached by the
107 * recursion is %$d$%, where:
111 * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum,
112 * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%.
114 * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an
115 * overestimate, since a @size_t@ representation may contain `holes'.
116 * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient
117 * for `some time to come'.
120 #define DEPTH (CHAR_BIT * sizeof(size_t) + 10)
122 /*----- Main code ---------------------------------------------------------*/
124 /* --- @mp_read@ --- *
126 * Arguments: @mp *m@ = destination multiprecision number
127 * @int radix@ = base to assume for data (or zero to guess)
128 * @const mptext_ops *ops@ = pointer to operations block
129 * @void *p@ = data for the operations block
131 * Returns: The integer read, or zero if it didn't work.
133 * Use: Reads an integer from some source. If the @radix@ is
134 * specified, the number is assumed to be given in that radix,
135 * with the letters `a' (either upper- or lower-case) upwards
136 * standing for digits greater than 9. Otherwise, base 10 is
137 * assumed unless the number starts with `0' (octal), `0x' (hex)
138 * or `nnn_' (base `nnn'). An arbitrary amount of whitespace
139 * before the number is ignored.
142 /* --- About the algorithm --- *
144 * The algorithm here is rather aggressive. I maintain an array of
145 * successive squarings of the radix, and a stack of partial results, each
146 * with a counter attached indicating which radix square to multiply by.
147 * Once the item at the top of the stack reaches the same counter level as
148 * the next item down, they are combined together and the result is given a
149 * counter level one higher than either of the results.
151 * Gluing the results together at the end is slightly tricky. Pay attention
154 * This is more complicated because of the need to handle the slightly
158 mp
*mp_read(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
160 int ch
; /* Current char being considered */
161 unsigned f
= 0; /* Flags about the current number */
162 int r
; /* Radix to switch over to */
163 mpw rd
; /* Radix as an @mp@ digit */
164 mp rr
; /* The @mp@ for the radix */
165 unsigned nf
= m ? m
->f
& MP_BURN
: 0; /* New @mp@ flags */
169 mp
*pow
[DEPTH
]; /* List of powers */
170 unsigned pows
; /* Next index to fill */
171 struct { unsigned i
; mp
*m
; } s
[DEPTH
]; /* Main stack */
172 unsigned sp
; /* Current stack pointer */
180 /* --- Initialize the stacks --- */
182 mp_build(&rr
, &rd
, &rd
+ 1);
188 /* --- Initialize the destination number --- */
193 /* --- Read an initial character --- */
199 /* --- Handle an initial sign --- */
201 if (radix
>= 0 && (ch
== '-' || ch
== '+')) {
204 do ch
= ops
->get(p
); while isspace(ch
);
207 /* --- If the radix is zero, look for leading zeros --- */
210 assert(((void)"ascii radix must be <= 62", radix
<= 62));
213 } else if (radix
< 0) {
215 assert(((void)"binary radix must fit in a byte", rd
< UCHAR_MAX
));
217 } else if (ch
!= '0') {
242 /* --- Use fast algorithm for binary radix --- *
244 * This is the restart point after having parsed a radix number from the
245 * input. We check whether the radix is binary, and if so use a fast
246 * algorithm which just stacks the bits up in the right order.
253 case 2: bit
= 1; goto bin
;
254 case 4: bit
= 2; goto bin
;
255 case 8: bit
= 3; goto bin
;
256 case 16: bit
= 4; goto bin
;
257 case 32: bit
= 5; goto bin
;
258 case 64: bit
= 6; goto bin
;
259 case 128: bit
= 7; goto bin
;
263 /* --- The fast binary algorithm --- *
265 * We stack bits up starting at the top end of a word. When one word is
266 * full, we write it to the integer, and start another with the left-over
267 * bits. When the array in the integer is full, we resize using low-level
268 * calls and copy the current data to the top end. Finally, we do a single
269 * bit-shift when we know where the end of the number is.
274 unsigned b
= MPW_BITS
;
278 m
= mp_dest(MP_NEW
, 1, nf
);
282 for (;; ch
= ops
->get(p
)) {
288 /* --- Check that the character is a digit and in range --- */
295 if (ch
>= '0' && ch
<= '9')
300 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
302 else if (ch
>= 'A' && ch
<= 'Z')
311 /* --- Feed the digit into the accumulator --- */
314 if (!x
&& !(f
& f_start
))
321 a
|= MPW(x
) >> (bit
- b
);
328 v
= mpalloc(m
->a
, len
);
329 memcpy(v
+ n
, m
->v
, MPWS(n
));
334 a
= (b
< MPW_BITS
) ?
MPW(x
) << b
: 0;
338 /* --- Finish up --- */
349 m
= mp_lsr(m
, m
, (unsigned long)n
* MPW_BITS
+ b
);
354 /* --- Time to start --- */
356 for (;; ch
= ops
->get(p
)) {
362 /* --- An underscore indicates a numbered base --- */
364 if (ch
== '_' && r
> 0 && r
<= 62) {
367 /* --- Clear out the stacks --- */
369 for (i
= 1; i
< pows
; i
++)
372 for (i
= 0; i
< sp
; i
++)
376 /* --- Restart the search --- */
385 /* --- Check that the character is a digit and in range --- */
392 if (ch
>= '0' && ch
<= '9')
397 if (ch
>= 'a' && ch
<= 'z') /* ASCII dependent! */
399 else if (ch
>= 'A' && ch
<= 'Z')
406 /* --- Sort out what to do with the character --- */
408 if (x
>= 10 && r
>= 0)
416 /* --- Stick the character on the end of my integer --- */
418 assert(((void)"Number is too unimaginably huge", sp
< DEPTH
));
419 s
[sp
].m
= m
= mp_new(1, nf
);
423 /* --- Now grind through the stack --- */
425 while (sp
> 0 && s
[sp
- 1].i
== s
[sp
].i
) {
427 /* --- Combine the top two items --- */
431 m
= mp_mul(m
, m
, pow
[s
[sp
].i
]);
432 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
434 MP_DROP(s
[sp
+ 1].m
);
437 /* --- Make a new radix power if necessary --- */
439 if (s
[sp
].i
>= pows
) {
440 assert(((void)"Number is too unimaginably huge", pows
< DEPTH
));
441 pow
[pows
] = mp_sqr(MP_NEW
, pow
[pows
- 1]);
451 /* --- If we're done, compute the rest of the number --- */
462 /* --- Combine the top two items --- */
466 z
= mp_mul(z
, z
, pow
[s
[sp
+ 1].i
]);
468 m
= mp_add(m
, m
, s
[sp
+ 1].m
);
470 MP_DROP(s
[sp
+ 1].m
);
472 /* --- Make a new radix power if necessary --- */
474 if (s
[sp
].i
>= pows
) {
475 assert(((void)"Number is too unimaginably huge", pows
< DEPTH
));
476 pow
[pows
] = mp_sqr(MP_NEW
, pow
[pows
- 1]);
485 for (i
= 0; i
< sp
; i
++)
489 /* --- Clear the radix power list --- */
493 for (i
= 1; i
< pows
; i
++)
497 /* --- Bail out if the number was bad --- */
503 /* --- Set the sign and return --- */
515 /* --- @mp_write@ --- *
517 * Arguments: @mp *m@ = pointer to a multi-precision integer
518 * @int radix@ = radix to use when writing the number out
519 * @const mptext_ops *ops@ = pointer to an operations block
520 * @void *p@ = data for the operations block
522 * Returns: Zero if it worked, nonzero otherwise.
524 * Use: Writes a large integer in textual form.
527 /* --- Simple case --- *
529 * Use a fixed-sized buffer and single-precision arithmetic to pick off
530 * low-order digits. Put each digit in a buffer, working backwards from the
531 * end. If the buffer becomes full, recurse to get another one. Ensure that
532 * there are at least @z@ digits by writing leading zeroes if there aren't
533 * enough real digits.
536 static int simple(mpw n
, int radix
, unsigned z
,
537 const mptext_ops
*ops
, void *p
)
541 unsigned i
= sizeof(buf
);
542 int rd
= radix
> 0 ? radix
: -radix
;
554 else if (x
< 36) /* Ascii specific */
564 rc
= simple(n
, radix
, z
, ops
, p
);
567 memset(zbuf
, (radix
< 0) ?
0 : '0', sizeof(zbuf
));
568 while (!rc
&& z
>= sizeof(zbuf
)) {
569 rc
= ops
->put(zbuf
, sizeof(zbuf
), p
);
573 rc
= ops
->put(zbuf
, z
, p
);
576 rc
= ops
->put(buf
+ i
, sizeof(buf
) - i
, p
);
581 /* --- Complicated case --- *
583 * If the number is small, fall back to the simple case above. Otherwise
584 * divide and take remainder by current large power of the radix, and emit
585 * each separately. Don't emit a zero quotient. Be very careful about
586 * leading zeroes on the remainder part, because they're deeply significant.
589 static int complicated(mp
*m
, int radix
, mp
**pr
, unsigned i
, unsigned z
,
590 const mptext_ops
*ops
, void *p
)
597 return (simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, z
, ops
, p
));
600 mp_div(&q
, &m
, m
, pr
[i
]);
608 rc
= complicated(q
, radix
, pr
, i
- 1, z
, ops
, p
);
611 rc
= complicated(m
, radix
, pr
, i
- 1, d
, ops
, p
);
616 /* --- Binary case --- *
618 * Special case for binary output. Goes much faster.
621 static int binary(mp
*m
, int bit
, int radix
, const mptext_ops
*ops
, void *p
)
636 /* --- Work out where to start --- */
640 n
+= bit
- (n
% bit
);
644 if (n
>= MP_LEN(m
)) {
651 mask
= (1 << bit
) - 1;
654 /* --- Main code --- */
670 if (!x
&& !(f
& f_out
))
678 ch
= 'a' + x
- 10; /* Ascii specific */
682 if (q
>= buf
+ sizeof(buf
)) {
683 if ((rc
= ops
->put(buf
, sizeof(buf
), p
)) != 0)
696 ch
= 'a' + x
- 10; /* Ascii specific */
700 rc
= ops
->put(buf
, q
- buf
, p
);
709 /* --- Main driver code --- */
711 int mp_write(mp
*m
, int radix
, const mptext_ops
*ops
, void *p
)
715 if (MP_EQ(m
, MP_ZERO
))
716 return (ops
->put("0", 1, p
));
718 /* --- Set various things up --- */
723 /* --- Check the radix for sensibleness --- */
726 assert(((void)"ascii radix must be <= 62", radix
<= 62));
728 assert(((void)"binary radix must fit in a byte", -radix
< UCHAR_MAX
));
730 assert(((void)"radix can't be zero in mp_write", 0));
732 /* --- If the number is negative, sort that out --- */
735 if (ops
->put("-", 1, p
))
740 /* --- Handle binary radix --- */
743 case 2: case -2: return (binary(m
, 1, radix
, ops
, p
));
744 case 4: case -4: return (binary(m
, 2, radix
, ops
, p
));
745 case 8: case -8: return (binary(m
, 3, radix
, ops
, p
));
746 case 16: case -16: return (binary(m
, 4, radix
, ops
, p
));
747 case 32: case -32: return (binary(m
, 5, radix
, ops
, p
));
748 case -64: return (binary(m
, 6, radix
, ops
, p
));
749 case -128: return (binary(m
, 7, radix
, ops
, p
));
752 /* --- If the number is small, do it the easy way --- */
755 rc
= simple(MP_LEN(m
) ? m
->v
[0] : 0, radix
, 0, ops
, p
);
757 /* --- Use a clever algorithm --- *
759 * Square the radix repeatedly, remembering old results, until I get
760 * something more than half the size of the number @m@. Use this to divide
761 * the number: the quotient and remainder will be approximately the same
762 * size, and I'll have split them on a digit boundary, so I can just emit
763 * the quotient and remainder recursively, in order.
768 size_t target
= (MP_LEN(m
) + 1) / 2;
770 mp
*z
= mp_new(1, 0);
772 /* --- Set up the exponent table --- */
774 z
->v
[0] = (radix
> 0 ? radix
: -radix
);
777 assert(((void)"Number is too unimaginably huge", i
< DEPTH
));
779 if (MP_LEN(z
) > target
)
781 z
= mp_sqr(MP_NEW
, z
);
784 /* --- Write out the answer --- */
786 rc
= complicated(m
, radix
, pr
, i
- 1, 0, ops
, p
);
788 /* --- Tidy away the array --- */
794 /* --- Tidying up code --- */
800 /*----- Test rig ----------------------------------------------------------*/
804 #include <mLib/testrig.h>
806 static int verify(dstr
*v
)
809 int ib
= *(int *)v
[0].buf
, ob
= *(int *)v
[2].buf
;
811 mp
*m
= mp_readdstr(MP_NEW
, &v
[1], 0, ib
);
814 fprintf(stderr
, "*** unexpected successful parse\n"
815 "*** input [%2i] = ", ib
);
817 type_hex
.dump(&v
[1], stderr
);
819 fputs(v
[1].buf
, stderr
);
820 mp_writedstr(m
, &d
, 10);
821 fprintf(stderr
, "\n*** (value = %s)\n", d
.buf
);
824 mp_writedstr(m
, &d
, ob
);
825 if (d
.len
!= v
[3].len
|| memcmp(d
.buf
, v
[3].buf
, d
.len
) != 0) {
826 fprintf(stderr
, "*** failed read or write\n"
827 "*** input [%2i] = ", ib
);
829 type_hex
.dump(&v
[1], stderr
);
831 fputs(v
[1].buf
, stderr
);
832 fprintf(stderr
, "\n*** output [%2i] = ", ob
);
834 type_hex
.dump(&d
, stderr
);
836 fputs(d
.buf
, stderr
);
837 fprintf(stderr
, "\n*** expected [%2i] = ", ob
);
839 type_hex
.dump(&v
[3], stderr
);
841 fputs(v
[3].buf
, stderr
);
849 fprintf(stderr
, "*** unexpected parse failure\n"
850 "*** input [%i] = ", ib
);
852 type_hex
.dump(&v
[1], stderr
);
854 fputs(v
[1].buf
, stderr
);
855 fprintf(stderr
, "\n*** expected [%i] = ", ob
);
857 type_hex
.dump(&v
[3], stderr
);
859 fputs(v
[3].buf
, stderr
);
866 assert(mparena_count(MPARENA_GLOBAL
) == 0);
870 static test_chunk tests
[] = {
871 { "mptext-ascii", verify
,
872 { &type_int
, &type_string
, &type_int
, &type_string
, 0 } },
873 { "mptext-bin-in", verify
,
874 { &type_int
, &type_hex
, &type_int
, &type_string
, 0 } },
875 { "mptext-bin-out", verify
,
876 { &type_int
, &type_string
, &type_int
, &type_hex
, 0 } },
880 int main(int argc
, char *argv
[])
883 test_run(argc
, argv
, tests
, SRCDIR
"/tests/mptext");
889 /*----- That's all, folks -------------------------------------------------*/