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

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.283   ! moko       15: volatile const char * IDENT_PA_STRING_C="$Id: pa_string.C,v 1.282 2025/05/25 17:44:27 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.282     moko      236:                        *this+=new String(String::Body::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.280     moko      243:        if(!singleton)
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.282     moko      250: String::Body String::Body::uitoa(size_t aindex) {
                    251:        static const size_t CACHE_SIZE=256;
                    252:        static String::Body cache[CACHE_SIZE];
                    253:        if (aindex < CACHE_SIZE)
                    254:                return !cache[aindex] ? (cache[aindex]=Body(pa_uitoa(aindex))) : cache[aindex];
                    255:        else
                    256:                return Body(pa_uitoa(aindex));
                    257: }
                    258: 
1.254     moko      259: 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       260:        size_t our_length=length();
                    261:        if(!our_length)
                    262:                return *this;
1.229     misha     263: 
                    264:        // check if any UTF-8 in chars
                    265:        bool fast=true;
                    266:        if(chars && source_charset && source_charset->isUTF8()){
                    267:                const char* pos=chars;
                    268:                while(unsigned char c=*pos++)
                    269:                        if(c>127){
                    270:                                fast=false;
                    271:                                break;
                    272:                        }
                    273:        }
                    274: 
                    275:        size_t start=0;
                    276:        size_t end=our_length;
1.195     paf       277:        if(!chars)
1.281     moko      278:                chars=" \t\r\n"; // white space
1.195     paf       279: 
1.229     misha     280:        if(fast){
                    281:                // from left...
                    282:                if(kind!=TRIM_END) {
                    283:                        CORD_pos pos; set_pos(pos, 0);
                    284:                        while(true) {
                    285:                                char c=CORD_pos_fetch(pos);
                    286:                                if(strchr(chars, c)) {
                    287:                                        if(++start==our_length)
1.283   ! moko      288:                                                return String::Body(); // all chars are empty, just return empty string
1.229     misha     289:                                } else
1.281     moko      290:                                        break;
1.229     misha     291: 
                    292:                                CORD_next(pos);
                    293:                        }
                    294:                }
                    295: 
                    296:                // from right..
                    297:                if(kind!=TRIM_START) {
                    298:                        CORD_pos pos; set_pos(pos, end-1);
                    299:                        while(true) {
                    300:                                char c=CORD_pos_fetch(pos);
                    301:                                if(strchr(chars, c)) {
                    302:                                        if(--end==0) // optimization: NO need to check for 'end>=start', that's(<) impossible
1.283   ! moko      303:                                                return String::Body(); // all chars are empty, just return empty string
1.229     misha     304:                                } else
1.281     moko      305:                                        break;
1.229     misha     306: 
                    307:                                CORD_prev(pos);
                    308:                        }
                    309:                }
                    310:        } else {
1.234     misha     311:                const XMLByte* src_begin=(const XMLByte*)cstr();
1.229     misha     312:                const XMLByte* src_end=src_begin+our_length;
                    313: 
                    314:                // from left...
                    315:                if(kind!=TRIM_END) {
                    316:                        while(src_begin<src_end){
                    317:                                uint char_length=1;
                    318:                                const XMLByte* ptr=src_begin;
1.231     misha     319:                                // searching first UTF-8 byte: http://tools.ietf.org/html/rfc3629#section-3
                    320:                                while(++src_begin<=src_end && (*src_begin>127 && *src_begin<0xC0))
1.229     misha     321:                                        char_length++;
                    322: 
                    323:                                bool found=false;
                    324:                                for(const char* chars_byte=chars; chars_byte=strchr(chars_byte, *ptr); chars_byte++)
                    325:                                        if(strncmp(chars_byte, (const char*)ptr, char_length)==0){
                    326:                                                found=true;
                    327:                                                break;
                    328:                                        }
                    329: 
                    330:                                if(found){
                    331:                                        start+=char_length;
                    332:                                        if(start==our_length)
1.283   ! moko      333:                                                return String::Body(); // all chars are empty, just return empty string
1.229     misha     334:                                } else
                    335:                                        break;
                    336:                        }
                    337:                }
1.196     paf       338: 
1.229     misha     339:                // from right..
                    340:                if(kind!=TRIM_START) {
                    341:                        while(src_begin<src_end){
                    342:                                uint char_length=1;
1.231     misha     343:                                // searching first UTF-8 byte: http://tools.ietf.org/html/rfc3629#section-3
                    344:                                while(src_begin<=--src_end && (*src_end>127 && *src_end<0xC0))
1.229     misha     345:                                        char_length++;
                    346: 
                    347:                                bool found=false;
                    348:                                for(const char* chars_byte=chars; chars_byte=strchr(chars_byte, *src_end); chars_byte++)
                    349:                                        if(strncmp(chars_byte, (const char*)src_end, char_length)==0){
                    350:                                                found=true;
                    351:                                                break;
                    352:                                        }
                    353: 
                    354:                                if(found){
                    355:                                        end-=char_length;
                    356:                                        if(end==0)
1.283   ! moko      357:                                                return String::Body(); // all chars are empty, just return empty string
1.229     misha     358:                                } else
                    359:                                        break;
                    360:                        }
1.196     paf       361:                }
                    362:        }
