#include "mt.h"
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
char *_strpbrk_escape(char *, char *);
char *
_strtok_escape(char *string, char *sepset, char **lasts)
{
char *r;
if (string == NULL)
string = *lasts;
if (string == 0)
return (NULL);
if (*string == '\0')
return (NULL);
if ((r = _strpbrk_escape(string, sepset)) == NULL)
*lasts = 0;
else {
*r = '\0';
*lasts = r+1;
}
return (string);
}
char *
_strpbrk_escape(char *string, char *brkset)
{
const char *p;
do {
for (p = brkset; *p != '\0' && *p != *string; ++p)
;
if (p == string)
return ((char *)string);
if (*p != '\0') {
if (*(string-1) != '\\')
return ((char *)string);
}
} while (*string++);
return (NULL);
}
char *
_escape(char *s, char *esc)
{
int nescs = 0;
int i, j;
int len_s;
char *tmp;
if (s == NULL || esc == NULL)
return (NULL);
len_s = strlen(s);
for (i = 0; i < len_s; i++)
if (strchr(esc, s[i]))
nescs++;
if ((tmp = malloc(nescs + len_s + 1)) == NULL)
return (NULL);
for (i = 0, j = 0; i < len_s; i++) {
if (strchr(esc, s[i])) {
tmp[j++] = '\\';
}
tmp[j++] = s[i];
}
tmp[len_s + nescs] = '\0';
return (tmp);
}
char *
_unescape(char *s, char *esc)
{
int len_s;
int i, j;
char *tmp;
if (s == NULL || esc == NULL)
return (NULL);
len_s = strlen(s);
if ((tmp = malloc(len_s + 1)) == NULL)
return (NULL);
for (i = 0, j = 0; i < len_s; i++) {
if (s[i] == '\\' && strchr(esc, s[i + 1]))
tmp[j++] = s[++i];
else
tmp[j++] = s[i];
}
tmp[j] = '\0';
return (tmp);
}
char *
_strdup_null(char *s)
{
return (strdup(s ? s : ""));
}
int
_readbufline(char *mapbuf,
int mapsize,
char *buffer,
int buflen,
int *lastlen)
{
int linelen;
for (;;) {
linelen = 0;
while (linelen < buflen - 1) {
if (*lastlen >= mapsize) {
if (linelen == 0 ||
buffer[linelen - 1] == '\\') {
return (-1);
} else {
buffer[linelen] = '\n';
buffer[linelen + 1] = '\0';
return (linelen);
}
}
switch (mapbuf[*lastlen]) {
case '\n':
(*lastlen)++;
if (linelen > 0 &&
buffer[linelen - 1] == '\\') {
--linelen;
} else {
buffer[linelen] = '\n';
buffer[linelen + 1] = '\0';
return (linelen);
}
break;
default:
buffer[linelen] = mapbuf[*lastlen];
(*lastlen)++;
linelen++;
}
}
while (mapbuf[*lastlen] != '\n') {
if (mapbuf[*lastlen] == EOF) {
return (-1);
}
(*lastlen)++;
};
}
}