hipack-string.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * hipack-string.c
  3. * Copyright (C) 2015 Adrian Perez <aperez@igalia.com>
  4. *
  5. * Distributed under terms of the MIT license.
  6. */
  7. #include "hipack.h"
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <assert.h>
  11. static hipack_string_t s_empty_string = { .size = 0 };
  12. hipack_string_t*
  13. hipack_string_new_from_string (const char *str)
  14. {
  15. assert (str);
  16. return hipack_string_new_from_lstring (str, strlen (str));
  17. }
  18. hipack_string_t*
  19. hipack_string_new_from_lstring (const char *str, uint32_t len)
  20. {
  21. assert (str);
  22. if (len > 0) {
  23. hipack_string_t *hstr = hipack_alloc_array_extra (NULL,
  24. len, sizeof (uint8_t), sizeof (hipack_string_t));
  25. memcpy (hstr->data, str, len);
  26. hstr->size = len;
  27. return hstr;
  28. } else {
  29. return &s_empty_string;
  30. }
  31. }
  32. hipack_string_t*
  33. hipack_string_copy (const hipack_string_t *hstr)
  34. {
  35. assert (hstr);
  36. if (hstr == &s_empty_string)
  37. return &s_empty_string;
  38. return hipack_string_new_from_lstring ((const char*) hstr->data,
  39. hstr->size);
  40. }
  41. void
  42. hipack_string_free (hipack_string_t *hstr)
  43. {
  44. if (hstr && hstr != &s_empty_string) {
  45. hipack_alloc_free (hstr);
  46. }
  47. }
  48. uint32_t
  49. hipack_string_hash (const hipack_string_t *hstr)
  50. {
  51. assert (hstr);
  52. uint32_t ret = 0;
  53. uint32_t ctr = 0;
  54. for (uint32_t i = 0; i < hstr->size; i++) {
  55. ret ^= hstr->data[i] << ctr;
  56. ctr = (ctr + 1) % sizeof (void*);
  57. }
  58. return ret;
  59. }
  60. bool
  61. hipack_string_equal (const hipack_string_t *hstr1,
  62. const hipack_string_t *hstr2)
  63. {
  64. assert (hstr1);
  65. assert (hstr2);
  66. return (hstr1->size == hstr2->size) &&
  67. memcmp (hstr1->data, hstr2->data, hstr1->size) == 0;
  68. }