Annotation of parser3/src/main/pa_string.C, revision 1.279

1.45      paf         1: /** @file
1.174     paf         2:        Parser: string class. @see untalength_t.C.
1.46      paf         3: 
1.277     moko        4:        Copyright (c) 2001-2024 Art. Lebedev Studio (http://www.artlebedev.com)
1.269     moko        5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.164     paf         6: */
1.46      paf         7: 
1.12      paf         8: #include "pa_string.h"
1.22      paf         9: #include "pa_exception.h"
1.61      paf        10: #include "pa_table.h"
1.101     parser     11: #include "pa_dictionary.h"
1.132     paf        12: #include "pa_charset.h"
1.222     misha      13: #include "pa_vregex.h"
1.215     misha      14: 
1.279   ! moko       15: volatile const char * IDENT_PA_STRING_C="$Id: pa_string.C,v 1.278 2024/11/10 20:28:15 moko Exp $" IDENT_PA_STRING_H;
1.240     moko       16: 
1.185     paf        17: const String String::Empty;
                     18: 
1.262     moko       19: #define COMPILE_ASSERT(x) extern int assert_checker[(x) ? 1 : -1]
1.261     moko       20: COMPILE_ASSERT(sizeof(String::Languages) == sizeof(CORD));
                     21: 
1.242     moko       22: // pa_atoui is based on Manuel Novoa III _strto_l for uClibc
                     23: 
1.249     moko       24: template<typename T> inline T pa_ato_any(const char *str, int base, const String* problem_source,const T max){
                     25:        T result = 0;
1.242     moko       26:        const char *pos = str;
                     27: 
                     28:        while (isspace(*pos)) /* skip leading whitespace */
                     29:                ++pos;
                     30: 
                     31:        if (base == 16 && *pos == '0') { /* handle option prefix */
                     32:                ++pos;
                     33:                if (*pos == 'x' || *pos == 'X') {
                     34:                        ++pos;
                     35:                }
                     36:        }
                     37: 
                     38:        if (base == 0) { /* dynamic base */
                     39:                base = 10; /* default is 10 */
                     40:                if (*pos == '0') {
                     41:                        ++pos;
1.245     moko       42:                        if (*pos == 'x' || *pos == 'X'){
1.242     moko       43:                                ++pos;
                     44:                                base=16;
1.245     moko       45:                        }
1.242     moko       46:                }
                     47:        }
                     48: 
1.274     moko       49:        if (base < 2 || base > 16) /* illegal base */
1.242     moko       50:                throw Exception(PARSER_RUNTIME, 0, "base to must be an integer from 2 to 16");
1.274     moko       51:        if (*pos == '-')
                     52:                throw Exception("number.format", problem_source, problem_source ? "out of range (negative)" : "'%s' is out if range (negative)", str);
1.242     moko       53: 
1.249     moko       54:        T cutoff = max / base;
                     55:        int cutoff_digit = (int)(max - cutoff * base);
1.242     moko       56: 
                     57:        while(true) {
                     58:                int digit;
                     59:                
                     60:                if ((*pos >= '0') && (*pos <= '9')) {
                     61:                        digit = (*pos - '0');
                     62:                } else if (*pos >= 'a') {
                     63:                        digit = (*pos - 'a' + 10);
                     64:                } else if (*pos >= 'A') {
                     65:                        digit = (*pos - 'A' + 10);
                     66:                } else break;
                     67: 
                     68:                if (digit >= base) {
                     69:                        break;
                     70:                }
                     71:                
                     72:                ++pos;
                     73:                
                     74:                /* adjust number, with overflow check */
                     75:                if ((result > cutoff) || ((result == cutoff) && (digit > cutoff_digit))) {
                     76:                        throw Exception("number.format", problem_source, problem_source ? "out of range (int)" : "'%s' is out of range (int)", str);
                     77:                } else {
                     78:                        result  = result * base + digit;
                     79:                }
                     80:        }
                     81: 
                     82:        while(char c=*pos++)
                     83:                if(!isspace(c))
1.274     moko       84:                        throw Exception("number.format", problem_source, problem_source ? "invalid number (int)" : "'%s' is an invalid number (int)", str);
1.242     moko       85: 
                     86:        return result;
                     87: }
                     88: 
1.249     moko       89: unsigned int pa_atoui(const char *str, int base, const String* problem_source){
1.263     moko       90:        if(!str)
                     91:                return 0;
                     92: 
1.254     moko       93:        return pa_ato_any<unsigned int>(str, base, problem_source, UINT_MAX);
1.249     moko       94: }
                     95: 
1.265     moko       96: uint64_t pa_atoul(const char *str, int base, const String* problem_source){
1.263     moko       97:        if(!str)
                     98:                return 0;
                     99: 
1.265     moko      100:        return pa_ato_any<uint64_t>(str, base, problem_source, ULLONG_MAX);
1.249     moko      101: }
                    102: 
1.264     moko      103: int pa_atoi(const char* str, int base, const String* problem_source) {
1.193     paf       104:        if(!str)
                    105:                return 0;
                    106: 
1.242     moko      107:        while(isspace(*str))
1.193     paf       108:                str++;
1.242     moko      109: 
1.193     paf       110:        if(!*str)
                    111:                return 0;
                    112: 
1.270     moko      113:        const char *str_copy=str;
1.200     paf       114:        bool negative=false;
                    115:        if(str[0]=='-') {
                    116:                negative=true;
                    117:                str++;
1.270     moko      118:                if(!*str || isspace(*str))
1.276     moko      119:                        throw Exception("number.format", problem_source, problem_source ? "invalid number (int)" : "'%s' is an invalid number (int)", str_copy);
1.200     paf       120:        } else if(str[0]=='+') {
                    121:                str++;
1.270     moko      122:                if(!*str || isspace(*str))
1.276     moko      123:                        throw Exception("number.format", problem_source, problem_source ? "invalid number (int)" : "'%s' is an invalid number (int)", str_copy);
1.200     paf       124:        }
1.193     paf       125: 
1.264     moko      126:        unsigned int result=pa_atoui(str, base, problem_source);
1.193     paf       127: 
1.242     moko      128:        if(negative && result <= ((unsigned int)(-(1+INT_MIN)))+1)
1.243     moko      129:                return -(int)result;
1.242     moko      130:        
                    131:        if(result<=INT_MAX)
1.243     moko      132:                return (int)result;
1.270     moko      133: 
                    134:        throw Exception("number.format", problem_source, problem_source ? "out of range (int)" : "'%s' is out of range (int)", str_copy);
1.193     paf       135: }
                    136: 
1.270     moko      137: double pa_atod(const char* str, const String* problem_source /* never null */) {
1.193     paf       138:        if(!str)
                    139:                return 0;
                    140: 
1.242     moko      141:        while(isspace(*str))
1.193     paf       142:                str++;
1.242     moko      143: 
1.193     paf       144:        if(!*str)
                    145:                return 0;
                    146: 
1.200     paf       147:        bool negative=false;
                    148:        if(str[0]=='-') {
                    149:                negative=true;
                    150:                str++;
1.270     moko      151:                if(!*str || isspace(*str))
                    152:                        throw Exception("number.format", problem_source, "invalid number (double)");
1.200     paf       153:        } else if(str[0]=='+') {
                    154:                str++;
1.270     moko      155:                if(!*str || isspace(*str))
                    156:                        throw Exception("number.format", problem_source, "invalid number (double)");
1.200     paf       157:        }
1.242     moko      158: 
                    159:        double result;
1.247     moko      160:        if(str[0]=='0') {
                    161:                if(str[1]=='x' || str[1]=='X') {
1.242     moko      162:                        // 0xABC
1.249     moko      163:                        result=(double)pa_atoul(str, 0, problem_source);
1.242     moko      164:                        return negative ? -result : result;
                    165:                } else {
1.200     paf       166:                         // skip leading 0000, to disable octal interpretation
1.242     moko      167:                        do str++; while(*str=='0');
1.200     paf       168:                }
1.247     moko      169:        }
1.242     moko      170: 
                    171:        char *error_pos;
                    172:        result=strtod(str, &error_pos);
1.193     paf       173: 
1.270     moko      174:        while(const char c=*error_pos++)
                    175:                if(!isspace(c))
                    176:                        throw Exception("number.format", problem_source, "invalid number (double)");
1.193     paf       177: 
1.242     moko      178:        return negative ? -result : result;
1.193     paf       179: }
                    180: 
1.176     paf       181: // cord lib extension
                    182: 
                    183: #ifndef DOXYGEN
                    184: typedef struct {
1.254     moko      185:        ssize_t countdown;
                    186:        int target;     /* Character we're looking for  */
1.176     paf       187: } chr_data;
                    188: #endif
1.248     moko      189: 
1.176     paf       190: static int CORD_range_contains_chr_greater_then_proc(char c, size_t size, void* client_data)
                    191: {
1.272     moko      192:        chr_data * d = (chr_data *)client_data;
1.254     moko      193: 
                    194:        if (d -> countdown<=0) return(2);
                    195:        d -> countdown -= size;
                    196:        if (c > d -> target) return(1);
                    197:        return(0);
1.176     paf       198: }
1.248     moko      199: 
1.176     paf       200: int CORD_range_contains_chr_greater_then(CORD x, size_t i, size_t n, int c)
                    201: {
1.254     moko      202:        chr_data d;
1.176     paf       203: 
1.254     moko      204:        d.countdown = n;
                    205:        d.target = c;
                    206:        return(CORD_block_iter(x, i, CORD_range_contains_chr_greater_then_proc, &d) == 1/*alternatives: 0 normally ended, 2=struck 'n'*/);
1.176     paf       207: }
                    208: 
1.187     paf       209: static int CORD_block_count_proc(char /*c*/, size_t /*size*/, void* client_data)
1.178     paf       210: {
1.254     moko      211:        int* result=(int*)client_data;
                    212:        (*result)++;
                    213:        return(0); // 0=continue
1.178     paf       214: }
1.248     moko      215: 
1.178     paf       216: size_t CORD_block_count(CORD x)
                    217: {
                    218:        size_t result=0;
                    219:        CORD_block_iter(x, 0, CORD_block_count_proc, &result);
1.254     moko      220:        return result;
1.178     paf       221: }
                    222: 
1.174     paf       223: // helpers
1.139     paf       224: 
1.174     paf       225: /// String::match uses this as replace & global search table columns
1.139     paf       226: 
1.174     paf       227: const int MAX_MATCH_GROUPS=100;
1.139     paf       228: 
1.174     paf       229: class String_match_table_template_columns: public ArrayString {
                    230: public:
                    231:        String_match_table_template_columns() {
                    232:                *this+=new String("prematch");
                    233:                *this+=new String("match");
                    234:                *this+=new String("postmatch");
                    235:                for(int i=0; i<MAX_MATCH_GROUPS; i++) {
1.273     moko      236:                        *this+=new String(pa_uitoa(1+i), String::L_CLEAN);
1.174     paf       237:                }
                    238:        }
                    239: };
                    240: 
1.278     moko      241: static Table &string_match_table_template(){
                    242:        static Table *singleton=NULL;
1.279   ! moko      243:        if(singleton==NULL)
1.278     moko      244:                singleton=new Table(new String_match_table_template_columns);
                    245:        return *singleton;
                    246: }
1.174     paf       247: 
1.176     paf       248: // String::Body methods
1.140     paf       249: 
1.254     moko      250: String::Body String::Body::trim(String::Trim_kind kind, const char* chars, size_t* out_start, size_t* out_length, Charset* source_charset) const {
1.195     paf       251:        size_t our_length=length();
                    252:        if(!our_length)
                    253:                return *this;
1.229     misha     254: 
                    255:        // check if any UTF-8 in chars
                    256:        bool fast=true;
                    257:        if(chars && source_charset && source_charset->isUTF8()){
                    258:                const char* pos=chars;
                    259:                while(unsigned char c=*pos++)
                    260:                        if(c>127){
                    261:                                fast=false;
                    262:                                break;
                    263:                        }
                    264:        }
                    265: 
                    266:        size_t start=0;
                    267:        size_t end=our_length;
1.195     paf       268:        if(!chars)
                    269:                chars=" \t\n"; // white space
                    270: 
1.229     misha     271:        if(fast){
                    272:                // from left...
                    273:                if(kind!=TRIM_END) {
                    274:                        CORD_pos pos; set_pos(pos, 0);
                    275:                        while(true) {
                    276:                                char c=CORD_pos_fetch(pos);
                    277:                                if(strchr(chars, c)) {
                    278:                                        if(++start==our_length)
                    279:                                                return 0; // all chars are empty, just return empty string
                    280:                                } else
                    281:                                        break;                  
                    282: 
                    283:                                CORD_next(pos);
                    284:                        }
                    285:                }
                    286: 
                    287:                // from right..
                    288:                if(kind!=TRIM_START) {
                    289:                        CORD_pos pos; set_pos(pos, end-1);
                    290:                        while(true) {
                    291:                                char c=CORD_pos_fetch(pos);
                    292:                                if(strchr(chars, c)) {
                    293:                                        if(--end==0) // optimization: NO need to check for 'end>=start', that's(<) impossible
                    294:                                                return 0; // all chars are empty, just return empty string
                    295:                                } else
                    296:                                        break;                  
                    297: 
                    298:                                CORD_prev(pos);
                    299:                        }
                    300:                }
                    301:        } else {
1.234     misha     302:                const XMLByte* src_begin=(const XMLByte*)cstr();
1.229     misha     303:                const XMLByte* src_end=src_begin+our_length;
                    304: 
                    305:                // from left...
                    306:                if(kind!=TRIM_END) {
                    307:                        while(src_begin<src_end){
                    308:                                uint char_length=1;
                    309:                                const XMLByte* ptr=src_begin;
1.231     misha     310:                                // searching first UTF-8 byte: http://tools.ietf.org/html/rfc3629#section-3
                    311:                                while(++src_begin<=src_end && (*src_begin>127 && *src_begin<0xC0))
1.229     misha     312:                                        char_length++;
                    313: 
                    314:                                bool found=false;
                    315:                                for(const char* chars_byte=chars; chars_byte=strchr(chars_byte, *ptr); chars_byte++)
                    316:                                        if(strncmp(chars_byte, (const char*)ptr, char_length)==0){
                    317:                                                found=true;
                    318:                                                break;
                    319:                                        }
                    320: 
                    321:                                if(found){
                    322:                                        start+=char_length;
                    323:                                        if(start==our_length)
                    324:                                                return 0; // all chars are empty, just return empty string
                    325:                                } else
                    326:                                        break;
                    327:                        }
                    328:                }
1.196     paf       329: 
1.229     misha     330:                // from right..
                    331:                if(kind!=TRIM_START) {
                    332:                        while(src_begin<src_end){
                    333:                                uint char_length=1;
1.231     misha     334:                                // searching first UTF-8 byte: http://tools.ietf.org/html/rfc3629#section-3
                    335:                                while(src_begin<=--src_end && (*src_end>127 && *src_end<0xC0))
1.229     misha     336:                                        char_length++;
                    337: 
                    338:                                bool found=false;
                    339:                                for(const char* chars_byte=chars; chars_byte=strchr(chars_byte, *src_end); chars_byte++)
                    340:                                        if(strncmp(chars_byte, (const char*)src_end, char_length)==0){
                    341:                                                found=true;
                    342:                                                break;
                    343:                                        }
                    344: 
                    345:                                if(found){
                    346:                                        end-=char_length;
                    347:                                        if(end==0)
                    348:                                                return 0; // all chars are empty, just return empty string
                    349:                                } else
                    350:                                        break;
                    351:                        }
1.196     paf       352:                }
                    353:        }
1.195     paf       354: 
                    355:        if(start==0 && end==our_length) // nobody moved a thing
                    356:                return *this;
                    357: 
                    358:        if(out_start)
                    359:                *out_start=start;
                    360:        size_t new_length=end-start;
                    361:        if(out_length)
                    362:                *out_length=new_length;
                    363: 
                    364:        return mid(start, new_length);
                    365: }
                    366: 
1.174     paf       367: static int CORD_batched_iter_fn_generic_hash_code(char c, void * client_data) {
                    368:        uint& result=*static_cast<uint*>(client_data);
                    369:        generic_hash_code(result, c);
                    370:        return 0;
                    371: }
1.248     moko      372: 
1.174     paf       373: static int CORD_batched_iter_fn_generic_hash_code(const char*  s, void * client_data) {
                    374:        uint& result=*static_cast<uint*>(client_data);
                    375:        generic_hash_code(result, s);
                    376:        return 0;
1.248     moko      377: }
                    378: 
1.225     misha     379: uint String::Body::get_hash_code() const {
                    380: #ifdef HASH_CODE_CACHING
                    381:        if(hash_code)
                    382:                return hash_code;
                    383: #else
                    384:        uint hash_code=0;
                    385: #endif
1.220     misha     386:        if (body && CORD_IS_STRING(body)){
1.250     moko      387:                generic_hash_code(hash_code, (const char *)body);
1.220     misha     388:        } else {
                    389:                CORD_iter5(body, 0,
                    390:                        CORD_batched_iter_fn_generic_hash_code, 
1.225     misha     391:                        CORD_batched_iter_fn_generic_hash_code, &hash_code);
1.220     misha     392:        }
1.225     misha     393:        return hash_code;
1.94      parser    394: }
                    395: 
