replace.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* stringlib: replace implementation */
  2. #ifndef STRINGLIB_FASTSEARCH_H
  3. #error must include "stringlib/fastsearch.h" before including this module
  4. #endif
  5. Py_LOCAL_INLINE(void)
  6. STRINGLIB(replace_1char_inplace)(STRINGLIB_CHAR* s, STRINGLIB_CHAR* end,
  7. Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
  8. {
  9. *s = u2;
  10. while (--maxcount && ++s != end) {
  11. /* Find the next character to be replaced.
  12. If it occurs often, it is faster to scan for it using an inline
  13. loop. If it occurs seldom, it is faster to scan for it using a
  14. function call; the overhead of the function call is amortized
  15. across the many characters that call covers. We start with an
  16. inline loop and use a heuristic to determine whether to fall back
  17. to a function call. */
  18. if (*s != u1) {
  19. int attempts = 10;
  20. /* search u1 in a dummy loop */
  21. while (1) {
  22. if (++s == end)
  23. return;
  24. if (*s == u1)
  25. break;
  26. if (!--attempts) {
  27. /* if u1 was not found for attempts iterations,
  28. use FASTSEARCH() or memchr() */
  29. #ifdef STRINGLIB_FAST_MEMCHR
  30. s++;
  31. s = STRINGLIB_FAST_MEMCHR(s, u1, end - s);
  32. if (s == NULL)
  33. return;
  34. #else
  35. Py_ssize_t i;
  36. STRINGLIB_CHAR ch1 = (STRINGLIB_CHAR) u1;
  37. s++;
  38. i = FASTSEARCH(s, end - s, &ch1, 1, 0, FAST_SEARCH);
  39. if (i < 0)
  40. return;
  41. s += i;
  42. #endif
  43. /* restart the dummy loop */
  44. break;
  45. }
  46. }
  47. }
  48. *s = u2;
  49. }
  50. }