Guest User

Untitled

a guest
Feb 20th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. #include <Python.h>
  2.  
  3. static PyObject* urlize(PyObject *self, PyObject *args)
  4. {
  5. PyObject* obj;
  6. PyObject* str;
  7. PyObject* res;
  8. const char* src;
  9. char* buf1;
  10. char* buf2;
  11. char c;
  12. size_t len;
  13. unsigned int i, j;
  14. unsigned short int repeat = 0;
  15.  
  16. if (!PyArg_ParseTuple(args, "O", &obj))
  17. return NULL;
  18.  
  19. str = PyObject_Str(obj);
  20. src = PyString_AsString(str);
  21. Py_DECREF(str);
  22.  
  23. if (src == NULL)
  24. return PyString_FromString("");
  25.  
  26. len = strlen(src);
  27. buf1 = (char*) PyMem_New(char, len + 1);
  28. if (buf1 == NULL)
  29. return PyErr_NoMemory();
  30.  
  31. /* Replace all non-alphanumeric characters with a dash */
  32. for (i = 0; i < len; ++i) {
  33. c = src[i];
  34. if (isalnum(c))
  35. buf1[i] = tolower(c);
  36. else
  37. buf1[i] = '-';
  38. }
  39. buf1[i] = '\0';
  40.  
  41. len = strlen(buf1);
  42. buf2 = (char*) PyMem_New(char, len + 1);
  43. if (buf2 == NULL)
  44. return PyErr_NoMemory();
  45.  
  46. /* Reduce multiple dashes to only one */
  47. for (i = 0, j = 0; i < len; ++i) {
  48. c = buf1[i];
  49. if (c == '-') {
  50. if (repeat)
  51. continue;
  52. repeat = 1;
  53. } else {
  54. repeat = 0;
  55. }
  56. buf2[j] = c;
  57. ++j;
  58. }
  59. buf2[j] = '\0';
  60.  
  61. /* Strip leading dashes */
  62. len = strlen(buf2);
  63.  
  64. i = 0;
  65. while (i < len) {
  66. if (buf2[i] != '-')
  67. break;
  68. ++i;
  69. }
  70. strcpy(buf1, buf2+i);
  71.  
  72. /* Strip trailing dashes */
  73. len = strlen(buf1);
  74.  
  75. i = len - 1;
  76. while (i >= 0) {
  77. if (buf1[i] != '-')
  78. break;
  79. --i;
  80. }
  81. strncpy(buf2, buf1, i+1);
  82. buf2[i+1] = '\0';
  83.  
  84. PyMem_Del(buf1);
  85.  
  86. res = PyString_FromString(buf2);
  87. PyMem_Del(buf2);
  88. return res;
  89. }
  90.  
  91. static PyMethodDef methods[] = {
  92. {"c_urlize", urlize, METH_VARARGS, ""},
  93. {NULL, NULL, 0, NULL}
  94. };
  95.  
  96. PyMODINIT_FUNC
  97. init_speedups(void)
  98. {
  99. (void) Py_InitModule("_speedups", methods);
  100. }
Add Comment
Please, Sign In to add comment