|
|
|
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
|
|
|
/* Copyright 2022 Ivan Polyakov */
|
|
|
|
|
|
|
|
#include "utils.h"
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
int count_char_entries(const char *str, char ch)
|
|
|
|
{
|
|
|
|
int cnt = 0;
|
|
|
|
while (*str) {
|
|
|
|
if (*str == ch) {
|
|
|
|
cnt++;
|
|
|
|
}
|
|
|
|
str++;
|
|
|
|
}
|
|
|
|
return cnt;
|
|
|
|
}
|
|
|
|
|
|
|
|
char *rpd_strdup(const char *src)
|
|
|
|
{
|
|
|
|
size_t size = strlen(src) + 1;
|
|
|
|
char *dest = (char *) malloc(sizeof(char) * size);
|
|
|
|
if (!dest) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
return memcpy(dest, src, size);
|
|
|
|
}
|
|
|
|
|
|
|
|
char *rpd_strsep(char **str, const char *sep)
|
|
|
|
{
|
|
|
|
char *s = *str, *end;
|
|
|
|
if (!s) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
end = s + strcspn(s, sep);
|
|
|
|
if (*end) {
|
|
|
|
*end++ = 0;
|
|
|
|
} else {
|
|
|
|
end = 0;
|
|
|
|
}
|
|
|
|
*str = end;
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
|
|
|
const char *rpd_splitbyc(char **dest1, char **dest2, const char *src, const char sep)
|
|
|
|
{
|
|
|
|
const char *start = src, *end = src;
|
|
|
|
|
|
|
|
if (!src)
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
while (*end) {
|
|
|
|
if (*end == sep) {
|
|
|
|
size_t len = end - start;
|
|
|
|
*dest1 = malloc(sizeof(char) * (len + 1));
|
|
|
|
if (!*dest1) {
|
|
|
|
perror("malloc");
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
memcpy(*dest1, start, len);
|
|
|
|
(*dest1)[len] = '\0';
|
|
|
|
|
|
|
|
end++;
|
|
|
|
len = strlen(start) - (end - start);
|
|
|
|
if (!len) {
|
|
|
|
*dest2 = NULL;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
*dest2 = malloc(sizeof(char) * (len + 1));
|
|
|
|
if ((!*dest2)) {
|
|
|
|
perror("malloc");
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
memcpy(*dest2, end, len);
|
|
|
|
(*dest2)[len + 1] = '\0';
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
end++;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void rpd_strerase(char *src, int nchars)
|
|
|
|
{
|
|
|
|
char *ptr = NULL;
|
|
|
|
size_t len = strlen(src);
|
|
|
|
if (!src)
|
|
|
|
return;
|
|
|
|
|
|
|
|
ptr = src + nchars;
|
|
|
|
while (*ptr != '\0') {
|
|
|
|
*(ptr - nchars) = *ptr;
|
|
|
|
ptr++;
|
|
|
|
}
|
|
|
|
|
|
|
|
ptr = src + len;
|
|
|
|
while (ptr >= (src + len) - nchars) {
|
|
|
|
*ptr = '\0';
|
|
|
|
ptr--;
|
|
|
|
}
|
|
|
|
}
|