Annotation of parser3/src/lib/cord/cordbscs.c, revision 1.1.2.3

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

E-mail: