libopenmpt_stream_callbacks_fd.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * libopenmpt_stream_callbacks_fd.h
  3. * --------------------------------
  4. * Purpose: libopenmpt public c interface
  5. * Notes : (currently none)
  6. * Authors: OpenMPT Devs
  7. * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
  8. */
  9. #ifndef LIBOPENMPT_STREAM_CALLBACKS_FD_H
  10. #define LIBOPENMPT_STREAM_CALLBACKS_FD_H
  11. #include "libopenmpt.h"
  12. #ifdef _MSC_VER
  13. #include <io.h>
  14. #endif
  15. #include <limits.h>
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #ifndef _MSC_VER
  20. #include <unistd.h>
  21. #endif
  22. /*! \addtogroup libopenmpt_c
  23. * @{
  24. */
  25. #ifdef __cplusplus
  26. extern "C" {
  27. #endif
  28. /* This stuff has to be in a header file because of possibly different MSVC CRTs which cause problems for fd crossing CRT boundaries. */
  29. static size_t openmpt_stream_fd_read_func( void * stream, void * dst, size_t bytes ) {
  30. int fd = 0;
  31. #if defined(_MSC_VER)
  32. size_t retval = 0;
  33. int to_read = 0;
  34. int ret_read = 0;
  35. #else
  36. ssize_t retval = 0;
  37. #endif
  38. fd = (int)(uintptr_t)stream;
  39. if ( fd < 0 ) {
  40. return 0;
  41. }
  42. #if defined(_MSC_VER)
  43. retval = 0;
  44. while ( bytes > 0 ) {
  45. to_read = 0;
  46. if ( bytes < (size_t)INT_MAX ) {
  47. to_read = (int)bytes;
  48. } else {
  49. to_read = INT_MAX;
  50. }
  51. ret_read = _read( fd, dst, to_read );
  52. if ( ret_read <= 0 ) {
  53. return retval;
  54. }
  55. bytes -= ret_read;
  56. retval += ret_read;
  57. }
  58. #else
  59. retval = read( fd, dst, bytes );
  60. #endif
  61. if ( retval <= 0 ) {
  62. return 0;
  63. }
  64. return retval;
  65. }
  66. /*! \brief Provide openmpt_stream_callbacks for standard POSIX file descriptors
  67. *
  68. * Fills openmpt_stream_callbacks suitable for passing a POSIX filer descriptor as a stream parameter to functions doing file input/output.
  69. *
  70. * \remarks The stream argument must be passed as `(void*)(uintptr_t)(int)fd`.
  71. * \sa \ref libopenmpt_c_fileio
  72. * \sa openmpt_stream_callbacks
  73. * \sa openmpt_could_open_probability2
  74. * \sa openmpt_probe_file_header_from_stream
  75. * \sa openmpt_module_create2
  76. */
  77. static openmpt_stream_callbacks openmpt_stream_get_fd_callbacks(void) {
  78. openmpt_stream_callbacks retval;
  79. memset( &retval, 0, sizeof( openmpt_stream_callbacks ) );
  80. retval.read = openmpt_stream_fd_read_func;
  81. return retval;
  82. }
  83. #ifdef __cplusplus
  84. }
  85. #endif
  86. /*!
  87. * @}
  88. */
  89. #endif /* LIBOPENMPT_STREAM_CALLBACKS_FD_H */