util.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <draw.h>
  5. #include <html.h>
  6. #include "dat.h"
  7. void*
  8. emalloc(ulong n)
  9. {
  10. void *p;
  11. p = malloc(n);
  12. if(p == nil)
  13. error("can't malloc: %r");
  14. memset(p, 0, n);
  15. return p;
  16. }
  17. void*
  18. erealloc(void *p, ulong n)
  19. {
  20. p = realloc(p, n);
  21. if(p == nil)
  22. error("can't malloc: %r");
  23. return p;
  24. }
  25. char*
  26. estrdup(char *s)
  27. {
  28. char *t;
  29. t = emalloc(strlen(s)+1);
  30. strcpy(t, s);
  31. return t;
  32. }
  33. char*
  34. estrstrdup(char *s, char *t)
  35. {
  36. long ns, nt;
  37. char *u;
  38. ns = strlen(s);
  39. nt = strlen(t);
  40. /* use malloc to avoid memset */
  41. u = malloc(ns+nt+1);
  42. if(u == nil)
  43. error("can't malloc: %r");
  44. memmove(u, s, ns);
  45. memmove(u+ns, t, nt);
  46. u[ns+nt] = '\0';
  47. return u;
  48. }
  49. char*
  50. eappend(char *s, char *sep, char *t)
  51. {
  52. long ns, nsep, nt;
  53. char *u;
  54. if(t == nil)
  55. u = estrstrdup(s, sep);
  56. else{
  57. ns = strlen(s);
  58. nsep = strlen(sep);
  59. nt = strlen(t);
  60. /* use malloc to avoid memset */
  61. u = malloc(ns+nsep+nt+1);
  62. if(u == nil)
  63. error("can't malloc: %r");
  64. memmove(u, s, ns);
  65. memmove(u+ns, sep, nsep);
  66. memmove(u+ns+nsep, t, nt);
  67. u[ns+nsep+nt] = '\0';
  68. }
  69. free(s);
  70. return u;
  71. }
  72. char*
  73. egrow(char *s, char *sep, char *t)
  74. {
  75. s = eappend(s, sep, t);
  76. free(t);
  77. return s;
  78. }
  79. void
  80. error(char *fmt, ...)
  81. {
  82. va_list arg;
  83. char buf[256];
  84. Fmt f;
  85. fmtfdinit(&f, 2, buf, sizeof buf);
  86. fmtprint(&f, "Mail: ");
  87. va_start(arg, fmt);
  88. fmtvprint(&f, fmt, arg);
  89. va_end(arg);
  90. fmtprint(&f, "\n");
  91. fmtfdflush(&f);
  92. exits(fmt);
  93. }
  94. void
  95. growbytes(Bytes *b, char *s, long ns)
  96. {
  97. if(b->nalloc < b->n + ns + 1){
  98. b->nalloc = b->n + ns + 8000;
  99. /* use realloc to avoid memset */
  100. b->b = realloc(b->b, b->nalloc);
  101. if(b->b == nil)
  102. error("growbytes: can't realloc: %r");
  103. }
  104. memmove(b->b+b->n, s, ns);
  105. b->n += ns;
  106. b->b[b->n] = '\0';
  107. }