DynString.c 962 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdbool.h>
  4. #include "DynString.h"
  5. #include "log.h"
  6. DynString DynString_alloc(const char* str, const size_t len) {
  7. DynString dstr = {
  8. .data = (char*) malloc(sizeof(char) * len),
  9. .len = len
  10. };
  11. if (dstr.data == NULL) {
  12. LOG_FATAL("Ran out of memory");
  13. }
  14. dstr.data = memcpy(dstr.data, str, len);
  15. return dstr;
  16. }
  17. void DynString_free(DynString* dstr) {
  18. if (dstr->data != NULL) {
  19. free(dstr->data);
  20. }
  21. dstr->len = 0;
  22. }
  23. bool DynString_is_null(const DynString* dstr) {
  24. return dstr->data == NULL;
  25. }
  26. bool DynString_equal(const DynString* s1, const DynString* s2) {
  27. if (s1->len != s2->len) {
  28. return false;
  29. }
  30. if (s1->data == NULL || s2->data == NULL) {
  31. return false;
  32. }
  33. for (size_t i = 0; i < s1->len; i++) {
  34. if (s1->data[i] != s2->data[i]) {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }