File:  [ELWIX - Embedded LightWeight unIX -] / libelwix / src / str.c
Revision 1.11: download - view: text, annotated - select for diffs - revision graph
Mon Oct 28 09:58:51 2024 UTC (3 weeks, 6 days ago) by misho
Branches: MAIN
CVS tags: elwix6_6, elwix6_5, HEAD, ELWIX6_5, ELWIX6_4
Version 6.4

/*************************************************************************
* (C) 2013 AITNET ltd - Sofia/Bulgaria - <misho@aitnet.org>
*  by Michael Pounov <misho@elwix.org>
*
* $Author: misho $
* $Id: str.c,v 1.11 2024/10/28 09:58:51 misho Exp $
*
**************************************************************************
The ELWIX and AITNET software is distributed under the following
terms:

All of the documentation and software included in the ELWIX and AITNET
Releases is copyrighted by ELWIX - Sofia/Bulgaria <info@elwix.org>

Copyright 2004 - 2024
	by Michael Pounov <misho@elwix.org>.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
This product includes software developed by Michael Pounov <misho@elwix.org>
ELWIX - Embedded LightWeight unIX and its contributors.
4. Neither the name of AITNET nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY AITNET AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include "global.h"


/*
 * str_FreeNullTerm() - Free dynamic allocated null terminated array with strings
 *
 * @arr = Pointer to array for free
 * return: none
 */
void
str_FreeNullTerm(char *** __restrict arr)
{
	char **a;

	if (arr && *arr) {
		a = *arr;
		while (a && *a)
			e_free(*a++);
		e_free(*arr);
		*arr = NULL;
	}
}

/*
 * str_ArgsNum() Parse and calculate number of arguments
 *
 * @csArgs = Input arguments line
 * @csDelim = Delimiter(s) for separate
 * return: 0 error format; -1 error:: can`t read; >0 ok, number of items
 */
int
str_ArgsNum(const char *csArgs, const char *csDelim)
{
	register int res;
	char *pos;

	if (!csArgs || !csDelim)
		return -1;

	for (res = 1, pos = (char*) csArgs; (pos = strpbrk(pos, csDelim)); res++, pos++);

	return res;
}

/*
 * str_ExecArgs() - Build exec arguments from other array
 *
 * @psProg = Program name for execute
 * @oldarg = Arguments array
 * return: NULL error; !=NULL Allocated execution array(must be e_free)
 */
char **
str_ExecArgs(const char *psProg, const char **oldarg)
{
	char **newarg, **el;
	register int i, num;

	if (!psProg || !oldarg)
		return NULL;
	else
		newarg = el = NULL;

	/* count items arguments */
	for (num = 0; oldarg[num]; num++);

	/* create and copy new arguments */
	newarg = e_calloc(num + 2, sizeof(char*));
	if (!newarg)
		return NULL;
	else
		el = newarg;

	*el = e_strdup(psProg);
	el++;

	for (i = 0; oldarg[i]; i++, el++)
		*el = e_strdup(oldarg[i]);
	*el = NULL;

	return newarg;
}

/*
 * str_CopyEnv() - Copy environment to new environment array;
 *
 * @oldenv = Environment array
 * return: NULL error; !=NULL Allocated new environment array(must be e_free)
 */
char **
str_CopyEnv(const char **oldenv)
{
	char **newenv, **el;
	register int i, num;

	if (!oldenv)
		return NULL;
	else
		newenv = el = NULL;

	/* count items environment */
	for (i = num = 0; oldenv[i]; i++)
		if (*strchr(oldenv[i], '='))
			num++;

	/* create and copy new environment */
	newenv = e_calloc(num + 1, sizeof(char*));
	if (!newenv)
		return NULL;
	else
		el = newenv;

	for (i = 0; oldenv[i]; i++)
		if (*strchr(oldenv[i], '=')) {
			*el = e_strdup(oldenv[i]);
			el++;
		}
	*el = NULL;

	return newenv;
}

/*
 * str_Ast() - Function for evaluate string like asterisk variable "{text[:[-]#[:#]]}"
 *
 * @csString = Input string
 * return: NULL error, !=NULL Allocated new string evaluated from input string, 
 * 		must be ait_freeVar()
 */
