Back to index

lightning-sunbird  0.9+nobinonly
cordbscs.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 1993-1994 by Xerox Corporation.  All rights reserved.
00003  *
00004  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
00005  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
00006  *
00007  * Permission is hereby granted to use or copy this program
00008  * for any purpose,  provided the above notices are retained on all copies.
00009  * Permission to modify the code and to distribute modified code is granted,
00010  * provided the above notices are retained, and a notice that the code was
00011  * modified is included with the above copyright notice.
00012  *
00013  * Author: Hans-J. Boehm (boehm@parc.xerox.com)
00014  */
00015 /* Boehm, October 3, 1994 5:19 pm PDT */
00016 # include "gc.h"
00017 # include "cord.h"
00018 # include <stdlib.h>
00019 # include <stdio.h>
00020 # include <string.h>
00021 
00022 /* An implementation of the cord primitives.  These are the only      */
00023 /* Functions that understand the representation.  We perform only     */
00024 /* minimal checks on arguments to these functions.  Out of bounds     */
00025 /* arguments to the iteration functions may result in client functions       */
00026 /* invoked on garbage data.  In most cases, client functions should be       */
00027 /* programmed defensively enough that this does not result in memory  */
00028 /* smashes.                                                    */ 
00029 
00030 typedef void (* oom_fn)(void);
00031 
00032 oom_fn CORD_oom_fn = (oom_fn) 0;
00033 
00034 # define OUT_OF_MEMORY {  if (CORD_oom_fn != (oom_fn) 0) (*CORD_oom_fn)(); \
00035                        ABORT("Out of memory\n"); }
00036 # define ABORT(msg) { fprintf(stderr, "%s\n", msg); abort(); }
00037 
00038 typedef unsigned long word;
00039 
00040 typedef union {
00041     struct Concatenation {
00042        char null;
00043        char header;
00044        char depth;   /* concatenation nesting depth. */
00045        unsigned char left_len;
00046                      /* Length of left child if it is sufficiently    */
00047                      /* short; 0 otherwise.                           */
00048 #          define MAX_LEFT_LEN 255
00049        word len;
00050        CORD left;    /* length(left) > 0  */
00051        CORD right;   /* length(right) > 0 */
00052     } concatenation;
00053     struct Function {
00054        char null;
00055        char header;
00056        char depth;   /* always 0   */
00057        char left_len;       /* always 0   */
00058        word len;
00059        CORD_fn fn;
00060        void * client_data;
00061     } function;
00062     struct Generic {
00063        char null;
00064        char header;
00065        char depth;
00066        char left_len;
00067        word len;
00068     } generic;
00069     char string[1];
00070 } CordRep;
00071 
00072 # define CONCAT_HDR 1
00073        
00074 # define FN_HDR 4
00075 # define SUBSTR_HDR 6
00076        /* Substring nodes are a special case of function nodes.       */
00077        /* The client_data field is known to point to a substr_args    */
00078        /* structure, and the function is either CORD_apply_access_fn  */
00079        /* or CORD_index_access_fn.                             */
00080 
00081 /* The following may be applied only to function and concatenation nodes: */
00082 #define IS_CONCATENATION(s)  (((CordRep *)s)->generic.header == CONCAT_HDR)
00083 
00084 #define IS_FUNCTION(s)  ((((CordRep *)s)->generic.header & FN_HDR) != 0)
00085 
00086 #define IS_SUBSTR(s) (((CordRep *)s)->generic.header == SUBSTR_HDR)
00087 
00088 #define LEN(s) (((CordRep *)s) -> generic.len)
00089 #define DEPTH(s) (((CordRep *)s) -> generic.depth)
00090 #define GEN_LEN(s) (CORD_IS_STRING(s) ? strlen(s) : LEN(s))
00091 
00092 #define LEFT_LEN(c) ((c) -> left_len != 0? \
00093                             (c) -> left_len \
00094                             : (CORD_IS_STRING((c) -> left) ? \
00095                                    (c) -> len - GEN_LEN((c) -> right) \
00096                                    : LEN((c) -> left)))
00097 
00098 #define SHORT_LIMIT (sizeof(CordRep) - 1)
00099        /* Cords shorter than this are C strings */
00100 
00101 
00102 /* Dump the internal representation of x to stdout, with initial      */
00103 /* indentation level n.                                               */
00104 void CORD_dump_inner(CORD x, unsigned n)
00105 {
00106     register size_t i;
00107     
00108     for (i = 0; i < (size_t)n; i++) {
00109         fputs("  ", stdout);
00110     }
00111     if (x == 0) {
00112        fputs("NIL\n", stdout);
00113     } else if (CORD_IS_STRING(x)) {
00114         for (i = 0; i <= SHORT_LIMIT; i++) {
00115             if (x[i] == '\0') break;
00116             putchar(x[i]);
00117         }
00118         if (x[i] != '\0') fputs("...", stdout);
00119         putchar('\n');
00120     } else if (IS_CONCATENATION(x)) {
00121         register struct Concatenation * conc =
00122                             &(((CordRep *)x) -> concatenation);
00123         printf("Concatenation: %p (len: %d, depth: %d)\n",
00124                x, (int)(conc -> len), (int)(conc -> depth));
00125         CORD_dump_inner(conc -> left, n+1);
00126         CORD_dump_inner(conc -> right, n+1);
00127     } else /* function */{
00128         register struct Function * func =
00129                             &(((CordRep *)x) -> function);
00130         if (IS_SUBSTR(x)) printf("(Substring) ");
00131         printf("Function: %p (len: %d): ", x, (int)(func -> len));
00132         for (i = 0; i < 20 && i < func -> len; i++) {
00133             putchar((*(func -> fn))(i, func -> client_data));
00134         }
00135         if (i < func -> len) fputs("...", stdout);
00136         putchar('\n');
00137     }
00138 }
00139 
00140 /* Dump the internal representation of x to stdout      */
00141 void CORD_dump(CORD x)
00142 {
00143     CORD_dump_inner(x, 0);
00144     fflush(stdout);
00145 }
00146 
00147 CORD CORD_cat_char_star(CORD x, const char * y, size_t leny)
00148 {
00149     register size_t result_len;
00150     register size_t lenx;
00151     register int depth;
00152     
00153     if (x == CORD_EMPTY) return(y);
00154     if (leny == 0) return(x);
00155     if (CORD_IS_STRING(x)) {
00156         lenx = strlen(x);
00157         result_len = lenx + leny;
00158         if (result_len <= SHORT_LIMIT) {
00159             register char * result = GC_MALLOC_ATOMIC(result_len+1);
00160         
00161             if (result == 0) OUT_OF_MEMORY;
00162             memcpy(result, x, lenx);
00163             memcpy(result + lenx, y, leny);
00164             result[result_len] = '\0';
00165             return((CORD) result);
00166         } else {
00167             depth = 1;
00168         }
00169     } else {
00170        register CORD right;
00171        register CORD left;
00172        register char * new_right;
00173        register size_t right_len;
00174        
00175        lenx = LEN(x);
00176        
00177         if (leny <= SHORT_LIMIT/2
00178            && IS_CONCATENATION(x)
00179             && CORD_IS_STRING(right = ((CordRep *)x) -> concatenation.right)) {
00180             /* Merge y into right part of x. */
00181             if (!CORD_IS_STRING(left = ((CordRep *)x) -> concatenation.left)) {
00182               right_len = lenx - LEN(left);
00183             } else if (((CordRep *)x) -> concatenation.left_len != 0) {
00184                 right_len = lenx - ((CordRep *)x) -> concatenation.left_len;
00185             } else {
00186               right_len = strlen(right);
00187             }
00188             result_len = right_len + leny;  /* length of new_right */
00189             if (result_len <= SHORT_LIMIT) {
00190               new_right = GC_MALLOC_ATOMIC(result_len + 1);
00191               memcpy(new_right, right, right_len);
00192               memcpy(new_right + right_len, y, leny);
00193               new_right[result_len] = '\0';
00194               y = new_right;
00195               leny = result_len;
00196               x = left;
00197               lenx -= right_len;
00198               /* Now fall through to concatenate the two pieces: */
00199             }
00200             if (CORD_IS_STRING(x)) {
00201                 depth = 1;
00202             } else {
00203                 depth = DEPTH(x) + 1;
00204             }
00205         } else {
00206             depth = DEPTH(x) + 1;
00207         }
00208         result_len = lenx + leny;
00209     }
00210     {
00211       /* The general case; lenx, result_len is known: */
00212        register struct Concatenation * result;
00213        
00214        result = GC_NEW(struct Concatenation);
00215        if (result == 0) OUT_OF_MEMORY;
00216        result->header = CONCAT_HDR;
00217        result->depth = depth;
00218        if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
00219        result->len = result_len;
00220        result->left = x;
00221        result->right = y;
00222        if (depth > MAX_DEPTH) {
00223            return(CORD_balance((CORD)result));
00224        } else {
00225            return((CORD) result);
00226        }
00227     }
00228 }
00229 
00230 
00231 CORD CORD_cat(CORD x, CORD y)
00232 {
00233     register size_t result_len;
00234     register int depth;
00235     register size_t lenx;
00236     
00237     if (x == CORD_EMPTY) return(y);
00238     if (y == CORD_EMPTY) return(x);
00239     if (CORD_IS_STRING(y)) {
00240         return(CORD_cat_char_star(x, y, strlen(y)));
00241     } else if (CORD_IS_STRING(x)) {
00242         lenx = strlen(x);
00243         depth = DEPTH(y) + 1;
00244     } else {
00245         register int depthy = DEPTH(y);
00246         
00247         lenx = LEN(x);
00248         depth = DEPTH(x) + 1;
00249         if (depthy >= depth) depth = depthy + 1;
00250     }
00251     result_len = lenx + LEN(y);
00252     {
00253        register struct Concatenation * result;
00254        
00255        result = GC_NEW(struct Concatenation);
00256        if (result == 0) OUT_OF_MEMORY;
00257        result->header = CONCAT_HDR;
00258        result->depth = depth;
00259        if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
00260        result->len = result_len;
00261        result->left = x;
00262        result->right = y;
00263        return((CORD) result);
00264     }
00265 }
00266 
00267 
00268 
00269 CORD CORD_from_fn(CORD_fn fn, void * client_data, size_t len)
00270 {
00271     if (len <= 0) return(0);
00272     if (len <= SHORT_LIMIT) {
00273         register char * result;
00274         register size_t i;
00275         char buf[SHORT_LIMIT+1];
00276         register char c;
00277         
00278         for (i = 0; i < len; i++) {
00279             c = (*fn)(i, client_data);
00280             if (c == '\0') goto gen_case;
00281             buf[i] = c;
00282         }
00283         buf[i] = '\0';
00284         result = GC_MALLOC_ATOMIC(len+1);
00285         if (result == 0) OUT_OF_MEMORY;
00286         strcpy(result, buf);
00287         result[len] = '\0';
00288         return((CORD) result);
00289     }
00290   gen_case:
00291     {
00292        register struct Function * result;
00293        
00294        result = GC_NEW(struct Function);
00295        if (result == 0) OUT_OF_MEMORY;
00296        result->header = FN_HDR;
00297        /* depth is already 0 */
00298        result->len = len;
00299        result->fn = fn;
00300        result->client_data = client_data;
00301        return((CORD) result);
00302     }
00303 }
00304 
00305 size_t CORD_len(CORD x)
00306 {
00307     if (x == 0) {
00308        return(0);
00309     } else {
00310        return(GEN_LEN(x));
00311     }
00312 }
00313 
00314 struct substr_args {
00315     CordRep * sa_cord;
00316     size_t sa_index;
00317 };
00318 
00319 char CORD_index_access_fn(size_t i, void * client_data)
00320 {
00321     register struct substr_args *descr = (struct substr_args *)client_data;
00322     
00323     return(((char *)(descr->sa_cord))[i + descr->sa_index]);
00324 }
00325 
00326 char CORD_apply_access_fn(size_t i, void * client_data)
00327 {
00328     register struct substr_args *descr = (struct substr_args *)client_data;
00329     register struct Function * fn_cord = &(descr->sa_cord->function);
00330     
00331     return((*(fn_cord->fn))(i + descr->sa_index, fn_cord->client_data));
00332 }
00333 
00334 /* A version of CORD_substr that simply returns a function node, thus */
00335 /* postponing its work.     The fourth argument is a function that may       */
00336 /* be used for efficient access to the ith character.                 */
00337 /* Assumes i >= 0 and i + n < length(x).                       */
00338 CORD CORD_substr_closure(CORD x, size_t i, size_t n, CORD_fn f)
00339 {
00340     register struct substr_args * sa = GC_NEW(struct substr_args);
00341     CORD result;
00342     
00343     if (sa == 0) OUT_OF_MEMORY;
00344     sa->sa_cord = (CordRep *)x;
00345     sa->sa_index = i;
00346     result = CORD_from_fn(f, (void *)sa, n);
00347     ((CordRep *)result) -> function.header = SUBSTR_HDR;
00348     return (result);
00349 }
00350 
00351 # define SUBSTR_LIMIT (10 * SHORT_LIMIT)
00352        /* Substrings of function nodes and flat strings shorter than  */
00353        /* this are flat strings.  Othewise we use a functional        */
00354        /* representation, which is significantly slower to access.    */
00355 
00356 /* A version of CORD_substr that assumes i >= 0, n > 0, and i + n < length(x).*/
00357 CORD CORD_substr_checked(CORD x, size_t i, size_t n)
00358 {
00359     if (CORD_IS_STRING(x)) {
00360         if (n > SUBSTR_LIMIT) {
00361             return(CORD_substr_closure(x, i, n, CORD_index_access_fn));
00362         } else {
00363             register char * result = GC_MALLOC_ATOMIC(n+1);
00364             
00365             if (result == 0) OUT_OF_MEMORY;
00366             strncpy(result, x+i, n);
00367             result[n] = '\0';
00368             return(result);
00369         }
00370     } else if (IS_CONCATENATION(x)) {
00371        register struct Concatenation * conc
00372                      = &(((CordRep *)x) -> concatenation);
00373        register size_t left_len;
00374        register size_t right_len;
00375        
00376        left_len = LEFT_LEN(conc);
00377        right_len = conc -> len - left_len;
00378        if (i >= left_len) {
00379            if (n == right_len) return(conc -> right);
00380            return(CORD_substr_checked(conc -> right, i - left_len, n));
00381        } else if (i+n <= left_len) {
00382            if (n == left_len) return(conc -> left);
00383            return(CORD_substr_checked(conc -> left, i, n));
00384        } else {
00385            /* Need at least one character from each side. */
00386            register CORD left_part;
00387            register CORD right_part;
00388            register size_t left_part_len = left_len - i;
00389        
00390            if (i == 0) {
00391                left_part = conc -> left;
00392            } else {
00393                left_part = CORD_substr_checked(conc -> left, i, left_part_len);
00394            }
00395            if (i + n == right_len + left_len) {
00396                 right_part = conc -> right;
00397            } else {
00398                 right_part = CORD_substr_checked(conc -> right, 0,
00399                                              n - left_part_len);
00400            }
00401            return(CORD_cat(left_part, right_part));
00402        }
00403     } else /* function */ {
00404         if (n > SUBSTR_LIMIT) {
00405             if (IS_SUBSTR(x)) {
00406               /* Avoid nesting substring nodes.  */
00407               register struct Function * f = &(((CordRep *)x) -> function);
00408               register struct substr_args *descr =
00409                             (struct substr_args *)(f -> client_data);
00410               
00411               return(CORD_substr_closure((CORD)descr->sa_cord,
00412                                       i + descr->sa_index,
00413                                       n, f -> fn));
00414             } else {
00415                 return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
00416             }
00417         } else {
00418             char * result;
00419             register struct Function * f = &(((CordRep *)x) -> function);
00420             char buf[SUBSTR_LIMIT+1];
00421             register char * p = buf;
00422             register char c;
00423             register int j;
00424             register int lim = i + n;
00425             
00426             for (j = i; j < lim; j++) {
00427               c = (*(f -> fn))(j, f -> client_data);
00428               if (c == '\0') {
00429                   return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
00430               }
00431               *p++ = c;
00432             }
00433             *p = '\0';
00434             result = GC_MALLOC_ATOMIC(n+1);
00435             if (result == 0) OUT_OF_MEMORY;
00436             strcpy(result, buf);
00437             return(result);
00438         }
00439     }
00440 }
00441 
00442 CORD CORD_substr(CORD x, size_t i, size_t n)
00443 {
00444     register size_t len = CORD_len(x);
00445     
00446     if (i >= len || n <= 0) return(0);
00447        /* n < 0 is impossible in a correct C implementation, but      */
00448        /* quite possible  under SunOS 4.X.                            */
00449     if (i + n > len) n = len - i;
00450 #   ifndef __STDC__
00451       if (i < 0) ABORT("CORD_substr: second arg. negative");
00452        /* Possible only if both client and C implementation are buggy.       */
00453        /* But empirically this happens frequently.                    */
00454 #   endif
00455     return(CORD_substr_checked(x, i, n));
00456 }
00457 
00458 /* See cord.h for definition.  We assume i is in range. */
00459 int CORD_iter5(CORD x, size_t i, CORD_iter_fn f1,
00460                       CORD_batched_iter_fn f2, void * client_data)
00461 {
00462     if (x == 0) return(0);
00463     if (CORD_IS_STRING(x)) {
00464        register const char *p = x+i;
00465        
00466        if (*p == '\0') ABORT("2nd arg to CORD_iter5 too big");
00467         if (f2 != CORD_NO_FN) {
00468             return((*f2)(p, client_data));
00469         } else {
00470            while (*p) {
00471                 if ((*f1)(*p, client_data)) return(1);
00472                 p++;
00473            }
00474            return(0);
00475         }
00476     } else if (IS_CONCATENATION(x)) {
00477        register struct Concatenation * conc
00478                      = &(((CordRep *)x) -> concatenation);
00479        
00480        
00481        if (i > 0) {
00482            register size_t left_len = LEFT_LEN(conc);
00483            
00484            if (i >= left_len) {
00485                return(CORD_iter5(conc -> right, i - left_len, f1, f2,
00486                               client_data));
00487            }
00488        }
00489        if (CORD_iter5(conc -> left, i, f1, f2, client_data)) {
00490            return(1);
00491        }
00492        return(CORD_iter5(conc -> right, 0, f1, f2, client_data));
00493     } else /* function */ {
00494         register struct Function * f = &(((CordRep *)x) -> function);
00495         register size_t j;
00496         register size_t lim = f -> len;
00497         
00498         for (j = i; j < lim; j++) {
00499             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
00500                 return(1);
00501             }
00502         }
00503         return(0);
00504     }
00505 }
00506                      
00507 #undef CORD_iter
00508 int CORD_iter(CORD x, CORD_iter_fn f1, void * client_data)
00509 {
00510     return(CORD_iter5(x, 0, f1, CORD_NO_FN, client_data));
00511 }
00512 
00513 int CORD_riter4(CORD x, size_t i, CORD_iter_fn f1, void * client_data)
00514 {
00515     if (x == 0) return(0);
00516     if (CORD_IS_STRING(x)) {
00517        register const char *p = x + i;
00518        register char c;
00519                
00520        for(;;) {
00521            c = *p;
00522            if (c == '\0') ABORT("2nd arg to CORD_riter4 too big");
00523             if ((*f1)(c, client_data)) return(1);
00524            if (p == x) break;
00525             p--;
00526        }
00527        return(0);
00528     } else if (IS_CONCATENATION(x)) {
00529        register struct Concatenation * conc
00530                      = &(((CordRep *)x) -> concatenation);
00531        register CORD left_part = conc -> left;
00532        register size_t left_len;
00533        
00534        left_len = LEFT_LEN(conc);
00535        if (i >= left_len) {
00536            if (CORD_riter4(conc -> right, i - left_len, f1, client_data)) {
00537               return(1);
00538            }
00539            return(CORD_riter4(left_part, left_len - 1, f1, client_data));
00540        } else {
00541            return(CORD_riter4(left_part, i, f1, client_data));
00542        }
00543     } else /* function */ {
00544         register struct Function * f = &(((CordRep *)x) -> function);
00545         register size_t j;
00546         
00547         for (j = i; ; j--) {
00548             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
00549                 return(1);
00550             }
00551             if (j == 0) return(0);
00552         }
00553     }
00554 }
00555 
00556 int CORD_riter(CORD x, CORD_iter_fn f1, void * client_data)
00557 {
00558     return(CORD_riter4(x, CORD_len(x) - 1, f1, client_data));
00559 }
00560 
00561 /*
00562  * The following functions are concerned with balancing cords.
00563  * Strategy:
00564  * Scan the cord from left to right, keeping the cord scanned so far
00565  * as a forest of balanced trees of exponentialy decreasing length.
00566  * When a new subtree needs to be added to the forest, we concatenate all
00567  * shorter ones to the new tree in the appropriate order, and then insert
00568  * the result into the forest.
00569  * Crucial invariants:
00570  * 1. The concatenation of the forest (in decreasing order) with the
00571  *     unscanned part of the rope is equal to the rope being balanced.
00572  * 2. All trees in the forest are balanced.
00573  * 3. forest[i] has depth at most i.
00574  */
00575 
00576 typedef struct {
00577     CORD c;
00578     size_t len;             /* Actual length of c       */
00579 } ForestElement;
00580 
00581 static size_t min_len [ MAX_DEPTH ];
00582 
00583 static int min_len_init = 0;
00584 
00585 int CORD_max_len;
00586 
00587 typedef ForestElement Forest [ MAX_DEPTH ];
00588                      /* forest[i].len >= fib(i+1)               */
00589                      /* The string is the concatenation */
00590                      /* of the forest in order of DECREASING */
00591                      /* indices.                        */
00592 
00593 void CORD_init_min_len()
00594 {
00595     register int i;
00596     register size_t last, previous, current;
00597         
00598     min_len[0] = previous = 1;
00599     min_len[1] = last = 2;
00600     for (i = 2; i < MAX_DEPTH; i++) {
00601        current = last + previous;
00602        if (current < last) /* overflow */ current = last;
00603        min_len[i] = current;
00604        previous = last;
00605        last = current;
00606     }
00607     CORD_max_len = last - 1;
00608     min_len_init = 1;
00609 }
00610 
00611 
00612 void CORD_init_forest(ForestElement * forest, size_t max_len)
00613 {
00614     register int i;
00615     
00616     for (i = 0; i < MAX_DEPTH; i++) {
00617        forest[i].c = 0;
00618        if (min_len[i] > max_len) return;
00619     }
00620     ABORT("Cord too long");
00621 }
00622 
00623 /* Add a leaf to the appropriate level in the forest, cleaning        */
00624 /* out lower levels as necessary.                              */
00625 /* Also works if x is a balanced tree of concatenations; however      */
00626 /* in this case an extra concatenation node may be inserted above x;  */
00627 /* This node should not be counted in the statement of the invariants.       */
00628 void CORD_add_forest(ForestElement * forest, CORD x, size_t len)
00629 {
00630     register int i = 0;
00631     register CORD sum = CORD_EMPTY;
00632     register size_t sum_len = 0;
00633     
00634     while (len > min_len[i + 1]) {
00635        if (forest[i].c != 0) {
00636            sum = CORD_cat(forest[i].c, sum);
00637            sum_len += forest[i].len;
00638            forest[i].c = 0;
00639        }
00640         i++;
00641     }
00642     /* Sum has depth at most 1 greter than what would be required     */
00643     /* for balance.                                            */
00644     sum = CORD_cat(sum, x);
00645     sum_len += len;
00646     /* If x was a leaf, then sum is now balanced.  To see this        */
00647     /* consider the two cases in which forest[i-1] either is or is    */
00648     /* not empty.                                              */
00649     while (sum_len >= min_len[i]) {
00650        if (forest[i].c != 0) {
00651            sum = CORD_cat(forest[i].c, sum);
00652            sum_len += forest[i].len;
00653            /* This is again balanced, since sum was balanced, and has */
00654            /* allowable depth that differs from i by at most 1.       */
00655            forest[i].c = 0;
00656        }
00657         i++;
00658     }
00659     i--;
00660     forest[i].c = sum;
00661     forest[i].len = sum_len;
00662 }
00663 
00664 CORD CORD_concat_forest(ForestElement * forest, size_t expected_len)
00665 {
00666     register int i = 0;
00667     CORD sum = 0;
00668     size_t sum_len = 0;
00669     
00670     while (sum_len != expected_len) {
00671        if (forest[i].c != 0) {
00672            sum = CORD_cat(forest[i].c, sum);
00673            sum_len += forest[i].len;
00674        }
00675         i++;
00676     }
00677     return(sum);
00678 }
00679 
00680 /* Insert the frontier of x into forest.  Balanced subtrees are       */
00681 /* treated as leaves.  This potentially adds one to the depth  */
00682 /* of the final tree.                                          */
00683 void CORD_balance_insert(CORD x, size_t len, ForestElement * forest)
00684 {
00685     register int depth;
00686     
00687     if (CORD_IS_STRING(x)) {
00688         CORD_add_forest(forest, x, len);
00689     } else if (IS_CONCATENATION(x)
00690                && ((depth = DEPTH(x)) >= MAX_DEPTH
00691                    || len < min_len[depth])) {
00692        register struct Concatenation * conc
00693                      = &(((CordRep *)x) -> concatenation);
00694        size_t left_len = LEFT_LEN(conc);
00695        
00696        CORD_balance_insert(conc -> left, left_len, forest);
00697        CORD_balance_insert(conc -> right, len - left_len, forest);
00698     } else /* function or balanced */ {
00699        CORD_add_forest(forest, x, len);
00700     }
00701 }
00702 
00703 
00704 CORD CORD_balance(CORD x)
00705 {
00706     Forest forest;
00707     register size_t len;
00708     
00709     if (x == 0) return(0);
00710     if (CORD_IS_STRING(x)) return(x);
00711     if (!min_len_init) CORD_init_min_len();
00712     len = LEN(x);
00713     CORD_init_forest(forest, len);
00714     CORD_balance_insert(x, len, forest);
00715     return(CORD_concat_forest(forest, len));
00716 }
00717 
00718 
00719 /* Position primitives      */
00720 
00721 /* Private routines to deal with the hard cases only: */
00722 
00723 /* P contains a prefix of the  path to cur_pos.  Extend it to a full  */
00724 /* path and set up leaf info.                                         */
00725 /* Return 0 if past the end of cord, 1 o.w.                           */
00726 void CORD__extend_path(register CORD_pos p)
00727 {
00728      register struct CORD_pe * current_pe = &(p[0].path[p[0].path_len]);
00729      register CORD top = current_pe -> pe_cord;
00730      register size_t pos = p[0].cur_pos;
00731      register size_t top_pos = current_pe -> pe_start_pos;
00732      register size_t top_len = GEN_LEN(top);
00733      
00734      /* Fill in the rest of the path. */
00735        while(!CORD_IS_STRING(top) && IS_CONCATENATION(top)) {
00736         register struct Concatenation * conc =
00737                      &(((CordRep *)top) -> concatenation);
00738         register size_t left_len;
00739         
00740         left_len = LEFT_LEN(conc);
00741         current_pe++;
00742         if (pos >= top_pos + left_len) {
00743             current_pe -> pe_cord = top = conc -> right;
00744             current_pe -> pe_start_pos = top_pos = top_pos + left_len;
00745             top_len -= left_len;
00746         } else {
00747             current_pe -> pe_cord = top = conc -> left;
00748             current_pe -> pe_start_pos = top_pos;
00749             top_len = left_len;
00750         }
00751         p[0].path_len++;
00752        }
00753      /* Fill in leaf description for fast access. */
00754        if (CORD_IS_STRING(top)) {
00755          p[0].cur_leaf = top;
00756          p[0].cur_start = top_pos;
00757          p[0].cur_end = top_pos + top_len;
00758        } else {
00759          p[0].cur_end = 0;
00760        }
00761        if (pos >= top_pos + top_len) p[0].path_len = CORD_POS_INVALID;
00762 }
00763 
00764 char CORD__pos_fetch(register CORD_pos p)
00765 {
00766     /* Leaf is a function node */
00767     struct CORD_pe * pe = &((p)[0].path[(p)[0].path_len]);
00768     CORD leaf = pe -> pe_cord;
00769     register struct Function * f = &(((CordRep *)leaf) -> function);
00770     
00771     if (!IS_FUNCTION(leaf)) ABORT("CORD_pos_fetch: bad leaf");
00772     return ((*(f -> fn))(p[0].cur_pos - pe -> pe_start_pos, f -> client_data));
00773 }
00774 
00775 void CORD__next(register CORD_pos p)
00776 {
00777     register size_t cur_pos = p[0].cur_pos + 1;
00778     register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
00779     register CORD leaf = current_pe -> pe_cord;
00780     
00781     /* Leaf is not a string or we're at end of leaf */
00782     p[0].cur_pos = cur_pos;
00783     if (!CORD_IS_STRING(leaf)) {
00784        /* Function leaf     */
00785        register struct Function * f = &(((CordRep *)leaf) -> function);
00786        register size_t start_pos = current_pe -> pe_start_pos;
00787        register size_t end_pos = start_pos + f -> len;
00788        
00789        if (cur_pos < end_pos) {
00790          /* Fill cache and return. */
00791            register size_t i;
00792            register size_t limit = cur_pos + FUNCTION_BUF_SZ;
00793            register CORD_fn fn = f -> fn;
00794            register void * client_data = f -> client_data;
00795            
00796            if (limit > end_pos) {
00797                limit = end_pos;
00798            }
00799            for (i = cur_pos; i < limit; i++) {
00800                p[0].function_buf[i - cur_pos] =
00801                      (*fn)(i - start_pos, client_data);
00802            }
00803            p[0].cur_start = cur_pos;
00804            p[0].cur_leaf = p[0].function_buf;
00805            p[0].cur_end = limit;
00806            return;
00807        }
00808     }
00809     /* End of leaf   */
00810     /* Pop the stack until we find two concatenation nodes with the   */
00811     /* same start position: this implies we were in left part.        */
00812     {
00813        while (p[0].path_len > 0
00814               && current_pe[0].pe_start_pos != current_pe[-1].pe_start_pos) {
00815            p[0].path_len--;
00816            current_pe--;
00817        }
00818        if (p[0].path_len == 0) {
00819            p[0].path_len = CORD_POS_INVALID;
00820             return;
00821        }
00822     }
00823     p[0].path_len--;
00824     CORD__extend_path(p);
00825 }
00826 
00827 void CORD__prev(register CORD_pos p)
00828 {
00829     register struct CORD_pe * pe = &(p[0].path[p[0].path_len]);
00830     
00831     if (p[0].cur_pos == 0) {
00832         p[0].path_len = CORD_POS_INVALID;
00833         return;
00834     }
00835     p[0].cur_pos--;
00836     if (p[0].cur_pos >= pe -> pe_start_pos) return;
00837     
00838     /* Beginning of leaf    */
00839     
00840     /* Pop the stack until we find two concatenation nodes with the   */
00841     /* different start position: this implies we were in right part.  */
00842     {
00843        register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
00844        
00845        while (p[0].path_len > 0
00846               && current_pe[0].pe_start_pos == current_pe[-1].pe_start_pos) {
00847            p[0].path_len--;
00848            current_pe--;
00849        }
00850     }
00851     p[0].path_len--;
00852     CORD__extend_path(p);
00853 }
00854 
00855 #undef CORD_pos_fetch
00856 #undef CORD_next
00857 #undef CORD_prev
00858 #undef CORD_pos_to_index
00859 #undef CORD_pos_to_cord
00860 #undef CORD_pos_valid
00861 
00862 char CORD_pos_fetch(register CORD_pos p)
00863 {
00864     if (p[0].cur_start <= p[0].cur_pos && p[0].cur_pos < p[0].cur_end) {
00865        return(p[0].cur_leaf[p[0].cur_pos - p[0].cur_start]);
00866     } else {
00867         return(CORD__pos_fetch(p));
00868     }
00869 }
00870 
00871 void CORD_next(CORD_pos p)
00872 {
00873     if (p[0].cur_pos < p[0].cur_end - 1) {
00874        p[0].cur_pos++;
00875     } else {
00876        CORD__next(p);
00877     }
00878 }
00879 
00880 void CORD_prev(CORD_pos p)
00881 {
00882     if (p[0].cur_end != 0 && p[0].cur_pos > p[0].cur_start) {
00883        p[0].cur_pos--;
00884     } else {
00885        CORD__prev(p);
00886     }
00887 }
00888 
00889 size_t CORD_pos_to_index(CORD_pos p)
00890 {
00891     return(p[0].cur_pos);
00892 }
00893 
00894 CORD CORD_pos_to_cord(CORD_pos p)
00895 {
00896     return(p[0].path[0].pe_cord);
00897 }
00898 
00899 int CORD_pos_valid(CORD_pos p)
00900 {
00901     return(p[0].path_len != CORD_POS_INVALID);
00902 }
00903 
00904 void CORD_set_pos(CORD_pos p, CORD x, size_t i)
00905 {
00906     if (x == CORD_EMPTY) {
00907        p[0].path_len = CORD_POS_INVALID;
00908        return;
00909     }
00910     p[0].path[0].pe_cord = x;
00911     p[0].path[0].pe_start_pos = 0;
00912     p[0].path_len = 0;
00913     p[0].cur_pos = i;
00914     CORD__extend_path(p);
00915 }