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

1.2       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: 
1.2.4.4 ! paf       101: /* paf: using knowledge of interal structure to speedup */
        !           102: char CORD_nul_func(size_t i, void * client_data);
1.2       paf       103: 
                    104: /* Dump the internal representation of x to stdout, with initial       */
                    105: /* indentation level n.                                                        */
                    106: void CORD_dump_inner(CORD x, unsigned n)
                    107: {
                    108:     register size_t i;
                    109:     
                    110:     for (i = 0; i < (size_t)n; i++) {
                    111:         fputs("  ", stdout);
                    112:     }
                    113:     if (x == 0) {
                    114:        fputs("NIL\n", stdout);
                    115:     } else if (CORD_IS_STRING(x)) {
                    116:         for (i = 0; i <= SHORT_LIMIT; i++) {
                    117:             if (x[i] == '\0') break;
                    118:             putchar(x[i]);
                    119:         }
                    120:         if (x[i] != '\0') fputs("...", stdout);
                    121:         putchar('\n');
                    122:     } else if (IS_CONCATENATION(x)) {
                    123:         register struct Concatenation * conc =
                    124:                                &(((CordRep *)x) -> concatenation);
                    125:         printf("Concatenation: %p (len: %d, depth: %d)\n",
                    126:                x, (int)(conc -> len), (int)(conc -> depth));
                    127:         CORD_dump_inner(conc -> left, n+1);
                    128:         CORD_dump_inner(conc -> right, n+1);
                    129:     } else /* function */{
                    130:         register struct Function * func =
                    131:                                &(((CordRep *)x) -> function);
                    132:         if (IS_SUBSTR(x)) printf("(Substring) ");
                    133:         printf("Function: %p (len: %d): ", x, (int)(func -> len));
                    134:         for (i = 0; i < 20 && i < func -> len; i++) {
                    135:             putchar((*(func -> fn))(i, func -> client_data));
                    136:         }
                    137:         if (i < func -> len) fputs("...", stdout);
                    138:         putchar('\n');
                    139:     }
                    140: }
                    141: 
                    142: /* Dump the internal representation of x to stdout     */
                    143: void CORD_dump(CORD x)
                    144: {
                    145:     CORD_dump_inner(x, 0);
                    146:     fflush(stdout);
                    147: }
                    148: 
                    149: CORD CORD_cat_char_star(CORD x, const char*  y, size_t leny)
                    150: {
                    151:     register size_t result_len;
                    152:     register size_t lenx;
                    153:     register int depth;
                    154: 
                    155:     if (x == CORD_EMPTY) return(y);
                    156:     //if (leny == 0) leny=strlen(y); // PAF
                    157:     if (y == 0) ABORT("CORD_cat_char_star(,y,) y==0"); // PAF
                    158:     if (*y == 0) ABORT("CORD_cat_char_star(,y,) y==\"\""); // PAF
                    159:     if (leny == 0) ABORT("CORD_cat_char_star(,y,) leny==0"); // PAF
                    160:     
                    161:     if (CORD_IS_STRING(x)) {
                    162:         lenx = strlen(x);
                    163:         result_len = lenx + leny;
                    164:         if (result_len <= SHORT_LIMIT) {
                    165:             register char * result = GC_MALLOC_ATOMIC(result_len+1);
                    166: 
                    167:             if (result == 0) OUT_OF_MEMORY;
                    168:             memcpy(result, x, lenx);
                    169:             memcpy(result + lenx, y, leny);
                    170:             result[result_len] = '\0';
                    171:             return((CORD) result);
                    172:         } else {
                    173:             depth = 1;
                    174:         }
                    175:     } else {
                    176:        register CORD right;
                    177:        register CORD left;
                    178:        register char * new_right;
                    179:        register size_t right_len;
                    180:        
                    181:        lenx = LEN(x);
                    182:        
                    183:         if (leny <= SHORT_LIMIT/2
                    184:            && IS_CONCATENATION(x)
                    185:             && CORD_IS_STRING(right = ((CordRep *)x) -> concatenation.right)) {
                    186:             /* Merge y into right part of x. */
                    187:             if (!CORD_IS_STRING(left = ((CordRep *)x) -> concatenation.left)) {
                    188:                right_len = lenx - LEN(left);
                    189:             } else if (((CordRep *)x) -> concatenation.left_len != 0) {
                    190:                 right_len = lenx - ((CordRep *)x) -> concatenation.left_len;
                    191:             } else {
                    192:                right_len = strlen(right);
                    193:             }
                    194:             result_len = right_len + leny;  /* length of new_right */
                    195:             if (result_len <= SHORT_LIMIT) {
                    196:                new_right = GC_MALLOC_ATOMIC(result_len + 1);
                    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) result->left_len = lenx;
                    225:        result->len = result_len;
                    226:        result->left = x;
                    227:        result->right = y;
                    228:        if (depth >= MAX_DEPTH) {
                    229:            return(CORD_balance((CORD)result));
                    230:        } else {
                    231:            return((CORD) result);
                    232:        }
                    233:     }
                    234: }
                    235: 
                    236: 
                    237: CORD CORD_cat(CORD x, CORD y)
                    238: {
                    239:     register size_t result_len;
                    240:     register int depth;
                    241:     register size_t lenx;
                    242:     
                    243:     if (x == CORD_EMPTY) return(y);
                    244:     if (y == CORD_EMPTY) return(x);
                    245:     if (CORD_IS_STRING(y)) {
                    246:         return(CORD_cat_char_star(x, y, strlen(y)));
                    247:     } else if (CORD_IS_STRING(x)) {
                    248:         lenx = strlen(x);
                    249:         depth = DEPTH(y) + 1;
                    250:     } else {
                    251:         register int depthy = DEPTH(y);
                    252:         
                    253:         lenx = LEN(x);
                    254:         depth = DEPTH(x) + 1;
                    255:         if (depthy >= depth) depth = depthy + 1;
                    256:     }
                    257:     result_len = lenx + LEN(y);
                    258:     {
                    259:        register struct Concatenation * result;
                    260:        
                    261:        result = GC_NEW(struct Concatenation);
                    262:        if (result == 0) OUT_OF_MEMORY;
                    263:        result->header = CONCAT_HDR;
                    264:        result->depth = depth;
                    265: //     printf("depth=%d\n", depth);
                    266:        if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
                    267:        result->len = result_len;
                    268:        result->left = x;
                    269:        result->right = y;
                    270:        // PAF@design.ru bug fix:
                    271:        if (depth >= MAX_DEPTH) {
                    272:            return(CORD_balance((CORD)result));
                    273:        } else {
                    274:            return((CORD) result);
                    275:        }
                    276:     }
                    277: }
                    278: 
1.2.4.4 ! paf       279: /* paf: assuming both x&y not empty and both of them functions or concatenations of them,
        !           280:     can modify x! [to speedup simple case]
        !           281: */ 
        !           282: CORD CORD_append_blocks(CORD x, CORD y)
        !           283: {
        !           284:     register size_t result_len;
        !           285:     register int depth;
        !           286:     register size_t lenx;
        !           287:     
        !           288:        if (CORD_IS_STRING(y)) {
        !           289:         return(CORD_cat_char_star(x, y, strlen(y)));
        !           290:     } else if (CORD_IS_STRING(x)) {
        !           291:         lenx = strlen(x);
        !           292:         depth = DEPTH(y) + 1;
        !           293:     } else {
        !           294:                // speedup simple case
        !           295:                if(IS_FUNCTION(x) 
        !           296:                        && IS_FUNCTION(y)
        !           297:                        && ((CordRep *)x) -> function.fn==CORD_nul_func
        !           298:                        && ((CordRep *)y) -> function.fn==CORD_nul_func
        !           299:                        && 
        !           300:                        ((CordRep *)x) -> function.client_data==
        !           301:                        ((CordRep *)y) -> function.client_data) {
        !           302:                                ((CordRep *)x) -> function.len+=
        !           303:                                        ((CordRep *)y) -> function.len;
        !           304:                                return x;
        !           305:                        }
        !           306:                {
        !           307:                        register int depthy = DEPTH(y);
        !           308:                
        !           309:                        lenx = LEN(x);
        !           310:                        depth = DEPTH(x) + 1;
        !           311:                        if (depthy >= depth) depth = depthy + 1;
        !           312:                }
        !           313:     }
        !           314:     result_len = lenx + LEN(y);
        !           315:     {
        !           316:        register struct Concatenation * result;
        !           317:        
        !           318:        result = GC_NEW(struct Concatenation);
        !           319:        if (result == 0) OUT_OF_MEMORY;
        !           320:        result->header = CONCAT_HDR;
        !           321:        result->depth = depth;
        !           322: //     printf("depth=%d\n", depth);
        !           323:        if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
        !           324:        result->len = result_len;
        !           325:        result->left = x;
        !           326:        result->right = y;
        !           327:        // PAF@design.ru bug fix:
        !           328:        if (depth >= MAX_DEPTH) {
        !           329:            return(CORD_balance((CORD)result));
        !           330:        } else {
        !           331:            return((CORD) result);
        !           332:        }
        !           333:     }
        !           334: }
        !           335: 
1.2       paf       336: 
                    337: 
                    338: CORD CORD_from_fn(CORD_fn fn, void * client_data, size_t len)
                    339: {
                    340:     if (len <= 0) return(0);
                    341:     if (len <= SHORT_LIMIT) {
                    342:         register char * result;
                    343:         register size_t i;
                    344:         char buf[SHORT_LIMIT+1];
                    345:         register char c;
                    346:         
                    347:         for (i = 0; i < len; i++) {
                    348:             c = (*fn)(i, client_data);
                    349:             if (c == '\0') goto gen_case;
                    350:             buf[i] = c;
                    351:         }
                    352:         buf[i] = '\0';
                    353:         result = GC_MALLOC_ATOMIC(len+1);
                    354:         if (result == 0) OUT_OF_MEMORY;
                    355:         strcpy(result, buf);
                    356:         result[len] = '\0';
                    357:         return((CORD) result);
                    358:     }
                    359:   gen_case:
                    360:     {
                    361:        register struct Function * result;
                    362:        
                    363:        result = GC_NEW(struct Function);
                    364:        if (result == 0) OUT_OF_MEMORY;
                    365:        result->header = FN_HDR;
                    366:        /* depth is already 0 */
                    367:        result->len = len;
                    368:        result->fn = fn;
                    369:        result->client_data = client_data;
                    370:        return((CORD) result);
                    371:     }
                    372: }
                    373: 
1.2.4.2   paf       374: CORD CORD_from_fn_gen(CORD_fn fn, void * client_data, size_t len)
1.2.4.1   paf       375: {
                    376:        register struct Function * result;
1.2.4.2   paf       377:     if (len <= 0) return(0);
1.2.4.1   paf       378: 
                    379:        result = GC_NEW(struct Function);
                    380:        if (result == 0) OUT_OF_MEMORY;
                    381:        result->header = FN_HDR;
                    382:        /* depth is already 0 */
                    383:        result->len = len;
                    384:        result->fn = fn;
                    385:        result->client_data = client_data;
                    386:        return((CORD) result);
                    387: }
                    388: 
1.2       paf       389: size_t CORD_len(CORD x)
                    390: {
                    391:     if (x == 0) {
                    392:        return(0);
                    393:     } else {
                    394:        return(GEN_LEN(x));
                    395:     }
                    396: }
                    397: 
                    398: struct substr_args {
                    399:     CordRep * sa_cord;
                    400:     size_t sa_index;
                    401: };
                    402: 
                    403: char CORD_index_access_fn(size_t i, void * client_data)
                    404: {
                    405:     register struct substr_args *descr = (struct substr_args *)client_data;
                    406:     
                    407:     return(((char *)(descr->sa_cord))[i + descr->sa_index]);
                    408: }
                    409: 
                    410: char CORD_apply_access_fn(size_t i, void * client_data)
                    411: {
                    412:     register struct substr_args *descr = (struct substr_args *)client_data;
                    413:     register struct Function * fn_cord = &(descr->sa_cord->function);
                    414:     
                    415:     return((*(fn_cord->fn))(i + descr->sa_index, fn_cord->client_data));
                    416: }
                    417: 
                    418: /* A version of CORD_substr that simply returns a function node, thus  */
                    419: /* postponing its work.        The fourth argument is a function that may      */
                    420: /* be used for efficient access to the ith character.                  */
                    421: /* Assumes i >= 0 and i + n < length(x).                               */
                    422: CORD CORD_substr_closure(CORD x, size_t i, size_t n, CORD_fn f)
                    423: {
                    424:     register struct substr_args * sa = GC_NEW(struct substr_args);
                    425:     CORD result;
                    426:     
                    427:     if (sa == 0) OUT_OF_MEMORY;
                    428:     sa->sa_cord = (CordRep *)x;
                    429:     sa->sa_index = i;
                    430:     result = CORD_from_fn(f, (void *)sa, n);
                    431:     ((CordRep *)result) -> function.header = SUBSTR_HDR;
                    432:     return (result);
                    433: }
                    434: 
                    435: # define SUBSTR_LIMIT (10 * SHORT_LIMIT)
                    436:        /* Substrings of function nodes and flat strings shorter than   */
                    437:        /* this are flat strings.  Othewise we use a functional         */
                    438:        /* representation, which is significantly slower to access.     */
                    439: 
                    440: /* A version of CORD_substr that assumes i >= 0, n > 0, and i + n < length(x).*/
                    441: CORD CORD_substr_checked(CORD x, size_t i, size_t n)
                    442: {
                    443:     if (CORD_IS_STRING(x)) {
                    444:         if (n > SUBSTR_LIMIT) {
                    445:             return(CORD_substr_closure(x, i, n, CORD_index_access_fn));
                    446:         } else {
                    447:             register char * result = GC_MALLOC_ATOMIC(n+1);
                    448:             
                    449:             if (result == 0) OUT_OF_MEMORY;
                    450:             strncpy(result, x+i, n);
                    451:             result[n] = '\0';
                    452:             return(result);
                    453:         }
                    454:     } else if (IS_CONCATENATION(x)) {
                    455:        register struct Concatenation * conc
                    456:                        = &(((CordRep *)x) -> concatenation);
                    457:        register size_t left_len;
                    458:        register size_t right_len;
                    459:        
                    460:        left_len = LEFT_LEN(conc);
                    461:        right_len = conc -> len - left_len;
                    462:        if (i >= left_len) {
                    463:            if (n == right_len) return(conc -> right);
                    464:            return(CORD_substr_checked(conc -> right, i - left_len, n));
                    465:        } else if (i+n <= left_len) {
                    466:            if (n == left_len) return(conc -> left);
                    467:            return(CORD_substr_checked(conc -> left, i, n));
                    468:        } else {
                    469:            /* Need at least one character from each side. */
                    470:            register CORD left_part;
                    471:            register CORD right_part;
                    472:            register size_t left_part_len = left_len - i;
                    473:        
                    474:            if (i == 0) {
                    475:                left_part = conc -> left;
                    476:            } else {
                    477:                left_part = CORD_substr_checked(conc -> left, i, left_part_len);
                    478:            }
                    479:            if (i + n == right_len + left_len) {
                    480:                 right_part = conc -> right;
                    481:            } else {
                    482:                 right_part = CORD_substr_checked(conc -> right, 0,
                    483:                                                  n - left_part_len);
                    484:            }
                    485:            return(CORD_cat(left_part, right_part));
                    486:        }
                    487:     } else /* function */ {
                    488:         if (n > SUBSTR_LIMIT) {
                    489:             if (IS_SUBSTR(x)) {
                    490:                /* Avoid nesting substring nodes.       */
                    491:                register struct Function * f = &(((CordRep *)x) -> function);
                    492:                register struct substr_args *descr =
                    493:                                (struct substr_args *)(f -> client_data);
                    494:                
                    495:                return(CORD_substr_closure((CORD)descr->sa_cord,
                    496:                                           i + descr->sa_index,
                    497:                                           n, f -> fn));
                    498:             } else {
                    499:                 return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
                    500:             }
                    501:         } else {
                    502:             char * result;
                    503:             register struct Function * f = &(((CordRep *)x) -> function);
                    504:             char buf[SUBSTR_LIMIT+1];
                    505:             register char * p = buf;
                    506:             register char c;
                    507:             register int j;
                    508:             register int lim = i + n;
                    509:             
                    510:             for (j = i; j < lim; j++) {
                    511:                c = (*(f -> fn))(j, f -> client_data);
                    512:                if (c == '\0') {
                    513:                    return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
                    514:                }
                    515:                *p++ = c;
                    516:             }
                    517:             *p = '\0';
                    518:             result = GC_MALLOC_ATOMIC(n+1);
                    519:             if (result == 0) OUT_OF_MEMORY;
                    520:             strcpy(result, buf);
                    521:             return(result);
                    522:         }
                    523:     }
                    524: }
                    525: 
                    526: CORD CORD_substr(CORD x, size_t i, size_t n)
                    527: {
                    528:     register size_t len = CORD_len(x);
                    529:     
                    530:     if (i >= len || n <= 0) return(0);
                    531:        /* n < 0 is impossible in a correct C implementation, but       */
                    532:        /* quite possible  under SunOS 4.X.                             */
                    533:     if (i + n > len) n = len - i;
                    534: #   ifndef __STDC__
                    535:       if (i < 0) ABORT("CORD_substr: second arg. negative");
                    536:        /* Possible only if both client and C implementation are buggy. */
                    537:        /* But empirically this happens frequently.                     */
                    538: #   endif
                    539:     return(CORD_substr_checked(x, i, n));
                    540: }
                    541: 
                    542: /* See cord.h for definition.  We assume i is in range.        */
                    543: int CORD_iter5(CORD x, size_t i, CORD_iter_fn f1,
                    544:                         CORD_batched_iter_fn f2, void * client_data)
                    545: {
1.2.4.3   paf       546:        int result;
1.2       paf       547:     if (x == 0) return(0);
                    548:     if (CORD_IS_STRING(x)) {
                    549:        register const char* p = x+i;
                    550:        
                    551:        if (*p == '\0') ABORT("2nd arg to CORD_iter5 too big");
                    552:         if (f2 != CORD_NO_FN) {
                    553:             return((*f2)(p, client_data));
                    554:         } else {
                    555:            while (*p) {
1.2.4.3   paf       556:                 if (result=(*f1)(*p, client_data)) 
                    557:                                        return result;
1.2       paf       558:                 p++;
                    559:            }
                    560:            return(0);
                    561:         }
                    562:     } else if (IS_CONCATENATION(x)) {
1.2.4.3   paf       563:        register struct Concatenation * conc = &(((CordRep *)x) -> concatenation);
1.2       paf       564:        if (i > 0) {
                    565:            register size_t left_len = LEFT_LEN(conc);
                    566:            
                    567:            if (i >= left_len) {
                    568:                return(CORD_iter5(conc -> right, i - left_len, f1, f2,
                    569:                                  client_data));
                    570:            }
                    571:        }
1.2.4.3   paf       572:                result=CORD_iter5(conc -> left, i, f1, f2, client_data);
                    573:        if (result) return result;
1.2       paf       574:        return(CORD_iter5(conc -> right, 0, f1, f2, client_data));
                    575:     } else /* function */ {
                    576:         register struct Function * f = &(((CordRep *)x) -> function);
                    577:         register size_t j;
                    578:         register size_t lim = f -> len;
                    579:         
                    580:         for (j = i; j < lim; j++) {
1.2.4.3   paf       581:             if (result=(*f1)((*(f -> fn))(j, f -> client_data), client_data)) 
                    582:                                return result;
1.2       paf       583:         }
                    584:         return(0);
1.2.4.1   paf       585:     }
                    586: }
                    587: 
                    588: /* See cord.h for definition.  We assume i is in range.        */
1.2.4.3   paf       589: int CORD_block_iter(CORD x, size_t i, CORD_block_iter_fn fb, void * client_data)
1.2.4.1   paf       590: {
1.2.4.3   paf       591:        int result;
1.2.4.1   paf       592:     if (x == 0) return(0);
1.2.4.3   paf       593:     if (CORD_IS_STRING(x)) {
                    594:        register const char* p = x+i;
                    595:                const char *b=p;
                    596:                char bc=*b;
                    597:                int pc;
1.2.4.1   paf       598:        
1.2.4.3   paf       599:        if (bc == '\0') ABORT("2nd arg to CORD_iter5 too big");
                    600:            do {
                    601:                        pc=*++p;
                    602:                        if(pc!=bc) {
                    603:                                if (result=fb(bc, p-b, client_data)) 
                    604:                                        return result;
                    605:                                b=p; bc=pc;
                    606:                        }
                    607:            } while (pc);
                    608:            return(0);
                    609:     } else if (IS_CONCATENATION(x)) {
                    610:        register struct Concatenation * conc= &(((CordRep *)x) -> concatenation);
1.2.4.1   paf       611:        if (i > 0) {
1.2.4.3   paf       612:            register size_t left_len = LEFT_LEN(conc);
1.2.4.1   paf       613:            
1.2.4.3   paf       614:            if (i >= left_len) {
                    615:                return(CORD_block_iter(conc -> right, i - left_len, fb, client_data));
                    616:            }
1.2.4.1   paf       617:        }
1.2.4.3   paf       618:                result=CORD_block_iter(conc -> left, i, fb, client_data);
                    619:        if (result) return result;
                    620:        return(CORD_block_iter(conc -> right, 0, fb, client_data));
                    621:     } else /* function */ {
1.2.4.1   paf       622:         register struct Function * f = &(((CordRep *)x) -> function);
1.2.4.3   paf       623:         register size_t lim = f -> len;
1.2.4.1   paf       624:         
1.2.4.3   paf       625:                if(f->fn == CORD_nul_func ) {
                    626:                        if (result=fb((char)(unsigned long)f -> client_data, f -> len-i, client_data)) return result;
                    627:                } else if(f->fn == CORD_apply_access_fn) {
                    628:                        register struct substr_args *descr = (struct substr_args *)f->client_data;
                    629:                        register struct Function * fn_cord = &(descr->sa_cord->function);
                    630: 
                    631:                        if(fn_cord->fn == CORD_nul_func ) {
                    632:                                if (result=fb((char)(unsigned long)fn_cord->client_data, f -> len-i, client_data)) 
                    633:                                        return result;
                    634:                        } else
                    635:                                ABORT("CORD_block_iter:CORD_apply_access_fn:unknown_fn should not happen");
                    636:                } else {
                    637:                        if(f->fn == CORD_index_access_fn)
                    638:                                ABORT("CORD_block_iter:CORD_index_access_fn should not happen");
                    639:                        ABORT("CORD_block_iter:unknown_fn should not happen");
                    640:                }
1.2       paf       641:     }
1.2.4.3   paf       642:        return(0);
1.2       paf       643: }
                    644:                        
1.2.4.3   paf       645: 
1.2       paf       646: #undef CORD_iter
                    647: int CORD_iter(CORD x, CORD_iter_fn f1, void * client_data)
                    648: {
                    649:     return(CORD_iter5(x, 0, f1, CORD_NO_FN, client_data));
                    650: }
                    651: 
                    652: int CORD_riter4(CORD x, size_t i, CORD_iter_fn f1, void * client_data)
                    653: {
                    654:     if (x == 0) return(0);
                    655:     if (CORD_IS_STRING(x)) {
                    656:        register const char* p = x + i;
                    657:        register char c;
                    658:                
                    659:        for(;;) {
                    660:            c = *p;
                    661:            if (c == '\0') ABORT("2nd arg to CORD_riter4 too big");
                    662:             if ((*f1)(c, client_data)) return(1);
                    663:            if (p == x) break;
                    664:             p--;
                    665:        }
                    666:        return(0);
                    667:     } else if (IS_CONCATENATION(x)) {
                    668:        register struct Concatenation * conc
                    669:                        = &(((CordRep *)x) -> concatenation);
                    670:        register CORD left_part = conc -> left;
                    671:        register size_t left_len;
                    672:        
                    673:        left_len = LEFT_LEN(conc);
                    674:        if (i >= left_len) {
                    675:            if (CORD_riter4(conc -> right, i - left_len, f1, client_data)) {
                    676:                return(1);
                    677:            }
                    678:            return(CORD_riter4(left_part, left_len - 1, f1, client_data));
                    679:        } else {
                    680:            return(CORD_riter4(left_part, i, f1, client_data));
                    681:        }
                    682:     } else /* function */ {
                    683:         register struct Function * f = &(((CordRep *)x) -> function);
                    684:         register size_t j;
                    685:         
                    686:         for (j = i; ; j--) {
                    687:             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
                    688:                 return(1);
                    689:             }
                    690:             if (j == 0) return(0);
                    691:         }
                    692:     }
                    693: }
                    694: 
                    695: int CORD_riter(CORD x, CORD_iter_fn f1, void * client_data)
                    696: {
                    697:     return(CORD_riter4(x, CORD_len(x) - 1, f1, client_data));
                    698: }
                    699: 
                    700: /*
                    701:  * The following functions are concerned with balancing cords.
                    702:  * Strategy:
                    703:  * Scan the cord from left to right, keeping the cord scanned so far
                    704:  * as a forest of balanced trees of exponentialy decreasing length.
                    705:  * When a new subtree needs to be added to the forest, we concatenate all
                    706:  * shorter ones to the new tree in the appropriate order, and then insert
                    707:  * the result into the forest.
                    708:  * Crucial invariants:
                    709:  * 1. The concatenation of the forest (in decreasing order) with the
                    710:  *     unscanned part of the rope is equal to the rope being balanced.
                    711:  * 2. All trees in the forest are balanced.
                    712:  * 3. forest[i] has depth at most i.
                    713:  */
                    714: 
                    715: typedef struct {
                    716:     CORD c;
                    717:     size_t len;                /* Actual length of c   */
                    718: } ForestElement;
                    719: 
                    720: static size_t min_len [ MAX_DEPTH ];
                    721: 
                    722: static int min_len_init = 0;
                    723: 
                    724: int CORD_max_len;
                    725: 
                    726: typedef ForestElement Forest [ MAX_DEPTH ];
                    727:                        /* forest[i].len >= fib(i+1)            */
                    728:                        /* The string is the concatenation      */
                    729:                        /* of the forest in order of DECREASING */
                    730:                        /* indices.                             */
                    731: 
                    732: void CORD_init_min_len()
                    733: {
                    734:     register int i;
                    735:     register size_t last, previous, current;
                    736:         
                    737:     min_len[0] = previous = 1;
                    738:     min_len[1] = last = 2;
                    739:     for (i = 2; i < MAX_DEPTH; i++) {
                    740:        current = last + previous;
                    741:        if (current < last) /* overflow */ current = last;
                    742:        min_len[i] = current;
                    743:        previous = last;
                    744:        last = current;
                    745:     }
                    746:     CORD_max_len = last - 1;
                    747:     min_len_init = 1;
                    748: }
                    749: 
                    750: 
                    751: void CORD_init_forest(ForestElement * forest, size_t max_len)
                    752: {
                    753:     register int i;
                    754:     
                    755:     for (i = 0; i < MAX_DEPTH; i++) {
                    756:        forest[i].c = 0;
                    757:        if (min_len[i] > max_len) return;
                    758:     }
                    759:     ABORT("Cord too long");
                    760: }
                    761: 
                    762: /* Add a leaf to the appropriate level in the forest, cleaning         */
                    763: /* out lower levels as necessary.                                      */
                    764: /* Also works if x is a balanced tree of concatenations; however       */
                    765: /* in this case an extra concatenation node may be inserted above x;   */
                    766: /* This node should not be counted in the statement of the invariants. */
                    767: void CORD_add_forest(ForestElement * forest, CORD x, size_t len)
                    768: {
                    769:     register int i = 0;
                    770:     register CORD sum = CORD_EMPTY;
                    771:     register size_t sum_len = 0;
                    772:     
                    773:     while (len > min_len[i + 1]) {
                    774:        if (forest[i].c != 0) {
                    775:            sum = CORD_cat(forest[i].c, sum);
                    776:            sum_len += forest[i].len;
                    777:            forest[i].c = 0;
                    778:        }
                    779:         i++;
                    780:     }
                    781:     /* Sum has depth at most 1 greter than what would be required      */
                    782:     /* for balance.                                                    */
                    783:     sum = CORD_cat(sum, x);
                    784:     sum_len += len;
                    785:     /* If x was a leaf, then sum is now balanced.  To see this         */
                    786:     /* consider the two cases in which forest[i-1] either is or is     */
                    787:     /* not empty.                                                      */
                    788:     while (sum_len >= min_len[i]) {
                    789:        if (forest[i].c != 0) {
                    790:            sum = CORD_cat(forest[i].c, sum);
                    791:            sum_len += forest[i].len;
                    792:            /* This is again balanced, since sum was balanced, and has  */
                    793:            /* allowable depth that differs from i by at most 1.        */
                    794:            forest[i].c = 0;
                    795:        }
                    796:         i++;
                    797:     }
                    798:     i--;
                    799:     forest[i].c = sum;
                    800:     forest[i].len = sum_len;
                    801: }
                    802: 
                    803: CORD CORD_concat_forest(ForestElement * forest, size_t expected_len)
                    804: {
                    805:     register int i = 0;
                    806:     CORD sum = 0;
                    807:     size_t sum_len = 0;
                    808:     
                    809:     while (sum_len != expected_len) {
                    810:        if (forest[i].c != 0) {
                    811:            sum = CORD_cat(forest[i].c, sum);
                    812:            sum_len += forest[i].len;
                    813:        }
                    814:         i++;
                    815:     }
                    816:     return(sum);
                    817: }
                    818: 
                    819: /* Insert the frontier of x into forest.  Balanced subtrees are        */
                    820: /* treated as leaves.  This potentially adds one to the depth  */
                    821: /* of the final tree.                                          */
                    822: void CORD_balance_insert(CORD x, size_t len, ForestElement * forest)
                    823: {
                    824:     register int depth;
                    825:     
                    826:     if (CORD_IS_STRING(x)) {
                    827:         CORD_add_forest(forest, x, len);
                    828:     } else if (IS_CONCATENATION(x)
                    829:                && ((depth = DEPTH(x)) >= MAX_DEPTH
                    830:                    || len < min_len[depth])) {
                    831:        register struct Concatenation * conc
                    832:                        = &(((CordRep *)x) -> concatenation);
                    833:        size_t left_len = LEFT_LEN(conc);
                    834:        
                    835:        CORD_balance_insert(conc -> left, left_len, forest);
                    836:        CORD_balance_insert(conc -> right, len - left_len, forest);
                    837:     } else /* function or balanced */ {
                    838:        CORD_add_forest(forest, x, len);
                    839:     }
                    840: }
                    841: 
                    842: 
                    843: CORD CORD_balance(CORD x)
                    844: {
                    845:     Forest forest;
                    846:     register size_t len;
                    847:     
                    848:     if (x == 0) return(0);
                    849:     if (CORD_IS_STRING(x)) return(x);
                    850:     if (!min_len_init) CORD_init_min_len();
                    851:     len = LEN(x);
                    852:     CORD_init_forest(forest, len);
                    853:     CORD_balance_insert(x, len, forest);
                    854:     return(CORD_concat_forest(forest, len));
                    855: }
                    856: 
                    857: 
                    858: /* Position primitives */
                    859: 
                    860: /* Private routines to deal with the hard cases only: */
                    861: 
                    862: /* P contains a prefix of the  path to cur_pos.        Extend it to a full     */
                    863: /* path and set up leaf info.                                          */
                    864: /* Return 0 if past the end of cord, 1 o.w.                            */
                    865: void CORD__extend_path(register CORD_pos p)
                    866: {
                    867:      register struct CORD_pe * current_pe = &(p[0].path[p[0].path_len]);
                    868:      register CORD top = current_pe -> pe_cord;
                    869:      register size_t pos = p[0].cur_pos;
                    870:      register size_t top_pos = current_pe -> pe_start_pos;
                    871:      register size_t top_len = GEN_LEN(top);
                    872:      
                    873:      /* Fill in the rest of the path. */
                    874:        while(!CORD_IS_STRING(top) && IS_CONCATENATION(top)) {
                    875:         register struct Concatenation * conc =
                    876:                        &(((CordRep *)top) -> concatenation);
                    877:         register size_t left_len;
                    878:         
                    879:         left_len = LEFT_LEN(conc);
                    880:         current_pe++;
                    881:         if (pos >= top_pos + left_len) {
                    882:             current_pe -> pe_cord = top = conc -> right;
                    883:             current_pe -> pe_start_pos = top_pos = top_pos + left_len;
                    884:             top_len -= left_len;
                    885:         } else {
                    886:             current_pe -> pe_cord = top = conc -> left;
                    887:             current_pe -> pe_start_pos = top_pos;
                    888:             top_len = left_len;
                    889:         }
                    890:         p[0].path_len++;
                    891:        }
                    892:      /* Fill in leaf description for fast access. */
                    893:        if (CORD_IS_STRING(top)) {
                    894:          p[0].cur_leaf = top;
                    895:          p[0].cur_start = top_pos;
                    896:          p[0].cur_end = top_pos + top_len;
                    897:        } else {
                    898:          p[0].cur_end = 0;
                    899:        }
                    900:        if (pos >= top_pos + top_len) p[0].path_len = CORD_POS_INVALID;
                    901: }
                    902: 
                    903: char CORD__pos_fetch(register CORD_pos p)
                    904: {
                    905:     /* Leaf is a function node */
                    906:     struct CORD_pe * pe = &((p)[0].path[(p)[0].path_len]);
                    907:     CORD leaf = pe -> pe_cord;
                    908:     register struct Function * f = &(((CordRep *)leaf) -> function);
                    909:     
                    910:     if (!IS_FUNCTION(leaf)) ABORT("CORD_pos_fetch: bad leaf");
                    911:     return ((*(f -> fn))(p[0].cur_pos - pe -> pe_start_pos, f -> client_data));
                    912: }
                    913: 
                    914: void CORD__next(register CORD_pos p)
                    915: {
                    916:     register size_t cur_pos = p[0].cur_pos + 1;
                    917:     register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
                    918:     register CORD leaf = current_pe -> pe_cord;
                    919:     
                    920:     /* Leaf is not a string or we're at end of leaf */
                    921:     p[0].cur_pos = cur_pos;
                    922:     if (!CORD_IS_STRING(leaf)) {
                    923:        /* Function leaf        */
                    924:        register struct Function * f = &(((CordRep *)leaf) -> function);
                    925:        register size_t start_pos = current_pe -> pe_start_pos;
                    926:        register size_t end_pos = start_pos + f -> len;
                    927:        
                    928:        if (cur_pos < end_pos) {
                    929:          /* Fill cache and return. */
                    930:            register size_t i;
                    931:            register size_t limit = cur_pos + FUNCTION_BUF_SZ;
                    932:            register CORD_fn fn = f -> fn;
                    933:            register void * client_data = f -> client_data;
                    934:            
                    935:            if (limit > end_pos) {
                    936:                limit = end_pos;
                    937:            }
                    938:            for (i = cur_pos; i < limit; i++) {
                    939:                p[0].function_buf[i - cur_pos] =
                    940:                        (*fn)(i - start_pos, client_data);
                    941:            }
                    942:            p[0].cur_start = cur_pos;
                    943:            p[0].cur_leaf = p[0].function_buf;
                    944:            p[0].cur_end = limit;
                    945:            return;
                    946:        }
                    947:     }
                    948:     /* End of leaf     */
                    949:     /* Pop the stack until we find two concatenation nodes with the    */
                    950:     /* same start position: this implies we were in left part.         */
                    951:     {
                    952:        while (p[0].path_len > 0
                    953:               && current_pe[0].pe_start_pos != current_pe[-1].pe_start_pos) {
                    954:            p[0].path_len--;
                    955:            current_pe--;
                    956:        }
                    957:        if (p[0].path_len == 0) {
                    958:            p[0].path_len = CORD_POS_INVALID;
                    959:             return;
                    960:        }
                    961:     }
                    962:     p[0].path_len--;
                    963:     CORD__extend_path(p);
                    964: }
                    965: 
                    966: void CORD__prev(register CORD_pos p)
                    967: {
                    968:     register struct CORD_pe * pe = &(p[0].path[p[0].path_len]);
                    969:     
                    970:     if (p[0].cur_pos == 0) {
                    971:         p[0].path_len = CORD_POS_INVALID;
                    972:         return;
                    973:     }
                    974:     p[0].cur_pos--;
                    975:     if (p[0].cur_pos >= pe -> pe_start_pos) return;
                    976:     
                    977:     /* Beginning of leaf       */
                    978:     
                    979:     /* Pop the stack until we find two concatenation nodes with the    */
                    980:     /* different start position: this implies we were in right part.   */
                    981:     {
                    982:        register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
                    983:        
                    984:        while (p[0].path_len > 0
                    985:               && current_pe[0].pe_start_pos == current_pe[-1].pe_start_pos) {
                    986:            p[0].path_len--;
                    987:            current_pe--;
                    988:        }
                    989:     }
                    990:     p[0].path_len--;
                    991:     CORD__extend_path(p);
                    992: }
                    993: 
                    994: #undef CORD_pos_fetch
                    995: #undef CORD_next
                    996: #undef CORD_prev
                    997: #undef CORD_pos_to_index
                    998: #undef CORD_pos_to_cord
                    999: #undef CORD_pos_valid
                   1000: 
                   1001: char CORD_pos_fetch(register CORD_pos p)
                   1002: {
                   1003:     if (p[0].cur_start <= p[0].cur_pos && p[0].cur_pos < p[0].cur_end) {
                   1004:        return(p[0].cur_leaf[p[0].cur_pos - p[0].cur_start]);
                   1005:     } else {
                   1006:         return(CORD__pos_fetch(p));
                   1007:     }
                   1008: }
                   1009: 
                   1010: void CORD_next(CORD_pos p)
                   1011: {
                   1012:     if (p[0].cur_pos < p[0].cur_end - 1) {
                   1013:        p[0].cur_pos++;
                   1014:     } else {
                   1015:        CORD__next(p);
                   1016:     }
                   1017: }
                   1018: 
                   1019: void CORD_prev(CORD_pos p)
                   1020: {
                   1021:     if (p[0].cur_end != 0 && p[0].cur_pos > p[0].cur_start) {
                   1022:        p[0].cur_pos--;
                   1023:     } else {
                   1024:        CORD__prev(p);
                   1025:     }
                   1026: }
                   1027: 
                   1028: size_t CORD_pos_to_index(CORD_pos p)
                   1029: {
                   1030:     return(p[0].cur_pos);
                   1031: }
                   1032: 
                   1033: CORD CORD_pos_to_cord(CORD_pos p)
                   1034: {
                   1035:     return(p[0].path[0].pe_cord);
                   1036: }
                   1037: 
                   1038: int CORD_pos_valid(CORD_pos p)
                   1039: {
                   1040:     return(p[0].path_len != CORD_POS_INVALID);
                   1041: }
                   1042: 
                   1043: void CORD_set_pos(CORD_pos p, CORD x, size_t i)
                   1044: {
                   1045:     if (x == CORD_EMPTY) {
                   1046:        p[0].path_len = CORD_POS_INVALID;
                   1047:        return;
                   1048:     }
                   1049:     p[0].path[0].pe_cord = x;
                   1050:     p[0].path[0].pe_start_pos = 0;
                   1051:     p[0].path_len = 0;
                   1052:     p[0].cur_pos = i;
                   1053:     CORD__extend_path(p);
                   1054: }

E-mail: