util.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <thread.h>
  5. #include "dat.h"
  6. void*
  7. emalloc(uint n)
  8. {
  9. void *p;
  10. p = malloc(n);
  11. if(p == nil)
  12. error("can't malloc: %r");
  13. memset(p, 0, n);
  14. return p;
  15. }
  16. char*
  17. estrdup(char *s)
  18. {
  19. char *t;
  20. t = emalloc(strlen(s)+1);
  21. strcpy(t, s);
  22. return t;
  23. }
  24. char*
  25. estrstrdup(char *s, char *t)
  26. {
  27. char *u;
  28. u = emalloc(strlen(s)+strlen(t)+1);
  29. sprint(u, "%s%s", s, t);
  30. return u;
  31. }
  32. char*
  33. eappend(char *s, char *sep, char *t)
  34. {
  35. char *u;
  36. if(t == nil)
  37. u = estrstrdup(s, sep);
  38. else{
  39. u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
  40. sprint(u, "%s%s%s", s, sep, t);
  41. }
  42. free(s);
  43. return u;
  44. }
  45. char*
  46. egrow(char *s, char *sep, char *t)
  47. {
  48. s = eappend(s, sep, t);
  49. free(t);
  50. return s;
  51. }
  52. void
  53. error(char *fmt, ...)
  54. {
  55. Fmt f;
  56. char buf[64];
  57. va_list arg;
  58. fmtfdinit(&f, 2, buf, sizeof buf);
  59. fmtprint(&f, "win: ");
  60. va_start(arg, fmt);
  61. fmtvprint(&f, fmt, arg);
  62. va_end(arg);
  63. fmtprint(&f, "\n");
  64. fmtfdflush(&f);
  65. threadexitsall(fmt);
  66. }
  67. void
  68. ctlprint(int fd, char *fmt, ...)
  69. {
  70. int n;
  71. va_list arg;
  72. va_start(arg, fmt);
  73. n = vfprint(fd, fmt, arg);
  74. va_end(arg);
  75. if(n <= 0)
  76. error("control file write error: %r");
  77. }