1.195     paf       363: 
                    364:        if(start==0 && end==our_length) // nobody moved a thing
                    365:                return *this;
                    366: 
                    367:        if(out_start)
                    368:                *out_start=start;
                    369:        size_t new_length=end-start;
                    370:        if(out_length)
                    371:                *out_length=new_length;
                    372: 
                    373:        return mid(start, new_length);
                    374: }
                    375: 
1.174     paf       376: static int CORD_batched_iter_fn_generic_hash_code(char c, void * client_data) {
                    377:        uint& result=*static_cast<uint*>(client_data);
                    378:        generic_hash_code(result, c);
                    379:        return 0;
                    380: }
1.248     moko      381: 
1.174     paf       382: static int CORD_batched_iter_fn_generic_hash_code(const char*  s, void * client_data) {
                    383:        uint& result=*static_cast<uint*>(client_data);
                    384:        generic_hash_code(result, s);
                    385:        return 0;
1.248     moko      386: }
                    387: 
1.225     misha     388: uint String::Body::get_hash_code() const {
                    389: #ifdef HASH_CODE_CACHING
                    390:        if(hash_code)
                    391:                return hash_code;
                    392: #else
                    393:        uint hash_code=0;
                    394: #endif
1.220     misha     395:        if (body && CORD_IS_STRING(body)){
1.250     moko      396:                generic_hash_code(hash_code, (const char *)body);
1.220     misha     397:        } else {
                    398:                CORD_iter5(body, 0,
                    399:                        CORD_batched_iter_fn_generic_hash_code, 
1.225     misha     400:                        CORD_batched_iter_fn_generic_hash_code, &hash_code);
1.220     misha     401:        }
1.225     misha     402:        return hash_code;
1.94      parser    403: }
                    404: 
1.241     misha     405: struct CORD_pos_info {
                    406:        const char* chars;
                    407:        size_t left;
                    408:        size_t pos;
                    409: };
                    410: 
                    411: // can be called only for IS_FUNCTION(CORD) which is used in String::Body::strrpbrk
                    412: static int CORD_iter_fn_rpos(char c, CORD_pos_info* info) {
                    413:        if(info->pos < info->left){
                    414:                info->pos=STRING_NOT_FOUND;
                    415:                return 1;
                    416:        }
                    417:        if(strchr(info->chars, c))
                    418:                return 1;
                    419:        --(info->pos);
                    420:        return 0;
                    421: }
                    422: 
                    423: size_t String::Body::strrpbrk(const char* chars, size_t left, size_t right) const {
                    424:        if(is_empty() || !chars || !strlen(chars))
                    425:                return STRING_NOT_FOUND;
                    426:        CORD_pos_info info={chars, left, right};
                    427:        if(CORD_riter4(body, right, (CORD_iter_fn)CORD_iter_fn_rpos, &info))
                    428:                return info.pos;
                    429:        else
                    430:                return STRING_NOT_FOUND;
                    431: }
                    432: 
                    433: 
                    434: // can be called only for IS_FUNCTION(CORD) which is used in String::Body::rskipchars
                    435: static int CORD_iter_fn_rskip(char c, CORD_pos_info* info) {
                    436:        if(info->pos < info->left) {
                    437:                info->pos=STRING_NOT_FOUND;
                    438:                return 1;
                    439:        }
                    440:        if(!strchr(info->chars, c))
                    441:                return 1;
                    442:        --(info->pos);
                    443:        return 0;
                    444: }
                    445: 
                    446: size_t String::Body::rskipchars(const char* chars, size_t left, size_t right) const {
                    447:        if(is_empty() || !chars || !strlen(chars))
                    448:                return STRING_NOT_FOUND;
                    449:        CORD_pos_info info={chars, left, right};
                    450:        if(CORD_riter4(body, right, (CORD_iter_fn)CORD_iter_fn_rskip, &info))
                    451:                return info.pos;
                    452:        else
                    453:                return STRING_NOT_FOUND;
                    454: }
                    455: 
