libgrapheme

unicode string library
git clone git://git.suckless.org/libgrapheme
Log | Files | Refs | README | LICENSE

util.c (21181B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <ctype.h>
      3 #include <errno.h>
      4 #include <inttypes.h>
      5 #include <stdbool.h>
      6 #include <stddef.h>
      7 #include <stdint.h>
      8 #include <stdio.h>
      9 #include <stdlib.h>
     10 #include <string.h>
     11 
     12 #include "util.h"
     13 
     14 struct range {
     15 	uint_least32_t lower;
     16 	uint_least32_t upper;
     17 };
     18 
     19 struct properties_payload {
     20 	struct properties *prop;
     21 	const struct property_spec *spec;
     22 	uint_least8_t speclen;
     23 	int (*set_value)(struct properties_payload *, uint_least32_t,
     24 	                 int_least64_t);
     25 	uint_least8_t (*handle_conflict)(uint_least32_t, uint_least8_t,
     26 	                                 uint_least8_t);
     27 };
     28 
     29 struct break_test_payload {
     30 	struct break_test **test;
     31 	size_t *testlen;
     32 };
     33 
     34 static void *
     35 reallocate_array(void *p, size_t len, size_t size)
     36 {
     37 	if (len > 0 && size > SIZE_MAX / len) {
     38 		errno = ENOMEM;
     39 		return NULL;
     40 	}
     41 
     42 	return realloc(p, len * size);
     43 }
     44 
     45 int
     46 hextocp(const char *str, size_t len, uint_least32_t *cp)
     47 {
     48 	size_t i;
     49 	int off;
     50 	char relative;
     51 
     52 	/* the maximum valid codepoint is 0x10FFFF */
     53 	if (len > 6) {
     54 		fprintf(stderr, "hextocp: '%.*s' is too long.\n", (int)len,
     55 		        str);
     56 		return 1;
     57 	}
     58 
     59 	for (i = 0, *cp = 0; i < len; i++) {
     60 		if (str[i] >= '0' && str[i] <= '9') {
     61 			relative = '0';
     62 			off = 0;
     63 		} else if (str[i] >= 'a' && str[i] <= 'f') {
     64 			relative = 'a';
     65 			off = 10;
     66 		} else if (str[i] >= 'A' && str[i] <= 'F') {
     67 			relative = 'A';
     68 			off = 10;
     69 		} else {
     70 			fprintf(stderr, "hextocp: '%.*s' is not hexadecimal.\n",
     71 			        (int)len, str);
     72 			return 1;
     73 		}
     74 
     75 		*cp += ((uint_least32_t)1 << (4 * (len - i - 1))) *
     76 		       (uint_least32_t)(str[i] - relative + off);
     77 	}
     78 
     79 	if (*cp > UINT32_C(0x10FFFF)) {
     80 		fprintf(stderr, "hextocp: '%.*s' is too large.\n", (int)len,
     81 		        str);
     82 		return 1;
     83 	}
     84 
     85 	return 0;
     86 }
     87 
     88 int
     89 parse_cp_list(const char *str, uint_least32_t **cp, size_t *cplen)
     90 {
     91 	size_t count, i;
     92 	const char *tmp1 = NULL, *tmp2 = NULL;
     93 
     94 	if (strlen(str) == 0) {
     95 		*cp = NULL;
     96 		*cplen = 0;
     97 		return 0;
     98 	}
     99 
    100 	/* count the number of spaces in the string and infer list length */
    101 	for (count = 1, tmp1 = str; (tmp2 = strchr(tmp1, ' ')) != NULL;
    102 	     count++, tmp1 = tmp2 + 1) {
    103 		;
    104 	}
    105 
    106 	/* allocate resources */
    107 	if (!(*cp = calloc((*cplen = count), sizeof(**cp)))) {
    108 		fprintf(stderr, "calloc: %s\n", strerror(errno));
    109 		exit(1);
    110 	}
    111 
    112 	/* go through the string again, parsing the numbers */
    113 	for (i = 0, tmp1 = tmp2 = str; tmp2 != NULL; i++) {
    114 		tmp2 = strchr(tmp1, ' ');
    115 		if (hextocp(tmp1, tmp2 ? (size_t)(tmp2 - tmp1) : strlen(tmp1),
    116 		            &((*cp)[i]))) {
    117 			return 1;
    118 		}
    119 		if (tmp2 != NULL) {
    120 			tmp1 = tmp2 + 1;
    121 		}
    122 	}
    123 
    124 	return 0;
    125 }
    126 
    127 static int
    128 range_parse(const char *str, struct range *range)
    129 {
    130 	char *p;
    131 
    132 	if ((p = strstr(str, "..")) == NULL) {
    133 		/* input has the form "XXXXXX" */
    134 		if (hextocp(str, strlen(str), &range->lower)) {
    135 			return 1;
    136 		}
    137 		range->upper = range->lower;
    138 	} else {
    139 		/* input has the form "XXXXXX..XXXXXX" */
    140 		if (hextocp(str, (size_t)(p - str), &range->lower) ||
    141 		    hextocp(p + 2, strlen(p + 2), &range->upper)) {
    142 			return 1;
    143 		}
    144 	}
    145 
    146 	return 0;
    147 }
    148 
    149 static bool
    150 get_line(char **buf, size_t *bufsize, FILE *fp, size_t *len)
    151 {
    152 	int ret = EOF;
    153 
    154 	for (*len = 0;; (*len)++) {
    155 		if (*len > 0 && *buf != NULL && (*buf)[*len - 1] == '\n') {
    156 			/*
    157 			 * if the previously read character was a newline,
    158 			 * we fake an end-of-file so we NUL-terminate and
    159 			 * are done.
    160 			 */
    161 			ret = EOF;
    162 		} else {
    163 			ret = fgetc(fp);
    164 		}
    165 
    166 		if (*len >= *bufsize) {
    167 			/* the buffer needs to be expanded */
    168 			*bufsize += 512;
    169 			if ((*buf = realloc(*buf, *bufsize)) == NULL) {
    170 				fprintf(stderr, "get_line: Out of memory.\n");
    171 				exit(1);
    172 			}
    173 		}
    174 
    175 		if (ret != EOF) {
    176 			(*buf)[*len] = (char)ret;
    177 		} else {
    178 			(*buf)[*len] = '\0';
    179 			break;
    180 		}
    181 	}
    182 
    183 	return *len == 0 && (feof(fp) || ferror(fp));
    184 }
    185 
    186 void
    187 parse_file_with_callback(const char *fname,
    188                          int (*callback)(const char *, char **, size_t, char *,
    189                                          void *),
    190                          void *payload)
    191 {
    192 	FILE *fp;
    193 	char *line = NULL, **field = NULL, *comment;
    194 	size_t linebufsize = 0, i, fieldbufsize = 0, j, nfields, len;
    195 
    196 	/* open file */
    197 	if (!(fp = fopen(fname, "r"))) {
    198 		fprintf(stderr, "parse_file_with_callback: fopen '%s': %s.\n",
    199 		        fname, strerror(errno));
    200 		exit(1);
    201 	}
    202 
    203 	while (!get_line(&line, &linebufsize, fp, &len)) {
    204 		/* remove trailing newline */
    205 		if (len > 0 && line[len - 1] == '\n') {
    206 			line[len - 1] = '\0';
    207 			len--;
    208 		}
    209 
    210 		/* skip empty lines and comment lines */
    211 		if (len == 0 || line[0] == '#') {
    212 			continue;
    213 		}
    214 
    215 		/* tokenize line into fields */
    216 		for (i = 0, nfields = 0, comment = NULL; i < (size_t)len; i++) {
    217 			/* skip leading whitespace */
    218 			while (line[i] == ' ') {
    219 				i++;
    220 			}
    221 
    222 			/* check if we crashed into the comment */
    223 			if (line[i] != '#') {
    224 				/* extend field buffer, if necessary */
    225 				if (++nfields > fieldbufsize) {
    226 					if ((field = realloc(
    227 						     field,
    228 						     nfields *
    229 							     sizeof(*field))) ==
    230 					    NULL) {
    231 						fprintf(stderr,
    232 						        "parse_file_with_"
    233 						        "callback: realloc: "
    234 						        "%s.\n",
    235 						        strerror(errno));
    236 						exit(1);
    237 					}
    238 					fieldbufsize = nfields;
    239 				}
    240 
    241 				/* set current position as field start */
    242 				field[nfields - 1] = &line[i];
    243 
    244 				/* continue until we reach ';' or '#' or end */
    245 				while (line[i] != ';' && line[i] != '#' &&
    246 				       line[i] != '\0') {
    247 					i++;
    248 				}
    249 			}
    250 
    251 			if (line[i] == '#') {
    252 				/* set comment-variable for later */
    253 				comment = &line[i + 1];
    254 			}
    255 
    256 			/* go back whitespace and terminate field there */
    257 			if (i > 0) {
    258 				for (j = i - 1; line[j] == ' '; j--) {
    259 					;
    260 				}
    261 				line[j + 1] = '\0';
    262 			} else {
    263 				line[i] = '\0';
    264 			}
    265 
    266 			/* if comment is set, we are done */
    267 			if (comment != NULL) {
    268 				break;
    269 			}
    270 		}
    271 
    272 		/* skip leading whitespace in comment */
    273 		while (comment != NULL && comment[0] == ' ') {
    274 			comment++;
    275 		}
    276 
    277 		/* call callback function */
    278 		if (callback(fname, field, nfields, comment, payload)) {
    279 			fprintf(stderr, "parse_file_with_callback: "
    280 			                "Malformed input.\n");
    281 			exit(1);
    282 		}
    283 	}
    284 
    285 	free(line);
    286 	free(field);
    287 }
    288 
    289 static int
    290 properties_callback(const char *file, char **field, size_t nfields,
    291                     char *comment, void *payload)
    292 {
    293 	/* prop always has the length 0x110000 */
    294 	struct properties_payload *p = (struct properties_payload *)payload;
    295 	struct range r;
    296 	uint_least8_t i;
    297 	uint_least32_t cp;
    298 
    299 	(void)comment;
    300 
    301 	if (nfields < 2) {
    302 		return 1;
    303 	}
    304 
    305 	for (i = 0; i < p->speclen; i++) {
    306 		/* identify fitting file and identifier */
    307 		if (p->spec[i].file && !strcmp(p->spec[i].file, file) &&
    308 		    (!strcmp(p->spec[i].ucdname, field[1]) ||
    309 		     (comment != NULL &&
    310 		      !strncmp(p->spec[i].ucdname, comment,
    311 		               strlen(p->spec[i].ucdname)) &&
    312 		      comment[strlen(p->spec[i].ucdname)] == ' '))) {
    313 			/* parse range in first field */
    314 			if (range_parse(field[0], &r)) {
    315 				return 1;
    316 			}
    317 
    318 			/* apply to all codepoints in the range */
    319 			for (cp = r.lower; cp <= r.upper; cp++) {
    320 				if (p->set_value(payload, cp, i)) {
    321 					exit(1);
    322 				}
    323 			}
    324 			break;
    325 		}
    326 	}
    327 
    328 	return 0;
    329 }
    330 
    331 void
    332 properties_compress(const struct properties *prop,
    333                     struct properties_compressed *comp)
    334 {
    335 	uint_least32_t cp, i;
    336 
    337 	/* initialization */
    338 	if (!(comp->offset = malloc((size_t)UINT32_C(0x110000) *
    339 	                            sizeof(*(comp->offset))))) {
    340 		fprintf(stderr, "malloc: %s\n", strerror(errno));
    341 		exit(1);
    342 	}
    343 	comp->data = NULL;
    344 	comp->datalen = 0;
    345 
    346 	for (cp = 0; cp < UINT32_C(0x110000); cp++) {
    347 		for (i = 0; i < comp->datalen; i++) {
    348 			if (!memcmp(&(prop[cp]), &(comp->data[i]),
    349 			            sizeof(*prop))) {
    350 				/* found a match! */
    351 				comp->offset[cp] = i;
    352 				break;
    353 			}
    354 		}
    355 		if (i == comp->datalen) {
    356 			/*
    357 			 * found no matching properties-struct, so
    358 			 * add current properties to data and add the
    359 			 * offset in the offset-table
    360 			 */
    361 			if (!(comp->data = reallocate_array(
    362 				      comp->data, ++(comp->datalen),
    363 				      sizeof(*(comp->data))))) {
    364 				fprintf(stderr, "reallocate_array: %s\n",
    365 				        strerror(errno));
    366 				exit(1);
    367 			}
    368 			memcpy(&(comp->data[comp->datalen - 1]), &(prop[cp]),
    369 			       sizeof(*prop));
    370 			comp->offset[cp] = comp->datalen - 1;
    371 		}
    372 	}
    373 }
    374 
    375 double
    376 properties_get_major_minor(const struct properties_compressed *comp,
    377                            struct properties_major_minor *mm)
    378 {
    379 	size_t i, j, compression_count = 0;
    380 
    381 	/*
    382 	 * we currently have an array comp->offset which maps the
    383 	 * codepoints 0..0x110000 to offsets into comp->data.
    384 	 * To improve cache-locality instead and allow a bit of
    385 	 * compressing, instead of directly mapping a codepoint
    386 	 * 0xAAAABB with comp->offset, we generate two arrays major
    387 	 * and minor such that
    388 	 *    comp->offset(0xAAAABB) == minor[major[0xAAAA] + 0xBB]
    389 	 * This yields a major-array of length 2^16 and a minor array
    390 	 * of variable length depending on how many common subsequences
    391 	 * can be filtered out.
    392 	 */
    393 
    394 	/* initialize */
    395 	if (!(mm->major = malloc((size_t)0x1100 * sizeof(*(mm->major))))) {
    396 		fprintf(stderr, "malloc: %s\n", strerror(errno));
    397 		exit(1);
    398 	}
    399 	mm->minor = NULL;
    400 	mm->minorlen = 0;
    401 
    402 	for (i = 0; i < (size_t)0x1100; i++) {
    403 		/*
    404 		 * we now look at the cp-range (i << 8)..(i << 8 + 0xFF)
    405 		 * and check if its corresponding offset-data already
    406 		 * exists in minor (because then we just point there
    407 		 * and need less storage)
    408 		 */
    409 		for (j = 0; j + 0xFF < mm->minorlen; j++) {
    410 			if (!memcmp(&(comp->offset[i << 8]), &(mm->minor[j]),
    411 			            sizeof(*(comp->offset)) * 0x100)) {
    412 				break;
    413 			}
    414 		}
    415 		if (j + 0xFF < mm->minorlen) {
    416 			/* found an index */
    417 			compression_count++;
    418 			mm->major[i] = j;
    419 		} else {
    420 			/*
    421 			 * add "new" sequence to minor and point to it
    422 			 * in major
    423 			 */
    424 			mm->minorlen += 0x100;
    425 			if (!(mm->minor =
    426 			              reallocate_array(mm->minor, mm->minorlen,
    427 			                               sizeof(*(mm->minor))))) {
    428 				fprintf(stderr, "reallocate_array: %s\n",
    429 				        strerror(errno));
    430 				exit(1);
    431 			}
    432 			memcpy(&(mm->minor[mm->minorlen - 0x100]),
    433 			       &(comp->offset[i << 8]),
    434 			       sizeof(*(mm->minor)) * 0x100);
    435 			mm->major[i] = mm->minorlen - 0x100;
    436 		}
    437 	}
    438 
    439 	/* return compression ratio */
    440 	return (double)compression_count / 0x1100 * 100;
    441 }
    442 
    443 void
    444 properties_print_lookup_table(const char *name, const size_t *data,
    445                               size_t datalen)
    446 {
    447 	const char *type;
    448 	size_t i, maxval;
    449 
    450 	for (i = 0, maxval = 0; i < datalen; i++) {
    451 		if (data[i] > maxval) {
    452 			maxval = data[i];
    453 		}
    454 	}
    455 
    456 	type = (maxval <= UINT_LEAST8_MAX)  ? "uint_least8_t" :
    457 	       (maxval <= UINT_LEAST16_MAX) ? "uint_least16_t" :
    458 	       (maxval <= UINT_LEAST32_MAX) ? "uint_least32_t" :
    459 	                                      "uint_least64_t";
    460 
    461 	printf("static const %s %s[] = {\n\t", type, name);
    462 	for (i = 0; i < datalen; i++) {
    463 		printf("%zu", data[i]);
    464 		if (i + 1 == datalen) {
    465 			printf("\n");
    466 		} else if ((i + 1) % 8 != 0) {
    467 			printf(", ");
    468 		} else {
    469 			printf(",\n\t");
    470 		}
    471 	}
    472 	printf("};\n");
    473 }
    474 
    475 void
    476 properties_print_derived_lookup_table(
    477 	char *name, size_t *offset, size_t offsetlen,
    478 	int_least64_t (*get_value)(const struct properties *, size_t),
    479 	const void *payload)
    480 {
    481 	const char *type;
    482 	size_t i;
    483 	int_least64_t minval, maxval;
    484 
    485 	for (i = 0, minval = INT_LEAST64_MAX, maxval = INT_LEAST64_MIN;
    486 	     i < offsetlen; i++) {
    487 		if (get_value(payload, offset[i]) > maxval) {
    488 			maxval = get_value(payload, offset[i]);
    489 		} else if (get_value(payload, offset[i]) < minval) {
    490 			minval = get_value(payload, offset[i]);
    491 		}
    492 	}
    493 
    494 	if (minval < 0) {
    495 		/* we need a signed type */
    496 		type = (minval >= INT_LEAST8_MIN && maxval <= INT_LEAST8_MAX) ?
    497 		               "int_least8_t" :
    498 		       (minval >= INT_LEAST16_MIN &&
    499 		        maxval <= INT_LEAST16_MAX) ?
    500 		               "int_least16_t" :
    501 		       (minval >= INT_LEAST32_MIN &&
    502 		        maxval <= INT_LEAST32_MAX) ?
    503 		               "int_least32_t" :
    504 		               "int_least64_t";
    505 	} else {
    506 		/* we are fine with an unsigned type */
    507 		type = (maxval <= UINT_LEAST8_MAX)  ? "uint_least8_t" :
    508 		       (maxval <= UINT_LEAST16_MAX) ? "uint_least16_t" :
    509 		       (maxval <= UINT_LEAST32_MAX) ? "uint_least32_t" :
    510 		                                      "uint_least64_t";
    511 	}
    512 
    513 	printf("static const %s %s[] = {\n\t", type, name);
    514 	for (i = 0; i < offsetlen; i++) {
    515 		printf("%" PRIiLEAST64, get_value(payload, offset[i]));
    516 		if (i + 1 == offsetlen) {
    517 			printf("\n");
    518 		} else if ((i + 1) % 8 != 0) {
    519 			printf(", ");
    520 		} else {
    521 			printf(",\n\t");
    522 		}
    523 	}
    524 	printf("};\n");
    525 }
    526 
    527 static void
    528 properties_print_enum(const struct property_spec *spec, size_t speclen,
    529                       const char *enumname, const char *enumprefix)
    530 {
    531 	size_t i;
    532 
    533 	printf("enum %s {\n", enumname);
    534 	for (i = 0; i < speclen; i++) {
    535 		printf("\t%s_%s,\n", enumprefix, spec[i].enumname);
    536 	}
    537 	printf("\tNUM_%sS,\n};\n\n", enumprefix);
    538 }
    539 
    540 static int
    541 set_value_bp(struct properties_payload *payload, uint_least32_t cp,
    542              int_least64_t value)
    543 {
    544 	if (payload->prop[cp].property != payload->speclen) {
    545 		if (payload->handle_conflict == NULL) {
    546 			fprintf(stderr,
    547 			        "set_value_bp: "
    548 			        "Unhandled character break property "
    549 			        "overwrite for 0x%06X (%s <- %s).\n",
    550 			        cp,
    551 			        payload->spec[payload->prop[cp].property]
    552 			                .enumname,
    553 			        payload->spec[value].enumname);
    554 			return 1;
    555 		} else {
    556 			value = payload->handle_conflict(
    557 				cp, (uint_least8_t)payload->prop[cp].property,
    558 				(uint_least8_t)value);
    559 		}
    560 	}
    561 	payload->prop[cp].property = value;
    562 
    563 	return 0;
    564 }
    565 
    566 static int_least64_t
    567 get_value_bp(const struct properties *prop, size_t offset)
    568 {
    569 	return prop[offset].property;
    570 }
    571 
    572 void
    573 properties_generate_break_property(
    574 	const struct property_spec *spec, uint_least8_t speclen,
    575 	uint_least8_t (*fill_missing)(uint_least32_t),
    576 	uint_least8_t (*handle_conflict)(uint_least32_t, uint_least8_t,
    577                                          uint_least8_t),
    578 	void (*post_process)(struct properties *), const char *prefix,
    579 	const char *argv0)
    580 {
    581 	struct properties_compressed comp;
    582 	struct properties_major_minor mm;
    583 	struct properties_payload payload;
    584 	struct properties *prop;
    585 	size_t i, j, prefixlen = strlen(prefix);
    586 	char buf1[64], prefix_uc[64], buf2[64], buf3[64], buf4[64];
    587 
    588 	/*
    589 	 * allocate property buffer for all 0x110000 codepoints and
    590 	 * initialize its entries to the known invalid value "speclen"
    591 	 */
    592 	if (!(prop = calloc(UINT32_C(0x110000), sizeof(*prop)))) {
    593 		fprintf(stderr, "calloc: %s\n", strerror(errno));
    594 		exit(1);
    595 	}
    596 	for (i = 0; i < UINT32_C(0x110000); i++) {
    597 		prop[i].property = speclen;
    598 	}
    599 
    600 	/* generate data */
    601 	payload.prop = prop;
    602 	payload.spec = spec;
    603 	payload.speclen = speclen;
    604 	payload.set_value = set_value_bp;
    605 	payload.handle_conflict = handle_conflict;
    606 
    607 	/* parse each file exactly once and ignore NULL-fields */
    608 	for (i = 0; i < speclen; i++) {
    609 		for (j = 0; j < i; j++) {
    610 			if (spec[i].file && spec[j].file &&
    611 			    !strcmp(spec[i].file, spec[j].file)) {
    612 				/* file has already been parsed */
    613 				break;
    614 			}
    615 		}
    616 		if (i == j && spec[i].file) {
    617 			/* file has not been processed yet */
    618 			parse_file_with_callback(spec[i].file,
    619 			                         properties_callback, &payload);
    620 		}
    621 	}
    622 
    623 	/* fill in the missing properties that weren't explicitly given */
    624 	for (i = 0; i < UINT32_C(0x110000); i++) {
    625 		if (payload.prop[i].property == speclen) {
    626 			if (fill_missing != NULL) {
    627 				payload.prop[i].property =
    628 					fill_missing((uint_least32_t)i);
    629 			} else {
    630 				payload.prop[i].property = 0;
    631 			}
    632 		}
    633 	}
    634 
    635 	/* post-processing */
    636 	if (post_process != NULL) {
    637 		post_process(payload.prop);
    638 	}
    639 
    640 	/* compress data */
    641 	printf("/* Automatically generated by %s */\n#include <stdint.h>\n\n",
    642 	       argv0);
    643 	properties_compress(prop, &comp);
    644 
    645 	fprintf(stderr, "%s: %s-LUT compression-ratio: %.2f%%\n", argv0, prefix,
    646 	        properties_get_major_minor(&comp, &mm));
    647 
    648 	/* prepare names */
    649 	if ((size_t)snprintf(buf1, LEN(buf1), "%s_property", prefix) >=
    650 	    LEN(buf1)) {
    651 		fprintf(stderr, "snprintf: String truncated.\n");
    652 		exit(1);
    653 	}
    654 	if (LEN(prefix_uc) + 1 < prefixlen) {
    655 		fprintf(stderr, "snprintf: Buffer too small.\n");
    656 		exit(1);
    657 	}
    658 	for (i = 0; i < prefixlen; i++) {
    659 		prefix_uc[i] = (char)toupper(prefix[i]);
    660 	}
    661 	prefix_uc[prefixlen] = '\0';
    662 	if ((size_t)snprintf(buf2, LEN(buf2), "%s_PROP", prefix_uc) >=
    663 	            LEN(buf2) ||
    664 	    (size_t)snprintf(buf3, LEN(buf3), "%s_major", prefix) >=
    665 	            LEN(buf3) ||
    666 	    (size_t)snprintf(buf4, LEN(buf4), "%s_minor", prefix) >=
    667 	            LEN(buf4)) {
    668 		fprintf(stderr, "snprintf: String truncated.\n");
    669 		exit(1);
    670 	}
    671 
    672 	/* print data */
    673 	properties_print_enum(spec, speclen, buf1, buf2);
    674 	properties_print_lookup_table(buf3, mm.major, 0x1100);
    675 	printf("\n");
    676 	properties_print_derived_lookup_table(buf4, mm.minor, mm.minorlen,
    677 	                                      get_value_bp, comp.data);
    678 
    679 	/* free data */
    680 	free(prop);
    681 	free(comp.data);
    682 	free(comp.offset);
    683 	free(mm.major);
    684 	free(mm.minor);
    685 }
    686 
    687 static int
    688 break_test_callback(const char *fname, char **field, size_t nfields,
    689                     char *comment, void *payload)
    690 {
    691 	struct break_test *t,
    692 		**test = ((struct break_test_payload *)payload)->test;
    693 	size_t i, *testlen = ((struct break_test_payload *)payload)->testlen,
    694 		  commentlen;
    695 	char *token;
    696 
    697 	(void)fname;
    698 
    699 	if (nfields < 1) {
    700 		return 1;
    701 	}
    702 
    703 	/* append new testcase and initialize with zeroes */
    704 	if ((*test = realloc(*test, ++(*testlen) * sizeof(**test))) == NULL) {
    705 		fprintf(stderr, "break_test_callback: realloc: %s.\n",
    706 		        strerror(errno));
    707 		return 1;
    708 	}
    709 	t = &(*test)[*testlen - 1];
    710 	memset(t, 0, sizeof(*t));
    711 
    712 	/* parse testcase "<÷|×> <cp> <÷|×> ... <cp> <÷|×>" */
    713 	for (token = strtok(field[0], " "), i = 0; token != NULL;
    714 	     i++, token = strtok(NULL, " ")) {
    715 		if (i % 2 == 0) {
    716 			/* delimiter or start of sequence */
    717 			if (i == 0 ||
    718 			    !strncmp(token, "\xC3\xB7", 2)) { /* UTF-8 */
    719 				/*
    720 				 * '÷' indicates a breakpoint,
    721 				 * the current length is done; allocate
    722 				 * a new length field and set it to 0
    723 				 */
    724 				if ((t->len = realloc(
    725 					     t->len,
    726 					     ++t->lenlen * sizeof(*t->len))) ==
    727 				    NULL) {
    728 					fprintf(stderr,
    729 					        "break_test_"
    730 					        "callback: realloc: %s.\n",
    731 					        strerror(errno));
    732 					return 1;
    733 				}
    734 				t->len[t->lenlen - 1] = 0;
    735 			} else if (!strncmp(token, "\xC3\x97", 2)) { /* UTF-8 */
    736 				/* '×' indicates a non-breakpoint, do nothing */
    737 			} else {
    738 				fprintf(stderr,
    739 				        "break_test_callback: "
    740 				        "Malformed delimiter '%s'.\n",
    741 				        token);
    742 				return 1;
    743 			}
    744 		} else {
    745 			/* add codepoint to cp-array */
    746 			if ((t->cp = realloc(t->cp,
    747 			                     ++t->cplen * sizeof(*t->cp))) ==
    748 			    NULL) {
    749 				fprintf(stderr,
    750 				        "break_test_callback: "
    751 				        "realloc: %s.\n",
    752 				        strerror(errno));
    753 				return 1;
    754 			}
    755 			if (hextocp(token, strlen(token),
    756 			            &t->cp[t->cplen - 1])) {
    757 				return 1;
    758 			}
    759 			if (t->lenlen > 0) {
    760 				t->len[t->lenlen - 1]++;
    761 			}
    762 		}
    763 	}
    764 	if (t->lenlen > 0 && t->len[t->lenlen - 1] == 0) {
    765 		/*
    766 		 * we allocated one more length than we needed because
    767 		 * the breakpoint was at the end
    768 		 */
    769 		t->lenlen--;
    770 	}
    771 
    772 	/* store comment */
    773 	if (comment != NULL) {
    774 		commentlen = strlen(comment) + 1;
    775 		if (((*test)[*testlen - 1].descr = malloc(commentlen)) ==
    776 		    NULL) {
    777 			fprintf(stderr, "break_test_callback: malloc: %s.\n",
    778 			        strerror(errno));
    779 			return 1;
    780 		}
    781 		memcpy((*test)[*testlen - 1].descr, comment, commentlen);
    782 	}
    783 
    784 	return 0;
    785 }
    786 
    787 void
    788 break_test_list_parse(char *fname, struct break_test **test, size_t *testlen)
    789 {
    790 	struct break_test_payload pl = {
    791 		.test = test,
    792 		.testlen = testlen,
    793 	};
    794 	*test = NULL;
    795 	*testlen = 0;
    796 
    797 	parse_file_with_callback(fname, break_test_callback, &pl);
    798 }
    799 
    800 void
    801 break_test_list_print(const struct break_test *test, size_t testlen,
    802                       const char *identifier, const char *progname)
    803 {
    804 	size_t i, j;
    805 
    806 	printf("/* Automatically generated by %s */\n"
    807 	       "#include <stdint.h>\n#include <stddef.h>\n\n"
    808 	       "#include \"../gen/types.h\"\n\n",
    809 	       progname);
    810 
    811 	printf("static const struct break_test %s[] = {\n", identifier);
    812 	for (i = 0; i < testlen; i++) {
    813 		printf("\t{\n");
    814 
    815 		printf("\t\t.cp     = (uint_least32_t[]){");
    816 		for (j = 0; j < test[i].cplen; j++) {
    817 			printf(" UINT32_C(0x%06X)", test[i].cp[j]);
    818 			if (j + 1 < test[i].cplen) {
    819 				putchar(',');
    820 			}
    821 		}
    822 		printf(" },\n");
    823 		printf("\t\t.cplen  = %zu,\n", test[i].cplen);
    824 
    825 		printf("\t\t.len    = (size_t[]){");
    826 		for (j = 0; j < test[i].lenlen; j++) {
    827 			printf(" %zu", test[i].len[j]);
    828 			if (j + 1 < test[i].lenlen) {
    829 				putchar(',');
    830 			}
    831 		}
    832 		printf(" },\n");
    833 		printf("\t\t.lenlen = %zu,\n", test[i].lenlen);
    834 
    835 		printf("\t\t.descr  = \"%s\",\n", test[i].descr);
    836 
    837 		printf("\t},\n");
    838 	}
    839 	printf("};\n");
    840 }
    841 
    842 void
    843 break_test_list_free(struct break_test *test, size_t testlen)
    844 {
    845 	size_t i;
    846 
    847 	for (i = 0; i < testlen; i++) {
    848 		free(test[i].cp);
    849 		free(test[i].len);
    850 		free(test[i].descr);
    851 	}
    852 
    853 	free(test);
    854 }