cstring.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef CSTRING_H
  2. #define CSTRING_H
  3. /* CSTRING RETURN CODE */
  4. #define CSTRING_RC_TYPE unsigned char
  5. extern __thread CSTRING_RC_TYPE logger_errno;
  6. #define CSTRING_RC_OK ((CSTRING_RC_TYPE) 0L) /* No Error */
  7. #define CSTRING_RC_EVN ((CSTRING_RC_TYPE) 1L) /* Value is Null */
  8. #include <stddef.h>
  9. __attribute__((__pure__))
  10. size_t
  11. cstring_len(const char *cstring);
  12. __attribute__((__pure__))
  13. _Bool
  14. cstring_equal(const char *restrict cstring_1, const char *restrict cstring_2);
  15. #if defined(CSTRING_IMP) || defined(IMPLEMENTATIONS)
  16. #include <stddef.h>
  17. #include <stdlib.h>
  18. #if defined(CSTRING_LOG) || defined(LOGS)
  19. #define __LOG(OUT, PFX, TXT) fprintf(OUT, PFX" %s: %s", __func__, TXT)
  20. #define LOG_ERROR(TXT) __LOG(stderr, "[ERROR]", TXT)
  21. #else
  22. #define LOG_ERROR(TXT) ;
  23. #endif /* CSTRING_LOG */
  24. #define true ((unsigned char) 1L)
  25. #define false ((unsigned char) 0L)
  26. #define TEST_FOR_NULL(POINTER) \
  27. if ( POINTER == NULL ) { \
  28. LOG_ERROR("Null Pointer Not Expected"); \
  29. logger_errno = CSTRING_RC_EVN; \
  30. return logger_errno; \
  31. }
  32. size_t
  33. cstring_len(const char *p_cstr) {
  34. TEST_FOR_NULL(p_cstr);
  35. size_t len = 0;
  36. while ( *(p_cstr + len++) ) {}
  37. return --len;
  38. }
  39. _Bool
  40. cstring_equal(const char *restrict p_cstr1, const char *restrict p_cstr2) {
  41. TEST_FOR_NULL(p_cstr1);
  42. TEST_FOR_NULL(p_cstr2);
  43. const size_t cstr1_size = cstring_len(p_cstr1);
  44. const size_t cstr2_size = cstring_len(p_cstr2);
  45. if ( cstr1_size != cstr2_size ) {
  46. return false;
  47. }
  48. for ( size_t i = 0; i < cstr1_size; ++i ) {
  49. if ( p_cstr1[i] != p_cstr2[i] ) {
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. #undef true
  56. #undef false
  57. #undef LOG_ERROR
  58. #undef TEST_FOR_NULL
  59. #endif /* CSTRING_IMP || IMPLEMENTATIONS */
  60. #endif /* CSTRING_H */