1.174     paf       456: // String methods
                    457: 
                    458: String& String::append_know_length(const char* str, size_t known_length, Language lang) {
                    459:        if(!known_length)
1.9       paf       460:                return *this;
1.122     paf       461: 
1.176     paf       462:        // first: langs
                    463:        langs.append(body, lang, known_length);
                    464:        // next: letters themselves
1.174     paf       465:        body.append_know_length(str, known_length);
1.1       paf       466: 
1.174     paf       467:        ASSERT_STRING_INVARIANT(*this);
1.1       paf       468:        return *this;
                    469: }
1.248     moko      470: 
1.174     paf       471: String& String::append_help_length(const char* str, size_t helper_length, Language lang) {
                    472:        if(!str)
                    473:                return *this;
                    474:        size_t known_length=helper_length?helper_length:strlen(str);
                    475:        if(!known_length)
                    476:                return *this;
1.1       paf       477: 
1.174     paf       478:        return append_know_length(str, known_length, lang);
1.5       paf       479: }
1.248     moko      480: 
1.244     moko      481: String::String(int value, const char *format) : langs(L_CLEAN){
1.226     misha     482:        char buf[MAX_NUMBER];
                    483:        body.append_strdup_know_length(buf, snprintf(buf, MAX_NUMBER, format, value));
                    484: }
1.248     moko      485: 
1.174     paf       486: String& String::append_strdup(const char* str, size_t helper_length, Language lang) {
                    487:        size_t known_length=helper_length?helper_length:strlen(str);
                    488:        if(!known_length)
                    489:                return *this;
1.5       paf       490: 
1.176     paf       491:        // first: langs
                    492:        langs.append(body, lang, known_length);
                    493:        // next: letters themselves
1.174     paf       494:        body.append_strdup_know_length(str, known_length);
1.33      paf       495: 
1.174     paf       496:        ASSERT_STRING_INVARIANT(*this);
                    497:        return *this;
1.5       paf       498: }
1.46      paf       499: 
1.234     misha     500: struct CORD_length_info {
                    501:        size_t len;
                    502:        size_t skip;
                    503: };
                    504: 
                    505: int CORD_batched_len(const char* s, CORD_length_info* info){
1.255     moko      506:        info->len += lengthUTF8( (const XMLByte *)s, (const XMLByte *)s+strlen(s));
                    507:        return 0;
1.221     misha     508: }
                    509: 
1.234     misha     510: // can be called only for IS_FUNCTION(CORD) which are used in large String::Body::mid
                    511: int CORD_batched_len(const char c, CORD_length_info* info){
                    512:        if (info->skip==0){
                    513:                info->len++;
                    514:                info->skip = lengthUTF8Char(c)-1;
                    515:        } else {
                    516:                info->skip--;
                    517:        }
1.220     misha     518:        return 0;
                    519: }
                    520: 
1.210     misha     521: size_t String::length(Charset& charset) const {
                    522:        if(charset.isUTF8()){
1.234     misha     523:                CORD_length_info info = {0, 0};
                    524:                body.for_each<CORD_length_info *>(CORD_batched_len, CORD_batched_len, &info);
                    525:                return info.len;
1.210     misha     526:        } else
                    527:                return body.length();
                    528: }
                    529: 
1.174     paf       530: /// @todo check in doc: whether it documents NOW bad situation "abc".mid(-1, 3) =were?="ab"
                    531: String& String::mid(size_t substr_begin, size_t substr_end) const {
                    532:        String& result=*new String;
                    533: 
                    534:        size_t self_length=length();
                    535:        substr_begin=min(substr_begin, self_length);
                    536:        substr_end=min(max(substr_end, substr_begin), self_length);
1.176     paf       537:        size_t substr_length=substr_end-substr_begin;
                    538:        if(!substr_length)
1.107     parser    539:                return result;
1.53      paf       540: 
1.176     paf       541:        // first: their langs
                    542:        result.langs.append(result.body, langs, substr_begin, substr_length);
                    543:        // next: letters themselves
                    544:        result.body=body.mid(substr_begin, substr_length);
1.174     paf       545: 
                    546:        ASSERT_STRING_INVARIANT(result);
1.53      paf       547:        return result;
1.54      paf       548: }
                    549: 
