xref: /illumos-gate/usr/src/cmd/mandoc/mandoc_aux.c (revision c2d5ab8758c7f6619e844d75eea8b27d25c95469)
1 /*	$Id: mandoc_aux.c,v 1.9 2015/11/07 14:22:29 schwarze Exp $ */
2 /*
3  * Copyright (c) 2009, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2014 Ingo Schwarze <schwarze@openbsd.org>
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 AUTHORS DISCLAIM ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS 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 #include "config.h"
19 
20 #include <sys/types.h>
21 
22 #if HAVE_ERR
23 #include <err.h>
24 #endif
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 
30 #include "mandoc.h"
31 #include "mandoc_aux.h"
32 
33 
34 int
35 mandoc_asprintf(char **dest, const char *fmt, ...)
36 {
37 	va_list	 ap;
38 	int	 ret;
39 
40 	va_start(ap, fmt);
41 	ret = vasprintf(dest, fmt, ap);
42 	va_end(ap);
43 
44 	if (ret == -1)
45 		err((int)MANDOCLEVEL_SYSERR, NULL);
46 	return ret;
47 }
48 
49 void *
50 mandoc_calloc(size_t num, size_t size)
51 {
52 	void	*ptr;
53 
54 	ptr = calloc(num, size);
55 	if (ptr == NULL)
56 		err((int)MANDOCLEVEL_SYSERR, NULL);
57 	return ptr;
58 }
59 
60 void *
61 mandoc_malloc(size_t size)
62 {
63 	void	*ptr;
64 
65 	ptr = malloc(size);
66 	if (ptr == NULL)
67 		err((int)MANDOCLEVEL_SYSERR, NULL);
68 	return ptr;
69 }
70 
71 void *
72 mandoc_realloc(void *ptr, size_t size)
73 {
74 
75 	ptr = realloc(ptr, size);
76 	if (ptr == NULL)
77 		err((int)MANDOCLEVEL_SYSERR, NULL);
78 	return ptr;
79 }
80 
81 void *
82 mandoc_reallocarray(void *ptr, size_t num, size_t size)
83 {
84 
85 	ptr = reallocarray(ptr, num, size);
86 	if (ptr == NULL)
87 		err((int)MANDOCLEVEL_SYSERR, NULL);
88 	return ptr;
89 }
90 
91 char *
92 mandoc_strdup(const char *ptr)
93 {
94 	char	*p;
95 
96 	p = strdup(ptr);
97 	if (p == NULL)
98 		err((int)MANDOCLEVEL_SYSERR, NULL);
99 	return p;
100 }
101 
102 char *
103 mandoc_strndup(const char *ptr, size_t sz)
104 {
105 	char	*p;
106 
107 	p = mandoc_malloc(sz + 1);
108 	memcpy(p, ptr, sz);
109 	p[(int)sz] = '\0';
110 	return p;
111 }
112