#pragma once #ifndef PTSD_PCOW_STRING_HEADER #define PTSD_PCOW_STRING_HEADER #if !defined(PTSD_PSTRING_STANDALONE) #include "general.h" #include "pstring.h" #include "stretchy_buffer.h" #else #error not implemented yet! #endif #include typedef struct pcow_t pcow_t; struct pcow_t { enum { PCOW_REFERENCE, PCOW_OWNED, } kind; usize length; char *c_str; }; PTSD_UNUSED static inline pcow_t pcow(char *c_str, usize length); PTSD_UNUSED static inline pcow_t pcow_new(char *c_str, usize length); PTSD_UNUSED static inline void pcow_free(pcow_t *str); PTSD_UNUSED static inline pcow_t pcow_from_str(pstring_t); PTSD_UNUSED static inline pcow_t pcow_new_from_str(pstring_t); PTSD_UNUSED static inline pcow_t pcow_alloc(const char *buffer, usize length); PTSD_UNUSED static inline pcow_t pcow_clone(const pcow_t str); PTSD_UNUSED static inline bool pcow_equal(const pcow_t lhs, const pcow_t rhs); PTSD_UNUSED static inline bool pcow_case_equal(const pcow_t lhs, const pcow_t rhs); PTSD_UNUSED static inline bool pcow_is_empty(const pcow_t str); PTSD_UNUSED static inline pcow_t pcow(char *c_str, usize length) { return (pcow_t){ PCOW_REFERENCE, length, c_str }; } PTSD_UNUSED static inline pcow_t pcow_new(char *c_str, usize length) { char *dst = pzero_allocate(length + 1); memcpy(dst, c_str, length); return (pcow_t){ PCOW_OWNED, length, dst }; } PTSD_UNUSED static inline pcow_t pcow_from_str(pstring_t str) { return pcow(str.c_str, str.length); } PTSD_UNUSED static inline pcow_t pcow_new_from_str(pstring_t str) { return pcow_new(str.c_str, str.length); } PTSD_UNUSED static inline void pcow_free(pcow_t *str) { if (!str || !str->c_str) return; if (str->kind == PCOW_REFERENCE) return; pfree(str->c_str); str->c_str = nullptr; } PTSD_UNUSED static inline pcow_t pcow_clone(const pcow_t str) { return pcow_new(str.c_str, str.length); } PTSD_UNUSED static inline bool pcow_equal(const pcow_t lhs, const pcow_t rhs) { if (lhs.length != rhs.length) return false; if (lhs.c_str == rhs.c_str) return true; for (register usize i = 0; i < lhs.length; i++) { if (lhs.c_str[i] != rhs.c_str[i]) return false; } return true; } PTSD_UNUSED static inline bool pcow_case_equal(const pcow_t lhs, const pcow_t rhs) { if (lhs.length != rhs.length) return false; if (lhs.c_str == rhs.c_str) return true; for (register usize i = 0; i < lhs.length; i++) { char left = (char)toupper(lhs.c_str[i]); char right = (char)toupper(rhs.c_str[i]); if (left != right) return false; } return true; } PTSD_UNUSED static inline bool pcow_is_empty(const pcow_t str) { return !(str.length || str.c_str); } #endif // PTSD_PSTRING_HEADER