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