1.211     misha     550: // from, to and helper_length in characters, not in bytes (it's important for utf-8)
                    551: String& String::mid(Charset& charset, size_t from, size_t to, size_t helper_length) const {
1.210     misha     552:        String& result=*new String;
                    553: 
1.255     moko      554:        size_t self_length=helper_length ? helper_length : length(charset);
1.211     misha     555: 
                    556:        if(!self_length)
                    557:                return result;
                    558: 
                    559:        from=min(min(to, from), self_length);
1.210     misha     560:        to=min(max(to, from), self_length);
1.211     misha     561: 
1.210     misha     562:        size_t substr_length=to-from;
1.211     misha     563: 
1.210     misha     564:        if(!substr_length)
                    565:                return result;
                    566: 
                    567:        if(charset.isUTF8()){
1.234     misha     568:                const XMLByte* src_begin=(const XMLByte*)cstr();
1.230     misha     569:                const XMLByte* src_end=src_begin+body.length();
1.210     misha     570: 
1.212     misha     571:                // convert 'from' and 'substr_length' from 'characters' to 'bytes'
1.230     misha     572:                from=getUTF8BytePos(src_begin, src_end, from);
                    573:                substr_length=getUTF8BytePos(src_begin+from, src_end, substr_length);
1.210     misha     574:                if(!substr_length)
                    575:                        return result;
                    576:        }
                    577: 
                    578:        // first: their langs
                    579:        result.langs.append(result.body, langs, from, substr_length);
                    580:        // next: letters themselves
                    581:        result.body=body.mid(from, substr_length);
                    582: 
                    583:        ASSERT_STRING_INVARIANT(result);
                    584:        return result;
                    585: }
                    586: 
1.176     paf       587: size_t String::pos(const String::Body substr, size_t this_offset, Language lang) const {
1.183     paf       588:        size_t substr_length=substr.length();
                    589:        while(true) {
                    590:                size_t substr_begin=body.pos(substr, this_offset);
                    591:                
                    592:                if(substr_begin==CORD_NOT_FOUND)
                    593:                        return STRING_NOT_FOUND;
1.174     paf       594: 
1.183     paf       595:                if(langs.check_lang(lang, substr_begin, substr_length))
                    596:                        return substr_begin;
                    597: 
                    598:                this_offset=substr_begin+substr_length;
                    599:        }
1.58      paf       600: }
                    601: 
1.254     moko      602: size_t String::pos(const String& substr, size_t this_offset, Language lang) const {
1.174     paf       603:        return pos(substr.body, this_offset, lang);
1.60      paf       604: }
                    605: 
1.254     moko      606: size_t String::pos(Charset& charset, const String& substr, size_t this_offset, Language lang) const {
1.210     misha     607: 
                    608:        if(charset.isUTF8()){
1.234     misha     609:                const XMLByte* srcPtr=(const XMLByte*)cstr();
1.212     misha     610:                const XMLByte* srcEnd=srcPtr+body.length();
                    611: 
                    612:                // convert 'this_offset' from 'characters' to 'bytes'
                    613:                this_offset=getUTF8BytePos(srcPtr, srcEnd, this_offset);
                    614: 
1.229     misha     615:                size_t result=pos(substr.body, this_offset, lang);
                    616:                return (result==CORD_NOT_FOUND)
                    617:                        ? STRING_NOT_FOUND
                    618:                        : getUTF8CharPos(srcPtr, srcEnd, result); // convert 'result' from 'bytes' to 'characters'
1.212     misha     619:        } else {
1.229     misha     620:                size_t result=pos(substr.body, this_offset, lang);
                    621:                return (result==CORD_NOT_FOUND)
                    622:                        ? STRING_NOT_FOUND
                    623:                        : result;
1.210     misha     624:        }
                    625: }
                    626: 
1.256     moko      627: void String::split(ArrayString& result, size_t pos_after, const char* delim, Language lang) const {
1.237     misha     628:        if(is_empty())
                    629:                return;
1.174     paf       630:        size_t self_length=length();
1.237     misha     631:        if(size_t delim_length=strlen(delim)) {
1.186     paf       632:                size_t pos_before;
1.60      paf       633:                // while we have 'delim'...
1.283   ! moko      634:                while((pos_before=pos(String::Body(delim), pos_after, lang)) != STRING_NOT_FOUND) {
1.69      paf       635:                        result+=&mid(pos_after, pos_before);
1.174     paf       636:                        pos_after=pos_before+delim_length;
1.60      paf       637:                }
                    638:                // last piece
1.256     moko      639:                if(pos_after<self_length)
1.174     paf       640:                        result+=&mid(pos_after, self_length);
1.60      paf       641:        } else { // empty delim
                    642:                result+=this;
                    643:        }
                    644: }
                    645: 
