Guest User

Untitled

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