1
0

Message.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #include "util/UniqueName.h"
  17. struct Message* Message_new(uint32_t messageLength,
  18. uint32_t amountOfPadding,
  19. struct Allocator* alloc)
  20. {
  21. uint8_t* buff = Allocator_malloc(alloc, messageLength + amountOfPadding);
  22. struct Message* out = Allocator_calloc(alloc, sizeof(struct Message), 1);
  23. out->_ad = buff;
  24. out->_adLen = 0;
  25. out->msgbytes = &buff[amountOfPadding];
  26. out->_length = out->_capacity = messageLength;
  27. out->_padding = amountOfPadding;
  28. out->_alloc = alloc;
  29. return out;
  30. }
  31. void Message_setAssociatedFd(struct Message* msg, int fd)
  32. {
  33. if (fd == -1) {
  34. msg->_associatedFd = 0;
  35. } else if (fd == 0) {
  36. msg->_associatedFd = -1;
  37. } else {
  38. msg->_associatedFd = fd;
  39. }
  40. }
  41. int Message_getAssociatedFd(struct Message* msg)
  42. {
  43. if (msg->_associatedFd == -1) {
  44. return 0;
  45. } else if (msg->_associatedFd == 0) {
  46. return -1;
  47. } else {
  48. return msg->_associatedFd;
  49. }
  50. }
  51. struct Message* Message_clone(struct Message* toClone, struct Allocator* alloc)
  52. {
  53. Assert_true(toClone->_capacity >= toClone->_length);
  54. int32_t len = toClone->_capacity + toClone->_padding + toClone->_adLen;
  55. uint8_t* allocation = Allocator_malloc(alloc, len + 8);
  56. while (((uintptr_t)allocation % 8) != (((uintptr_t)toClone->msgbytes - toClone->_padding - toClone->_adLen) % 8)) {
  57. allocation++;
  58. }
  59. Bits_memcpy(allocation, toClone->msgbytes - toClone->_padding - toClone->_adLen, len);
  60. return Allocator_clone(alloc, (&(struct Message) {
  61. ._length = toClone->_length,
  62. ._padding = toClone->_padding,
  63. .msgbytes = allocation + toClone->_adLen + toClone->_padding,
  64. ._ad = allocation + toClone->_adLen,
  65. ._adLen = toClone->_adLen,
  66. ._capacity = toClone->_capacity,
  67. ._alloc = alloc
  68. }));
  69. }