xdr.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*!
  2. \file lib/db/dbmi_base/xdr.c
  3. \brief DBMI Library (base) - external data representation
  4. (C) 1999-2009, 2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. \author Joel Jones (CERL/UIUC), Radim Blazek, Brad Douglas, Markus Neteler
  8. \author Doxygenized by Martin Landa <landa.martin gmail.com> (2011)
  9. */
  10. #include "xdr.h"
  11. #ifdef __MINGW32__
  12. #define USE_STDIO 0
  13. #define USE_READN 1
  14. #else
  15. #define USE_STDIO 1
  16. #define USE_READN 0
  17. #endif
  18. #ifndef USE_STDIO
  19. #include <unistd.h>
  20. #endif
  21. static FILE *_send, *_recv;
  22. #if USE_READN
  23. static ssize_t readn(int fd, void *buf, size_t count)
  24. {
  25. ssize_t total = 0;
  26. while (total < count) {
  27. ssize_t n = read(fd, (char *)buf + total, count - total);
  28. if (n < 0)
  29. return n;
  30. if (n == 0)
  31. break;
  32. total += n;
  33. }
  34. return total;
  35. }
  36. static ssize_t writen(int fd, const void *buf, size_t count)
  37. {
  38. ssize_t total = 0;
  39. while (total < count) {
  40. ssize_t n = write(fd, (const char *)buf + total, count - total);
  41. if (n < 0)
  42. return n;
  43. if (n == 0)
  44. break;
  45. total += n;
  46. }
  47. return total;
  48. }
  49. #endif
  50. /*!
  51. \brief ?
  52. \param send
  53. \param recv
  54. */
  55. void db__set_protocol_fds(FILE * send, FILE * recv)
  56. {
  57. _send = send;
  58. _recv = recv;
  59. }
  60. /*!
  61. \brief ?
  62. \param buf
  63. \param size
  64. \return
  65. */
  66. int db__send(const void *buf, size_t size)
  67. {
  68. #if USE_STDIO
  69. return fwrite(buf, 1, size, _send) == size;
  70. #elif USE_READN
  71. return writen(fileno(_send), buf, size) == size;
  72. #else
  73. return write(fileno(_send), buf, size) == size;
  74. #endif
  75. }
  76. int db__recv(void *buf, size_t size)
  77. {
  78. #if USE_STDIO
  79. #ifdef USE_BUFFERED_IO
  80. fflush(_send);
  81. #endif
  82. return fread(buf, 1, size, _recv) == size;
  83. #elif USE_READN
  84. return readn(fileno(_recv), buf, size) == size;
  85. #else
  86. return read(fileno(_recv), buf, size) == size;
  87. #endif
  88. }