1.241     misha     396: struct CORD_pos_info {
                    397:        const char* chars;
                    398:        size_t left;
                    399:        size_t pos;
                    400: };
                    401: 
                    402: // can be called only for IS_FUNCTION(CORD) which is used in String::Body::strrpbrk
                    403: static int CORD_iter_fn_rpos(char c, CORD_pos_info* info) {
                    404:        if(info->pos < info->left){
                    405:                info->pos=STRING_NOT_FOUND;
                    406:                return 1;
                    407:        }
                    408:        if(strchr(info->chars, c))
                    409:                return 1;
                    410:        --(info->pos);
                    411:        return 0;
                    412: }
                    413: 
                    414: size_t String::Body::strrpbrk(const char* chars, size_t left, size_t right) const {
                    415:        if(is_empty() || !chars || !strlen(chars))
                    416:                return STRING_NOT_FOUND;
                    417:        CORD_pos_info info={chars, left, right};
                    418:        if(CORD_riter4(body, right, (CORD_iter_fn)CORD_iter_fn_rpos, &info))
                    419:                return info.pos;
                    420:        else
                    421:                return STRING_NOT_FOUND;
                    422: }
                    423: 
                    424: 
                    425: // can be called only for IS_FUNCTION(CORD) which is used in String::Body::rskipchars
                    426: static int CORD_iter_fn_rskip(char c, CORD_pos_info* info) {
                    427:        if(info->pos < info->left) {
                    428:                info->pos=STRING_NOT_FOUND;
                    429:                return 1;
                    430:        }
                    431:        if(!strchr(info->chars, c))
                    432:                return 1;
                    433:        --(info->pos);
                    434:        return 0;
                    435: }
                    436: 
                    437: size_t String::Body::rskipchars(const char* chars, size_t left, size_t right) const {
                    438:        if(is_empty() || !chars || !strlen(chars))
                    439:                return STRING_NOT_FOUND;
                    440:        CORD_pos_info info={chars, left, right};
                    441:        if(CORD_riter4(body, right, (CORD_iter_fn)CORD_iter_fn_rskip, &info))
                    442:                return info.pos;
                    443:        else
                    444:                return STRING_NOT_FOUND;
                    445: }
                    446: 
1.174     paf       447: // String methods
                    448: 
                    449: String& String::append_know_length(const char* str, size_t known_length, Language lang) {
                    450:        if(!known_length)
1.9       paf       451:                return *this;
1.122     paf       452: 
1.176     paf       453:        // first: langs
                    454:        langs.append(body, lang, known_length);
                    455:        // next: letters themselves
1.174     paf       456:        body.append_know_length(str, known_length);
1.1       paf       457: 
1.174     paf       458:        ASSERT_STRING_INVARIANT(*this);
1.1       paf       459:        return *this;
                    460: }
1.248     moko      461: 
1.174     paf       462: String& String::append_help_length(const char* str, size_t helper_length, Language lang) {
                    463:        if(!str)
                    464:                return *this;
                    465:        size_t known_length=helper_length?helper_length:strlen(str);
                    466:        if(!known_length)
                    467:                return *this;
1.1       paf       468: 
1.174     paf       469:        return append_know_length(str, known_length, lang);
1.5       paf       470: }
1.248     moko      471: 
1.244     moko      472: String::String(int value, const char *format) : langs(L_CLEAN){
1.226     misha     473:        char buf[MAX_NUMBER];
                    474:        body.append_strdup_know_length(buf, snprintf(buf, MAX_NUMBER, format, value));
                    475: }
1.248     moko      476: 
1.174     paf       477: String& String::append_strdup(const char* str, size_t helper_length, Language lang) {
                    478:        size_t known_length=helper_length?helper_length:strlen(str);
                    479:        if(!known_length)
                    480:                return *this;
1.5       paf       481: 
1.176     paf       482:        // first: langs
                    483:        langs.append(body, lang, known_length);
                    484:        // next: letters themselves
1.174     paf       485:        body.append_strdup_know_length(str, known_length);
1.33      paf       486: 
1.174     paf       487:        ASSERT_STRING_INVARIANT(*this);
                    488:        return *this;
1.5       paf       489: }
1.46      paf       490: 
1.234     misha     491: struct CORD_length_info {
                    492:        size_t len;
                    493:        size_t skip;
                    494: };
                    495: 
                    496: int CORD_batched_len(const char* s, CORD_length_info* info){
1.255     moko      497:        info->len += lengthUTF8( (const XMLByte *)s, (const XMLByte *)s+strlen(s));
                    498:        return 0;
1.221     misha     499: }
                    500: 
1.234     misha     501: // can be called only for IS_FUNCTION(CORD) which are used in large String::Body::mid
                    502: int CORD_batched_len(const char c, CORD_length_info* info){
                    503:        if (info->skip==0){
                    504:                info->len++;
                    505:                info->skip = lengthUTF8Char(c)-1;
                    506:        } else {
                    507:                info->skip--;
                    508:        }
1.220     misha     509:        return 0;
                    510: }
                    511: 
1.210     misha     512: size_t String::length(Charset& charset) const {
                    513:        if(charset.isUTF8()){
1.234     misha     514:                CORD_length_info info = {0, 0};
                    515:                body.for_each<CORD_length_info *>(CORD_batched_len, CORD_batched_len, &info);
                    516:                return info.len;
1.210     misha     517:        } else
                    518:                return body.length();
                    519: }
                    520: 
1.174     paf       521: /// @todo check in doc: whether it documents NOW bad situation "abc".mid(-1, 3) =were?="ab"
                    522: String& String::mid(size_t substr_begin, size_t substr_end) const {
                    523:        String& result=*new String;
                    524: 
                    525:        size_t self_length=length();
                    526:        substr_begin=min(substr_begin, self_length);
                    527:        substr_end=min(max(substr_end, substr_begin), self_length);
1.176     paf       528:        size_t substr_length=substr_end-substr_begin;
                    529:        if(!substr_length)
1.107     parser    530:                return result;
1.53      paf       531: 
1.176     paf       532:        // first: their langs
                    533:        result.langs.append(result.body, langs, substr_begin, substr_length);
                    534:        // next: letters themselves
                    535:        result.body=body.mid(substr_begin, substr_length);
1.174     paf       536: 
                    537:        ASSERT_STRING_INVARIANT(result);
1.53      paf       538:        return result;
1.54      paf       539: }
                    540: 