1.256     moko      646: void String::split(ArrayString& result, size_t pos_after, const String& delim, Language lang) const {
1.237     misha     647:        if(is_empty())
                    648:                return;
                    649:        if(!delim.is_empty()) {
1.186     paf       650:                size_t pos_before;
1.60      paf       651:                // while we have 'delim'...
1.256     moko      652:                while((pos_before=pos(delim, pos_after, lang))!=STRING_NOT_FOUND) {
1.69      paf       653:                        result+=&mid(pos_after, pos_before);
1.174     paf       654:                        pos_after=pos_before+delim.length();
1.60      paf       655:                }
                    656:                // last piece
1.256     moko      657:                if(pos_after<length())
1.174     paf       658:                        result+=&mid(pos_after, length());
1.60      paf       659:        } else { // empty delim
                    660:                result+=this;
                    661:        }
1.61      paf       662: }
                    663: 
1.254     moko      664: Table* String::match(VRegex* vregex, Row_action row_action, void *info, int& matches_count) const {
1.209     misha     665: 
1.222     misha     666:        // vregex->info(); // I have no idea what does it for?
1.63      paf       667: 
1.222     misha     668:        bool need_pre_post_match=vregex->is_pre_post_match_needed();
                    669:        bool global=vregex->is_global_search();
1.63      paf       670: 
1.174     paf       671:        const char* subject=cstr();
1.234     misha     672:        size_t subject_length=length();
1.271     moko      673:        const int ovector_size=(1/*match*/+MAX_MATCH_GROUPS)*3; /* 1/3 is used as workspace by pcre_exec() */
1.222     misha     674:        int ovector[ovector_size];
1.155     paf       675: 
1.173     paf       676:        Table::Action_options table_options;
1.278     moko      677:        Table& table=*new Table(string_match_table_template(), table_options);
1.63      paf       678: 
1.154     paf       679:        int prestart=0;
                    680:        int poststart=0;
1.174     paf       681:        int postfinish=length();
1.267     moko      682:        int action_was_executed=-1;
1.63      paf       683:        while(true) {
1.222     misha     684:                int exec_result=vregex->exec(subject, subject_length, ovector, ovector_size, prestart);
1.63      paf       685: 
1.222     misha     686:                if(exec_result<0) // only PCRE_ERROR_NOMATCH might be here, other negative results cause an exception
                    687:                        break;
1.63      paf       688: 
1.154     paf       689:                int prefinish=ovector[0];
                    690:                poststart=ovector[1];
1.236     moko      691: 
1.267     moko      692:                if (prestart==poststart && action_was_executed==1){
1.236     moko      693:                        prestart++;
1.267     moko      694:                        action_was_executed=0;
1.236     moko      695:                        continue;
                    696:                }
                    697: 
1.232     misha     698:                ArrayString* row=new ArrayString(3);
1.174     paf       699:                if(need_pre_post_match) {
                    700:                        *row+=&mid(0, prefinish); // .prematch column value
                    701:                        *row+=&mid(prefinish, poststart); // .match
                    702:                        *row+=&mid(poststart, postfinish); // .postmatch
                    703:                } else {
1.185     paf       704:                        *row+=&Empty; // .prematch column value
                    705:                        *row+=&Empty; // .match
                    706:                        *row+=&Empty; // .postmatch
1.174     paf       707:                }
1.63      paf       708:                
1.222     misha     709:                for(int i=1; i<exec_result; i++) {
1.69      paf       710:                        // -1:-1 case handled peacefully by mid() itself
1.232     misha     711:                        *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       712:                }
                    713:                
1.209     misha     714:                matches_count++;
1.267     moko      715:                row_action(table, row, prestart - !action_was_executed, prefinish, poststart, postfinish, info);
1.63      paf       716: 
1.275     moko      717:                if(!global || (size_t)poststart>=subject_length) // last step, avoid prestart++ after last char
1.222     misha     718:                        break;
                    719: 
1.154     paf       720:                prestart=poststart;
1.267     moko      721:                action_was_executed=1;
1.222     misha     722:        }
1.63      paf       723: 
1.222     misha     724:        row_action(table, 0/*last time, no raw*/, 0, 0, poststart, postfinish, info);
                    725:        return vregex->is_just_count() ? 0 : &table;
1.82      parser    726: }
                    727: 
