util.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "awiki.h"
  10. void*
  11. emalloc(uint n)
  12. {
  13. void *p;
  14. p = malloc(n);
  15. if(p == nil)
  16. error("can't malloc: %r");
  17. memset(p, 0, n);
  18. return p;
  19. }
  20. char*
  21. estrdup(char *s)
  22. {
  23. char *t;
  24. t = emalloc(strlen(s)+1);
  25. strcpy(t, s);
  26. return t;
  27. }
  28. char*
  29. estrstrdup(char *s, char *t)
  30. {
  31. char *u;
  32. u = emalloc(strlen(s)+strlen(t)+1);
  33. strcpy(u, s);
  34. strcat(u, t);
  35. return u;
  36. }
  37. char*
  38. eappend(char *s, char *sep, char *t)
  39. {
  40. char *u;
  41. if(t == nil)
  42. u = estrstrdup(s, sep);
  43. else{
  44. u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
  45. strcpy(u, s);
  46. strcat(u, sep);
  47. strcat(u, t);
  48. }
  49. free(s);
  50. return u;
  51. }
  52. char*
  53. egrow(char *s, char *sep, char *t)
  54. {
  55. s = eappend(s, sep, t);
  56. free(t);
  57. return s;
  58. }
  59. void
  60. error(char *fmt, ...)
  61. {
  62. int n;
  63. va_list arg;
  64. char buf[256];
  65. fprint(2, "Wiki: ");
  66. va_start(arg, fmt);
  67. n = vseprint(buf, buf+sizeof buf, fmt, arg) - buf;
  68. va_end(arg);
  69. write(2, buf, n);
  70. write(2, "\n", 1);
  71. threadexitsall(fmt);
  72. }
  73. void
  74. ctlprint(int fd, char *fmt, ...)
  75. {
  76. int n;
  77. va_list arg;
  78. char buf[256];
  79. va_start(arg, fmt);
  80. n = vseprint(buf, buf+sizeof buf, fmt, arg) - buf;
  81. va_end(arg);
  82. if(write(fd, buf, n) != n)
  83. error("control file write(%s) error: %r", buf);
  84. }