qsort_s.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "../git-compat-util.h"
  2. /*
  3. * A merge sort implementation, simplified from the qsort implementation
  4. * by Mike Haertel, which is a part of the GNU C Library.
  5. * Added context pointer, safety checks and return value.
  6. */
  7. static void msort_with_tmp(void *b, size_t n, size_t s,
  8. int (*cmp)(const void *, const void *, void *),
  9. char *t, void *ctx)
  10. {
  11. char *tmp;
  12. char *b1, *b2;
  13. size_t n1, n2;
  14. if (n <= 1)
  15. return;
  16. n1 = n / 2;
  17. n2 = n - n1;
  18. b1 = b;
  19. b2 = (char *)b + (n1 * s);
  20. msort_with_tmp(b1, n1, s, cmp, t, ctx);
  21. msort_with_tmp(b2, n2, s, cmp, t, ctx);
  22. tmp = t;
  23. while (n1 > 0 && n2 > 0) {
  24. if (cmp(b1, b2, ctx) <= 0) {
  25. memcpy(tmp, b1, s);
  26. tmp += s;
  27. b1 += s;
  28. --n1;
  29. } else {
  30. memcpy(tmp, b2, s);
  31. tmp += s;
  32. b2 += s;
  33. --n2;
  34. }
  35. }
  36. if (n1 > 0)
  37. memcpy(tmp, b1, n1 * s);
  38. memcpy(b, t, (n - n2) * s);
  39. }
  40. int git_qsort_s(void *b, size_t n, size_t s,
  41. int (*cmp)(const void *, const void *, void *), void *ctx)
  42. {
  43. const size_t size = st_mult(n, s);
  44. char buf[1024];
  45. if (!n)
  46. return 0;
  47. if (!b || !cmp)
  48. return -1;
  49. if (size < sizeof(buf)) {
  50. /* The temporary array fits on the small on-stack buffer. */
  51. msort_with_tmp(b, n, s, cmp, buf, ctx);
  52. } else {
  53. /* It's somewhat large, so malloc it. */
  54. char *tmp = xmalloc(size);
  55. msort_with_tmp(b, n, s, cmp, tmp, ctx);
  56. free(tmp);
  57. }
  58. return 0;
  59. }