1.174     paf       728: String& String::change_case(Charset& source_charset, Change_case_kind kind) const {
                    729:        String& result=*new String();
                    730:        if(is_empty())
                    731:                return result;
                    732: 
                    733:        char* new_cstr=cstrm();
1.216     misha     734: 
1.181     paf       735:        if(source_charset.isUTF8()) {
1.216     misha     736:                size_t new_cstr_len=length();
1.181     paf       737:                switch(kind) {
                    738:                case CC_UPPER:
1.192     paf       739:                        change_case_UTF8((const XMLByte*)new_cstr, new_cstr_len, (XMLByte*)new_cstr, new_cstr_len, UTF8CaseToUpper);
1.181     paf       740:                        break;
                    741:                case CC_LOWER:
1.192     paf       742:                        change_case_UTF8((const XMLByte*)new_cstr, new_cstr_len, (XMLByte*)new_cstr, new_cstr_len, UTF8CaseToLower);
1.181     paf       743:                        break;
                    744:                default:
                    745:                        assert(!"unknown change case kind");
                    746:                        break; // never
                    747:                }       
                    748:                
                    749:        } else {
                    750:                const unsigned char *tables=source_charset.pcre_tables;
1.82      parser    751: 
1.181     paf       752:                const unsigned char *a;
                    753:                const unsigned char *b;
                    754:                switch(kind) {
                    755:                case CC_UPPER:
                    756:                        a=tables+lcc_offset;
                    757:                        b=tables+fcc_offset;
                    758:                        break;
                    759:                case CC_LOWER:
                    760:                        a=tables+lcc_offset;
                    761:                        b=0;
                    762:                        break;
                    763:                default:
                    764:                        assert(!"unknown change case kind");
                    765:                        a=b=0; // calm, compiler
                    766:                        break; // never
                    767:                }       
                    768: 
1.192     paf       769:                char *dest=new_cstr;
1.181     paf       770:                unsigned char index;
1.190     paf       771:                for(const char* current=new_cstr; (index=(unsigned char)*current); current++) {
1.181     paf       772:                        unsigned char c=a[index];
                    773:                        if(b)
                    774:                                c=b[c];
                    775: 
                    776:                        *dest++=(char)c;
                    777:                }
1.174     paf       778:        }
1.176     paf       779:        result.langs=langs;
1.283   ! moko      780:        result.body=String::Body(new_cstr);
1.89      parser    781: 
1.101     parser    782:        return result;
                    783: }
                    784: 
1.213     misha     785: const String& String::escape(Charset& source_charset) const {
                    786:        if(is_empty())
                    787:                return *this;
                    788: 
                    789:        return Charset::escape(*this, source_charset);
                    790: }
                    791: 
1.238     misha     792: #define STRING_APPEND(result, from_cstr, langs, langs_offset, length) \
                    793:                        result.langs.append(result.body, langs, langs_offset, length); \
                    794:                        result.body.append_strdup_know_length(from_cstr, length);
                    795: 
1.174     paf       796: const String& String::replace(const Dictionary& dict) const {
1.238     misha     797:        if(!dict.count() || is_empty())
                    798:                return *this;
                    799: 
1.174     paf       800:        String& result=*new String();
                    801:        const char* old_cstr=cstr();
                    802:        const char* prematch_begin=old_cstr;
                    803: 
1.238     misha     804:        if(dict.count()==1) {
                    805:                // optimized simple case
                    806: 
                    807:                Dictionary::Subst subst=dict.get(0);
1.239     moko      808:                while(const char* p=strstr(prematch_begin, subst.from)) {
1.174     paf       809:                        // prematch
1.238     misha     810:                        if(size_t prematch_length=p-prematch_begin) {
                    811:                                STRING_APPEND(result, prematch_begin, langs, prematch_begin-old_cstr, prematch_length)
1.101     parser    812:                        }
                    813: 
1.174     paf       814:                        // match
1.238     misha     815:                        prematch_begin=p+subst.from_length;
1.174     paf       816: 
1.184     paf       817:                        if(const String* b=subst.to) // are there any b?
1.174     paf       818:                                result<<*b;
1.238     misha     819:                }
                    820: 
                    821:        } else {
                    822: 
                    823:                const char* current=old_cstr;
                    824:                while(*current) {
                    825:                        if(Dictionary::Subst subst=dict.first_that_begins(current)) {
                    826:                                // prematch
                    827:                                if(size_t prematch_length=current-prematch_begin) {
                    828:                                        STRING_APPEND(result, prematch_begin, langs, prematch_begin-old_cstr, prematch_length)
                    829:                                }
                    830: 
                    831:                                // match
                    832:                                // skip 'a' in 'current'; move prematch_begin
                    833:                                current+=subst.from_length; prematch_begin=current;
                    834: 
                    835:                                if(const String* b=subst.to) // are there any b?
                    836:                                        result<<*b;
                    837:                        } else // simply advance
                    838:                                current++; 
                    839:                }
                    840: 
1.174     paf       841:        }
1.156     paf       842: 
1.238     misha     843:        if(prematch_begin==old_cstr) // not modified
                    844:                return *this;
                    845: 
1.174     paf       846:        // postmatch
1.238     misha     847:        if(size_t postmatch_length=old_cstr+length()-prematch_begin) {
                    848:                STRING_APPEND(result, prematch_begin, langs, prematch_begin-old_cstr, postmatch_length)
1.174     paf       849:        }
1.156     paf       850: 
1.174     paf       851:        ASSERT_STRING_INVARIANT(result);
1.82      parser    852:        return result;
1.61      paf       853: }
1.113     parser    854: 
1.180     paf       855: static int serialize_body_char(char c, char** cur) {
                    856:        *((*cur)++)=c;
                    857:        return 0; // 0=continue
1.248     moko      858: }
                    859: 
