Files
c-programming/c/stringview/stringv.c
T

61 lines
1.8 KiB
C

#include "stringv.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
/*
* @brief Create a string view from a const char* and set their lenght
*
* @details This string view provides a view of a string. It does not allocate
* memory, therefore, it lives only while the source is alive. The
* lenght is a bytes number of the string. It does not represents the number of
* characters.
*
* @param str pointer from the original string. It can be NULL.
*
* @return a StringView with the view of original string with corresponding
* lenght.
*/
#define STRING_VIEW_NULL (StringView){.text = NULL, .lenght = 0}
StringView sv_from_cstr(const char *str) {
if (str == NULL) {
return STRING_VIEW_NULL;
}
return (StringView){.text = (char *)str, .lenght = strlen(str)};
}
StringView sv_left(const StringView *sv, size_t l) {
if (sv == NULL) {
perror("sv_left: pointer is NULL\n");
return STRING_VIEW_NULL;
}
if (sv->text == NULL) {
perror("sv_left: text pointer is NULL\n");
return STRING_VIEW_NULL;
}
if (sv->lenght < l) {
perror("sv_left: text length is less than specified length\n");
return STRING_VIEW_NULL;
}
return (StringView){.text = sv->text, .lenght = l};
}
StringView sv_right(const StringView *sv, size_t r) {
if (sv == NULL) {
perror("sv_right: pointer is NULL\n");
return STRING_VIEW_NULL;
}
if (sv->text == NULL) {
perror("sv_right: text pointer is NULL\n");
return STRING_VIEW_NULL;
}
if (sv->lenght < r) {
perror("sv_right: text length is less than specified length\n");
return STRING_VIEW_NULL;
}
size_t nlength = sv->lenght - r;
return (StringView){.text = sv->text + nlength, .lenght = r};
}