summaryrefslogtreecommitdiff
path: root/src/tet3/dtet2lib/bufchk.c
blob: 2218579ad763478a9ecd6c450f6f2d3d40ecf4f3 (plain)
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
/*
 *      SCCS:  @(#)bufchk.c	1.8 (98/08/28) 
 *
 *	UniSoft Ltd., London, England
 *
 * (C) Copyright 1992 X/Open Company Limited
 *
 * All rights reserved.  No part of this source code may be reproduced,
 * stored in a retrieval system, or transmitted, in any form or by any
 * means, electronic, mechanical, photocopying, recording or otherwise,
 * except as stated in the end-user licence agreement, without the prior
 * permission of the copyright owners.
 *
 * X/Open and the 'X' symbol are trademarks of X/Open Company Limited in
 * the UK and other countries.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

/************************************************************************

SCCS:   	@(#)bufchk.c	1.8 98/08/28 TETware release 3.3
NAME:		bufchk.c
PRODUCT:	TETware
AUTHOR:		Andrew Dingwall, UniSoft Ltd.
DATE CREATED:	April 1992

DESCRIPTION:
	buffer check and (re)allocation function

MODIFICATIONS:

	Andrew Dingwall, UniSoft Ltd., July 1998
	Added support for shared API libraries.
 
************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "dtmac.h"
#include "error.h"
#include "ltoa.h"
#include "dtetlib.h"


/*
**	tet_bufchk() - check that there is enough space in a data buffer
**		pointed to by *bpp, length at *lp, and grow it if necessary
**
**	return 0 if successful or -1 on error
*/

TET_IMPORT int tet_bufchk(bpp, lp, newlen)
register char **bpp;
register int *lp, newlen;
{
	register char *bp;

#ifndef NOTRACE
	/* the assert was done in buftrace.c */
#else
	ASSERT(newlen >= 0);
#endif

	if (*lp >= newlen)
		return(0);

	errno = 0;
	if (*bpp == (char *) 0) {
		TRACE1(tet_Tbuf, 8, "allocate new buffer");
		bp = malloc((size_t) newlen);
	}
	else {
		TRACE1(tet_Tbuf, 8, "grow existing buffer");
		bp = realloc(*bpp, (size_t) newlen);
	}

	if (bp) {
		*bpp = bp;
		*lp = newlen;
		return(0);
	}

	/* here if malloc/realloc failed */
	error(errno, "can't grow data buffer, wanted", tet_i2a(newlen));
	if (*bpp) {
		errno = 0;
		if ((bp = realloc(*bpp, (size_t) *lp)) == (char *) 0) {
			error(errno, "can't realloc old data buffer",
				(char *) 0);
			*lp = 0;
		}
		else
			TRACE2(tet_Tbuf, 8, "realloc old buffer at %s",
				tet_i2x(bp));
		*bpp = bp;
	}
	else
		*lp = 0;

	return(-1);
}