File: stdrusty.c

package info (click to toggle)
ccontrol 0.9.1+20060806-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 440 kB
  • ctags: 188
  • sloc: ansic: 1,478; sh: 302; makefile: 142; python: 141; xml: 64
file content (113 lines) | stat: -rw-r--r-- 2,174 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#define _GNU_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <signal.h>
#include <limits.h>

#include "stdrusty.h"

const char *int_to_string(int val)
{
	unsigned int ord, i;
	static char buf[2][CHAR_SIZE(val)];
	static int which;
	char *p = buf[which];

	if (val < 0) {
		*(p++) = '-';
		val = -val;
	}

	for (i = 0, ord = 1000000; ord; ord /= 10) {
		if (val >= ord || i != 0) {
			p[i++] = '0' + val / ord;
			val %= ord;
		}
	}
	if (i == 0)
		p[i++] = '0';
	p[i] = '\0';
	which = !which;
	return buf[!which];
}

void fatal(const char *msg, int err, ...)
{
	const char *str;
	va_list arglist;

	write(STDERR_FILENO, "ccontrol error: ", strlen("ccontrol error: "));
	write(STDERR_FILENO, msg, strlen(msg));

	va_start(arglist, err);
	while ((str = va_arg(arglist, const char *)) != NULL)
		write(STDERR_FILENO, str, strlen(str));
	va_end(arglist);
	if (err) {
		str = int_to_string(err);
		write(STDERR_FILENO, ": ", strlen(": "));
		write(STDERR_FILENO, str, strlen(str));
	}
	write(STDERR_FILENO, "\n", 1);
	exit(1);
}

#ifndef SIZE_MAX
#define SIZE_MAX UINT_MAX
#endif

void *_realloc_array(void *ptr, size_t size, size_t num)
{
        if (num >= SIZE_MAX/size)
                return NULL;
        return realloc_nofail(ptr, size * num);
}

void *realloc_nofail(void *ptr, size_t size)
{
        ptr = realloc(ptr, size);
	if (ptr)
		return ptr;
	fatal("realloc failed", errno, NULL);
}

/* This version adds one byte (for nul term) */
void *suck_file(int fd, unsigned long *size)
{
	unsigned int max = 16384;
	int ret, savederr = 0;
	void *buffer;

	if (fd < 0)
		return NULL;

	buffer = malloc(max+1);
	*size = 0;
	while ((ret = read(fd, buffer + *size, max - *size)) > 0) {
		*size += ret;
		if (*size == max)
			buffer = realloc(buffer, max *= 2 + 1);
		else
			/* Should never get short reads on file. */
			break;
	}
	if (ret < 0) {
		savederr = errno;
		free(buffer);
		buffer = NULL;
	} else
		((char *)buffer)[*size] = '\0';
	errno = savederr;
	return buffer;
}

void release_file(void *data, unsigned long size)
{
	free(data);
}