1.174     paf       860: static int serialize_body_piece(const char* s, char** cur) {
                    861:        size_t length=strlen(s);
                    862:        memcpy(*cur, s, length);  *cur+=length;
1.178     paf       863:        return 0; // 0=continue
1.248     moko      864: }
                    865: 
1.178     paf       866: static int serialize_lang_piece(char alang, size_t asize, char** cur) {
                    867:        // lang
1.191     paf       868:        **cur=alang; (*cur)++;
                    869:        // length [WARNING: not cast, addresses must be %4=0 on sparc]
1.178     paf       870:        memcpy(*cur, &asize, sizeof(asize));  *cur+=sizeof(asize);
                    871: 
                    872:        return 0; // 0=continue
                    873: }
1.248     moko      874: 
1.174     paf       875: String::Cm String::serialize(size_t prolog_length) const {
1.178     paf       876:        size_t fragments_count=langs.count();
1.202     paf       877:        size_t body_length=body.length();
1.174     paf       878:        size_t buf_length=
1.178     paf       879:                prolog_length //1
                    880:                +sizeof(size_t) //2
1.202     paf       881:                +body_length //3
                    882:                +1 // 4 for zero terminator used in deserialize
                    883:                +sizeof(size_t) //5
                    884:                +fragments_count*(sizeof(char)+sizeof(size_t)); //6
                    885: 
1.174     paf       886:        String::Cm result(new(PointerFreeGC) char[buf_length], buf_length);
                    887: 
                    888:        // 1: prolog
                    889:        char *cur=result.str+prolog_length;
1.202     paf       890:        // 2: chars.count [WARNING: not cast, addresses must be %4=0 on sparc]
                    891:        memcpy(cur, &body_length, sizeof(body_length));  cur+=sizeof(body_length);
                    892:        // 3: letters
                    893:        body.for_each(serialize_body_char, serialize_body_piece, &cur);
                    894:        // 4: zero terminator
                    895:        *cur++=0;
                    896:        // 5: langs.count [WARNING: not cast, addresses must be %4=0 on sparc]
1.174     paf       897:        memcpy(cur, &fragments_count, sizeof(fragments_count));  cur+=sizeof(fragments_count);
1.202     paf       898:        // 6: lang info
1.178     paf       899:        langs.for_each(body, serialize_lang_piece, &cur);
1.113     parser    900: 
1.174     paf       901:        return result;
1.113     parser    902: }
1.248     moko      903: 
1.202     paf       904: bool String::deserialize(size_t prolog_size, void *buf, size_t buf_size) {
                    905:        size_t in_buf=buf_size;
                    906:        if(in_buf<=prolog_size)
1.148     paf       907:                return false;
1.202     paf       908:        in_buf-=prolog_size;
1.135     paf       909: 
1.174     paf       910:        // 1: prolog
1.202     paf       911:        const char* cur=(const char* )buf+prolog_size;
1.113     parser    912: 
1.207     paf       913:        // 2: chars.count
1.202     paf       914:        size_t body_length;
                    915:        if(in_buf<sizeof(body_length)) // body.length don't fit?
                    916:                return false;
                    917:        // [WARNING: not cast, addresses must be %4=0 on sparc]
                    918:        memcpy(&body_length, cur, sizeof(body_length));  cur+=sizeof(body_length);
                    919:        in_buf-=sizeof(body_length);
                    920: 
                    921:        if(in_buf<body_length+1) // letters+terminator don't fit?
                    922:                return false;
                    923:        // 4: zero terminator
                    924:        if(cur[body_length] != 0) // in place?
                    925:                return false;
                    926:        // 3: letters
1.251     moko      927:        body=String::Body(String::C(cur, body_length));
1.202     paf       928:        cur+=body_length+1;
                    929:        in_buf-=body_length+1;
                    930: 
                    931:        // 5: langs.count
1.191     paf       932:        size_t fragments_count;
1.202     paf       933:        if(in_buf<sizeof(fragments_count)) // langs.count don't fit?
1.174     paf       934:                return false;
1.191     paf       935:        // [WARNING: not cast, addresses must be %4=0 on sparc]
                    936:        memcpy(&fragments_count, cur, sizeof(fragments_count));  cur+=sizeof(fragments_count);
1.202     paf       937:        in_buf-=sizeof(fragments_count);
1.174     paf       938:        
                    939:        if(fragments_count) {
1.202     paf       940:                // 6: lang info
1.174     paf       941:                size_t total_length=0;
                    942:                for(size_t f=0; f<fragments_count; f++) {
1.191     paf       943:                        char lang;
                    944:                        size_t fragment_length;
                    945:                        size_t piece_length=sizeof(lang)+sizeof(fragment_length);
1.202     paf       946:                        if(in_buf<piece_length) // lang+length
1.174     paf       947:                                return false;
                    948: 
1.191     paf       949:                        // lang
                    950:                        lang=*cur++;
                    951:                        // length [WARNING: not cast, addresses must be %4=0 on sparc]
                    952:                        memcpy(&fragment_length, cur, sizeof(fragment_length));  cur+=sizeof(fragment_length);
                    953: 
1.206     paf       954:                        size_t combined_length=total_length+fragment_length;
                    955:                        if(combined_length>body_length)
                    956:                                return false; // file curruption
1.191     paf       957:                        // uchar needed to prevent propagating 0x80 bit to upper bytes
                    958:                        langs.append(total_length, (String::Language)(uchar)lang, fragment_length);
1.206     paf       959:                        total_length=combined_length;
1.202     paf       960:                        in_buf-=piece_length;
1.174     paf       961:                }
1.128     paf       962: 
1.202     paf       963:                if(total_length!=body_length) // length(all language fragments) vs length(letters)
1.148     paf       964:                        return false;
1.174     paf       965:        }
1.202     paf       966:        if(in_buf!=0) // some strange extra bytes
                    967:                return false;
1.113     parser    968: 
1.174     paf       969:        ASSERT_STRING_INVARIANT(*this);
1.148     paf       970:        return true;
1.176     paf       971: }
                    972: 
