aboutsummaryrefslogtreecommitdiff
path: root/src/houdini_html_u.c
blob: b88b9d1471eb5127149eea845b992ee8147f2c9a (plain)
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "buffer.h"
  5. #include "houdini.h"
  6. #include "utf8.h"
  7. #include "html_unescape.h"
  8. size_t
  9. houdini_unescape_ent(strbuf *ob, const uint8_t *src, size_t size)
  10. {
  11. size_t i = 0;
  12. if (size > 3 && src[0] == '#') {
  13. int codepoint = 0;
  14. if (_isdigit(src[1])) {
  15. for (i = 1; i < size && _isdigit(src[i]); ++i) {
  16. int cp = (codepoint * 10) + (src[i] - '0');
  17. if (cp < codepoint)
  18. return 0;
  19. codepoint = cp;
  20. }
  21. }
  22. else if (src[1] == 'x' || src[1] == 'X') {
  23. for (i = 2; i < size && _isxdigit(src[i]); ++i) {
  24. int cp = (codepoint * 16) + ((src[i] | 32) % 39 - 9);
  25. if (cp < codepoint)
  26. return 0;
  27. codepoint = cp;
  28. }
  29. }
  30. if (i < size && src[i] == ';' && codepoint) {
  31. utf8proc_encode_char(codepoint, ob);
  32. return i + 1;
  33. }
  34. }
  35. else {
  36. if (size > MAX_WORD_LENGTH)
  37. size = MAX_WORD_LENGTH;
  38. for (i = MIN_WORD_LENGTH; i < size; ++i) {
  39. if (src[i] == ' ')
  40. break;
  41. if (src[i] == ';') {
  42. const struct html_ent *entity = find_entity((char *)src, i);
  43. if (entity != NULL) {
  44. strbuf_put(ob, entity->utf8, entity->utf8_len);
  45. return i + 1;
  46. }
  47. break;
  48. }
  49. }
  50. }
  51. return 0;
  52. }
  53. int
  54. houdini_unescape_html(strbuf *ob, const uint8_t *src, size_t size)
  55. {
  56. size_t i = 0, org, ent;
  57. while (i < size) {
  58. org = i;
  59. while (i < size && src[i] != '&')
  60. i++;
  61. if (likely(i > org)) {
  62. if (unlikely(org == 0)) {
  63. if (i >= size)
  64. return 0;
  65. strbuf_grow(ob, HOUDINI_UNESCAPED_SIZE(size));
  66. }
  67. strbuf_put(ob, src + org, i - org);
  68. }
  69. /* escaping */
  70. if (i >= size)
  71. break;
  72. i++;
  73. ent = houdini_unescape_ent(ob, src + i, size - i);
  74. i += ent;
  75. /* not really an entity */
  76. if (ent == 0)
  77. strbuf_putc(ob, '&');
  78. }
  79. return 1;
  80. }
  81. void houdini_unescape_html_f(strbuf *ob, const uint8_t *src, size_t size)
  82. {
  83. if (!houdini_unescape_html(ob, src, size))
  84. strbuf_put(ob, src, size);
  85. }