util.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <String.h>
  5. #include <ctype.h>
  6. #include <thread.h>
  7. #include "wiki.h"
  8. void*
  9. erealloc(void *v, ulong n)
  10. {
  11. v = realloc(v, n);
  12. if(v == nil)
  13. sysfatal("out of memory reallocating %lud", n);
  14. setmalloctag(v, getcallerpc(&v));
  15. return v;
  16. }
  17. void*
  18. emalloc(ulong n)
  19. {
  20. void *v;
  21. v = malloc(n);
  22. if(v == nil)
  23. sysfatal("out of memory allocating %lud", n);
  24. memset(v, 0, n);
  25. setmalloctag(v, getcallerpc(&n));
  26. return v;
  27. }
  28. char*
  29. estrdup(char *s)
  30. {
  31. int l;
  32. char *t;
  33. if (s == nil)
  34. return nil;
  35. l = strlen(s)+1;
  36. t = emalloc(l);
  37. memmove(t, s, l);
  38. setmalloctag(t, getcallerpc(&s));
  39. return t;
  40. }
  41. char*
  42. estrdupn(char *s, int n)
  43. {
  44. int l;
  45. char *t;
  46. l = strlen(s);
  47. if(l > n)
  48. l = n;
  49. t = emalloc(l+1);
  50. memmove(t, s, l);
  51. t[l] = '\0';
  52. setmalloctag(t, getcallerpc(&s));
  53. return t;
  54. }
  55. char*
  56. strlower(char *s)
  57. {
  58. char *p;
  59. for(p=s; *p; p++)
  60. if('A' <= *p && *p <= 'Z')
  61. *p += 'a'-'A';
  62. return s;
  63. }
  64. String*
  65. s_appendsub(String *s, char *p, int n, Sub *sub, int nsub)
  66. {
  67. int i, m;
  68. char *q, *r, *ep;
  69. ep = p+n;
  70. while(p<ep){
  71. q = ep;
  72. m = -1;
  73. for(i=0; i<nsub; i++){
  74. if(sub[i].sub && (r = strstr(p, sub[i].match)) && r < q){
  75. q = r;
  76. m = i;
  77. }
  78. }
  79. s = s_nappend(s, p, q-p);
  80. p = q;
  81. if(m >= 0){
  82. s = s_append(s, sub[m].sub);
  83. p += strlen(sub[m].match);
  84. }
  85. }
  86. return s;
  87. }
  88. String*
  89. s_appendlist(String *s, ...)
  90. {
  91. char *x;
  92. va_list arg;
  93. va_start(arg, s);
  94. while(x = va_arg(arg, char*))
  95. s = s_append(s, x);
  96. va_end(arg);
  97. return s;
  98. }
  99. int
  100. opentemp(char *template)
  101. {
  102. int fd, i;
  103. char *p;
  104. p = estrdup(template);
  105. fd = -1;
  106. for(i=0; i<10; i++){
  107. mktemp(p);
  108. if(access(p, 0) < 0 && (fd=create(p, ORDWR|ORCLOSE, 0444)) >= 0)
  109. break;
  110. strcpy(p, template);
  111. }
  112. if(fd >= 0)
  113. strcpy(template, p);
  114. free(p);
  115. return fd;
  116. }