util.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #include "a.h"
  2. void*
  3. emalloc(uint n)
  4. {
  5. void *v;
  6. v = mallocz(n, 1);
  7. if(v == nil)
  8. sysfatal("out of memory");
  9. return v;
  10. }
  11. char*
  12. estrdup(char *s)
  13. {
  14. char *t;
  15. t = strdup(s);
  16. if(t == nil)
  17. sysfatal("out of memory");
  18. return t;
  19. }
  20. Rune*
  21. erunestrdup(Rune *s)
  22. {
  23. Rune *t;
  24. t = emalloc(sizeof(Rune)*(runestrlen(s)+1));
  25. if(t == nil)
  26. sysfatal("out of memory");
  27. runestrcpy(t, s);
  28. return t;
  29. }
  30. void*
  31. erealloc(void *ov, uint n)
  32. {
  33. void *v;
  34. v = realloc(ov, n);
  35. if(v == nil)
  36. sysfatal("out of memory");
  37. return v;
  38. }
  39. Rune*
  40. erunesmprint(char *fmt, ...)
  41. {
  42. Rune *s;
  43. va_list arg;
  44. va_start(arg, fmt);
  45. s = runevsmprint(fmt, arg);
  46. va_end(arg);
  47. if(s == nil)
  48. sysfatal("out of memory");
  49. return s;
  50. }
  51. char*
  52. esmprint(char *fmt, ...)
  53. {
  54. char *s;
  55. va_list arg;
  56. va_start(arg, fmt);
  57. s = vsmprint(fmt, arg);
  58. va_end(arg);
  59. if(s == nil)
  60. sysfatal("out of memory");
  61. return s;
  62. }
  63. void
  64. warn(char *fmt, ...)
  65. {
  66. va_list arg;
  67. fprint(2, "htmlroff: %L: ");
  68. va_start(arg, fmt);
  69. vfprint(2, fmt, arg);
  70. va_end(arg);
  71. fprint(2, "\n");
  72. }
  73. /*
  74. * For non-Unicode compilers, so we can say
  75. * L("asdf") and get a Rune string. Assumes strings
  76. * are identified by their pointers, so no mutable strings!
  77. */
  78. typedef struct Lhash Lhash;
  79. struct Lhash
  80. {
  81. char *s;
  82. Lhash *next;
  83. Rune r[1];
  84. };
  85. static Lhash *hash[1127];
  86. Rune*
  87. L(char *s)
  88. {
  89. Rune *p;
  90. Lhash *l;
  91. uint h;
  92. h = (uintptr)s%nelem(hash);
  93. for(l=hash[h]; l; l=l->next)
  94. if(l->s == s)
  95. return l->r;
  96. l = emalloc(sizeof *l+(utflen(s)+1)*sizeof(Rune));
  97. p = l->r;
  98. l->s = s;
  99. while(*s)
  100. s += chartorune(p++, s);
  101. *p = 0;
  102. l->next = hash[h];
  103. hash[h] = l;
  104. return l->r;
  105. }