tlibc/include/tlibc/string/str.h
2025-11-01 19:49:31 +05:00

73 lines
2.0 KiB
C
Executable File

#pragma once
#include "../std.h"
#include "char.h"
#include "cstr.h"
#include "../collections/Array.h"
typedef struct str {
char* data;
u32 size; // size of data in bytes without \0
bool isZeroTerminated;
} str;
/// creates str from a string literal
#define STR(LITERAL) str_construct(LITERAL, ARRAY_LEN(LITERAL) - 1, true)
#define str_construct(DATA, LEN, ZERO_TERMINATED) ((str){ .data = DATA, .size = LEN, .isZeroTerminated = ZERO_TERMINATED })
static inline str str_from_cstr(cstr s_ptr){
return str_construct((void*)s_ptr, strlen(s_ptr), true);
}
static inline Array_ str_castTo_Array(str s) {
return Array_construct_size(s.data, s.size);
}
static inline str Array_castTo_str(Array_ a, bool isZeroTerminated) {
return str_construct(a.data, a.size, isZeroTerminated);
}
static const str str_null = str_construct(NULL, 0, 0);
/// copies src content to new string and adds \0 at the end
str str_copy(str src);
/// compares two strings, NullPtr-friendly
bool str_equals(str str0, str str1);
/// allocates new string which is reversed variant of <s>
str str_reverse(str s);
i32 str_seek(str src, str fragment, u32 startIndex);
i32 str_seekReverse(str src, str fragment, u32 startIndex);
i32 str_seekChar(str src, char c, u32 startIndex);
i32 str_seekCharReverse(str src, char c, u32 startIndex);
bool str_startsWith(str src, str fragment);
bool str_endsWith(str src, str fragment);
/// @brief calculates string hash using sdbm32 algorythm (something like lightweight crc32)
/// @return non-cryptografic hash of the string
u32 str_hash32(str s);
str str_toUpper(str src);
str str_toLower(str src);
str hex_to_str(Array(u8) buf, bool uppercase);
/// @brief removes blank characters from start and end of the line
void str_trim(str* line, bool set_zero_at_end);
///@return s[0..n]
static inline str str_sliceBefore(str s, u32 n){
return str_construct(s.data, n, false);
}
///@return s[n...]
static inline str str_sliceAfter(str s, u32 n){
return str_construct(s.data + n, s.size - n, s.isZeroTerminated);
}