BufferWriter.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * @file BufferWriter.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #include <misc/debug.h>
  23. #include <flow/BufferWriter.h>
  24. static void output_handler_recv (BufferWriter *o, uint8_t *data)
  25. {
  26. ASSERT(!o->out_have)
  27. // set output packet
  28. o->out_have = 1;
  29. o->out = data;
  30. }
  31. void BufferWriter_Init (BufferWriter *o, int mtu, BPendingGroup *pg)
  32. {
  33. ASSERT(mtu >= 0)
  34. // init output
  35. PacketRecvInterface_Init(&o->recv_interface, mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, pg);
  36. // set no output packet
  37. o->out_have = 0;
  38. DebugObject_Init(&o->d_obj);
  39. #ifndef NDEBUG
  40. o->d_mtu = mtu;
  41. o->d_writing = 0;
  42. #endif
  43. }
  44. void BufferWriter_Free (BufferWriter *o)
  45. {
  46. DebugObject_Free(&o->d_obj);
  47. // free output
  48. PacketRecvInterface_Free(&o->recv_interface);
  49. }
  50. PacketRecvInterface * BufferWriter_GetOutput (BufferWriter *o)
  51. {
  52. DebugObject_Access(&o->d_obj);
  53. return &o->recv_interface;
  54. }
  55. int BufferWriter_StartPacket (BufferWriter *o, uint8_t **buf)
  56. {
  57. ASSERT(!o->d_writing)
  58. DebugObject_Access(&o->d_obj);
  59. if (!o->out_have) {
  60. return 0;
  61. }
  62. if (buf) {
  63. *buf = o->out;
  64. }
  65. #ifndef NDEBUG
  66. o->d_writing = 1;
  67. #endif
  68. return 1;
  69. }
  70. void BufferWriter_EndPacket (BufferWriter *o, int len)
  71. {
  72. ASSERT(len >= 0)
  73. ASSERT(len <= o->d_mtu)
  74. ASSERT(o->out_have)
  75. ASSERT(o->d_writing)
  76. DebugObject_Access(&o->d_obj);
  77. // set no output packet
  78. o->out_have = 0;
  79. // finish packet
  80. PacketRecvInterface_Done(&o->recv_interface, len);
  81. #ifndef NDEBUG
  82. o->d_writing = 0;
  83. #endif
  84. }