Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions entities.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define UNICODE_MAX 0x10FFFFul

Expand Down Expand Up @@ -391,3 +393,33 @@ size_t decode_html_entities_utf8(char *dest, const char *src)
return (size_t)(to - dest);
}

size_t encode_html_entities(char *dest, const char *src) {
char *to = dest;
for( const char *from = src ; *from ; from++ ) {
if ( *from>=0 ) {
if ( (*from>='A' && *from<='Z') || (*from>='a' && *from<='z') ) {
*to = *from;
to++;
continue;
}
}
unsigned i;
for( i=0 ; i<sizeof NAMED_ENTITIES / sizeof *NAMED_ENTITIES ; i++ )
if ( strncmp(from,NAMED_ENTITIES[i][1],strlen(NAMED_ENTITIES[i][1]))==0 )
break;
if ( i<sizeof NAMED_ENTITIES / sizeof *NAMED_ENTITIES ) {
*to = '&';
to++;
strcpy(to,NAMED_ENTITIES[i][0]);
to += strlen(NAMED_ENTITIES[i][0]);
from += strlen(NAMED_ENTITIES[i][1])-1;
}
else {
*to = *from;
to++;
}
}
*to = 0;
return (size_t)(to - dest);
}

4 changes: 4 additions & 0 deletions entities.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,9 @@ extern size_t decode_html_entities_utf8(char *dest, const char *src);
The function returns the length of the decoded string.
*/



size_t encode_html_entities(char *dest, const char *src);

#endif

19 changes: 19 additions & 0 deletions t-entities.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,25 @@ int main(void)
assert(strcmp(buffer, SAMPLE) == 0);
}

{
static const char INPUT[] = ""
"Miguel Leitão\n"
"[email protected]\n"
"<p>Hello!!</p>";
static char GOAL[] = ""
"Miguel Leit&atilde;o\n"
"test&commat;example.org\n"
"&lt;p&gt;Hello!!&lt;/p&gt;";
char OUTPUT[sizeof GOAL];
char REVERT[sizeof GOAL];
assert(encode_html_entities(OUTPUT, INPUT) == sizeof GOAL - 1);
assert(strcmp(OUTPUT, GOAL) == 0);

decode_html_entities_utf8(REVERT, OUTPUT);
assert(strcmp(INPUT, REVERT) == 0);
}


fprintf(stdout, "All tests passed :-)\n");
return EXIT_SUCCESS;
}
Expand Down