1.211     misha     541: // from, to and helper_length in characters, not in bytes (it's important for utf-8)
                    542: String& String::mid(Charset& charset, size_t from, size_t to, size_t helper_length) const {
1.210     misha     543:        String& result=*new String;
                    544: 
1.255     moko      545:        size_t self_length=helper_length ? helper_length : length(charset);
1.211     misha     546: 
                    547:        if(!self_length)
                    548:                return result;
                    549: 
                    550:        from=min(min(to, from), self_length);
1.210     misha     551:        to=min(max(to, from), self_length);
1.211     misha     552: 
1.210     misha     553:        size_t substr_length=to-from;
1.211     misha     554: 
1.210     misha     555:        if(!substr_length)
                    556:                return result;
                    557: 
                    558:        if(charset.isUTF8()){
1.234     misha     559:                const XMLByte* src_begin=(const XMLByte*)cstr();
1.230     misha     560:                const XMLByte* src_end=src_begin+body.length();
1.210     misha     561: 
1.212     misha     562:                // convert 'from' and 'substr_length' from 'characters' to 'bytes'
1.230     misha     563:                from=getUTF8BytePos(src_begin, src_end, from);
                    564:                substr_length=getUTF8BytePos(src_begin+from, src_end, substr_length);
1.210     misha     565:                if(!substr_length)
                    566:                        return result;
                    567:        }
                    568: 
                    569:        // first: their langs
                    570:        result.langs.append(result.body, langs, from, substr_length);
                    571:        // next: letters themselves
                    572:        result.body=body.mid(from, substr_length);
                    573: 
                    574:        ASSERT_STRING_INVARIANT(result);
                    575:        return result;
                    576: }
                    577: 
1.176     paf       578: size_t String::pos(const String::Body substr, size_t this_offset, Language lang) const {
1.183     paf       579:        size_t substr_length=substr.length();
                    580:        while(true) {
                    581:                size_t substr_begin=body.pos(substr, this_offset);
                    582:                
                    583:                if(substr_begin==CORD_NOT_FOUND)
                    584:                        return STRING_NOT_FOUND;
1.174     paf       585: 
1.183     paf       586:                if(langs.check_lang(lang, substr_begin, substr_length))
                    587:                        return substr_begin;
                    588: 
                    589:                this_offset=substr_begin+substr_length;
                    590:        }
1.58      paf       591: }
                    592: 
1.254     moko      593: size_t String::pos(const String& substr, size_t this_offset, Language lang) const {
1.174     paf       594:        return pos(substr.body, this_offset, lang);
1.60      paf       595: }
                    596: 
1.254     moko      597: size_t String::pos(Charset& charset, const String& substr, size_t this_offset, Language lang) const {
1.210     misha     598: 
                    599:        if(charset.isUTF8()){
1.234     misha     600:                const XMLByte* srcPtr=(const XMLByte*)cstr();
1.212     misha     601:                const XMLByte* srcEnd=srcPtr+body.length();
                    602: 
                    603:                // convert 'this_offset' from 'characters' to 'bytes'
                    604:                this_offset=getUTF8BytePos(srcPtr, srcEnd, this_offset);
                    605: 
1.229     misha     606:                size_t result=pos(substr.body, this_offset, lang);
                    607:                return (result==CORD_NOT_FOUND)
                    608:                        ? STRING_NOT_FOUND
                    609:                        : getUTF8CharPos(srcPtr, srcEnd, result); // convert 'result' from 'bytes' to 'characters'
1.212     misha     610:        } else {
1.229     misha     611:                size_t result=pos(substr.body, this_offset, lang);
                    612:                return (result==CORD_NOT_FOUND)
                    613:                        ? STRING_NOT_FOUND
                    614:                        : result;
1.210     misha     615:        }
                    616: }
                    617: 
1.256     moko      618: void String::split(ArrayString& result, size_t pos_after, const char* delim, Language lang) const {
1.237     misha     619:        if(is_empty())
                    620:                return;
1.174     paf       621:        size_t self_length=length();
1.237     misha     622:        if(size_t delim_length=strlen(delim)) {
1.186     paf       623:                size_t pos_before;
1.60      paf       624:                // while we have 'delim'...
1.256     moko      625:                while((pos_before=pos(delim, pos_after, lang))!=STRING_NOT_FOUND) {
1.69      paf       626:                        result+=&mid(pos_after, pos_before);
1.174     paf       627:                        pos_after=pos_before+delim_length;
1.60      paf       628:                }
                    629:                // last piece
1.256     moko      630:                if(pos_after<self_length)
1.174     paf       631:                        result+=&mid(pos_after, self_length);
1.60      paf       632:        } else { // empty delim
                    633:                result+=this;
                    634:        }
                    635: }
                    636: 
1.256     moko      637: void String::split(ArrayString& result, size_t pos_after, const String& delim, Language lang) const {
1.237     misha     638:        if(is_empty())
                    639:                return;
                    640:        if(!delim.is_empty()) {
1.186     paf       641:                size_t pos_before;
1.60      paf       642:                // while we have 'delim'...
1.256     moko      643:                while((pos_before=pos(delim, pos_after, lang))!=STRING_NOT_FOUND) {
1.69      paf       644:                        result+=&mid(pos_after, pos_before);
1.174     paf       645:                        pos_after=pos_before+delim.length();
1.60      paf       646:                }
                    647:                // last piece
1.256     moko      648:                if(pos_after<length())
1.174     paf       649:                        result+=&mid(pos_after, length());
1.60      paf       650:        } else { // empty delim
                    651:                result+=this;
                    652:        }
1.61      paf       653: }
                    654: 
