1 /*
2  * Copyright (c) 1993-1994 by Xerox Corporation.  All rights reserved.
3  *
4  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
5  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
6  *
7  * Permission is hereby granted to use or copy this program
8  * for any purpose,  provided the above notices are retained on all copies.
9  * Permission to modify the code and to distribute modified code is granted,
10  * provided the above notices are retained, and a notice that the code was
11  * modified is included with the above copyright notice.
12  */
13 
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17 #ifndef CORD_BUILD
18 # define CORD_BUILD
19 #endif
20 
21 # include "gc.h"
22 # include "cord.h"
23 # include <stdlib.h>
24 # include <stdio.h>
25 # include <string.h>
26 
27 /* An implementation of the cord primitives.  These are the only        */
28 /* Functions that understand the representation.  We perform only       */
29 /* minimal checks on arguments to these functions.  Out of bounds       */
30 /* arguments to the iteration functions may result in client functions  */
31 /* invoked on garbage data.  In most cases, client functions should be  */
32 /* programmed defensively enough that this does not result in memory    */
33 /* smashes.                                                             */
34 
35 typedef void (* oom_fn)(void);
36 
37 oom_fn CORD_oom_fn = (oom_fn) 0;
38 
39 # define OUT_OF_MEMORY {  if (CORD_oom_fn != (oom_fn) 0) (*CORD_oom_fn)(); \
40                           ABORT("Out of memory"); }
41 # define ABORT(msg) { fprintf(stderr, "%s\n", msg); abort(); }
42 
43 typedef unsigned long word;
44 
45 typedef union {
46     struct Concatenation {
47         char null;
48         char header;
49         char depth;     /* concatenation nesting depth. */
50         unsigned char left_len;
51                         /* Length of left child if it is sufficiently   */
52                         /* short; 0 otherwise.                          */
53 #           define MAX_LEFT_LEN 255
54         word len;
55         CORD left;      /* length(left) > 0     */
56         CORD right;     /* length(right) > 0    */
57     } concatenation;
58     struct Function {
59         char null;
60         char header;
61         char depth;     /* always 0     */
62         char left_len;  /* always 0     */
63         word len;
64         CORD_fn fn;
65         void * client_data;
66     } function;
67     struct Generic {
68         char null;
69         char header;
70         char depth;
71         char left_len;
72         word len;
73     } generic;
74     char string[1];
75 } CordRep;
76 
77 # define CONCAT_HDR 1
78 
79 # define FN_HDR 4
80 # define SUBSTR_HDR 6
81         /* Substring nodes are a special case of function nodes.        */
82         /* The client_data field is known to point to a substr_args     */
83         /* structure, and the function is either CORD_apply_access_fn   */
84         /* or CORD_index_access_fn.                                     */
85 
86 /* The following may be applied only to function and concatenation nodes: */
87 #define IS_CONCATENATION(s)  (((CordRep *)s)->generic.header == CONCAT_HDR)
88 
89 #define IS_FUNCTION(s)  ((((CordRep *)s)->generic.header & FN_HDR) != 0)
90 
91 #define IS_SUBSTR(s) (((CordRep *)s)->generic.header == SUBSTR_HDR)
92 
93 #define LEN(s) (((CordRep *)s) -> generic.len)
94 #define DEPTH(s) (((CordRep *)s) -> generic.depth)
95 #define GEN_LEN(s) (CORD_IS_STRING(s) ? strlen(s) : LEN(s))
96 
97 #define LEFT_LEN(c) ((c) -> left_len != 0? \
98                                 (c) -> left_len \
99                                 : (CORD_IS_STRING((c) -> left) ? \
100                                         (c) -> len - GEN_LEN((c) -> right) \
101                                         : LEN((c) -> left)))
102 
103 #define SHORT_LIMIT (sizeof(CordRep) - 1)
104         /* Cords shorter than this are C strings */
105 
106 
107 /* Dump the internal representation of x to stdout, with initial        */
108 /* indentation level n.                                                 */
CORD_dump_inner(CORD x,unsigned n)109 void CORD_dump_inner(CORD x, unsigned n)
110 {
111     register size_t i;
112 
113     for (i = 0; i < (size_t)n; i++) {
114         fputs("  ", stdout);
115     }
116     if (x == 0) {
117         fputs("NIL\n", stdout);
118     } else if (CORD_IS_STRING(x)) {
119         for (i = 0; i <= SHORT_LIMIT; i++) {
120             if (x[i] == '\0') break;
121             putchar(x[i]);
122         }
123         if (x[i] != '\0') fputs("...", stdout);
124         putchar('\n');
125     } else if (IS_CONCATENATION(x)) {
126         register struct Concatenation * conc =
127                                 &(((CordRep *)x) -> concatenation);
128         printf("Concatenation: %p (len: %d, depth: %d)\n",
129                x, (int)(conc -> len), (int)(conc -> depth));
130         CORD_dump_inner(conc -> left, n+1);
131         CORD_dump_inner(conc -> right, n+1);
132     } else /* function */{
133         register struct Function * func =
134                                 &(((CordRep *)x) -> function);
135         if (IS_SUBSTR(x)) printf("(Substring) ");
136         printf("Function: %p (len: %d): ", x, (int)(func -> len));
137         for (i = 0; i < 20 && i < func -> len; i++) {
138             putchar((*(func -> fn))(i, func -> client_data));
139         }
140         if (i < func -> len) fputs("...", stdout);
141         putchar('\n');
142     }
143 }
144 
145 /* Dump the internal representation of x to stdout      */
CORD_dump(CORD x)146 void CORD_dump(CORD x)
147 {
148     CORD_dump_inner(x, 0);
149     fflush(stdout);
150 }
151 
CORD_cat_char_star(CORD x,const char * y,size_t leny)152 CORD CORD_cat_char_star(CORD x, const char * y, size_t leny)
153 {
154     register size_t result_len;
155     register size_t lenx;
156     register int depth;
157 
158     if (x == CORD_EMPTY) return(y);
159     if (leny == 0) return(x);
160     if (CORD_IS_STRING(x)) {
161         lenx = strlen(x);
162         result_len = lenx + leny;
163         if (result_len <= SHORT_LIMIT) {
164             register char * result = GC_MALLOC_ATOMIC(result_len+1);
165 
166             if (result == 0) OUT_OF_MEMORY;
167             memcpy(result, x, lenx);
168             memcpy(result + lenx, y, leny);
169             result[result_len] = '\0';
170             return((CORD) result);
171         } else {
172             depth = 1;
173         }
174     } else {
175         register CORD right;
176         register CORD left;
177         register char * new_right;
178         register size_t right_len;
179 
180         lenx = LEN(x);
181 
182         if (leny <= SHORT_LIMIT/2
183             && IS_CONCATENATION(x)
184             && CORD_IS_STRING(right = ((CordRep *)x) -> concatenation.right)) {
185             /* Merge y into right part of x. */
186             if (!CORD_IS_STRING(left = ((CordRep *)x) -> concatenation.left)) {
187                 right_len = lenx - LEN(left);
188             } else if (((CordRep *)x) -> concatenation.left_len != 0) {
189                 right_len = lenx - ((CordRep *)x) -> concatenation.left_len;
190             } else {
191                 right_len = strlen(right);
192             }
193             result_len = right_len + leny;  /* length of new_right */
194             if (result_len <= SHORT_LIMIT) {
195                 new_right = GC_MALLOC_ATOMIC(result_len + 1);
196                 if (new_right == 0) OUT_OF_MEMORY;
197                 memcpy(new_right, right, right_len);
198                 memcpy(new_right + right_len, y, leny);
199                 new_right[result_len] = '\0';
200                 y = new_right;
201                 leny = result_len;
202                 x = left;
203                 lenx -= right_len;
204                 /* Now fall through to concatenate the two pieces: */
205             }
206             if (CORD_IS_STRING(x)) {
207                 depth = 1;
208             } else {
209                 depth = DEPTH(x) + 1;
210             }
211         } else {
212             depth = DEPTH(x) + 1;
213         }
214         result_len = lenx + leny;
215     }
216     {
217       /* The general case; lenx, result_len is known: */
218         register struct Concatenation * result;
219 
220         result = GC_NEW(struct Concatenation);
221         if (result == 0) OUT_OF_MEMORY;
222         result->header = CONCAT_HDR;
223         result->depth = depth;
224         if (lenx <= MAX_LEFT_LEN)
225             result->left_len = (unsigned char)lenx;
226         result->len = result_len;
227         result->left = x;
228         result->right = y;
229         if (depth >= MAX_DEPTH) {
230             return(CORD_balance((CORD)result));
231         } else {
232             return((CORD) result);
233         }
234     }
235 }
236 
237 
CORD_cat(CORD x,CORD y)238 CORD CORD_cat(CORD x, CORD y)
239 {
240     register size_t result_len;
241     register int depth;
242     register size_t lenx;
243 
244     if (x == CORD_EMPTY) return(y);
245     if (y == CORD_EMPTY) return(x);
246     if (CORD_IS_STRING(y)) {
247         return(CORD_cat_char_star(x, y, strlen(y)));
248     } else if (CORD_IS_STRING(x)) {
249         lenx = strlen(x);
250         depth = DEPTH(y) + 1;
251     } else {
252         register int depthy = DEPTH(y);
253 
254         lenx = LEN(x);
255         depth = DEPTH(x) + 1;
256         if (depthy >= depth) depth = depthy + 1;
257     }
258     result_len = lenx + LEN(y);
259     {
260         register struct Concatenation * result;
261 
262         result = GC_NEW(struct Concatenation);
263         if (result == 0) OUT_OF_MEMORY;
264         result->header = CONCAT_HDR;
265         result->depth = depth;
266         if (lenx <= MAX_LEFT_LEN)
267             result->left_len = (unsigned char)lenx;
268         result->len = result_len;
269         result->left = x;
270         result->right = y;
271         if (depth >= MAX_DEPTH) {
272             return(CORD_balance((CORD)result));
273         } else {
274             return((CORD) result);
275         }
276     }
277 }
278 
279 
280 
CORD_from_fn(CORD_fn fn,void * client_data,size_t len)281 CORD CORD_from_fn(CORD_fn fn, void * client_data, size_t len)
282 {
283     if (len <= 0) return(0);
284     if (len <= SHORT_LIMIT) {
285         register char * result;
286         register size_t i;
287         char buf[SHORT_LIMIT+1];
288         register char c;
289 
290         for (i = 0; i < len; i++) {
291             c = (*fn)(i, client_data);
292             if (c == '\0') goto gen_case;
293             buf[i] = c;
294         }
295 
296         result = GC_MALLOC_ATOMIC(len+1);
297         if (result == 0) OUT_OF_MEMORY;
298         memcpy(result, buf, len);
299         result[len] = '\0';
300         return((CORD) result);
301     }
302   gen_case:
303     {
304         register struct Function * result;
305 
306         result = GC_NEW(struct Function);
307         if (result == 0) OUT_OF_MEMORY;
308         result->header = FN_HDR;
309         /* depth is already 0 */
310         result->len = len;
311         result->fn = fn;
312         result->client_data = client_data;
313         return((CORD) result);
314     }
315 }
316 
CORD_len(CORD x)317 size_t CORD_len(CORD x)
318 {
319     if (x == 0) {
320         return(0);
321     } else {
322         return(GEN_LEN(x));
323     }
324 }
325 
326 struct substr_args {
327     CordRep * sa_cord;
328     size_t sa_index;
329 };
330 
CORD_index_access_fn(size_t i,void * client_data)331 char CORD_index_access_fn(size_t i, void * client_data)
332 {
333     register struct substr_args *descr = (struct substr_args *)client_data;
334 
335     return(((char *)(descr->sa_cord))[i + descr->sa_index]);
336 }
337 
CORD_apply_access_fn(size_t i,void * client_data)338 char CORD_apply_access_fn(size_t i, void * client_data)
339 {
340     register struct substr_args *descr = (struct substr_args *)client_data;
341     register struct Function * fn_cord = &(descr->sa_cord->function);
342 
343     return((*(fn_cord->fn))(i + descr->sa_index, fn_cord->client_data));
344 }
345 
346 /* A version of CORD_substr that simply returns a function node, thus   */
347 /* postponing its work. The fourth argument is a function that may      */
348 /* be used for efficient access to the ith character.                   */
349 /* Assumes i >= 0 and i + n < length(x).                                */
CORD_substr_closure(CORD x,size_t i,size_t n,CORD_fn f)350 CORD CORD_substr_closure(CORD x, size_t i, size_t n, CORD_fn f)
351 {
352     register struct substr_args * sa = GC_NEW(struct substr_args);
353     CORD result;
354 
355     if (sa == 0) OUT_OF_MEMORY;
356     sa->sa_cord = (CordRep *)x;
357     sa->sa_index = i;
358     result = CORD_from_fn(f, (void *)sa, n);
359     if (result == CORD_EMPTY) return CORD_EMPTY; /* n == 0 */
360     ((CordRep *)result) -> function.header = SUBSTR_HDR;
361     return (result);
362 }
363 
364 # define SUBSTR_LIMIT (10 * SHORT_LIMIT)
365         /* Substrings of function nodes and flat strings shorter than   */
366         /* this are flat strings.  Othewise we use a functional         */
367         /* representation, which is significantly slower to access.     */
368 
369 /* A version of CORD_substr that assumes i >= 0, n > 0, and i + n < length(x).*/
CORD_substr_checked(CORD x,size_t i,size_t n)370 CORD CORD_substr_checked(CORD x, size_t i, size_t n)
371 {
372     if (CORD_IS_STRING(x)) {
373         if (n > SUBSTR_LIMIT) {
374             return(CORD_substr_closure(x, i, n, CORD_index_access_fn));
375         } else {
376             register char * result = GC_MALLOC_ATOMIC(n+1);
377 
378             if (result == 0) OUT_OF_MEMORY;
379             strncpy(result, x+i, n);
380             result[n] = '\0';
381             return(result);
382         }
383     } else if (IS_CONCATENATION(x)) {
384         register struct Concatenation * conc
385                         = &(((CordRep *)x) -> concatenation);
386         register size_t left_len;
387         register size_t right_len;
388 
389         left_len = LEFT_LEN(conc);
390         right_len = conc -> len - left_len;
391         if (i >= left_len) {
392             if (n == right_len) return(conc -> right);
393             return(CORD_substr_checked(conc -> right, i - left_len, n));
394         } else if (i+n <= left_len) {
395             if (n == left_len) return(conc -> left);
396             return(CORD_substr_checked(conc -> left, i, n));
397         } else {
398             /* Need at least one character from each side. */
399             register CORD left_part;
400             register CORD right_part;
401             register size_t left_part_len = left_len - i;
402 
403             if (i == 0) {
404                 left_part = conc -> left;
405             } else {
406                 left_part = CORD_substr_checked(conc -> left, i, left_part_len);
407             }
408             if (i + n == right_len + left_len) {
409                  right_part = conc -> right;
410             } else {
411                  right_part = CORD_substr_checked(conc -> right, 0,
412                                                   n - left_part_len);
413             }
414             return(CORD_cat(left_part, right_part));
415         }
416     } else /* function */ {
417         if (n > SUBSTR_LIMIT) {
418             if (IS_SUBSTR(x)) {
419                 /* Avoid nesting substring nodes.       */
420                 register struct Function * f = &(((CordRep *)x) -> function);
421                 register struct substr_args *descr =
422                                 (struct substr_args *)(f -> client_data);
423 
424                 return(CORD_substr_closure((CORD)descr->sa_cord,
425                                            i + descr->sa_index,
426                                            n, f -> fn));
427             } else {
428                 return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
429             }
430         } else {
431             char * result;
432             register struct Function * f = &(((CordRep *)x) -> function);
433             char buf[SUBSTR_LIMIT+1];
434             register char * p = buf;
435             register char c;
436             register int j;
437             register int lim = i + n;
438 
439             for (j = i; j < lim; j++) {
440                 c = (*(f -> fn))(j, f -> client_data);
441                 if (c == '\0') {
442                     return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
443                 }
444                 *p++ = c;
445             }
446             result = GC_MALLOC_ATOMIC(n+1);
447             if (result == 0) OUT_OF_MEMORY;
448             memcpy(result, buf, n);
449             result[n] = '\0';
450             return(result);
451         }
452     }
453 }
454 
CORD_substr(CORD x,size_t i,size_t n)455 CORD CORD_substr(CORD x, size_t i, size_t n)
456 {
457     register size_t len = CORD_len(x);
458 
459     if (i >= len || n <= 0) return(0);
460         /* n < 0 is impossible in a correct C implementation, but       */
461         /* quite possible  under SunOS 4.X.                             */
462     if (i + n > len) n = len - i;
463     return(CORD_substr_checked(x, i, n));
464 }
465 
466 /* See cord.h for definition.  We assume i is in range. */
CORD_iter5(CORD x,size_t i,CORD_iter_fn f1,CORD_batched_iter_fn f2,void * client_data)467 int CORD_iter5(CORD x, size_t i, CORD_iter_fn f1,
468                          CORD_batched_iter_fn f2, void * client_data)
469 {
470     if (x == 0) return(0);
471     if (CORD_IS_STRING(x)) {
472         register const char *p = x+i;
473 
474         if (*p == '\0') ABORT("2nd arg to CORD_iter5 too big");
475         if (f2 != CORD_NO_FN) {
476             return((*f2)(p, client_data));
477         } else {
478             while (*p) {
479                 if ((*f1)(*p, client_data)) return(1);
480                 p++;
481             }
482             return(0);
483         }
484     } else if (IS_CONCATENATION(x)) {
485         register struct Concatenation * conc
486                         = &(((CordRep *)x) -> concatenation);
487 
488 
489         if (i > 0) {
490             register size_t left_len = LEFT_LEN(conc);
491 
492             if (i >= left_len) {
493                 return(CORD_iter5(conc -> right, i - left_len, f1, f2,
494                                   client_data));
495             }
496         }
497         if (CORD_iter5(conc -> left, i, f1, f2, client_data)) {
498             return(1);
499         }
500         return(CORD_iter5(conc -> right, 0, f1, f2, client_data));
501     } else /* function */ {
502         register struct Function * f = &(((CordRep *)x) -> function);
503         register size_t j;
504         register size_t lim = f -> len;
505 
506         for (j = i; j < lim; j++) {
507             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
508                 return(1);
509             }
510         }
511         return(0);
512     }
513 }
514 
515 #undef CORD_iter
CORD_iter(CORD x,CORD_iter_fn f1,void * client_data)516 int CORD_iter(CORD x, CORD_iter_fn f1, void * client_data)
517 {
518     return(CORD_iter5(x, 0, f1, CORD_NO_FN, client_data));
519 }
520 
CORD_riter4(CORD x,size_t i,CORD_iter_fn f1,void * client_data)521 int CORD_riter4(CORD x, size_t i, CORD_iter_fn f1, void * client_data)
522 {
523     if (x == 0) return(0);
524     if (CORD_IS_STRING(x)) {
525         register const char *p = x + i;
526         register char c;
527 
528         for(;;) {
529             c = *p;
530             if (c == '\0') ABORT("2nd arg to CORD_riter4 too big");
531             if ((*f1)(c, client_data)) return(1);
532             if (p == x) break;
533             p--;
534         }
535         return(0);
536     } else if (IS_CONCATENATION(x)) {
537         register struct Concatenation * conc
538                         = &(((CordRep *)x) -> concatenation);
539         register CORD left_part = conc -> left;
540         register size_t left_len;
541 
542         left_len = LEFT_LEN(conc);
543         if (i >= left_len) {
544             if (CORD_riter4(conc -> right, i - left_len, f1, client_data)) {
545                 return(1);
546             }
547             return(CORD_riter4(left_part, left_len - 1, f1, client_data));
548         } else {
549             return(CORD_riter4(left_part, i, f1, client_data));
550         }
551     } else /* function */ {
552         register struct Function * f = &(((CordRep *)x) -> function);
553         register size_t j;
554 
555         for (j = i; ; j--) {
556             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
557                 return(1);
558             }
559             if (j == 0) return(0);
560         }
561     }
562 }
563 
CORD_riter(CORD x,CORD_iter_fn f1,void * client_data)564 int CORD_riter(CORD x, CORD_iter_fn f1, void * client_data)
565 {
566     size_t len = CORD_len(x);
567     if (len == 0) return(0);
568     return(CORD_riter4(x, len - 1, f1, client_data));
569 }
570 
571 /*
572  * The following functions are concerned with balancing cords.
573  * Strategy:
574  * Scan the cord from left to right, keeping the cord scanned so far
575  * as a forest of balanced trees of exponentially decreasing length.
576  * When a new subtree needs to be added to the forest, we concatenate all
577  * shorter ones to the new tree in the appropriate order, and then insert
578  * the result into the forest.
579  * Crucial invariants:
580  * 1. The concatenation of the forest (in decreasing order) with the
581  *     unscanned part of the rope is equal to the rope being balanced.
582  * 2. All trees in the forest are balanced.
583  * 3. forest[i] has depth at most i.
584  */
585 
586 typedef struct {
587     CORD c;
588     size_t len;         /* Actual length of c   */
589 } ForestElement;
590 
591 static size_t min_len [ MAX_DEPTH ];
592 
593 static int min_len_init = 0;
594 
595 int CORD_max_len;
596 
597 typedef ForestElement Forest [ MAX_DEPTH ];
598                         /* forest[i].len >= fib(i+1)            */
599                         /* The string is the concatenation      */
600                         /* of the forest in order of DECREASING */
601                         /* indices.                             */
602 
CORD_init_min_len(void)603 void CORD_init_min_len(void)
604 {
605     register int i;
606     register size_t last, previous, current;
607 
608     min_len[0] = previous = 1;
609     min_len[1] = last = 2;
610     for (i = 2; i < MAX_DEPTH; i++) {
611         current = last + previous;
612         if (current < last) /* overflow */ current = last;
613         min_len[i] = current;
614         previous = last;
615         last = current;
616     }
617     CORD_max_len = last - 1;
618     min_len_init = 1;
619 }
620 
621 
CORD_init_forest(ForestElement * forest,size_t max_len)622 void CORD_init_forest(ForestElement * forest, size_t max_len)
623 {
624     register int i;
625 
626     for (i = 0; i < MAX_DEPTH; i++) {
627         forest[i].c = 0;
628         if (min_len[i] > max_len) return;
629     }
630     ABORT("Cord too long");
631 }
632 
633 /* Add a leaf to the appropriate level in the forest, cleaning          */
634 /* out lower levels as necessary.                                       */
635 /* Also works if x is a balanced tree of concatenations; however        */
636 /* in this case an extra concatenation node may be inserted above x;    */
637 /* This node should not be counted in the statement of the invariants.  */
CORD_add_forest(ForestElement * forest,CORD x,size_t len)638 void CORD_add_forest(ForestElement * forest, CORD x, size_t len)
639 {
640     register int i = 0;
641     register CORD sum = CORD_EMPTY;
642     register size_t sum_len = 0;
643 
644     while (len > min_len[i + 1]) {
645         if (forest[i].c != 0) {
646             sum = CORD_cat(forest[i].c, sum);
647             sum_len += forest[i].len;
648             forest[i].c = 0;
649         }
650         i++;
651     }
652     /* Sum has depth at most 1 greter than what would be required       */
653     /* for balance.                                                     */
654     sum = CORD_cat(sum, x);
655     sum_len += len;
656     /* If x was a leaf, then sum is now balanced.  To see this          */
657     /* consider the two cases in which forest[i-1] either is or is      */
658     /* not empty.                                                       */
659     while (sum_len >= min_len[i]) {
660         if (forest[i].c != 0) {
661             sum = CORD_cat(forest[i].c, sum);
662             sum_len += forest[i].len;
663             /* This is again balanced, since sum was balanced, and has  */
664             /* allowable depth that differs from i by at most 1.        */
665             forest[i].c = 0;
666         }
667         i++;
668     }
669     i--;
670     forest[i].c = sum;
671     forest[i].len = sum_len;
672 }
673 
CORD_concat_forest(ForestElement * forest,size_t expected_len)674 CORD CORD_concat_forest(ForestElement * forest, size_t expected_len)
675 {
676     register int i = 0;
677     CORD sum = 0;
678     size_t sum_len = 0;
679 
680     while (sum_len != expected_len) {
681         if (forest[i].c != 0) {
682             sum = CORD_cat(forest[i].c, sum);
683             sum_len += forest[i].len;
684         }
685         i++;
686     }
687     return(sum);
688 }
689 
690 /* Insert the frontier of x into forest.  Balanced subtrees are */
691 /* treated as leaves.  This potentially adds one to the depth   */
692 /* of the final tree.                                           */
CORD_balance_insert(CORD x,size_t len,ForestElement * forest)693 void CORD_balance_insert(CORD x, size_t len, ForestElement * forest)
694 {
695     register int depth;
696 
697     if (CORD_IS_STRING(x)) {
698         CORD_add_forest(forest, x, len);
699     } else if (IS_CONCATENATION(x)
700                && ((depth = DEPTH(x)) >= MAX_DEPTH
701                    || len < min_len[depth])) {
702         register struct Concatenation * conc
703                         = &(((CordRep *)x) -> concatenation);
704         size_t left_len = LEFT_LEN(conc);
705 
706         CORD_balance_insert(conc -> left, left_len, forest);
707         CORD_balance_insert(conc -> right, len - left_len, forest);
708     } else /* function or balanced */ {
709         CORD_add_forest(forest, x, len);
710     }
711 }
712 
713 
CORD_balance(CORD x)714 CORD CORD_balance(CORD x)
715 {
716     Forest forest;
717     register size_t len;
718 
719     if (x == 0) return(0);
720     if (CORD_IS_STRING(x)) return(x);
721     if (!min_len_init) CORD_init_min_len();
722     len = LEN(x);
723     CORD_init_forest(forest, len);
724     CORD_balance_insert(x, len, forest);
725     return(CORD_concat_forest(forest, len));
726 }
727 
728 
729 /* Position primitives  */
730 
731 /* Private routines to deal with the hard cases only: */
732 
733 /* P contains a prefix of the  path to cur_pos. Extend it to a full     */
734 /* path and set up leaf info.                                           */
735 /* Return 0 if past the end of cord, 1 o.w.                             */
CORD__extend_path(register CORD_pos p)736 void CORD__extend_path(register CORD_pos p)
737 {
738      register struct CORD_pe * current_pe = &(p[0].path[p[0].path_len]);
739      register CORD top = current_pe -> pe_cord;
740      register size_t pos = p[0].cur_pos;
741      register size_t top_pos = current_pe -> pe_start_pos;
742      register size_t top_len = GEN_LEN(top);
743 
744      /* Fill in the rest of the path. */
745        while(!CORD_IS_STRING(top) && IS_CONCATENATION(top)) {
746          register struct Concatenation * conc =
747                         &(((CordRep *)top) -> concatenation);
748          register size_t left_len;
749 
750          left_len = LEFT_LEN(conc);
751          current_pe++;
752          if (pos >= top_pos + left_len) {
753              current_pe -> pe_cord = top = conc -> right;
754              current_pe -> pe_start_pos = top_pos = top_pos + left_len;
755              top_len -= left_len;
756          } else {
757              current_pe -> pe_cord = top = conc -> left;
758              current_pe -> pe_start_pos = top_pos;
759              top_len = left_len;
760          }
761          p[0].path_len++;
762        }
763      /* Fill in leaf description for fast access. */
764        if (CORD_IS_STRING(top)) {
765          p[0].cur_leaf = top;
766          p[0].cur_start = top_pos;
767          p[0].cur_end = top_pos + top_len;
768        } else {
769          p[0].cur_end = 0;
770        }
771        if (pos >= top_pos + top_len) p[0].path_len = CORD_POS_INVALID;
772 }
773 
CORD__pos_fetch(register CORD_pos p)774 char CORD__pos_fetch(register CORD_pos p)
775 {
776     /* Leaf is a function node */
777     struct CORD_pe * pe = &((p)[0].path[(p)[0].path_len]);
778     CORD leaf = pe -> pe_cord;
779     register struct Function * f = &(((CordRep *)leaf) -> function);
780 
781     if (!IS_FUNCTION(leaf)) ABORT("CORD_pos_fetch: bad leaf");
782     return ((*(f -> fn))(p[0].cur_pos - pe -> pe_start_pos, f -> client_data));
783 }
784 
CORD__next(register CORD_pos p)785 void CORD__next(register CORD_pos p)
786 {
787     register size_t cur_pos = p[0].cur_pos + 1;
788     register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
789     register CORD leaf = current_pe -> pe_cord;
790 
791     /* Leaf is not a string or we're at end of leaf */
792     p[0].cur_pos = cur_pos;
793     if (!CORD_IS_STRING(leaf)) {
794         /* Function leaf        */
795         register struct Function * f = &(((CordRep *)leaf) -> function);
796         register size_t start_pos = current_pe -> pe_start_pos;
797         register size_t end_pos = start_pos + f -> len;
798 
799         if (cur_pos < end_pos) {
800           /* Fill cache and return. */
801             register size_t i;
802             register size_t limit = cur_pos + FUNCTION_BUF_SZ;
803             register CORD_fn fn = f -> fn;
804             register void * client_data = f -> client_data;
805 
806             if (limit > end_pos) {
807                 limit = end_pos;
808             }
809             for (i = cur_pos; i < limit; i++) {
810                 p[0].function_buf[i - cur_pos] =
811                         (*fn)(i - start_pos, client_data);
812             }
813             p[0].cur_start = cur_pos;
814             p[0].cur_leaf = p[0].function_buf;
815             p[0].cur_end = limit;
816             return;
817         }
818     }
819     /* End of leaf      */
820     /* Pop the stack until we find two concatenation nodes with the     */
821     /* same start position: this implies we were in left part.          */
822     {
823         while (p[0].path_len > 0
824                && current_pe[0].pe_start_pos != current_pe[-1].pe_start_pos) {
825             p[0].path_len--;
826             current_pe--;
827         }
828         if (p[0].path_len == 0) {
829             p[0].path_len = CORD_POS_INVALID;
830             return;
831         }
832     }
833     p[0].path_len--;
834     CORD__extend_path(p);
835 }
836 
CORD__prev(register CORD_pos p)837 void CORD__prev(register CORD_pos p)
838 {
839     register struct CORD_pe * pe = &(p[0].path[p[0].path_len]);
840 
841     if (p[0].cur_pos == 0) {
842         p[0].path_len = CORD_POS_INVALID;
843         return;
844     }
845     p[0].cur_pos--;
846     if (p[0].cur_pos >= pe -> pe_start_pos) return;
847 
848     /* Beginning of leaf        */
849 
850     /* Pop the stack until we find two concatenation nodes with the     */
851     /* different start position: this implies we were in right part.    */
852     {
853         register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
854 
855         while (p[0].path_len > 0
856                && current_pe[0].pe_start_pos == current_pe[-1].pe_start_pos) {
857             p[0].path_len--;
858             current_pe--;
859         }
860     }
861     p[0].path_len--;
862     CORD__extend_path(p);
863 }
864 
865 #undef CORD_pos_fetch
866 #undef CORD_next
867 #undef CORD_prev
868 #undef CORD_pos_to_index
869 #undef CORD_pos_to_cord
870 #undef CORD_pos_valid
871 
CORD_pos_fetch(register CORD_pos p)872 char CORD_pos_fetch(register CORD_pos p)
873 {
874     if (p[0].cur_start <= p[0].cur_pos && p[0].cur_pos < p[0].cur_end) {
875         return(p[0].cur_leaf[p[0].cur_pos - p[0].cur_start]);
876     } else {
877         return(CORD__pos_fetch(p));
878     }
879 }
880 
CORD_next(CORD_pos p)881 void CORD_next(CORD_pos p)
882 {
883     if (p[0].cur_pos < p[0].cur_end - 1) {
884         p[0].cur_pos++;
885     } else {
886         CORD__next(p);
887     }
888 }
889 
CORD_prev(CORD_pos p)890 void CORD_prev(CORD_pos p)
891 {
892     if (p[0].cur_end != 0 && p[0].cur_pos > p[0].cur_start) {
893         p[0].cur_pos--;
894     } else {
895         CORD__prev(p);
896     }
897 }
898 
CORD_pos_to_index(CORD_pos p)899 size_t CORD_pos_to_index(CORD_pos p)
900 {
901     return(p[0].cur_pos);
902 }
903 
CORD_pos_to_cord(CORD_pos p)904 CORD CORD_pos_to_cord(CORD_pos p)
905 {
906     return(p[0].path[0].pe_cord);
907 }
908 
CORD_pos_valid(CORD_pos p)909 int CORD_pos_valid(CORD_pos p)
910 {
911     return(p[0].path_len != CORD_POS_INVALID);
912 }
913 
CORD_set_pos(CORD_pos p,CORD x,size_t i)914 void CORD_set_pos(CORD_pos p, CORD x, size_t i)
915 {
916     if (x == CORD_EMPTY) {
917         p[0].path_len = CORD_POS_INVALID;
918         return;
919     }
920     p[0].path[0].pe_cord = x;
921     p[0].path[0].pe_start_pos = 0;
922     p[0].path_len = 0;
923     p[0].cur_pos = i;
924     CORD__extend_path(p);
925 }
926