chiark / gitweb /
rand/rand-x86ish.S: Hoist argument register allocation outside.
[catacomb] / math / mptext-string.c
1 /* -*-c-*-
2  *
3  * Reading and writing large integers on strings
4  *
5  * (c) 1999 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Catacomb.
11  *
12  * Catacomb is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * Catacomb is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with Catacomb; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include <string.h>
31
32 #include "mptext.h"
33
34 /*----- Main code ---------------------------------------------------------*/
35
36 /* --- Operations table --- */
37
38 static int get(void *p)
39 {
40   mptext_stringctx *c = p;
41   if (c->buf >= c->lim)
42     return (EOF);
43   return ((unsigned char)*c->buf++);
44 }
45
46 static void unget(int ch, void *p)
47 {
48   mptext_stringctx *c = p;
49   if (ch != EOF)
50     c->buf--;
51 }
52
53 static int put(const char *s, size_t sz, void *p)
54 {
55   mptext_stringctx *c = p;
56   int rc = 0;
57   if (sz > c->lim - c->buf) {
58     sz = c->lim - c->buf;
59     rc = EOF;
60   }
61   if (sz) {
62     memcpy(c->buf, s, sz);
63     c->buf += sz;
64   }
65   return (rc);
66 }
67
68 const mptext_ops mptext_stringops = { get, unget, put };
69
70 /* --- Convenience functions --- */
71
72 mp *mp_readstring(mp *m, const char *p, char **end, int radix)
73 {
74   mptext_stringctx c;
75   c.buf = (/*unconst */ char *)p;
76   c.lim = c.buf + strlen(p);
77   m = mp_read(m, radix, &mptext_stringops, &c);
78   if (end)
79     *end = c.buf;
80   return (m);
81 }
82
83 int mp_writestring(mp *m, char *p, size_t sz, int radix)
84 {
85   mptext_stringctx c;
86   int rc;
87   if (!sz)
88     return (0);
89   c.buf = p;
90   c.lim = p + sz - 1;
91   rc = mp_write(m, radix, &mptext_stringops, &c);
92   *c.buf = 0;
93   return (rc);
94 }
95
96 /*----- That's all, folks -------------------------------------------------*/