1.254     moko      655: Table* String::match(VRegex* vregex, Row_action row_action, void *info, int& matches_count) const {
1.209     misha     656: 
1.222     misha     657:        // vregex->info(); // I have no idea what does it for?
1.63      paf       658: 
1.222     misha     659:        bool need_pre_post_match=vregex->is_pre_post_match_needed();
                    660:        bool global=vregex->is_global_search();
1.63      paf       661: 
1.174     paf       662:        const char* subject=cstr();
1.234     misha     663:        size_t subject_length=length();
1.271     moko      664:        const int ovector_size=(1/*match*/+MAX_MATCH_GROUPS)*3; /* 1/3 is used as workspace by pcre_exec() */
1.222     misha     665:        int ovector[ovector_size];
1.155     paf       666: 
1.173     paf       667:        Table::Action_options table_options;
1.278     moko      668:        Table& table=*new Table(string_match_table_template(), table_options);
1.63      paf       669: 
1.154     paf       670:        int prestart=0;
                    671:        int poststart=0;
1.174     paf       672:        int postfinish=length();
1.267     moko      673:        int action_was_executed=-1;
1.63      paf       674:        while(true) {
1.222     misha     675:                int exec_result=vregex->exec(subject, subject_length, ovector, ovector_size, prestart);
1.63      paf       676: 
1.222     misha     677:                if(exec_result<0) // only PCRE_ERROR_NOMATCH might be here, other negative results cause an exception
                    678:                        break;
1.63      paf       679: 
1.154     paf       680:                int prefinish=ovector[0];
                    681:                poststart=ovector[1];
1.236     moko      682: 
1.267     moko      683:                if (prestart==poststart && action_was_executed==1){
1.236     moko      684:                        prestart++;
1.267     moko      685:                        action_was_executed=0;
1.236     moko      686:                        continue;
                    687:                }
                    688: 
1.232     misha     689:                ArrayString* row=new ArrayString(3);
1.174     paf       690:                if(need_pre_post_match) {
                    691:                        *row+=&mid(0, prefinish); // .prematch column value
                    692:                        *row+=&mid(prefinish, poststart); // .match
                    693:                        *row+=&mid(poststart, postfinish); // .postmatch
                    694:                } else {
1.185     paf       695:                        *row+=&Empty; // .prematch column value
                    696:                        *row+=&Empty; // .match
                    697:                        *row+=&Empty; // .postmatch
1.174     paf       698:                }
1.63      paf       699:                
1.222     misha     700:                for(int i=1; i<exec_result; i++) {
1.69      paf       701:                        // -1:-1 case handled peacefully by mid() itself
1.232     misha     702:                        *row+=(ovector[i*2+0]>=0 && ovector[i*2+1]>0)?&mid(ovector[i*2+0], ovector[i*2+1]):new String; // .i column value
1.63      paf       703:                }
                    704:                
1.209     misha     705:                matches_count++;
1.267     moko      706:                row_action(table, row, prestart - !action_was_executed, prefinish, poststart, postfinish, info);
1.63      paf       707: 
1.275     moko      708:                if(!global || (size_t)poststart>=subject_length) // last step, avoid prestart++ after last char
1.222     misha     709:                        break;
                    710: 
1.154     paf       711:                prestart=poststart;
1.267     moko      712:                action_was_executed=1;
1.222     misha     713:        }
1.63      paf       714: 
1.222     misha     715:        row_action(table, 0/*last time, no raw*/, 0, 0, poststart, postfinish, info);
                    716:        return vregex->is_just_count() ? 0 : &table;
1.82      parser    717: }
                    718: 
1.174     paf       719: String& String::change_case(Charset& source_charset, Change_case_kind kind) const {
                    720:        String& result=*new String();
                    721:        if(is_empty())
                    722:                return result;
                    723: 
                    724:        char* new_cstr=cstrm();
1.216     misha     725: 
1.181     paf       726:        if(source_charset.isUTF8()) {
1.216     misha     727:                size_t new_cstr_len=length();
1.181     paf       728:                switch(kind) {
                    729:                case CC_UPPER:
1.192     paf       730:                        change_case_UTF8((const XMLByte*)new_cstr, new_cstr_len, (XMLByte*)new_cstr, new_cstr_len, UTF8CaseToUpper);
1.181     paf       731:                        break;
                    732:                case CC_LOWER:
1.192     paf       733:                        change_case_UTF8((const XMLByte*)new_cstr, new_cstr_len, (XMLByte*)new_cstr, new_cstr_len, UTF8CaseToLower);
1.181     paf       734:                        break;
                    735:                default:
                    736:                        assert(!"unknown change case kind");
                    737:                        break; // never
                    738:                }       
                    739:                
                    740:        } else {
                    741:                const unsigned char *tables=source_charset.pcre_tables;
1.82      parser    742: 
1.181     paf       743:                const unsigned char *a;
                    744:                const unsigned char *b;
                    745:                switch(kind) {
                    746:                case CC_UPPER:
                    747:                        a=tables+lcc_offset;
                    748:                        b=tables+fcc_offset;
                    749:                        break;
                    750:                case CC_LOWER:
                    751:                        a=tables+lcc_offset;
                    752:                        b=0;
                    753:                        break;
                    754:                default:
                    755:                        assert(!"unknown change case kind");
                    756:                        a=b=0; // calm, compiler
                    757:                        break; // never
                    758:                }       
                    759: 
1.192     paf       760:                char *dest=new_cstr;
1.181     paf       761:                unsigned char index;
1.190     paf       762:                for(const char* current=new_cstr; (index=(unsigned char)*current); current++) {
1.181     paf       763:                        unsigned char c=a[index];
                    764:                        if(b)
                    765:                                c=b[c];
                    766: 
                    767:                        *dest++=(char)c;
                    768:                }
1.174     paf       769:        }
1.176     paf       770:        result.langs=langs;
1.174     paf       771:        result.body=new_cstr;
1.89      parser    772: 
1.101     parser    773:        return result;
                    774: }
                    775: 
