aboutsummaryrefslogtreecommitdiff
path: root/src/houdini_html_u.c
blob: ecd7faa20c4c115fe2a806f4573dfea00bce036f (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(cmark_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. size_t len = strnlen((const char *)entity->utf8, 4);
  45. cmark_strbuf_put(ob, entity->utf8, len);
  46. return i + 1;
  47. }
  48. break;
  49. }
  50. }
  51. }
  52. return 0;
  53. }
  54. int
  55. houdini_unescape_html(cmark_strbuf *ob, const uint8_t *src, size_t size)
  56. {
  57. size_t i = 0, org, ent;
  58. while (i < size) {
  59. org = i;
  60. while (i < size && src[i] != '&')
  61. i++;
  62. if (likely(i > org)) {
  63. if (unlikely(org == 0)) {
  64. if (i >= size)
  65. return 0;
  66. cmark_strbuf_grow(ob, HOUDINI_UNESCAPED_SIZE(size));
  67. }
  68. cmark_strbuf_put(ob, src + org, i - org);
  69. }
  70. /* escaping */
  71. if (i >= size)
  72. break;
  73. i++;
  74. ent = houdini_unescape_ent(ob, src + i, size - i);
  75. i += ent;
  76. /* not really an entity */
  77. if (ent == 0)
  78. cmark_strbuf_putc(ob, '&');
  79. }
  80. return 1;
  81. }
  82. void houdini_unescape_html_f(cmark_strbuf *ob, const uint8_t *src, size_t size)
  83. {
  84. if (!houdini_unescape_html(ob, src, size))
  85. cmark_strbuf_put(ob, src, size);
  86. }