mplutils.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* -*- mode: c++; c-basic-offset: 4 -*- */
  2. /* Small utilities that are shared by most extension modules. */
  3. #ifndef MPLUTILS_H
  4. #define MPLUTILS_H
  5. #define PY_SSIZE_T_CLEAN
  6. #include <Python.h>
  7. #include <stdint.h>
  8. #ifdef _POSIX_C_SOURCE
  9. # undef _POSIX_C_SOURCE
  10. #endif
  11. #ifndef _AIX
  12. #ifdef _XOPEN_SOURCE
  13. # undef _XOPEN_SOURCE
  14. #endif
  15. #endif
  16. // Prevent multiple conflicting definitions of swab from stdlib.h and unistd.h
  17. #if defined(__sun) || defined(sun)
  18. #if defined(_XPG4)
  19. #undef _XPG4
  20. #endif
  21. #if defined(_XPG3)
  22. #undef _XPG3
  23. #endif
  24. #endif
  25. inline int mpl_round_to_int(double v)
  26. {
  27. return (int)(v + ((v >= 0.0) ? 0.5 : -0.5));
  28. }
  29. inline double mpl_round(double v)
  30. {
  31. return (double)mpl_round_to_int(v);
  32. }
  33. // 'kind' codes for paths.
  34. enum {
  35. STOP = 0,
  36. MOVETO = 1,
  37. LINETO = 2,
  38. CURVE3 = 3,
  39. CURVE4 = 4,
  40. CLOSEPOLY = 0x4f
  41. };
  42. const size_t NUM_VERTICES[] = { 1, 1, 1, 2, 3, 1 };
  43. inline int prepare_and_add_type(PyTypeObject *type, PyObject *module)
  44. {
  45. if (PyType_Ready(type)) {
  46. return -1;
  47. }
  48. char const* ptr = strrchr(type->tp_name, '.');
  49. if (!ptr) {
  50. PyErr_SetString(PyExc_ValueError, "tp_name should be a qualified name");
  51. return -1;
  52. }
  53. if (PyModule_AddObject(module, ptr + 1, (PyObject *)type)) {
  54. return -1;
  55. }
  56. return 0;
  57. }
  58. #ifdef __cplusplus // not for macosx.m
  59. // Check that array has shape (N, d1) or (N, d1, d2). We cast d1, d2 to longs
  60. // so that we don't need to access the NPY_INTP_FMT macro here.
  61. template<typename T>
  62. inline bool check_trailing_shape(T array, char const* name, long d1)
  63. {
  64. if (array.dim(1) != d1) {
  65. PyErr_Format(PyExc_ValueError,
  66. "%s must have shape (N, %ld), got (%ld, %ld)",
  67. name, d1, array.dim(0), array.dim(1));
  68. return false;
  69. }
  70. return true;
  71. }
  72. template<typename T>
  73. inline bool check_trailing_shape(T array, char const* name, long d1, long d2)
  74. {
  75. if (array.dim(1) != d1 || array.dim(2) != d2) {
  76. PyErr_Format(PyExc_ValueError,
  77. "%s must have shape (N, %ld, %ld), got (%ld, %ld, %ld)",
  78. name, d1, d2, array.dim(0), array.dim(1), array.dim(2));
  79. return false;
  80. }
  81. return true;
  82. }
  83. #endif
  84. #endif