1.213     misha     776: const String& String::escape(Charset& source_charset) const {
                    777:        if(is_empty())
                    778:                return *this;
                    779: 
                    780:        return Charset::escape(*this, source_charset);
                    781: }
                    782: 
1.238     misha     783: #define STRING_APPEND(result, from_cstr, langs, langs_offset, length) \
                    784:                        result.langs.append(result.body, langs, langs_offset, length); \
                    785:                        result.body.append_strdup_know_length(from_cstr, length);
                    786: 
1.174     paf       787: const String& String::replace(const Dictionary& dict) const {
1.238     misha     788:        if(!dict.count() || is_empty())
                    789:                return *this;
                    790: 
1.174     paf       791:        String& result=*new String();
                    792:        const char* old_cstr=cstr();
                    793:        const char* prematch_begin=old_cstr;
                    794: 
1.238     misha     795:        if(dict.count()==1) {
                    796:                // optimized simple case
                    797: 
                    798:                Dictionary::Subst subst=dict.get(0);
1.239     moko      799:                while(const char* p=strstr(prematch_begin, subst.from)) {
1.174     paf       800:                        // prematch
1.238     misha     801:                        if(size_t prematch_length=p-prematch_begin) {
                    802:                                STRING_APPEND(result, prematch_begin, langs, prematch_begin-old_cstr, prematch_length)
1.101     parser    803:                        }
                    804: 
1.174     paf       805:                        // match
1.238     misha     806:                        prematch_begin=p+subst.from_length;
1.174     paf       807: 
1.184     paf       808:                        if(const String* b=subst.to) // are there any b?
1.174     paf       809:                                result<<*b;
1.238     misha     810:                }
                    811: 
                    812:        } else {
                    813: 
                    814:                const char* current=old_cstr;
                    815:                while(*current) {
                    816:                        if(Dictionary::Subst subst=dict.first_that_begins(current)) {
                    817:                                // prematch
                    818:                                if(size_t prematch_length=current-prematch_begin) {
                    819:                                        STRING_APPEND(result, prematch_begin, langs, prematch_begin-old_cstr, prematch_length)
                    820:                                }
                    821: 
                    822:                                // match
                    823:                                // skip 'a' in 'current'; move prematch_begin
                    824:                                current+=subst.from_length; prematch_begin=current;
                    825: 
                    826:                                if(const String* b=subst.to) // are there any b?
                    827:                                        result<<*b;
                    828:                        } else // simply advance
                    829:                                current++; 
                    830:                }
                    831: 
1.174     paf       832:        }
1.156     paf       833: 
1.238     misha     834:        if(prematch_begin==old_cstr) // not modified
                    835:                return *this;
                    836: 
1.174     paf       837:        // postmatch
1.238     misha     838:        if(size_t postmatch_length=old_cstr+length()-prematch_begin) {
                    839:                STRING_APPEND(result, prematch_begin, langs, prematch_begin-old_cstr, postmatch_length)
1.174     paf       840:        }
1.156     paf       841: 
1.174     paf       842:        ASSERT_STRING_INVARIANT(result);
1.82      parser    843:        return result;
1.61      paf       844: }
1.113     parser    845: 
1.180     paf       846: static int serialize_body_char(char c, char** cur) {
                    847:        *((*cur)++)=c;
                    848:        return 0; // 0=continue
1.248     moko      849: }
                    850: 
1.174     paf       851: static int serialize_body_piece(const char* s, char** cur) {
                    852:        size_t length=strlen(s);
                    853:        memcpy(*cur, s, length);  *cur+=length;
1.178     paf       854:        return 0; // 0=continue
1.248     moko      855: }
                    856: 
1.178     paf       857: static int serialize_lang_piece(char alang, size_t asize, char** cur) {
                    858:        // lang
1.191     paf       859:        **cur=alang; (*cur)++;
                    860:        // length [WARNING: not cast, addresses must be %4=0 on sparc]
1.178     paf       861:        memcpy(*cur, &asize, sizeof(asize));  *cur+=sizeof(asize);
                    862: 
                    863:        return 0; // 0=continue
                    864: }
