Commit ce3f65c4 authored by Jan Včelák's avatar Jan Včelák 🚀

libknot internal: implement strstrip()

parent 1bc9eca4
......@@ -14,6 +14,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
......@@ -131,6 +132,31 @@ char *strcdup(const char *s1, const char *s2)
return dst;
}
char *strstrip(const char *str)
{
// leading white-spaces
const char *scan = str;
while (isspace((int)scan[0])) {
scan += 1;
}
// trailing white-spaces
size_t len = strlen(scan);
while (len > 1 && isspace((int)scan[len - 1])) {
len -= 1;
}
char *trimmed = malloc(len);
if (!trimmed) {
return NULL;
}
memcpy(trimmed, scan, len + 1);
trimmed[len] = '\0';
return trimmed;
}
#ifdef MEM_DEBUG
/*
* ((destructor)) attribute executes this function after main().
......
......@@ -80,3 +80,10 @@ char *sprintf_alloc(const char *fmt, ...);
* \retval NULL on error.
*/
char *strcdup(const char *s1, const char *s2);
/*!
* \brief Create a copy of a string skipping leading and trailing white spaces.
*
* \return Newly allocated string, NULL in case of error.
*/
char *strstrip(const char *str);
......@@ -19,6 +19,7 @@ endian
fdset
hattrie
hhash
internal_mem
journal
namedb
net_shortwrite
......
......@@ -23,6 +23,7 @@ check_PROGRAMS = \
fdset \
hattrie \
hhash \
internal_mem \
journal \
namedb \
net_shortwrite \
......
/* Copyright (C) 2015 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
This program 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 3 of the License, or
(at your option) any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <tap/basic.h>
#include "libknot/internal/mem.h"
static void test_strstrip(void)
{
char *c = NULL;
c = strstrip("hello");
is_string("hello", c, "strstrip: no whitespace");
free(c);
c = strstrip("world \n");
is_string("world", c, "strstrip: trailing whitespace");
free(c);
c = strstrip(" \n banana");
is_string("banana", c, "strstrip: leading whitespace");
free(c);
c = strstrip(" \t hello world \n");
is_string("hello world", c, "strstrip: leading and trailing");
free(c);
c = strstrip("");
is_string("", c, "strstrip: empty string");
free(c);
}
int main(int argc, char *argv[])
{
plan_lazy();
test_strstrip();
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment