codec_fd.c 1.4 KB

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