ait_val_t *
str_Ast(const char *csString)
{
	char *ext, *str, *eb;
	int e[2] = { 0, 0 };
	ait_val_t *out = NULL;

	if (!csString)
		return NULL;

	if (!strchr(csString, '{') || !strrchr(csString, '}')) {
		elwix_SetErr(EINVAL, "Invalid input string format ... must be like "
				"{text[:[-]#[:#]]}");
		return NULL;
	} else if (!(out = ait_allocVar()))
		return NULL;
	else {
		AIT_INIT_VAL2(out, string);

		str = e_strdup(strchr(csString, '{') + 1);
		*strrchr(str, '}') = 0;
	}

	if ((ext = strchr(str, ':'))) {
		*ext++ = 0;
		e[0] = strtol(ext, &eb, 0);
		if ((ext = strchr(eb, ':')))
			e[1] = strtol(++ext, NULL, 0);

		/* make cut prefix */
		if (e[0] >= 0)
			ext = str + MIN(e[0], strlen(str));
		else
			ext = str + MAX(strlen(str) + e[0], 0);
		/* make cut suffix */
		if (e[1] > 0)
			*(ext + MIN(e[1], strlen(ext))) = 0;
	} else
		/* ok, clear show */
		ext = str;

	AIT_SET_STR(out, ext);
	e_free(str);

	return out;
}

/*
 * str_Hex2Dig() - Convert from Hex string to digit array
 *
 * @psLine = Text string
 * return: NULL nothing to do or error; 
 * 		!=0 Allocated new converted data (must be ait_freeVar())
 */
ait_val_t *
str_Hex2Dig(const char *psLine)
{
	register int i, j;
	char *str, szWork[3] = { 0, 0, 0 };
	ait_val_t *v, s = AIT_VAL_INIT;
	u_char *b;
	int n;

	if (!psLine || !*psLine)
		return NULL;
	else {
		v = ait_allocVar();
		if (!v)
			return NULL;

		/* normalize input string if not even */
		n = strlen(psLine);
		if (n % 2)
			n++;
		AIT_SET_STRSIZ(&s, n);
		for (i = strlen(psLine) - 1, j = n - 1, str = AIT_GET_STR(&s), *str = '0'; 
				i > -1; i--, j--)
			str[j] = psLine[i];
	}

	AIT_SET_BUFSIZ(v, 0, n / 2);
	for (i = 0, b = AIT_GET_BUF(v); i < n && str[i * 2]; i++) {
		strncpy(szWork, &str[i * 2], 2);
		b[i] = (u_char) strtol(szWork, NULL, 16);
	}

	AIT_FREE_VAL(&s);
	return v;
}

/*
 * str_Dig2Hex() - Convert from digit array to Hex string
 *
 * @digz = Digits
 * return: NULL nothing to do or error; 
 * 		!=0 Allocated new converted string (must be e_free())
*/
char *
str_Dig2Hex(ait_val_t *digz)
{
	register int i;
	char szWork[3] = { 0, 0, 0 }, *str;
	u_char *b;

	if (!digz || AIT_ISEMPTY(digz))
		return NULL;

	str = e_malloc(AIT_LEN(digz) * 2 + 1);
	if (!str)
		return NULL;
	else
		memset(str, 0, AIT_LEN(digz) * 2 + 1);

	for (i = 0, b = AIT_GET_BUF(digz); i < AIT_LEN(digz); i++) {
		snprintf(szWork, sizeof szWork, "%02hhX", b[i]);
		strcat(str, szWork);
	}

	return str;
}

/*
 * str_Dig2Hex2() - Convert from digit array to Hex string
 *
 * @digz = Digits array
 * @diglen = Array length
 * return: NULL nothing to do or error; 
 * 		!=0 Allocated new converted string (must be e_free())
*/
char *
str_Dig2Hex2(u_char * __restrict digz, int diglen)
{
	register int i;
	char szWork[3] = { 0, 0, 0 }, *str;
	u_char *b;

	if (!digz || !diglen)
		return NULL;

	str = e_malloc(diglen * 2 + 1);
	if (!str)
		return NULL;
	else
		memset(str, 0, diglen * 2 + 1);

	for (i = 0, b = digz; i < diglen; i++) {
		snprintf(szWork, sizeof szWork, "%02hhX", b[i]);
		strcat(str, szWork);
	}

	return str;
}

/*
 * str_LTrim() - Remove left whitespaces from text string
 *
 * @psLine = Text string
 * return: 0 nothing to do; !=0 Removed bytes
 */
int
str_LTrim(char * __restrict psLine)
{
	int pos = 0;
	char *s;

	if (!psLine || !*psLine)
		return 0;

	for (s = psLine; isspace((u_char) *s); s++);
	pos = s - psLine;

	memmove(psLine, s, (strlen(psLine) - pos) + 1);
	return pos;
}

/*
 * str_RTrim() - Remove right whitespaces from text string
 *
 * @psLine = Text string
 * return: 0 nothing to do; !=0 Removed bytes
 */
int
str_RTrim(char * __restrict psLine)
{
	char *t, *pos;

	if (!psLine || !*psLine)
		return 0;

	pos = psLine + strlen(psLine);
	for (t = pos - 1; t > psLine && isspace((u_char) *t); t--);
	*++t = 0;

	return pos - t;
}

/*
 * str_Trim() - Remove left and right whitespaces from text string
 *
 * @psLine = Text string
 * return: 0 nothing to do; !=0 Removed bytes
 */
