xref: /titanic_52/usr/src/cmd/mandoc/mandoc_aux.c (revision 260e9a87725c090ba5835b1f9f0b62fa2f96036f)
1 /*	$Id: mandoc_aux.c,v 1.4 2014/08/10 23:54:41 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 #include <stdarg.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 
27 #include "mandoc.h"
28 #include "mandoc_aux.h"
29 
30 int
31 mandoc_asprintf(char **dest, const char *fmt, ...)
32 {
33 	va_list	 ap;
34 	int	 ret;
35 
36 	va_start(ap, fmt);
37 	ret = vasprintf(dest, fmt, ap);
38 	va_end(ap);
39 
40 	if (-1 == ret) {
41 		perror(NULL);
42 		exit((int)MANDOCLEVEL_SYSERR);
43 	}
44 	return(ret);
45 }
46 
47 void *
48 mandoc_calloc(size_t num, size_t size)
49 {
50 	void	*ptr;
51 
52 	ptr = calloc(num, size);
53 	if (NULL == ptr) {
54 		perror(NULL);
55 		exit((int)MANDOCLEVEL_SYSERR);
56 	}
57 	return(ptr);
58 }
59 
60 void *
61 mandoc_malloc(size_t size)
62 {
63 	void	*ptr;
64 
65 	ptr = malloc(size);
66 	if (NULL == ptr) {
67 		perror(NULL);
68 		exit((int)MANDOCLEVEL_SYSERR);
69 	}
70 	return(ptr);
71 }
72 
73 void *
74 mandoc_realloc(void *ptr, size_t size)
75 {
76 
77 	ptr = realloc(ptr, size);
78 	if (NULL == ptr) {
79 		perror(NULL);
80 		exit((int)MANDOCLEVEL_SYSERR);
81 	}
82 	return(ptr);
83 }
84 
85 void *
86 mandoc_reallocarray(void *ptr, size_t num, size_t size)
87 {
88 
89 	ptr = reallocarray(ptr, num, size);
90 	if (NULL == ptr) {
91 		perror(NULL);
92 		exit((int)MANDOCLEVEL_SYSERR);
93 	}
94 	return(ptr);
95 }
96 
97 char *
98 mandoc_strdup(const char *ptr)
99 {
100 	char	*p;
101 
102 	p = strdup(ptr);
103 	if (NULL == p) {
104 		perror(NULL);
105 		exit((int)MANDOCLEVEL_SYSERR);
106 	}
107 	return(p);
108 }
109 
110 char *
111 mandoc_strndup(const char *ptr, size_t sz)
112 {
113 	char	*p;
114 
115 	p = mandoc_malloc(sz + 1);
116 	memcpy(p, ptr, sz);
117 	p[(int)sz] = '\0';
118 	return(p);
119 }
120