Message.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "wire/Message.h"
  16. Message_t* Message_new(uint32_t messageLength,
  17. uint32_t amountOfPadding,
  18. struct Allocator* alloc)
  19. {
  20. uint8_t* buff = Allocator_malloc(alloc, messageLength + amountOfPadding);
  21. Message_t* out = Allocator_calloc(alloc, sizeof(struct Message), 1);
  22. out->_ad = buff;
  23. out->_adLen = 0;
  24. out->_msgbytes = &buff[amountOfPadding];
  25. out->_length = out->_capacity = messageLength;
  26. out->_padding = amountOfPadding;
  27. out->_alloc = alloc;
  28. return out;
  29. }
  30. void Message_setAssociatedFd(Message_t* msg, int fd)
  31. {
  32. if (fd == -1) {
  33. msg->_associatedFd = 0;
  34. } else if (fd == 0) {
  35. msg->_associatedFd = -1;
  36. } else {
  37. msg->_associatedFd = fd;
  38. }
  39. }
  40. int Message_getAssociatedFd(Message_t* msg)
  41. {
  42. if (msg->_associatedFd == -1) {
  43. return 0;
  44. } else if (msg->_associatedFd == 0) {
  45. return -1;
  46. } else {
  47. return msg->_associatedFd;
  48. }
  49. }
  50. Message_t* Message_clone(Message_t* toClone, struct Allocator* alloc)
  51. {
  52. Assert_true(toClone->_capacity >= toClone->_length);
  53. int32_t len = toClone->_capacity + toClone->_padding + toClone->_adLen;
  54. uint8_t* allocation = Allocator_malloc(alloc, len + 8);
  55. while (((uintptr_t)allocation % 8) != (((uintptr_t)toClone->_msgbytes - toClone->_padding - toClone->_adLen) % 8)) {
  56. allocation++;
  57. }
  58. Bits_memcpy(allocation, toClone->_msgbytes - toClone->_padding - toClone->_adLen, len);
  59. return Allocator_clone(alloc, (&(struct Message) {
  60. ._length = toClone->_length,
  61. ._padding = toClone->_padding,
  62. ._msgbytes = allocation + toClone->_adLen + toClone->_padding,
  63. ._ad = allocation + toClone->_adLen,
  64. ._adLen = toClone->_adLen,
  65. ._capacity = toClone->_capacity,
  66. ._alloc = alloc
  67. }));
  68. }