/*-GNU-GPL-BEGIN-*
nepim - network pipemeter
Copyright (C) 2005 Everton da Silva Marques
nepim is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
nepim is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with nepim; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*-GNU-GPL-END-*/
/* $Id: str.c,v 1.2 2005/07/26 23:14:15 evertonm Exp $ */
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "str.h"
static int addr_list_sep(int c)
{
return isspace(c) || (c == '/');
}
int addr_list_size(const char *list)
{
int size = 0;
int spc = 1;
assert(list);
for (; *list; ++list) {
int hit_spc = addr_list_sep(*list);
if (spc) {
/* inside space */
if (!hit_spc) {
spc = 0; /* word found */
++size;
}
}
else {
/* inside word */
if (hit_spc)
spc = 1; /* space found */
}
}
return size;
}
static int addr_copy(const char *list, const char *word, char *buf, int buf_size)
{
int word_len;
assert(word);
assert(list > word);
word_len = list - word;
if (word_len >= buf_size)
return -1;
memcpy(buf, word, word_len);
buf[word_len] = '\0';
return 0;
}
int addr_list_get(const char *list, int i, char *buf, int buf_size)
{
int index = -1;
int spc = 1;
const char *word = 0;
assert(list);
assert(i >= 0);
assert(buf_size > 0);
for (; *list; ++list) {
int hit_spc = addr_list_sep(*list);
if (spc) {
/* inside space */
if (!hit_spc) {
/* word found */
spc = 0;
word = list; /* save begin of most recent word */
++index;
}
}
else {
/* inside word */
if (hit_spc) {
/* space found */
spc = 1;
if (index == i)
return addr_copy(list, word, buf, buf_size);
} /* space found */
} /* inside word */
} /* for loop: scan string */
/* consider unended last word */
if (!spc && (index == i))
return addr_copy(list, word, buf, buf_size);
return -1;
}
char *addr_list_append(char *list, const char *tail)
{
assert(tail);
if (!list) {
list = strdup(tail);
assert(list);
return list;
}
list = realloc(list, strlen(list) + strlen(tail) + 2);
assert(list);
strcat(list, "/");
strcat(list, tail);
return list;
}
int addr_split_port(char *buf, int buf_size, const char **port)
{
const char *eos;
char *p;
int len;
assert(buf_size > 0);
eos = memchr(buf, '\0', buf_size);
assert(eos);
len = eos - buf;
assert(len > 0);
p = memchr(buf, ',', len);
if (p) {
*p = '\0';
*port = p + 1;
return 0;
}
return -1;
}
syntax highlighted by Code2HTML, v. 0.9.1