1.248     moko      865: 
1.174     paf       866: String::Cm String::serialize(size_t prolog_length) const {
1.178     paf       867:        size_t fragments_count=langs.count();
1.202     paf       868:        size_t body_length=body.length();
1.174     paf       869:        size_t buf_length=
1.178     paf       870:                prolog_length //1
                    871:                +sizeof(size_t) //2
1.202     paf       872:                +body_length //3
                    873:                +1 // 4 for zero terminator used in deserialize
                    874:                +sizeof(size_t) //5
                    875:                +fragments_count*(sizeof(char)+sizeof(size_t)); //6
                    876: 
1.174     paf       877:        String::Cm result(new(PointerFreeGC) char[buf_length], buf_length);
                    878: 
                    879:        // 1: prolog
                    880:        char *cur=result.str+prolog_length;
1.202     paf       881:        // 2: chars.count [WARNING: not cast, addresses must be %4=0 on sparc]
                    882:        memcpy(cur, &body_length, sizeof(body_length));  cur+=sizeof(body_length);
                    883:        // 3: letters
                    884:        body.for_each(serialize_body_char, serialize_body_piece, &cur);
                    885:        // 4: zero terminator
                    886:        *cur++=0;
                    887:        // 5: langs.count [WARNING: not cast, addresses must be %4=0 on sparc]
1.174     paf       888:        memcpy(cur, &fragments_count, sizeof(fragments_count));  cur+=sizeof(fragments_count);
1.202     paf       889:        // 6: lang info
1.178     paf       890:        langs.for_each(body, serialize_lang_piece, &cur);
1.113     parser    891: 
1.174     paf       892:        return result;
1.113     parser    893: }
1.248     moko      894: 
1.202     paf       895: bool String::deserialize(size_t prolog_size, void *buf, size_t buf_size) {
                    896:        size_t in_buf=buf_size;
                    897:        if(in_buf<=prolog_size)
1.148     paf       898:                return false;
1.202     paf       899:        in_buf-=prolog_size;
1.135     paf       900: 
1.174     paf       901:        // 1: prolog
1.202     paf       902:        const char* cur=(const char* )buf+prolog_size;
1.113     parser    903: 
1.207     paf       904:        // 2: chars.count
1.202     paf       905:        size_t body_length;
                    906:        if(in_buf<sizeof(body_length)) // body.length don't fit?
                    907:                return false;
                    908:        // [WARNING: not cast, addresses must be %4=0 on sparc]
                    909:        memcpy(&body_length, cur, sizeof(body_length));  cur+=sizeof(body_length);
                    910:        in_buf-=sizeof(body_length);
                    911: 
                    912:        if(in_buf<body_length+1) // letters+terminator don't fit?
                    913:                return false;
                    914:        // 4: zero terminator
                    915:        if(cur[body_length] != 0) // in place?
                    916:                return false;
                    917:        // 3: letters
1.251     moko      918:        body=String::Body(String::C(cur, body_length));
1.202     paf       919:        cur+=body_length+1;
                    920:        in_buf-=body_length+1;
                    921: 
                    922:        // 5: langs.count
1.191     paf       923:        size_t fragments_count;
1.202     paf       924:        if(in_buf<sizeof(fragments_count)) // langs.count don't fit?
1.174     paf       925:                return false;
1.191     paf       926:        // [WARNING: not cast, addresses must be %4=0 on sparc]
                    927:        memcpy(&fragments_count, cur, sizeof(fragments_count));  cur+=sizeof(fragments_count);
1.202     paf       928:        in_buf-=sizeof(fragments_count);
1.174     paf       929:        
                    930:        if(fragments_count) {
1.202     paf       931:                // 6: lang info
1.174     paf       932:                size_t total_length=0;
                    933:                for(size_t f=0; f<fragments_count; f++) {
1.191     paf       934:                        char lang;
                    935:                        size_t fragment_length;
                    936:                        size_t piece_length=sizeof(lang)+sizeof(fragment_length);
1.202     paf       937:                        if(in_buf<piece_length) // lang+length
1.174     paf       938:                                return false;
                    939: 
1.191     paf       940:                        // lang
                    941:                        lang=*cur++;
                    942:                        // length [WARNING: not cast, addresses must be %4=0 on sparc]
                    943:                        memcpy(&fragment_length, cur, sizeof(fragment_length));  cur+=sizeof(fragment_length);
                    944: 
1.206     paf       945:                        size_t combined_length=total_length+fragment_length;
                    946:                        if(combined_length>body_length)
                    947:                                return false; // file curruption
1.191     paf       948:                        // uchar needed to prevent propagating 0x80 bit to upper bytes
                    949:                        langs.append(total_length, (String::Language)(uchar)lang, fragment_length);
1.206     paf       950:                        total_length=combined_length;
1.202     paf       951:                        in_buf-=piece_length;
1.174     paf       952:                }
1.128     paf       953: 
1.202     paf       954:                if(total_length!=body_length) // length(all language fragments) vs length(letters)
1.148     paf       955:                        return false;
1.174     paf       956:        }
1.202     paf       957:        if(in_buf!=0) // some strange extra bytes
                    958:                return false;
1.113     parser    959: 
1.174     paf       960:        ASSERT_STRING_INVARIANT(*this);
1.148     paf       961:        return true;
1.176     paf       962: }
                    963: 
1.201     paf       964: void String::Body::dump() const {
                    965:        CORD_dump(body);
                    966: }
                    967: 
1.257     moko      968: const char* String::Languages::visualize() const {
1.177     paf       969:        if(opt.is_not_just_lang)
1.233     misha     970:                return CORD_to_const_char_star(langs, 0);
1.176     paf       971:        else
1.257     moko      972:                return 0;
1.176     paf       973: }
1.248     moko      974: 
1.201     paf       975: void String::Languages::dump() const {
                    976:        if(opt.is_not_just_lang)
                    977:                CORD_dump(langs);
                    978:        else
                    979:                puts((const char*)&langs);
                    980: }
1.248     moko      981: 
1.257     moko      982: void String::dump() const {
                    983:        body.dump();
                    984:        langs.dump();
                    985: }
1.176     paf       986: 
1.257     moko      987: static char *n_chars(char c, size_t length){
                    988:        char *result=(char *)pa_malloc_atomic(length+1);
                    989:        memset(result, c, length);
                    990:        result[length] = '\0';
                    991:        return result;
1.113     parser    992: }
1.229     misha     993: 
1.257     moko      994: char* String::visualize_langs() const {
1.258     moko      995:        return is_not_just_lang() ? pa_strdup(langs.visualize()) : n_chars((char)just_lang(), length());
1.201     paf       996: }
1.229     misha     997: 
                    998: const String& String::trim(String::Trim_kind kind, const char* chars, Charset* source_charset) const {
1.223     misha     999:        if(is_empty())
1.195     paf      1000:                return *this;
                   1001: 
                   1002:        size_t substr_begin, substr_length;
1.229     misha    1003:        Body new_body=body.trim(kind, chars, &substr_begin, &substr_length, source_charset);
1.195     paf      1004:        if(new_body==body) // we received unchanged pointer, do likewise
                   1005:                return *this;
                   1006:        // new_body differs from body, adjust langs along
                   1007: 
                   1008:        String& result=*new String;
                   1009:        if(!new_body) // body.trim produced empty result
                   1010:                return result;
                   1011:        // body.trim produced nonempty result
                   1012: 
                   1013:        // first: their langs
                   1014:        result.langs.append(result.body, langs, substr_begin, substr_length);
                   1015:        // next: letters themselves
                   1016:        result.body=new_body;
                   1017: 
                   1018:        ASSERT_STRING_INVARIANT(result);
                   1019:        return result;
1.198     paf      1020: }

E-mail: