cstring.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #define IMPLEMENTATIONS
  16. #if defined(CSTRING_IMP) || defined(IMPLEMENTATIONS)
  17. #include <stddef.h>
  18. #include <stdlib.h>
  19. #if defined(CSTRING_LOG) || defined(LOGS)
  20. #define __LOG(OUT, PFX, TXT) fprintf(OUT, PFX" %s: %s", __func__, TXT)
  21. #define LOG_ERROR(TXT) __LOG(stderr, "[ERROR]", TXT)
  22. #else
  23. #define LOG_ERROR(TXT) ;
  24. #endif /* CSTRING_LOG */
  25. #define true ((unsigned char) 1L)
  26. #define false ((unsigned char) 0L)
  27. #define TEST_FOR_NULL(POINTER) \
  28. if ( POINTER == NULL ) { \
  29. LOG_ERROR("Null Pointer Not Expected"); \
  30. logger_errno = CSTRING_RC_EVN; \
  31. return logger_errno; \
  32. }
  33. size_t
  34. cstring_len(const char *p_cstr) {
  35. TEST_FOR_NULL(p_cstr);
  36. size_t len = 0;
  37. while ( *(p_cstr + len++) ) {}
  38. return --len;
  39. }
  40. _Bool
  41. cstring_equal(const char *restrict p_cstr1, const char *restrict p_cstr2) {
  42. TEST_FOR_NULL(p_cstr1);
  43. TEST_FOR_NULL(p_cstr2);
  44. const size_t cstr1_size = cstring_len(p_cstr1);
  45. const size_t cstr2_size = cstring_len(p_cstr2);
  46. if ( cstr1_size != cstr2_size ) {
  47. return false;
  48. }
  49. for ( size_t i = 0; i < cstr1_size; ++i ) {
  50. if ( p_cstr1[i] != p_cstr2[i] ) {
  51. return false;
  52. }
  53. }
  54. return true;
  55. }
  56. #undef true
  57. #undef false
  58. #undef LOG_ERROR
  59. #undef TEST_FOR_NULL
  60. #endif /* CSTRING_IMP || IMPLEMENTATIONS */
  61. #endif /* CSTRING_H */