xrp_rb_file.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) 2018 Cadence Design Systems Inc.
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include <string.h>
  24. #include "xrp_rb_file.h"
  25. static size_t xrp_rb_write_some(void *cookie, const void *buf, size_t size)
  26. {
  27. volatile struct xrp_ring_buffer *rb = cookie;
  28. uint32_t read = rb->read;
  29. uint32_t write = rb->write;
  30. size_t tail;
  31. if (read > write) {
  32. tail = read - 1 - write;
  33. } else if (read) {
  34. tail = rb->size - write;
  35. } else {
  36. tail = rb->size - 1 - write;
  37. }
  38. if (size < tail)
  39. tail = size;
  40. memcpy((char *)rb->data + write, buf, tail);
  41. write += tail;
  42. if (write == rb->size)
  43. write = 0;
  44. rb->write = write;
  45. return tail;
  46. }
  47. size_t xrp_rb_write(void *cookie, const void *buf, size_t size)
  48. {
  49. size_t write_total = 0;
  50. const char *p = buf;
  51. while (size) {
  52. size_t write = xrp_rb_write_some(cookie, p, size);
  53. if (write == 0)
  54. break;
  55. p += write;
  56. size -= write;
  57. write_total += write;
  58. }
  59. return write_total;
  60. }