util.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* See LICENSE file for copyright and license details. */
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "util.h"
  7. void *
  8. ecalloc(size_t nmemb, size_t size)
  9. {
  10. void *p;
  11. if (!(p = calloc(nmemb, size)))
  12. die("calloc:");
  13. return p;
  14. }
  15. void
  16. die(const char *fmt, ...) {
  17. va_list ap;
  18. va_start(ap, fmt);
  19. vfprintf(stderr, fmt, ap);
  20. va_end(ap);
  21. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  22. fputc(' ', stderr);
  23. perror(NULL);
  24. } else {
  25. fputc('\n', stderr);
  26. }
  27. exit(1);
  28. }
  29. /*
  30. * Splits a string into segments according to a separator. A '\0' is written to
  31. * the end of every segment. The beginning of every segment is written to
  32. * 'pbegin'. Only the first 'maxcount' segments will be written if
  33. * maxcount > 0. Inspired by python's split.
  34. *
  35. * Used exclusively by fakesignal() to split arguments.
  36. */
  37. size_t
  38. split(char *s, const char* sep, char **pbegin, size_t maxcount) {
  39. char *p, *q;
  40. const size_t seplen = strlen(sep);
  41. size_t count = 0;
  42. maxcount = maxcount == 0 ? (size_t)-1 : maxcount;
  43. p = s;
  44. while ((q = strstr(p, sep)) != NULL && count < maxcount) {
  45. pbegin[count] = p;
  46. *q = '\0';
  47. p = q + seplen;
  48. count++;
  49. }
  50. if (count < maxcount) {
  51. pbegin[count] = p;
  52. count++;
  53. }
  54. return count;
  55. }