Generic interface.
[u/mdw/catacomb] / mptext-string.c
CommitLineData
d3409d5e 1/* -*-c-*-
2 *
3 * $Id: mptext-string.c,v 1.1 1999/11/17 18:02:16 mdw Exp $
4 *
5 * Reading and writing large integers on strings
6 *
7 * (c) 1999 Straylight/Edgeware
8 */
9
10/*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Catacomb.
13 *
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.
18 *
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.
23 *
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,
27 * MA 02111-1307, USA.
28 */
29
30/*----- Revision history --------------------------------------------------*
31 *
32 * $Log: mptext-string.c,v $
33 * Revision 1.1 1999/11/17 18:02:16 mdw
34 * New multiprecision integer arithmetic suite.
35 *
36 */
37
38/*----- Header files ------------------------------------------------------*/
39
40#include <string.h>
41
42#include "mptext.h"
43
44/*----- Main code ---------------------------------------------------------*/
45
46/* --- Operations table --- */
47
48static int get(void *p)
49{
50 mptext_stringctx *c = p;
51 if (c->buf >= c->lim)
52 return (EOF);
53 return (*c->buf++);
54}
55
56static void unget(int ch, void *p)
57{
58 mptext_stringctx *c = p;
59 if (ch != EOF)
60 c->buf--;
61}
62
63static int put(char *s, size_t sz, void *p)
64{
65 mptext_stringctx *c = p;
66 int rc = 0;
67 if (sz > c->lim - c->buf) {
68 sz = c->lim - c->buf;
69 rc = EOF;
70 }
71 if (sz) {
72 memcpy(c->buf, s, sz);
73 c->buf += sz;
74 }
75 return (rc);
76}
77
78const mptext_ops mptext_stringops = { get, unget, put };
79
80/* --- Convenience functions --- */
81
82mp *mp_readstring(mp *m, const char *p, char **end, int radix)
83{
84 mptext_stringctx c;
85 c.buf = (char *)p;
86 c.lim = c.buf + strlen(p);
87 m = mp_read(m, radix, &mptext_stringops, &c);
88 if (end)
89 *end = c.buf;
90 return (m);
91}
92
93int mp_writestring(mp *m, char *p, size_t sz, int radix)
94{
95 mptext_stringctx c;
96 int rc;
97 if (!sz)
98 return (0);
99 c.buf = p;
100 c.lim = p + sz - 1;
101 rc = mp_write(m, radix, &mptext_stringops, &c);
102 *c.buf = 0;
103 return (rc);
104}
105
106/*----- That's all, folks -------------------------------------------------*/