1.201     paf       973: void String::Body::dump() const {
                    974:        CORD_dump(body);
                    975: }
                    976: 
1.257     moko      977: const char* String::Languages::visualize() const {
1.177     paf       978:        if(opt.is_not_just_lang)
1.233     misha     979:                return CORD_to_const_char_star(langs, 0);
1.176     paf       980:        else
1.257     moko      981:                return 0;
1.176     paf       982: }
1.248     moko      983: 
1.201     paf       984: void String::Languages::dump() const {
                    985:        if(opt.is_not_just_lang)
                    986:                CORD_dump(langs);
                    987:        else
                    988:                puts((const char*)&langs);
                    989: }
1.248     moko      990: 
1.257     moko      991: void String::dump() const {
                    992:        body.dump();
                    993:        langs.dump();
                    994: }
1.176     paf       995: 
1.257     moko      996: static char *n_chars(char c, size_t length){
                    997:        char *result=(char *)pa_malloc_atomic(length+1);
                    998:        memset(result, c, length);
                    999:        result[length] = '\0';
                   1000:        return result;
1.113     parser   1001: }
1.229     misha    1002: 
1.257     moko     1003: char* String::visualize_langs() const {
1.258     moko     1004:        return is_not_just_lang() ? pa_strdup(langs.visualize()) : n_chars((char)just_lang(), length());
1.201     paf      1005: }
1.229     misha    1006: 
                   1007: const String& String::trim(String::Trim_kind kind, const char* chars, Charset* source_charset) const {
1.223     misha    1008:        if(is_empty())
1.195     paf      1009:                return *this;
                   1010: 
                   1011:        size_t substr_begin, substr_length;
1.229     misha    1012:        Body new_body=body.trim(kind, chars, &substr_begin, &substr_length, source_charset);
1.195     paf      1013:        if(new_body==body) // we received unchanged pointer, do likewise
                   1014:                return *this;
                   1015:        // new_body differs from body, adjust langs along
                   1016: 
                   1017:        String& result=*new String;
                   1018:        if(!new_body) // body.trim produced empty result
                   1019:                return result;
                   1020:        // body.trim produced nonempty result
                   1021: 
                   1022:        // first: their langs
                   1023:        result.langs.append(result.body, langs, substr_begin, substr_length);
                   1024:        // next: letters themselves
                   1025:        result.body=new_body;
                   1026: 
                   1027:        ASSERT_STRING_INVARIANT(result);
                   1028:        return result;
1.198     paf      1029: }

E-mail: