libclod
C library for interacting with NBTs, region files, LOD data and other things.
Loading...
Searching...
No Matches
sstr.h
Go to the documentation of this file.
1
8#ifndef CLOD_SSTR_H
9#define CLOD_SSTR_H
10
11#include <clod/lib.h>
12#include <stddef.h>
13#include <string.h>
14
19typedef struct {
22 char *ptr;
24 size_t size;
25} clod_sstr;
26
27// Create a sized string from char array and size. The string retains ptr_v.
28#define clod_sstr(ptr_v, size_v) ((clod_sstr){ .ptr = (char*)(ptr_v), .size = (size_v) })
29// Null string value
30#define CLOD_SSTR_NULL ((clod_sstr){ .ptr = nullptr, .size = 0 })
31// C string to sized string. The string retains c_string.
32#define CLOD_SSTR_C(c_string) ((clod_sstr){ .ptr = (char*)(c_string), .size = strlen(c_string) })
33
43CLOD_INLINE
44static inline bool clod_sstr_eq(const clod_sstr str1, const clod_sstr str2) {
45 if (str1.size != str2.size) return false;
46 if (str1.ptr == str2.ptr) return true;
47 if (str1.ptr == nullptr || str2.ptr == nullptr) return false;
48 return memcmp(str1.ptr, str2.ptr, str1.size) == 0;
49}
50
57CLOD_INLINE
58static inline void clod_sstr_cat(clod_sstr *str1, const clod_sstr str2) {
59 if (str2.size == 0) return;
60 memcpy(str1->ptr + str1->size, str2.ptr, str2.size);
61 str1->size += str2.size;
62}
63
73CLOD_INLINE
74static inline clod_sstr clod_sstr_contains(const clod_sstr str, const clod_sstr elem) {
75 if (str.size < elem.size) return CLOD_SSTR_NULL;
76 if (elem.size == 0) return clod_sstr(str.ptr, 0);
77
78 for (size_t i = 0; i < str.size - elem.size; i++)
79 if (memcmp(str.ptr + i, elem.ptr, elem.size) == 0)
80 return clod_sstr(str.ptr + i, elem.size);
81
82 return CLOD_SSTR_NULL;
83}
84
98CLOD_INLINE
99static inline clod_sstr clod_sstr_find(const clod_sstr str, const char elem, ptrdiff_t occurrence) {
100 if (occurrence > 0) {
101 for (size_t i = 0; i < str.size; i++) {
102 if (str.ptr[i] == elem) occurrence--;
103 if (occurrence == 0) return clod_sstr(str.ptr + i, str.size - i);
104 }
105 return CLOD_SSTR_NULL;
106 }
107
108 if (occurrence < 0) {
109 for (size_t i = str.size; i > 0; i--) {
110 if (str.ptr[i - 1] == elem) occurrence++;
111 if (occurrence == 0) return clod_sstr(str.ptr + i - 1, str.size - i + 1);
112 }
113 return CLOD_SSTR_NULL;
114 }
115
116 // occurrence == 0
117 return str;
118}
119
120#endif
static clod_sstr clod_sstr_find(const clod_sstr str, const char elem, ptrdiff_t occurrence)
Definition sstr.h:99
static clod_sstr clod_sstr_contains(const clod_sstr str, const clod_sstr elem)
Definition sstr.h:74
static void clod_sstr_cat(clod_sstr *str1, const clod_sstr str2)
Definition sstr.h:58
static bool clod_sstr_eq(const clod_sstr str1, const clod_sstr str2)
Definition sstr.h:44
char * ptr
Definition sstr.h:22
size_t size
Definition sstr.h:24