codec_fd.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "Python.h"
  2. #include "Imaging.h"
  3. #include "../py3.h"
  4. Py_ssize_t
  5. _imaging_read_pyFd(PyObject *fd, char* dest, Py_ssize_t bytes)
  6. {
  7. /* dest should be a buffer bytes long, returns length of read
  8. -1 on error */
  9. PyObject *result;
  10. char *buffer;
  11. Py_ssize_t length;
  12. int bytes_result;
  13. result = PyObject_CallMethod(fd, "read", "n", bytes);
  14. bytes_result = PyBytes_AsStringAndSize(result, &buffer, &length);
  15. if (bytes_result == -1) {
  16. goto err;
  17. }
  18. if (length > bytes) {
  19. goto err;
  20. }
  21. memcpy(dest, buffer, length);
  22. Py_DECREF(result);
  23. return length;
  24. err:
  25. Py_DECREF(result);
  26. return -1;
  27. }
  28. Py_ssize_t
  29. _imaging_write_pyFd(PyObject *fd, char* src, Py_ssize_t bytes)
  30. {
  31. PyObject *result;
  32. PyObject *byteObj;
  33. byteObj = PyBytes_FromStringAndSize(src, bytes);
  34. result = PyObject_CallMethod(fd, "write", "O", byteObj);
  35. Py_DECREF(byteObj);
  36. Py_DECREF(result);
  37. return bytes;
  38. }
  39. int
  40. _imaging_seek_pyFd(PyObject *fd, Py_ssize_t offset, int whence)
  41. {
  42. PyObject *result;
  43. result = PyObject_CallMethod(fd, "seek", "ni", offset, whence);
  44. Py_DECREF(result);
  45. return 0;
  46. }
  47. Py_ssize_t
  48. _imaging_tell_pyFd(PyObject *fd)
  49. {
  50. PyObject *result;
  51. Py_ssize_t location;
  52. result = PyObject_CallMethod(fd, "tell", NULL);
  53. location = PyInt_AsSsize_t(result);
  54. Py_DECREF(result);
  55. return location;
  56. }