/*
 * Copyright (c) 2002, 2004, 2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: strnew.c,v 1.21 2005/06/02 19:00:37 ca Exp $")

#include "sm/assert.h"
#include "sm/magic.h"
#include "sm/memops.h"
#include "sm/rpool.h"
#include "sm/strrcb.h"
#include "sm/str-int.h"
#include "sm/str2rcb.h"

#ifndef SM_MIN_BUF_SIZE
# define SM_MIN_BUF_SIZE	8
#endif

/*
**  SM_STR_NEW -- Create a new buf structure.
**
**	Parameters:
**		rpool -- The rpool in which to allocate.
**		len -- Best guess as to how long the buf will be.
**		maxlen -- Maximum length of buf data, if 0 a system
**			default will be used.
**
**	Returns:
**		New buf object.
**		NULL on error (ENOMEM)
**
**	Side Effects: none on error
**
**	Last code review: 2005-03-18 18:16:53
**	Last code change: 2005-03-18 18:16:35
*/

sm_str_P
sm_str_new(sm_rpool_P rpool, uint len, uint maxlen)
{
	sm_str_P str;

	if (len < SM_MIN_BUF_SIZE)
		len = SM_MIN_BUF_SIZE;
	if (maxlen == 0)
		maxlen = SM_STR_MAX_LEN;
	if (maxlen < SM_MIN_BUF_SIZE)
		maxlen = SM_MIN_BUF_SIZE;
#if SM_STR_READ
#if SM_RCB_END_RCB
	XXX THIS IS UGLY... and broken
	len += SM_RCB_EORCB_LEN;
	maxlen += SM_RCB_EORCB_LEN;
#endif /* SM_RCB_END_RCB */
#endif /* SM_STR_READ */

	SM_REQUIRE(maxlen == 0 || len <= maxlen);

	str = sm_rpool_malloc(rpool, sizeof(*str));
	if (str == NULL)
		return NULL;
	str->sm_str_base = sm_rpool_malloc(rpool, len);
	if (str->sm_str_base == NULL)
	{
		sm_rpool_free_size(rpool, str, sizeof(*str));
		return NULL;
	}
#if SM_STR_CHECK
	sm_memzero(str->sm_str_base, len);
#endif
	str->sm_str_size = len;
	str->sm_str_len = 0;
#if SM_STR_READ
	str->sm_rcb_rw = 0;
# if SM_RCB_CHECK
	str->sm_rcb_state = SM_RCB_NONE;
# endif /* SM_RCB_CHECK */
#endif /* SM_STR_READ */
	str->sm_str_max = maxlen;
	str->sm_str_rpool = rpool;
	str->sm_magic = SM_STR_MAGIC;
	return str;
}


syntax highlighted by Code2HTML, v. 0.9.1