xref: /openbsd-src/usr.bin/dc/mem.c (revision 8500990981f885cbe5e6a4958549cacc238b5ae6)
1 /*	$OpenBSD: mem.c,v 1.3 2003/10/18 20:34:26 otto Exp $	*/
2 
3 /*
4  * Copyright (c) 2003, Otto Moerbeek <otto@drijf.net>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #ifndef lint
20 static const char rcsid[] = "$OpenBSD: mem.c,v 1.3 2003/10/18 20:34:26 otto Exp $";
21 #endif /* not lint */
22 
23 #include <ssl/err.h>
24 
25 #include <err.h>
26 #include <stdlib.h>
27 #include <string.h>
28 
29 #include "extern.h"
30 
31 struct number *
32 new_number(void)
33 {
34 	struct number *n;
35 
36 	n = bmalloc(sizeof(*n));
37 	n->scale = 0;
38 	n->number = BN_new();
39 	if (n->number == NULL)
40 		err(1, NULL);
41 	return n;
42 }
43 
44 void
45 free_number(struct number *n)
46 {
47 	BN_free(n->number);
48 	free(n);
49 }
50 
51 struct number *
52 dup_number(const struct number *a)
53 {
54 	struct number *n;
55 
56 	n = bmalloc(sizeof(*n));
57 	n->scale = a->scale;
58 	n->number = BN_dup(a->number);
59 	bn_checkp(n->number);
60 	return n;
61 }
62 
63 void *
64 bmalloc(size_t sz)
65 {
66 	void *p;
67 
68 	p = malloc(sz);
69 	if (p == NULL)
70 		err(1, NULL);
71 	return p;
72 }
73 
74 void *
75 brealloc(void *p, size_t sz)
76 {
77 	void *q;
78 
79 	q = realloc(p, sz);
80 	if (q == NULL) {
81 		free(p);
82 		err(1, NULL);
83 	}
84 	return q;
85 }
86 
87 char *
88 bstrdup(const char *p)
89 {
90 	char *q;
91 
92 	q = strdup(p);
93 	if (q == NULL)
94 		err(1, NULL);
95 	return q;
96 }
97 
98 void
99 bn_check(int x)						\
100 {
101 	if (x == 0)
102 		err(1, "big number failure %lx", ERR_get_error());
103 }
104 
105 void
106 bn_checkp(const void *p)						\
107 {
108 	if (p == NULL)
109 		err(1, "allocation failure %lx", ERR_get_error());
110 }
111