hexml-0.3.5/0000755000000000000000000000000007346545000011025 5ustar0000000000000000hexml-0.3.5/CHANGES.txt0000644000000000000000000000126707346545000012644 0ustar0000000000000000Changelog for Hexml 0.3.5, released 2024-08-25 #1, add support for 0.3.4, released 2018-09-10 #15, licensed under BSD-3-Clause OR Apache-2.0 0.3.3, released 2017-10-27 #13, allow the . character in tags and attributes 0.3.2, released 2017-05-22 #10, mark the small fast FFI calls as "unsafe" (up to 10x faster) 0.3.1, released 2016-12-27 #9, don't walk off the end of the character table 0.3, released 2016-12-22 #8, Mac compatibility Fix a bug when parsing closing comments #7, prefix all the C functions with hexml_ 0.2, released 2016-12-14 #6, remove buffer overruns #5, add lower bounds 0.1, released 2016-12-04 Initial version hexml-0.3.5/LICENSE0000644000000000000000000002537207346545000012043 0ustar0000000000000000Copyright Neil Mitchell 2016-2024. Licensed under either of: * BSD-3-Clause license (https://opensource.org/licenses/BSD-3-Clause) * Apache License, version 2.0 (https://opensource.org/licenses/Apache-2.0) As a user, you may use this code under either license, at your option. --------------------------------------------------------------------- BSD 3-Clause License All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Neil Mitchell nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------- Apache License Version 2.0, January 2004 Terms and Conditions for use, reproduction, and distribution 1. Definitions "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. hexml-0.3.5/README.md0000644000000000000000000000314407346545000012306 0ustar0000000000000000# Hexml [![Hackage version](https://img.shields.io/hackage/v/hexml.svg?label=Hackage)](https://hackage.haskell.org/package/hexml) [![Stackage version](https://www.stackage.org/package/hexml/badge/nightly?label=Stackage)](https://www.stackage.org/package/hexml) [![Build status](https://img.shields.io/github/actions/workflow/status/ndmitchell/hexml/ci.yml?branch=master)](https://github.com/ndmitchell/hexml/actions) An XML DOM-style parser, that only parses a subset of XML, but is designed to be fast. In particular: * Entities, e.g. `&`, are not expanded. * Not all the validity conditions are checked. * No support for ` #include #include #include "hexml.c" int main(int ac, char** av) { #ifdef __AFL_HAVE_MANUAL_CONTROL __AFL_INIT(); #endif FILE *f = fopen(av[1], "rb"); fseek(f, 0, SEEK_END); size_t fsize = ftell(f); rewind(f); char* string = malloc(fsize+1); memset(string, 0, fsize+1); (void) fread(string, fsize, 1, f); fclose(f); document *doc = hexml_document_parse(string, fsize); hexml_document_free(doc); free(string); return 0; } hexml-0.3.5/cbits/hexml.c0000644000000000000000000003702407346545000013420 0ustar0000000000000000#include "hexml.h" #include #include #include #include #include typedef int bool; ///////////////////////////////////////////////////////////////////// // TYPES static inline int end(str s) { return s.start + s.length; } static inline str start_length(int32_t start, int32_t length) { assert(start >= 0 && length >= 0); str res; res.start = start; res.length = length; return res; } static inline str start_end(int32_t start, int32_t end) { return start_length(start, end - start); } typedef struct { int size; int used; attr* attrs; // dynamically allocated buffer attr* alloc; // what to call free on } attr_buffer; typedef struct { // have a cursor at the front, which is all the stuff I have written out, final // have a cursor at the end, which is stack scoped, so children write out, then I do // when you commit, you copy over from end to front // nodes int size; int used_front; // front entries, stored for good int used_back; // back entries, stack based, copied into front node* nodes; // dynamically allocated buffer node* alloc; // what to call free on } node_buffer; struct document { const char* body; // pointer to initial argument, not owned by us // things only used while parsing const char* cursor; // pointer to where we are in body const char* end; // pointer to one past the last char // if cursor is > end we have gone past the end char* error_message; node_buffer nodes; attr_buffer attrs; }; static inline int doc_length(const document* d) { return (int) (d->end - d->body); } static inline int doc_position(const document* d) { return (int) (d->cursor - d->body); } ///////////////////////////////////////////////////////////////////// // RENDER CODE typedef struct { const document* d; char* buffer; int length; int cursor; } render; static inline void render_char(render* r, char c) { if (r->cursor < r->length) r->buffer[r->cursor] = c; r->cursor++; } static inline void bound(int idx, int mn, int mx) { assert(idx >= mn && idx <= mx); } static inline void bound_str(str s, int mn, int mx) { assert(s.length >= 0); bound(s.start, mn, mx); bound(end(s), mn, mx); } static void render_str(render* r, str s) { bound_str(s, 0, doc_length(r->d)); for (int i = 0; i < s.length; i++) render_char(r, r->d->body[s.start + i]); } static void render_tag(render* r, const node* n); static void render_content(render* r, const node* n) { bound_str(n->inner, 0, doc_length(r->d)); bound_str(n->nodes, 0, r->d->nodes.used_front); bound_str(n->attrs, 0, r->d->attrs.used); int done = n->inner.start; for (int i = 0; i < n->nodes.length; i++) { node* x = &r->d->nodes.nodes[n->nodes.start + i]; render_str(r, start_end(done, x->outer.start)); done = end(x->outer); render_tag(r, x); } render_str(r, start_end(done, end(n->inner))); } static void render_tag(render* r, const node* n) { render_char(r, '<'); render_str(r, n->name); for (int i = 0; i < n->attrs.length; i++) { attr* x = &r->d->attrs.attrs[n->attrs.start + i]; render_char(r, ' '); render_str(r, x->name); render_char(r, '='); render_char(r, '\"'); render_str(r, x->value); render_char(r, '\"'); } render_char(r, '>'); render_content(r, n); render_char(r, '<'); render_char(r, '/'); render_str(r, n->name); render_char(r, '>'); } int hexml_node_render(const document* d, const node* n, char* buffer, int length) { render r; r.d = d; r.buffer = buffer; r.length = length; r.cursor = 0; // The root node (and only the root node) has an empty length, so just render its innards if (n->name.length == 0) render_content(&r, n); else render_tag(&r, n); return r.cursor; } ///////////////////////////////////////////////////////////////////// // NOT THE PARSER char* hexml_document_error(const document* d){return d->error_message;} node* hexml_document_node(const document* d){return &d->nodes.nodes[0];} void hexml_document_free(document* d) { free(d->error_message); free(d->nodes.alloc); free(d->attrs.alloc); free(d); } node* hexml_node_children(const document* d, const node* n, int* res) { *res = n->nodes.length; return &d->nodes.nodes[n->nodes.start]; } attr* hexml_node_attributes(const document* d, const node* n, int* res) { *res = n->attrs.length; return &d->attrs.attrs[n->attrs.start]; } attr* hexml_node_attribute(const document* d, const node* n, const char* s, int slen) { if (slen == -1) slen = (int) strlen(s); const int limit = end(n->attrs); for (int i = n->attrs.start; i < limit; i++) { attr* r = &d->attrs.attrs[i]; if (r->name.length == slen && memcmp(s, &d->body[r->name.start], slen) == 0) return r; } return NULL; } // Search for given strings within a node node* hexml_node_child(const document* d, const node* parent, const node* prev, const char* s, int slen) { if (slen == -1) slen = (int) strlen(s); int i = prev == NULL ? parent->nodes.start : (int) (prev + 1 - d->nodes.nodes); const int limit = end(parent->nodes); for (; i < limit; i++) { node* r = &d->nodes.nodes[i]; if (r->name.length == slen && memcmp(s, &d->body[r->name.start], slen) == 0) return r; } return NULL; } ///////////////////////////////////////////////////////////////////// // PARSE TABLE static const char tag_name1 = 0x1; static const char tag_name = 0x2; static const char tag_space = 0x4; static char parse_table[256]; static void init_parse_table() { static bool done = 0; if (done) return; for (int i = 0; i < 256; i++) { bool name1 = i == ':' || i == '_' || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z'); bool name = name1 || i == '-' || i == '.' || (i >= '0' && i <= '9'); bool space = i == ' ' || i == '\t' || i == '\r' || i == '\n'; parse_table[i] = (name1 ? tag_name1 : 0) | (name ? tag_name : 0) | (space ? tag_space : 0); } done = 1; } static inline bool is(char c, char tag) { return parse_table[(unsigned char) c] & tag; } static inline bool is_name1(char c) { return is(c, tag_name1); } static inline bool is_name(char c) { return is(c, tag_name); } static inline bool is_space(char c) { return is(c, tag_space); } ///////////////////////////////////////////////////////////////////// // PARSER COMBINATORS static inline char peek_at(const document* d, int i) { return d->cursor[i]; } static inline char peek(const document* d) { return peek_at(d, 0); } static inline void skip(document* d, int i) { d->cursor += i; } static inline char get(document* d) { char c = peek(d); skip(d, 1); return c; } // Remove whitespace characters from the cursor while they are still whitespace static inline void trim(document* d) { while (is_space(peek(d))) skip(d, 1); } // Find this character form the cursor onwards, if true adjust the cursor to that char, otherwise leave it at the end static bool find(document* d, char c) { char* x = memchr(d->cursor, c, d->end - d->cursor); if (x == NULL) { d->cursor = d->end; return 0; } else { d->cursor = x; return 1; } } ///////////////////////////////////////////////////////////////////// // PARSING CODE static inline void node_alloc(node_buffer* b, int ask) { int space = b->size - b->used_back - b->used_front; if (space >= ask) return; int size2 = (b->size + 1000 + ask) * 2; node* buf2 = malloc(size2 * sizeof(node)); assert(buf2); memcpy(buf2, b->nodes, b->used_front * sizeof(node)); memcpy(&buf2[size2 - b->used_back], &b->nodes[b->size - b->used_back], b->used_back * sizeof(node)); free(b->alloc); b->size = size2; b->nodes = buf2; b->alloc = buf2; } static inline void attr_alloc(attr_buffer* b, int ask) { int space = b->size - b->used; if (space >= ask) return; int size2 = (b->size + 1000 + ask) * 2; attr* buf2 = malloc(size2 * sizeof(attr)); assert(buf2); memcpy(buf2, b->attrs, b->used * sizeof(attr)); free(b->alloc); b->size = size2; b->attrs = buf2; b->alloc = buf2; } static void set_error(document* d, const char* msg) { if (d->error_message != NULL) return; // keep the first error message d->error_message = malloc(strlen(msg)+1); assert(d->error_message); strcpy(d->error_message, msg); } // you now expect a name, perhaps preceeded by whitespace // the name may be empty static inline str parse_name(document* d) { int start = doc_position(d); if (!is_name1(peek(d))) return start_length(start, 0); skip(d, 1); while (is_name(peek(d))) skip(d, 1); return start_end(start, doc_position(d)); } static inline str parse_attrval(document* d) { trim(d); if (peek(d) != '=') { set_error(d, "Expected = in attribute, but missing"); return start_length(0, 0); } skip(d, 1); trim(d); char c = peek(d); if (c == '\"' || c == '\'') { skip(d, 1); int start = doc_position(d); if (!find(d, c)) { set_error(d, "Couldn't find closing attribute bit"); return start_length(0, 0); } skip(d, 1); return start_end(start, doc_position(d) - 1); } else { set_error(d, "Invalid attribute"); return start_length(0, 0); } } // seen a tag name, now looking for attributes terminated by > // puts the attributes it finds in the attribute buffer static inline str parse_attributes(document* d) { int start = d->attrs.used; while (d->error_message == NULL) { trim(d); str name = parse_name(d); if (name.length == 0) break; attr_alloc(&d->attrs, 1); d->attrs.attrs[d->attrs.used].name = name; d->attrs.attrs[d->attrs.used].value = parse_attrval(d); d->attrs.used++; } return start_end(start, d->attrs.used); } static str parse_content(document* d); // Add a new entry into tag, am at a '<' static inline void parse_tag(document* d) { node_alloc(&d->nodes, 1); d->nodes.used_back++; node* me = &d->nodes.nodes[d->nodes.size - d->nodes.used_back]; me->outer.start = doc_position(d); char c = get(d); assert(c == '<'); if (peek(d) == '?') skip(d, 1); me->name = parse_name(d); if (me->name.length == 0) { set_error(d, "Missing tag name"); return; } me->attrs = parse_attributes(d); if (d->error_message != NULL) return; c = peek(d); if ((c == '/' || c == '?') && peek_at(d, 1) == '>') { skip(d, 2); me->nodes = start_length(0, 0); me->outer.length = start_end(me->outer.start, doc_position(d)).length; me->inner = start_length(doc_position(d), 0); return; } else if (c != '>') { set_error(d, "Gunk at the end of the tag"); return; } else skip(d, 1); me->inner.start = doc_position(d); str content = parse_content(d); // parse_content may have allocated more nodes, so recompute me me = &d->nodes.nodes[d->nodes.size - d->nodes.used_back]; me->nodes = content; me->inner.length = start_end(me->inner.start, doc_position(d)).length; if (d->error_message != NULL) return; if (peek(d) == '<' && peek_at(d, 1) == '/') { skip(d, 2); if (d->end - d->cursor >= me->name.length && memcmp(d->cursor, &d->body[me->name.start], me->name.length) == 0) { skip(d, me->name.length); trim(d); if (get(d) == '>') { me->outer.length = start_end(me->outer.start, doc_position(d)).length; return; } } set_error(d, "Mismatch in closing tags"); return; } set_error(d, "Weirdness when trying to close tags"); } // Parser until nodes.used_back; while (d->error_message == NULL) { // only < can have any impact if (!find(d, '<')) { break; } else if (peek_at(d, 1) == '/') { // have found a ')) { set_error(d, "Didn't get a closing comment"); return start_end(0, 0); } skip(d, 1); if (peek_at(d, -3) == '-' && peek_at(d, -2) == '-') break; } } else if (d->end - d->cursor >= 9 && memcmp(d->cursor + 2, "[CDATA[", 7) == 0) { skip(d, 9); for (;;) { if (!find(d, '>')) { set_error(d, "Didn't close CDATA"); return start_end(0, 0); } skip(d, 1); if (peek_at(d, -3) == ']' && peek_at(d, -2) == ']') break; } } else { parse_tag(d); } } else { parse_tag(d); } } int diff = d->nodes.used_back - before; node_alloc(&d->nodes, diff); str res = start_length(d->nodes.used_front, diff); for (int i = 0; i < diff; i++) d->nodes.nodes[d->nodes.used_front + i] = d->nodes.nodes[d->nodes.size - d->nodes.used_back + diff - 1 - i]; d->nodes.used_front += diff; d->nodes.used_back -= diff; return res; } // Based on looking at ~50Kb XML documents, they seem to have ~700 attributes // and ~300 nodes, so size appropriately to cope with that. typedef struct { document document; attr attrs[1000]; node nodes[500]; } buffer; document* hexml_document_parse(const char* s, int slen) { if (slen == -1) slen = (int) strlen(s); assert(s[slen] == 0); init_parse_table(); buffer* buf = malloc(sizeof(buffer)); assert(buf); document* d = &buf->document; d->body = s; d->cursor = s; d->end = &s[slen]; d->error_message = NULL; d->attrs.size = 1000; d->attrs.used = 0; d->attrs.attrs = buf->attrs; d->attrs.alloc = NULL; d->nodes.size = 500; d->nodes.used_back = 0; d->nodes.used_front = 1; d->nodes.nodes = buf->nodes; d->nodes.alloc = NULL; d->nodes.nodes[0].name = start_length(0, 0); d->nodes.nodes[0].outer = start_length(0, slen); d->nodes.nodes[0].inner = start_length(0, slen); d->nodes.nodes[0].attrs = start_length(0, 0); // Introduce an intermediate result, otherwise behaviour is undefined // because there is no guaranteed ordering between LHS and RHS evaluation str content = parse_content(d); d->nodes.nodes[0].nodes = content; if (d->cursor < d->end) set_error(d, "Trailing junk at the end of the document"); return d; } hexml-0.3.5/cbits/hexml.h0000644000000000000000000000404307346545000013420 0ustar0000000000000000 #include typedef struct document document; // Pair of indexes into the input string typedef struct { int32_t start; int32_t length; } str; typedef struct { str name; str value; } attr; typedef struct { str name; // tag name, e.g. <[foo]> str inner; // inner text, [bar] str outer; // outer text, [bar] // Not usable, but required to get the correct sizing when returning arrays of nodes str attrs; // all the attributes, in the attribute buffer (not usable) str nodes; // all the nodes, in the node buffer (not usable) } node; // Convention: if slen can be -1 for nul-terminated, or given explicitly // Parse a document, returns a potentially invalid document - use document_error to check // Must use document_free to release the memory (even if invalid). // The string must be nul terminated, e.g. slen != -1 ==> slen[0] document* hexml_document_parse(const char* s, int slen); // Free the memory returned from document_parse. void hexml_document_free(document* d); // Generate a fresh string with the same semantics as the node. // Requires an input buffer, returns the size of the rendered document. // Requires the string passed to document_parse to be valid. int hexml_node_render(const document* d, const node* n, char* buffer, int length); // Return either NULL (successful parse) or the error message. char* hexml_document_error(const document* d); // Return the root node of the document - imagine the document is wrapped in <>$DOC tags. node* hexml_document_node(const document* d); // List all items within a node node* hexml_node_children(const document* d, const node* n, int* res); attr* hexml_node_attributes(const document* d, const node* n, int* res); // Search for given strings within a node, note that prev may be NULL // Requires the string passed to document_parse to be valid. node* hexml_node_child(const document* d, const node* parent, const node* prev, const char* s, int slen); attr* hexml_node_attribute(const document* d, const node* n, const char* s, int slen); hexml-0.3.5/cbits/main.c0000644000000000000000000000226207346545000013223 0ustar0000000000000000#include "hexml.h" #include #include #include #include #include char* readFile(char* file) { FILE* f = fopen(file, "rb"); fseek(f, 0, SEEK_END); int len = ftell(f); fseek(f, 0, SEEK_SET); char* res = malloc(len + 1); assert(res); res[len] = 0; size_t n = fread(res, 1, len, f); assert(n == len); fclose(f); return res; } char* example = "quuxhoge>piyopiyo<"; int main(int argc, char **argv) { setbuf(stdout, NULL); char* body = argv[1] == NULL ? example : readFile(argv[1]); document* doc = hexml_document_parse(body, -1); char* err = hexml_document_error(doc); if (err == NULL) { int len = hexml_node_render(doc, hexml_document_node(doc), NULL, 0); char* s = malloc(len + 1); assert(s); hexml_node_render(doc, hexml_document_node(doc), s, len); s[len] = 0; printf("Parse successful\n"); // , %s\n", s); return 0; } else { printf("Parse failed, %s\n", err); return 1; } } hexml-0.3.5/hexml.cabal0000644000000000000000000000273207346545000013132 0ustar0000000000000000cabal-version: 1.18 build-type: Simple name: hexml version: 0.3.5 license: BSD3 x-license: BSD-3-Clause OR Apache-2.0 license-file: LICENSE category: XML author: Neil Mitchell maintainer: Neil Mitchell copyright: Neil Mitchell 2016-2024 synopsis: XML subset DOM parser description: An XML DOM-style parser, that only parses a subset of XML, but is designed to be fast. homepage: https://github.com/ndmitchell/hexml#readme bug-reports: https://github.com/ndmitchell/hexml/issues tested-with: GHC==9.6, GHC==9.4, GHC==9.2, GHC==9.0, GHC==8.10, GHC==8.8 extra-doc-files: README.md CHANGES.txt extra-source-files: cbits/*.h cbits/*.c source-repository head type: git location: https://github.com/ndmitchell/hexml.git library hs-source-dirs: src default-language: Haskell2010 build-depends: base >= 4.5 && < 5, bytestring, extra >= 0.3 c-sources: cbits/hexml.c include-dirs: cbits includes: hexml.h install-includes: hexml.h cc-options: -std=c99 exposed-modules: Text.XML.Hexml test-suite hexml-test type: exitcode-stdio-1.0 main-is: src/Main.hs default-language: Haskell2010 build-depends: base, bytestring, hexml hexml-0.3.5/src/0000755000000000000000000000000007346545000011614 5ustar0000000000000000hexml-0.3.5/src/Main.hs0000644000000000000000000000673707346545000013051 0ustar0000000000000000{-# LANGUAGE OverloadedStrings #-} module Main(main) where import Text.XML.Hexml as X import qualified Data.ByteString.Char8 as BS import Control.Monad import Data.Monoid import Data.Char import Prelude examples :: [(Bool, BS.ByteString)] examples = [(True, "herethere") ,(True, "") ,(True, "") ,(True, "here more text at the end") ,(False, "") ,(False, "\nHello, world!") ,(True, "") ,(True, "]]]>]baz]]>") ] main :: IO () main = do forM_ examples $ \(parses, src) -> case parse src of Left err -> when parses $ fail $ "Unexpected parse failure, " ++ show err Right doc -> do unless parses $ fail "Unexpected parse success" checkFind doc let r = render doc r === rerender doc let Right d = parse r r === render d let Right doc = parse "\n" map name (children doc) === ["test","test","b","test","test"] location (children doc !! 2) === (2,16) length (childrenBy doc "test") === 4 length (childrenBy doc "b") === 1 length (childrenBy doc "extra") === 0 attributes (head $ children doc) === [Attribute "id" "1", Attribute "extra" "2"] map (`attributeBy` "id") (childrenBy doc "test") === map (fmap (Attribute "id")) [Just "1", Just "2", Just "4", Nothing] Right _ <- pure $ parse $ " BS.unwords [BS.pack $ "x" ++ show i ++ "='value'" | i <- [1..10000]] <> " />" Right _ <- pure $ parse $ BS.unlines $ replicate 10000 "" let attrs = ["usd:jpy","test","extra","more","stuff","jpy:usd","xxx","xxxx"] Right doc <- pure $ parse $ " BS.unwords [x <> "='" <> x <> "'" | x <- attrs] <> ">middle" [c] <- pure $ childrenBy doc "test" forM_ attrs $ \a -> attributeBy c a === Just (Attribute a a) forM_ ["missing","gone","nothing"] $ \a -> attributeBy c a === Nothing putStrLn "\nSuccess" checkFind :: Node -> IO () checkFind n = do forM_ (attributes n) $ \a -> attributeBy n (attributeName a) === Just a attributeBy n "xxx" === Nothing let cs = children n forM_ ("xxx":map name cs) $ \c -> map outer (filter ((==) c . name) cs) === map outer (childrenBy n c) mapM_ checkFind $ children n a === b = if a == b then putChar '.' else fail $ "mismatch, " ++ show a ++ " /= " ++ show b rerender :: Node -> BS.ByteString rerender = inside where inside x = BS.concat $ map (either validStr node) $ contents x node x = "<" <> BS.unwords (validName (name x) : map attr (attributes x)) <> ">" <> inside x <> " name x <> ">" attr (Attribute a b) = validName a <> "=\"" <> validAttr b <> "\"" validName x | BS.all (\x -> isAlphaNum x || x `elem` ("-.:_" :: String)) x = x | otherwise = error "Invalid name" validAttr x | BS.notElem '\"' x = x | otherwise = error "Invalid attribute" validStr x | BS.notElem '<' x || BS.isInfixOf "