xdr.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /****************************************************************************
  2. *
  3. * MODULE: dbmi_base
  4. * AUTHOR(S): CERL (Joel Jones + possible other original contributors)
  5. * Radim Blazek <radim.blazek gmail.com>,
  6. * Brad Douglas <rez touchofmadness.com>,
  7. * Markus Neteler <neteler itc.it>
  8. * PURPOSE: database management functions for modules and drivers
  9. * COPYRIGHT: (C) 2003-2006 by the GRASS Development Team
  10. *
  11. * This program is free software under the GNU General Public
  12. * License (>=v2). Read the file COPYING that comes with GRASS
  13. * for details.
  14. *
  15. *****************************************************************************/
  16. #include "xdr.h"
  17. #ifdef __MINGW32__
  18. #define USE_STDIO 0
  19. #define USE_READN 1
  20. #else
  21. #define USE_STDIO 1
  22. #define USE_READN 0
  23. #endif
  24. #ifndef USE_STDIO
  25. #include <unistd.h>
  26. #endif
  27. static FILE *_send, *_recv;
  28. #if USE_READN
  29. static ssize_t readn(int fd, void *buf, size_t count)
  30. {
  31. ssize_t total = 0;
  32. while (total < count) {
  33. ssize_t n = read(fd, (char *)buf + total, count - total);
  34. if (n < 0)
  35. return n;
  36. if (n == 0)
  37. break;
  38. total += n;
  39. }
  40. return total;
  41. }
  42. static ssize_t writen(int fd, const void *buf, size_t count)
  43. {
  44. ssize_t total = 0;
  45. while (total < count) {
  46. ssize_t n = write(fd, (const char *)buf + total, count - total);
  47. if (n < 0)
  48. return n;
  49. if (n == 0)
  50. break;
  51. total += n;
  52. }
  53. return total;
  54. }
  55. #endif
  56. void db__set_protocol_fds(FILE * send, FILE * recv)
  57. {
  58. _send = send;
  59. _recv = recv;
  60. }
  61. int db__send(const void *buf, size_t size)
  62. {
  63. #if USE_STDIO
  64. return fwrite(buf, 1, size, _send) == size;
  65. #elif USE_READN
  66. return writen(fileno(_send), buf, size) == size;
  67. #else
  68. return write(fileno(_send), buf, size) == size;
  69. #endif
  70. }
  71. int db__recv(void *buf, size_t size)
  72. {
  73. #if USE_STDIO
  74. #ifdef USE_BUFFERED_IO
  75. fflush(_send);
  76. #endif
  77. return fread(buf, 1, size, _recv) == size;
  78. #elif USE_READN
  79. return readn(fileno(_recv), buf, size) == size;
  80. #else
  81. return read(fileno(_recv), buf, size) == size;
  82. #endif
  83. }