int
str_Trim(char * __restrict psLine)
{
	int ret = 0;

	ret = str_LTrim(psLine);
	ret += str_RTrim(psLine);

	return ret;
}

/*
 * str_Unquot() - Remove quots from input text string 
 *
 * @psLine = Text string
 * return: 0 nothing to do; 1 successful unquoted string
 */
int
str_Unquot(char * __restrict psLine)
{
	char *pos, *str = NULL;
	int flg;

	if (!psLine || !*psLine)
		return 0;

	if (*psLine == '"' || *psLine == '\'') {
		str = e_strdup(psLine + 1);
		for (pos = str, flg = 0; *pos; flg = ('\\' == *pos), pos++) {
			if (!flg && *pos == *psLine) {
				*pos = 0;
				strlcpy(psLine, str, strlen(psLine) + 1);
				break;
			}
		}
		e_free(str);
		return 1;
	}

	return 0;
}

/*
 * str_Upper() - Convert all lower characters to upper
 *
 * @psLine = Text string
 * return: 0 nothing to do; !=0 converted chars
 */
int
str_Upper(char * __restrict psLine)
{
	char *s;
	register int cx = 0;

	if (!psLine || !*psLine)
		return 0;

	for (s = psLine; *s; s++)
		if (islower(*s)) {
			*s = toupper(*s);
			cx++;
		}

	return cx;
}

/*
 * str_Lower() - Convert all upper characters to lower
 *
 * @psLine = Text string
 * return: 0 nothing to do; !=0 converted chars
 */
int
str_Lower(char * __restrict psLine)
{
	char *s;
	register int cx = 0;

	if (!psLine || !*psLine)
		return 0;

	for (s = psLine; *s; s++)
		if (isupper(*s)) {
			*s = tolower(*s);
			cx++;
		}

	return cx;
}

/*
 * str_getString() - Get NULL delimited string from data buffer
 *
 * @data = Const data buffer
 * @dlen = Data length
 * @next = Return next position after string if !=NULL
 * return: -1 error or size of string 
 */
int
str_getString(const u_char * __restrict data, int dlen, char ** __restrict next)
{
	const u_char *pos;

	if (!data || !dlen)
		return -1;

	for (pos = data; pos < data + dlen; pos++)
		if (!*pos)
			break;
	if (*pos) {
		elwix_SetErr(ENOEXEC, "Not found null-terminated string");
		return -1;
	}

	if (next)
		*next = (char*) pos + 1;
	return pos - data + 1;
}

/*
 * str_getString2() - Get string from data buffer with delimiter
 *
 * @data = Data buffer
 * @dlen = Data length
 * @delim = Data delimiter
 * @next = Return next position after delimited string if !=NULL
 * return: -1 error or size of string 
 */
int
str_getString2(char * __restrict data, int dlen, char delim, char ** __restrict next)
{
	char *pos;

	if (!data || !dlen)
		return -1;

	for (pos = data; pos < data + dlen; pos++)
		if (!*pos || *pos == (u_char) delim) {
			*pos = 0;
			break;
		}
	if (*pos) {
		elwix_SetErr(ENOEXEC, "Not found null-terminated string");
		return -1;
	}

	if (next)
		*next = (char*) pos + 1;
	return pos - data;
}

/*
 * str_find2replace() - Search find string into data and replace
 *
 * @data = input string
 * @find = search for string
 * @replace = replace to string. If it is NULL then deletes found search string
 * @str = new produced allocate string. If it is NULL then just return found occurances of find
 * @mlen = allocated memory size for new string
 * return: -1 error, 0 not found or >0 how many occurances we have for find string
 */
int
str_find2replace(const char *data, const char *find, const char *replace, char **str, int *mlen)
{
	int cnt = 0, data_len, slen, find_len, replace_len = 0;
	const char *pos, *s;

	if (!data || !find)
		return -1;

	find_len = strlen(find);
	data_len = strlen(data);
	for (pos = data; (pos = strstr(pos, find)); pos += find_len, cnt++);

	/* just count occurances */
	if (!str || !mlen)
		return cnt;

	slen = data_len - find_len * cnt;
	if (replace) {
		replace_len = strlen(replace);
		slen += replace_len * cnt;
	}
	/* alloc exports string */
	*mlen = slen + 1;
	*str = e_malloc(*mlen);
	if (!*str)
		return -1;
	else
		memset(*str, 0, *mlen);

	/* search & replace */
	for (pos = data; *pos;) {
		s = strstr(pos, find);
		if (s)
			slen = s - pos;
		else
			slen = strlen(pos);
		/* 
		 * This hack was made due to behaviour of compiler against strncat(*str, pos, slen)!
		 */
		memcpy(*str + strlen(*str), pos, slen);
		if (s) {
			if (replace)
				strncat(*str, replace, replace_len);
			pos += find_len;
		}
		pos += slen;
	}

	return cnt;
}

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>