util.c 2.0 KB

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