Annotation of parser3/src/main/pa_charset.C, revision 1.65

1.1       paf         1: /** @file
                      2:        Parser: Charset connection implementation.
                      3: 
1.52      paf         4:        Copyright(c) 2001-2005 ArtLebedev Group (http://www.artlebedev.com)
1.4       paf         5:        Author: Alexander Petrosyan<paf@design.ru>(http://paf.design.ru)
1.27      paf         6: */
1.1       paf         7: 
1.65    ! misha       8: static const char * const IDENT_CHARSET_C="$Date: 2008-07-21 07:36:42 $";
1.1       paf         9: 
                     10: #include "pa_charset.h"
1.35      paf        11: #include "pa_charsets.h"
1.1       paf        12: 
                     13: #ifdef XML
1.8       paf        14: #include "libxml/encoding.h"
1.1       paf        15: #endif
                     16: 
1.46      paf        17: //#define PA_PATCHED_LIBXML_BACKWARD
1.60      misha      18: #define PRECALCULATE_DEST_LENGTH
1.46      paf        19: 
1.38      paf        20: // globals
                     21: 
                     22: Charset::UTF8CaseTable::Rec UTF8CaseToUpperRecords[]={
                     23: #include "utf8-to-upper.inc"
                     24: };
                     25: Charset::UTF8CaseTable UTF8CaseToUpper={
                     26:        sizeof(UTF8CaseToUpperRecords)/sizeof(Charset::UTF8CaseTable::Rec),
                     27:        UTF8CaseToUpperRecords};
                     28: 
                     29: Charset::UTF8CaseTable::Rec UTF8CaseToLowerRecords[]={
                     30: #include "utf8-to-lower.inc"
                     31: };
                     32: Charset::UTF8CaseTable UTF8CaseToLower={
                     33:        sizeof(UTF8CaseToLowerRecords)/sizeof(Charset::UTF8CaseTable::Rec),
                     34:        UTF8CaseToLowerRecords};
                     35: 
1.1       paf        36: // helpers
                     37: 
                     38: inline void prepare_case_tables(unsigned char *tables) {
                     39:        unsigned char *lcc_table=tables+lcc_offset;
                     40:        unsigned char *fcc_table=tables+fcc_offset;
                     41:        for(int i=0; i<0x100; i++)
1.53      paf        42:                lcc_table[i]=fcc_table[i]=(unsigned char)i;
1.1       paf        43: }
                     44: inline void cstr2ctypes(unsigned char *tables, const unsigned char *cstr, 
                     45:                                                unsigned char bit) {
                     46:        unsigned char *ctypes_table=tables+ctypes_offset;
                     47:        ctypes_table[0]=bit;
                     48:        for(; *cstr; cstr++) {
                     49:                unsigned char c=*cstr;
                     50:                ctypes_table[c]|=bit;
                     51:        }
                     52: }
1.35      paf        53: inline unsigned int to_wchar_code(const char* cstr) {
1.1       paf        54:        if(!cstr || !*cstr)
                     55:                return 0;
                     56:        if(cstr[1]==0)
1.4       paf        57:                return(unsigned int)(unsigned char)cstr[0];
1.1       paf        58: 
                     59:        char *error_pos;
1.4       paf        60:        return(unsigned int)strtol(cstr, &error_pos, 0);
1.1       paf        61: }
1.35      paf        62: inline bool to_bool(const char* cstr) {
1.1       paf        63:        return cstr && *cstr!=0;
                     64: }
                     65: static void element2ctypes(unsigned char c, bool belongs,
                     66:                                                   unsigned char *tables,  unsigned char bit, int group_offset=-1) {
                     67:        if(!belongs)
                     68:                return;
                     69: 
                     70:        unsigned char *ctypes_table=tables+ctypes_offset;
                     71: 
                     72:        ctypes_table[c]|=bit;
                     73:        if(group_offset>=0)
1.4       paf        74:                tables[cbits_offset+group_offset+c/8] |= 1<<(c%8);
1.1       paf        75: }
                     76: static void element2case(unsigned char from, unsigned char to,
                     77:                                                 unsigned char *tables) {
                     78:        if(!to) 
                     79:                return;
                     80: 
                     81:        unsigned char *lcc_table=tables+lcc_offset;
                     82:        unsigned char *fcc_table=tables+fcc_offset;
                     83:        lcc_table[from]=to;
                     84:        fcc_table[from]=to; fcc_table[to]=from;
                     85: }
                     86: 
                     87: // methods
                     88: 
1.37      paf        89: Charset::Charset(Request_charsets* charsets, const String::Body ANAME, const String* afile_spec): 
1.35      paf        90:        FNAME(ANAME),
                     91:        FNAME_CSTR(ANAME.cstrm()) {
1.7       paf        92: 
1.35      paf        93:        if(afile_spec) {
1.1       paf        94:                fisUTF8=false;
1.35      paf        95:                load_definition(*charsets, *afile_spec);
1.1       paf        96: #ifdef XML
1.35      paf        97:                addEncoding(FNAME_CSTR);
1.1       paf        98: #endif
                     99:        } else {
                    100:                fisUTF8=true;
1.4       paf       101:                // grab default onces [for UTF-8 so to be able to make a-z =>A-Z
1.65    ! misha     102:                memcpy(pcre_tables, _pcre_default_tables, sizeof(pcre_tables));
1.1       paf       103:        }
                    104: 
                    105: #ifdef XML
1.35      paf       106:        initTranscoder(FNAME, FNAME_CSTR);
1.1       paf       107: #endif
                    108: }
                    109: 
1.35      paf       110: void Charset::load_definition(Request_charsets& charsets, const String& afile_spec) {
1.1       paf       111:        // pcre_tables
                    112:        // lowcase, flipcase, bits digit+word+whitespace, masks
                    113: 
                    114:        // must not move this inside of prepare_case_tables
                    115:        // don't know the size there
                    116:        memset(pcre_tables, 0, sizeof(pcre_tables)); 
                    117:        prepare_case_tables(pcre_tables);
1.4       paf       118:        cstr2ctypes(pcre_tables,(const unsigned char *)"*+?{^.$|()[", ctype_meta);
1.1       paf       119: 
                    120:        // charset
1.35      paf       121:        memset(&tables, 0, sizeof(tables));
1.1       paf       122: 
                    123:        // loading text
1.35      paf       124:        char *data=file_read_text(charsets, afile_spec);
1.1       paf       125: 
                    126:        // ignore header
                    127:        getrow(&data);
                    128: 
                    129:        // parse cells
                    130:        char *row;
1.42      paf       131:        while((row=getrow(&data))) {
1.1       paf       132:                // remove empty&comment lines
                    133:                if(!*row || *row=='#')
                    134:                        continue;
                    135: 
                    136:                // char white-space     digit   hex-digit       letter  word    lowercase       unicode1        unicode2        
1.53      paf       137:                unsigned char c=0;
1.1       paf       138:                char *cell;
1.42      paf       139:                for(int column=0; (cell=lsplit(&row, '\t')); column++) {
1.1       paf       140:                        switch(column) {
1.53      paf       141:                        case 0: c=(unsigned char)to_wchar_code(cell); break;
1.1       paf       142:                        // pcre_tables
                    143:                        case 1: element2ctypes(c, to_bool(cell), pcre_tables, ctype_space, cbit_space); break;
                    144:                        case 2: element2ctypes(c, to_bool(cell), pcre_tables, ctype_digit, cbit_digit); break;
                    145:                        case 3: element2ctypes(c, to_bool(cell), pcre_tables, ctype_xdigit); break;
                    146:                        case 4: element2ctypes(c, to_bool(cell), pcre_tables, ctype_letter); break;
                    147:                        case 5: element2ctypes(c, to_bool(cell), pcre_tables, ctype_word, cbit_word); break;
1.53      paf       148:                        case 6: element2case(c, (unsigned char)to_wchar_code(cell), pcre_tables); break;
1.1       paf       149:                        case 7:
                    150:                        case 8:
                    151:                                // charset
1.10      paf       152:                                if(tables.toTableSize>MAX_CHARSET_UNI_CODES)
1.56      misha     153:                                        throw Exception(PARSER_RUNTIME,
1.35      paf       154:                                                &afile_spec,
1.1       paf       155:                                                "charset must contain not more then %d unicode values", MAX_CHARSET_UNI_CODES);
                    156: 
                    157:                                XMLCh unicode=(XMLCh)to_wchar_code(cell);
                    158:                                if(!unicode && column==7/*unicode1 column*/)
                    159:                                        unicode=(XMLCh)c;
                    160:                                if(unicode) {
1.10      paf       161:                                        if(!tables.fromTable[c])
                    162:                                                tables.fromTable[c]=unicode;
                    163:                                        tables.toTable[tables.toTableSize].intCh=unicode;
                    164:                                        tables.toTable[tables.toTableSize].extCh=(XMLByte)c;
                    165:                                        tables.toTableSize++;
1.1       paf       166:                                }
                    167:                                break;
                    168:                        }
                    169:                }
                    170:        };
                    171: 
                    172:        // sort by the Unicode code point
                    173:        sort_ToTable();
                    174: }
                    175: 
                    176: static int sort_cmp_Trans_rec_intCh(const void *a, const void *b) {
                    177:        return 
1.38      paf       178:                static_cast<const Charset::Tables::Rec *>(a)->intCh-
                    179:                static_cast<const Charset::Tables::Rec *>(b)->intCh;
1.1       paf       180: }
                    181: 
                    182: void Charset::sort_ToTable() {
1.10      paf       183:        _qsort(tables.toTable, tables.toTableSize, sizeof(*tables.toTable), 
1.1       paf       184:                sort_cmp_Trans_rec_intCh);
                    185:        //FILE *f=fopen("c:\\temp\\a", "wb");
1.10      paf       186:        //fwrite(tables.toTable, tables.toTableSize, sizeof(*tables.toTable), f);
1.1       paf       187:        //fclose(f);
                    188: }
                    189: 
1.60      misha     190: // @todo: precache for spedup searching
1.10      paf       191: static XMLByte xlatOneTo(const XMLCh toXlat,
1.35      paf       192:                         const Charset::Tables& tables,
                    193:                         XMLByte not_found) {
1.39      paf       194:        int    lo = 0;
                    195:        int    hi = tables.toTableSize - 1;
                    196:        while(lo<=hi) {
1.35      paf       197:                // Calc the mid point of the low and high offset.
1.39      paf       198:                const unsigned int i = (lo + hi) / 2;
                    199: 
                    200:                XMLCh cur=tables.toTable[i].intCh;
                    201:                if(toXlat==cur)
                    202:                        return tables.toTable[i].extCh;
                    203:                if(toXlat>cur)
                    204:                        lo = i+1;
1.1       paf       205:                else
1.39      paf       206:                        hi = i-1;
                    207:        }
1.35      paf       208:        
                    209:        return not_found;
1.1       paf       210: }
                    211: 
1.35      paf       212: String::C Charset::transcode(const String::C src,
                    213:        const Charset& source_charset, 
                    214:        const Charset& dest_charset) {
                    215:        if(!src.length)
                    216:                return String::C("", 0);
1.4       paf       217: 
1.1       paf       218:        switch((source_charset.isUTF8()?0x10:0x00)|(dest_charset.isUTF8()?0x01:0x00)) {
                    219:                default: // 0x00
1.35      paf       220:                        return source_charset.transcodeToCharset(src, dest_charset);
1.1       paf       221:                case 0x01:
1.35      paf       222:                        return source_charset.transcodeToUTF8(src);
1.1       paf       223:                case 0x10:
1.35      paf       224:                        return dest_charset.transcodeFromUTF8(src);
1.1       paf       225:                case 0x11:
1.35      paf       226:                        return src;
1.1       paf       227:        }
                    228: }
                    229: 
                    230: // ---------------------------------------------------------------------------
                    231: //  Local static data
                    232: //
                    233: //  gUTFBytes
                    234: //      A list of counts of trailing bytes for each initial byte in the input.
                    235: //
                    236: //  gUTFOffsets
                    237: //      A list of values to offset each result char type, according to how
                    238: //      many source bytes when into making it.
                    239: //
                    240: //  gFirstByteMark
                    241: //      A list of values to mask onto the first byte of an encoded sequence,
                    242: //      indexed by the number of bytes used to create the sequence.
                    243: // ---------------------------------------------------------------------------
                    244: static const XMLByte gUTFBytes[0x100] = {
                    245:         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    246:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    247:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    248:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    249:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    250:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    251:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    252:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    253:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    254:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    255:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    256:     ,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    257:     ,   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
                    258:     ,   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
                    259:     ,   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
                    260:     ,   3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
                    261: };
                    262: 
                    263: static const uint gUTFOffsets[6] = {
                    264:     0, 0x3080, 0xE2080, 0x3C82080, 0xFA082080, 0x82082080
                    265: };
                    266: 
                    267: static const XMLByte gFirstByteMark[7] = {
                    268:     0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
                    269: };
                    270: 
1.35      paf       271: static int transcodeToUTF8(const XMLByte* srcData, size_t& srcLen,
                    272:                           XMLByte *toFill, size_t& toFillLen,
                    273:                           const Charset::Tables& tables) {
1.11      paf       274:        const XMLByte* srcPtr=srcData;
                    275:        const XMLByte* srcEnd=srcData+srcLen;
                    276:        XMLByte* outPtr=toFill;
                    277:        XMLByte* outEnd=toFill+toFillLen;
1.1       paf       278: 
1.35      paf       279:        while(srcPtr<srcEnd) {
                    280:                uint curVal = tables.fromTable[*srcPtr];
1.1       paf       281:                if(!curVal) {
1.35      paf       282:                        // use the replacement character
                    283:                        *outPtr++= '?';
                    284:                        srcPtr++;
                    285:                        continue;
                    286:                }
1.1       paf       287: 
1.35      paf       288:                // Figure out how many bytes we need
                    289:                unsigned int encodedBytes;
                    290:                if(curVal<0x80)
                    291:                        encodedBytes = 1;
                    292:                else if(curVal<0x800)
                    293:                        encodedBytes = 2;
                    294:                else if(curVal<0x10000)
                    295:                        encodedBytes = 3;
                    296:                else if(curVal<0x200000)
                    297:                        encodedBytes = 4;
                    298:                else if(curVal<0x4000000)
                    299:                        encodedBytes = 5;
                    300:                else if(curVal<= 0x7FFFFFFF)
                    301:                        encodedBytes = 6;
                    302:                else {
                    303:                        // use the replacement character
                    304:                        *outPtr++= '?';
                    305:                        srcPtr++;
                    306:                        continue;
                    307:                }
1.11      paf       308: 
1.35      paf       309:                //  If we cannot fully get this char into the output buffer
                    310:                if (outPtr + encodedBytes > outEnd)
                    311:                        break;
                    312:                
                    313:                // We can do it, so update the source index
                    314:                srcPtr++;
                    315:                
                    316:                //  And spit out the bytes. We spit them out in reverse order
                    317:                //  here, so bump up the output pointer and work down as we go.
                    318:                outPtr+= encodedBytes;
                    319:                switch(encodedBytes) {
1.60      misha     320:                        case 6: *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
                    321:                                curVal>>= 6;
                    322:                        case 5: *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
                    323:                                curVal>>= 6;
                    324:                        case 4: *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
                    325:                                curVal>>= 6;
                    326:                        case 3: *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
                    327:                                curVal>>= 6;
                    328:                        case 2: *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
                    329:                                curVal>>= 6;
                    330:                        case 1: *--outPtr = XMLByte(curVal | gFirstByteMark[encodedBytes]);
1.35      paf       331:                }
                    332:                
                    333:                // Add the encoded bytes back in again to indicate we've eaten them
                    334:                outPtr+= encodedBytes;
                    335:        }
                    336:        
                    337:        // Update the bytes eaten
                    338:        srcLen = srcPtr - srcData;
                    339:        
                    340:        // Return the characters read
                    341:        toFillLen = outPtr - toFill;
                    342:        
1.29      paf       343:        //return srcPtr==srcEnd?(int)toFillLen:-1;
                    344: /*
                    345: xmlCharEncodingInputFunc
                    346: Returns :
                    347: the number of byte written, or -1 by lack of space, or -2 if the transcoding failed. The value of inlen after return is the
                    348: number of octets consumed as the return value is positive, else unpredictiable. The value of outlen after return is the number
                    349: of ocetes consumed.
                    350: */
                    351:        return 0;
1.1       paf       352: }
1.26      paf       353: /// @todo digital entites only when xml/html output [at output in html/xml mode, in html part of a letter]
1.35      paf       354: static int transcodeFromUTF8(const XMLByte* srcData, size_t& srcLen,
                    355:                             XMLByte* toFill, size_t& toFillLen,
                    356:                             const Charset::Tables& tables) {
1.11      paf       357:        const XMLByte* srcPtr=srcData;
                    358:        const XMLByte* srcEnd=srcData+srcLen;
                    359:        XMLByte* outPtr=toFill;
                    360:        XMLByte* outEnd=toFill+toFillLen;
1.1       paf       361: 
1.35      paf       362:        //  We now loop until we either run out of input data, or room to store
                    363:        while ((srcPtr < srcEnd) && (outPtr < outEnd)) {
                    364:                // Get the next leading byte out
                    365:                const XMLByte firstByte =* srcPtr;
                    366:                
                    367:                // Special-case ASCII, which is a leading byte value of<= 127
1.60      misha     368:                if(firstByte<=127) {
1.35      paf       369:                        *outPtr++= firstByte;
                    370:                        srcPtr++;
                    371:                        continue;
                    372:                }
                    373:                
                    374:                // See how many trailing src bytes this sequence is going to require
                    375:                const unsigned int trailingBytes = gUTFBytes[firstByte];
                    376:                
                    377:                //  If there are not enough source bytes to do this one, then we
                    378:                //  are done. Note that we done>= here because we are implicitly
                    379:                //  counting the 1 byte we get no matter what.
                    380:                if(srcPtr+trailingBytes>= srcEnd)
                    381:                        break;
                    382:                
                    383:                // Looks ok, so lets build up the value
                    384:                uint tmpVal=0;
                    385:                switch(trailingBytes) {
                    386:                case 5: tmpVal+=*srcPtr++; tmpVal<<=6;
                    387:                case 4: tmpVal+=*srcPtr++; tmpVal<<=6;
                    388:                case 3: tmpVal+=*srcPtr++; tmpVal<<=6;
                    389:                case 2: tmpVal+=*srcPtr++; tmpVal<<=6;
                    390:                case 1: tmpVal+=*srcPtr++; tmpVal<<=6;
                    391:                case 0: tmpVal+=*srcPtr++;
                    392:                        break;
                    393:                        
                    394:                default:
                    395:                        throw Exception(0,
                    396:                                0,
1.49      paf       397:                                "transcodeFromUTF8 error: wrong trailingBytes value(%d)", trailingBytes); // never
1.35      paf       398:                }
                    399:                tmpVal-=gUTFOffsets[trailingBytes];
                    400:                
                    401:                //  If it will fit into a single char, then put it in. Otherwise
                    402:                //  fail [*encode it as a surrogate pair. If its not valid, use the
                    403:                //  replacement char.*]
                    404:                if(!(tmpVal & 0xFFFF0000)) {
1.25      paf       405:                        if(XMLByte xlat=xlatOneTo(tmpVal, tables, 0))
                    406:                                *outPtr++=xlat;
1.49      paf       407:                        else {
1.50      paf       408:                                outPtr+=sprintf((char *)outPtr, "&#%u;", tmpVal); // &#decimal;
1.49      paf       409:                        }
                    410:                } else {
                    411:                        const XMLByte* recoverPtr=srcPtr-trailingBytes-1;
                    412:                        for(uint i=0; i<=trailingBytes; i++)
                    413:                                outPtr+=sprintf((char*)outPtr, "%%%02X", *recoverPtr++);
                    414:                }
1.1       paf       415:        }
1.35      paf       416:        
                    417:        // Update the bytes eaten
                    418:        srcLen = srcPtr - srcData;
                    419:        
                    420:        // Return the characters read
                    421:        toFillLen = outPtr - toFill;
1.11      paf       422: 
1.29      paf       423:        //return srcPtr==srcEnd?(int)toFillLen:-1;
                    424: /*
                    425: xmlCharEncodingOutputFunc
                    426: Returns :
                    427: the number of byte written, or -1 by lack of space, or -2 if the transcoding failed. The value of inlen after return is the
                    428: number of octets consumed as the return value is positive, else unpredictiable. The value of outlen after return is the number
                    429: of ocetes consumed.
                    430: */
                    431:        return 0;
1.10      paf       432: }
                    433: 
1.60      misha     434: static bool is_escaped(char c){
                    435:        return
                    436:                !(c<=127
                    437:                && (
                    438:                        ((c>='0') && (c<='9'))
                    439:                        || ((c>='A') && (c<='Z'))
                    440:                        || ((c>='a') && (c<='z'))
                    441:                        || strchr("*@-_+./", c)!=0
                    442:                ));
                    443: }
                    444: 
                    445: // read one utf8 character, return number of bytes needed for store it
1.61      misha     446: static unsigned int readChar(const XMLByte*& srcPtr, const XMLByte* srcEnd, XMLByte& firstByte, XMLCh& UTF8Char){
1.60      misha     447:        if(!srcPtr || !*srcPtr || srcPtr>=srcEnd)
                    448:                return 0;
                    449: 
                    450:        firstByte=*srcPtr;
                    451: 
                    452:        if(firstByte<=127){
                    453:                UTF8Char=firstByte;
                    454:                srcPtr++;
                    455:                return 1;
                    456:        }
                    457: 
                    458:        unsigned int trailingBytes=gUTFBytes[firstByte];
                    459: 
                    460:        if(srcPtr+trailingBytes>=srcEnd){
                    461:                return 0; // not enough bytes in source string for reading
                    462:        }
                    463: 
                    464:        uint tmpVal=0;
                    465:        switch(trailingBytes){
                    466:                case 5: tmpVal+=*srcPtr++; tmpVal<<=6;
                    467:                case 4: tmpVal+=*srcPtr++; tmpVal<<=6;
                    468:                case 3: tmpVal+=*srcPtr++; tmpVal<<=6;
                    469:                case 2: tmpVal+=*srcPtr++; tmpVal<<=6;
                    470:                case 1: tmpVal+=*srcPtr++; tmpVal<<=6;
                    471:                case 0: tmpVal+=*srcPtr++;
                    472:        }
                    473: 
                    474:        tmpVal-=gUTFOffsets[trailingBytes];
                    475:        UTF8Char=tmpVal;
                    476: 
                    477:        return trailingBytes+1;
                    478: }
                    479: 
1.62      misha     480: static unsigned int skipChar(const XMLByte*& srcPtr, const XMLByte* srcEnd){
                    481:        if(!srcPtr || !*srcPtr || srcPtr>=srcEnd)
                    482:                return 0;
                    483: 
1.63      misha     484:        unsigned int trailingBytes=gUTFBytes[*srcPtr]+1;
                    485:        srcPtr+=trailingBytes;
1.62      misha     486: 
                    487:        return trailingBytes;
1.61      misha     488: }
                    489: 
1.60      misha     490: // read char, return number of bytes needed for store it as UTF8
1.61      misha     491: static unsigned int readChar(const XMLByte*& srcPtr, const XMLByte* srcEnd, XMLByte& firstByte, XMLCh& UTF8Char, const Charset::Tables& tables){
1.60      misha     492:        if(!srcPtr || !*srcPtr || srcPtr>=srcEnd)
                    493:                return 0;
                    494: 
                    495:        firstByte=*srcPtr++;
                    496:        UTF8Char=tables.fromTable[firstByte];
                    497: 
                    498:        if(UTF8Char<0x80)
                    499:                return 1;
                    500:        else if(UTF8Char<0x800)
                    501:                return 2;
                    502:        else if(UTF8Char<0x10000)
                    503:                return 3;
                    504:        else if(UTF8Char<0x200000)
                    505:                return 4;
                    506:        else if(UTF8Char<0x4000000)
                    507:                return 5;
                    508:        else if(UTF8Char<= 0x7FFFFFFF)
                    509:                return 6;
                    510: 
                    511:        // will use the replacement character '?'
                    512:        firstByte=0;
                    513:        return 1;
                    514: }
                    515: 
                    516: static int escape(const XMLByte* srcData, size_t& srcLen,
                    517:                             XMLByte* toFill, size_t& toFillLen) {
                    518:        const XMLByte* srcPtr=srcData;
                    519:        const XMLByte* srcEnd=srcData+srcLen;
                    520:        XMLByte* outPtr=toFill;
                    521:        XMLByte* outEnd=toFill+toFillLen;
                    522:        XMLByte firstByte;
                    523:        XMLCh UTF8Char;
                    524:        uint charSize;
                    525: 
                    526:        // loop until we either run out of input data, or room to store
                    527:        while((outPtr < outEnd) && (charSize=readChar(srcPtr, srcEnd, firstByte, UTF8Char))){
                    528:                if(charSize==1){
                    529:                        if(is_escaped(firstByte)) // %XX
                    530:                                outPtr+=sprintf((char*)outPtr, "%%%02X", firstByte);
                    531:                        else
                    532:                                *outPtr++=firstByte;
                    533:                } else
                    534:                        outPtr+=sprintf((char*)outPtr, "%%u%04X", UTF8Char); // %uXXXX
                    535:        }
                    536:        
                    537:        // Update the bytes eaten
                    538:        srcLen=srcPtr-srcData;
                    539:        
                    540:        // Return the characters read
                    541:        toFillLen=outPtr-toFill;
                    542: 
                    543:        return 0;
                    544: }
                    545: 
                    546: static int escape(const XMLByte* srcData, size_t& srcLen,
                    547:                           XMLByte *toFill, size_t& toFillLen,
                    548:                           const Charset::Tables& tables) {
                    549:        const XMLByte* srcPtr=srcData;
                    550:        const XMLByte* srcEnd=srcData+srcLen;
                    551:        XMLByte* outPtr=toFill;
                    552:        //XMLByte* outEnd=toFill+toFillLen;
                    553:        XMLByte firstByte;
                    554:        XMLCh UTF8Char;
                    555:        uint charSize;
                    556: 
                    557:        while(charSize=readChar(srcPtr, srcEnd, firstByte, UTF8Char, tables)){
                    558:                if(charSize==1){
                    559:                        if(firstByte){
                    560:                                if(is_escaped(firstByte)) // %XX
                    561:                                        outPtr+=sprintf((char*)outPtr, "%%%02X", firstByte);
                    562:                                else
                    563:                                        *outPtr++=firstByte;
                    564:                        } else // add replacement char '?'
                    565:                                *outPtr++='?';
                    566:                } else
                    567:                        outPtr+=sprintf((char*)outPtr, "%%u%04X", UTF8Char); // %uXXXX
                    568:        }
                    569: 
                    570:        // Update the bytes eaten
                    571:        srcLen = srcPtr - srcData;
                    572:        
                    573:        // Return the characters read
                    574:        toFillLen = outPtr - toFill;
                    575:        
                    576:        return 0;
                    577: }
                    578: 
                    579: 
                    580: String::C Charset::escape(const String::C src, const Charset& source_charset){
                    581:        size_t src_length=src.length;
                    582:        if(!src_length)
                    583:                return String::C("", 0);
                    584: 
                    585: #ifdef PRECALCULATE_DEST_LENGTH
                    586:        size_t dest_length=0;
                    587:        const XMLByte* srcPtr=(XMLByte*)src.str;
                    588:        const XMLByte* srcEnd=srcPtr+src_length;
                    589:        XMLByte firstByte;
                    590:        XMLCh UTF8Char;
                    591: 
                    592:        if(source_charset.isUTF8()){
                    593:                while(uint charSize=readChar(srcPtr, srcEnd, firstByte, UTF8Char)){
                    594:                        if(charSize==1)
                    595:                                dest_length+=!is_escaped(firstByte)?1:3/*%XX*/;
                    596:                        else
                    597:                                dest_length+=6; // '%uXXXX'
                    598:                }
                    599:        } else {
                    600:                while(uint charSize=readChar(srcPtr, srcEnd, firstByte, UTF8Char, source_charset.tables)){
                    601:                        if(charSize==1)
                    602:                                dest_length+=(!firstByte/*replacement char '?'*/ || !is_escaped(firstByte))?1:3/*'%XX'*/;
                    603:                        else
                    604:                                dest_length+=6; // '%uXXXX'
                    605:                }
                    606:        }
                    607: #else
                    608:        size_t dest_length=src_length*6; // enough for %uXXXX but too memory-hungry
                    609: #endif
                    610: 
                    611:        //throw Exception(0,0,"%u",dest_length);
                    612: 
                    613: #ifndef NDEBUG
                    614:        size_t saved_dest_length=dest_length;
                    615: #endif
                    616:        XMLByte *dest_body=new(PointerFreeGC) XMLByte[dest_length+1/*for terminator*/];
                    617: 
                    618:        int status;
                    619:        if(source_charset.isUTF8()){
                    620:                status=::escape((XMLByte *)src.str, src_length, dest_body, dest_length);
                    621:        } else {
                    622:                status=::escape((XMLByte *)src.str, src_length, dest_body, dest_length, source_charset.tables);
                    623:        }
                    624: 
                    625:        if(status<0)
                    626:                throw Exception(0,
                    627:                        0,
                    628:                        "Charset::escapeString buffer overflow");
                    629: 
                    630:        assert(dest_length<=saved_dest_length);
                    631:        dest_body[dest_length]=0; // terminator
                    632:        return String::C((char*)dest_body, dest_length);
                    633: }
                    634:        
1.64      misha     635: String::Body Charset::escape(const String::Body src, const Charset& source_charset) {
                    636:        const char *src_ptr=src.cstr();
                    637:        size_t src_size=strlen(src_ptr);
                    638: 
                    639:        String::C dest=Charset::escape(String::C(src_ptr, src_size),
                    640:                source_charset);
                    641: 
                    642:        return String::Body(dest.str, dest.length);
                    643: }
                    644: 
                    645: String& Charset::escape(const String& src, const Charset& source_charset) {
                    646:        if(!src.length())
                    647:                return *new String("", 0, false);
                    648: 
                    649:        return *new String(escape((String::Body)src, source_charset), String::L_CLEAN);
                    650: }
1.60      misha     651: 
1.35      paf       652: const String::C Charset::transcodeToUTF8(const String::C src) const {
                    653:        size_t src_length=src.length;
1.60      misha     654: 
                    655: #ifdef PRECALCULATE_DEST_LENGTH
                    656:        size_t dest_length=0;
                    657:        const XMLByte* srcPtr=(XMLByte*)src.str;
                    658:        const XMLByte* srcEnd=srcPtr+src_length;
                    659:        XMLByte firstByte;
                    660:        XMLCh UTF8Char;
                    661:        while(uint charSize=readChar(srcPtr, srcEnd, firstByte, UTF8Char, tables))
                    662:                dest_length+=charSize;
                    663: #else
                    664:        size_t dest_length=src_length*6; // so that surly enough (max utf8 seq len=6) but too memory-hyngry
                    665: #endif
                    666: 
                    667:        //throw Exception(0,0,"%u",dest_length);
                    668: 
1.35      paf       669: #ifndef NDEBUG
                    670:        size_t saved_dest_length=dest_length;
                    671: #endif
                    672:        XMLByte *dest_body=new(PointerFreeGC) XMLByte[dest_length+1/*for terminator*/];
1.11      paf       673: 
                    674:        if(::transcodeToUTF8(
1.35      paf       675:                (XMLByte *)src.str, src_length,
                    676:                dest_body, dest_length,
1.11      paf       677:                tables)<0)
1.43      paf       678:                throw Exception(0,
1.10      paf       679:                        0,
1.11      paf       680:                        "Charset::transcodeToUTF8 buffer overflow");
1.10      paf       681: 
1.60      misha     682:        assert(dest_length<=saved_dest_length);
                    683:        dest_body[dest_length]=0; // terminator
1.35      paf       684:        return String::C((char*)dest_body, dest_length);
1.10      paf       685: }
1.38      paf       686: 
                    687: static XMLCh change_case_UTF8(const XMLCh src, const Charset::UTF8CaseTable& table) {
1.39      paf       688:        int    lo = 0;
                    689:        int    hi = table.size - 1;
                    690:        while(lo<=hi) {
1.38      paf       691:                // Calc the mid point of the low and high offset.
1.39      paf       692:                const unsigned int i = (lo + hi) / 2;
                    693: 
                    694:                XMLCh cur=table.records[i].from;
                    695:                if(src==cur)
                    696:                        return table.records[i].to;
                    697:                if(src>cur)
                    698:                        lo = i+1;
1.38      paf       699:                else
1.39      paf       700:                        hi = i-1;
                    701:        }
                    702: 
                    703:        // not found
1.38      paf       704:        return src;
                    705: }
                    706: 
1.58      misha     707: static void store_UTF8(XMLCh src, XMLByte*& outPtr){
1.38      paf       708:        if(!src) {
                    709:                // use the replacement character
                    710:                *outPtr++= '?';
                    711:                return;
                    712:        }
                    713: 
                    714:        // Figure out how many bytes we need
                    715:        unsigned int encodedBytes;
                    716:        if(src<0x80)
                    717:                encodedBytes = 1;
                    718:        else if(src<0x800)
                    719:                encodedBytes = 2;
                    720:        else if(src<0x10000)
                    721:                encodedBytes = 3;
                    722:        else if(src<0x200000)
                    723:                encodedBytes = 4;
                    724:        else if(src<0x4000000)
                    725:                encodedBytes = 5;
                    726:        else if(src<= 0x7FFFFFFF)
                    727:                encodedBytes = 6;
                    728:        else {
                    729:                // use the replacement character
                    730:                *outPtr++= '?';
                    731:                return;
                    732:        }
                    733: 
                    734:        //  And spit out the bytes. We spit them out in reverse order
                    735:        //  here, so bump up the output pointer and work down as we go.
                    736:        outPtr+= encodedBytes;
                    737:        switch(encodedBytes) {
                    738:        case 6: *--outPtr = XMLByte((src | 0x80UL) & 0xBFUL);
                    739:                src>>= 6;
                    740:        case 5: *--outPtr = XMLByte((src | 0x80UL) & 0xBFUL);
                    741:                src>>= 6;
                    742:        case 4: *--outPtr = XMLByte((src | 0x80UL) & 0xBFUL);
                    743:                src>>= 6;
                    744:        case 3: *--outPtr = XMLByte((src | 0x80UL) & 0xBFUL);
                    745:                src>>= 6;
                    746:        case 2: *--outPtr = XMLByte((src | 0x80UL) & 0xBFUL);
                    747:                src>>= 6;
                    748:        case 1: *--outPtr = XMLByte(src | gFirstByteMark[encodedBytes]);
                    749:        }
                    750:        
                    751:        // Add the encoded bytes back in again to indicate we've eaten them
                    752:        outPtr+= encodedBytes;
                    753: }
                    754: 
                    755: static void change_case_UTF8(XMLCh src, XMLByte*& outPtr, 
                    756:                                                const Charset::UTF8CaseTable& table) {
                    757:        store_UTF8(change_case_UTF8(src, table), outPtr);
                    758: };
1.44      paf       759: void change_case_UTF8(const XMLByte* srcData, size_t srcLen,
                    760:                                          XMLByte* toFill, size_t toFillLen,
                    761:                                          const Charset::UTF8CaseTable& table) {
1.38      paf       762:        const XMLByte* srcPtr=srcData;
1.44      paf       763:        const XMLByte* srcEnd=srcData+srcLen;
1.38      paf       764:        XMLByte* outPtr=toFill;
1.44      paf       765:        XMLByte* outEnd=toFill+toFillLen;
                    766: 
                    767:        //  We now loop until we either run out of input data, or room to store
                    768:        while ((srcPtr < srcEnd) && (outPtr < outEnd)) {
                    769:                // Get the next leading byte out
                    770:                const XMLByte firstByte =* srcPtr;
1.38      paf       771: 
1.60      misha     772:                if(firstByte<=127) {
1.38      paf       773:                        change_case_UTF8(firstByte, outPtr, table);
                    774:                        srcPtr++;
                    775:                        continue;
                    776:                }
                    777:                
                    778:                // See how many trailing src bytes this sequence is going to require
                    779:                const unsigned int trailingBytes = gUTFBytes[firstByte];
                    780:                
                    781:                // Looks ok, so lets build up the value
                    782:                uint tmpVal=0;
                    783:                switch(trailingBytes) {
                    784:                case 5: tmpVal+=*srcPtr++; tmpVal<<=6;
                    785:                case 4: tmpVal+=*srcPtr++; tmpVal<<=6;
                    786:                case 3: tmpVal+=*srcPtr++; tmpVal<<=6;
                    787:                case 2: tmpVal+=*srcPtr++; tmpVal<<=6;
                    788:                case 1: tmpVal+=*srcPtr++; tmpVal<<=6;
                    789:                case 0: tmpVal+=*srcPtr++;
                    790:                        break;
                    791:                        
                    792:                default:
                    793:                        throw Exception(0,
                    794:                                0,
                    795:                                "change_case_UTF8 error: wrong trailingBytes value(%d)", trailingBytes);
                    796:                }
                    797:                tmpVal-=gUTFOffsets[trailingBytes];
                    798:                
                    799:                //  If it will fit into a single char, then put it in. Otherwise
                    800:                //  fail [*encode it as a surrogate pair. If its not valid, use the
                    801:                //  replacement char.*]
                    802:                if(!(tmpVal & 0xFFFF0000))
                    803:                        change_case_UTF8(tmpVal, outPtr, table);
                    804:                else
                    805:                        throw Exception(0,
                    806:                                0,
                    807:                                "change_case_UTF8 error: too big tmpVal(0x%08X)", tmpVal);
                    808:        }
                    809:        
                    810:        if(srcPtr!=outPtr)
                    811:                throw Exception(0,  
                    812:                        0,
                    813:                        "change_case_UTF8 error: end pointers do not match");
                    814: }
                    815: 
1.60      misha     816: static size_t getDecNumLength(XMLCh UTF8Char){
                    817:        return
                    818:                (UTF8Char < 100)
                    819:                        ?2
                    820:                        :(UTF8Char < 1000)
                    821:                                ?3
                    822:                                :(UTF8Char < 10000)
                    823:                                        ?4
                    824:                                        :5;
                    825: }
1.38      paf       826: 
1.35      paf       827: const String::C Charset::transcodeFromUTF8(const String::C src) const {
                    828:        size_t src_length=src.length;
1.60      misha     829: 
                    830: #ifdef PRECALCULATE_DEST_LENGTH
                    831:        size_t dest_length=0;
                    832:        const XMLByte* srcPtr=(XMLByte*)src.str;
                    833:        const XMLByte* srcEnd=srcPtr+src_length;
                    834:        XMLByte firstByte;
                    835:        XMLCh UTF8Char;
                    836:        while(uint charSize=readChar(srcPtr, srcEnd, firstByte, UTF8Char)){
                    837:                if(charSize==1)
                    838:                        dest_length++;
                    839:                else
                    840:                        dest_length+=(UTF8Char & 0xFFFF0000)
                    841:                                                        ?charSize*3     // '%XX' for each byte
                    842:                                                        :(xlatOneTo(UTF8Char, tables, 0)!=0)
                    843:                                                                ?1              // can convert it to single char
                    844:                                                                :getDecNumLength(UTF8Char)+3;           // &#XX; - &#XXXXX;
                    845:        }
                    846: #else
                    847:        // so that surly enough, "&#XXX;" has max ratio (huh? 8 bytes needed for '&#XXXXX;')
                    848:        size_t dest_length=src_length*6;
                    849: #endif
                    850: 
                    851:        //throw Exception(0,0,"%u",dest_length);
                    852: 
1.35      paf       853: #ifndef NDEBUG
                    854:        size_t saved_dest_length=dest_length;
                    855: #endif
                    856:        XMLByte *dest_body=new(PointerFreeGC) XMLByte[dest_length+1/*for terminator*/];
1.11      paf       857: 
                    858:        if(::transcodeFromUTF8(
1.35      paf       859:                (XMLByte *)src.str, src_length,
                    860:                dest_body, dest_length,
1.11      paf       861:                tables)<0)
1.43      paf       862:                throw Exception(0, 
1.10      paf       863:                        0,
1.35      paf       864:                        "Charset::transcodeFromUTF8 buffer overflow");
1.10      paf       865: 
1.60      misha     866:        assert(dest_length<=saved_dest_length);
                    867:        dest_body[dest_length]=0; // terminator
1.35      paf       868:        return String::C((char*)dest_body, dest_length);
1.1       paf       869: }
                    870: 
                    871: /// transcode using both charsets
1.35      paf       872: const String::C Charset::transcodeToCharset(const String::C src, 
                    873:                                            const Charset& dest_charset) const {
                    874:        if(&dest_charset==this) 
                    875:                return src;
                    876:        else {
                    877:                size_t dest_length=src.length;
                    878:                XMLByte* dest_body=new(PointerFreeGC) XMLByte[dest_length+1/*for terminator*/];
                    879: 
                    880:                XMLByte* output=dest_body;
                    881:                const XMLByte* input=(XMLByte *)src.str;
                    882:                while(XMLCh c=*input++) {
                    883:                        XMLCh curVal = tables.fromTable[c];
                    884:                        *output++=curVal?
                    885:                                xlatOneTo(curVal, dest_charset.tables, '?') // OK
                    886:                                :'?'; // use the replacement character
1.6       paf       887:                }
1.1       paf       888: 
1.35      paf       889:                dest_body[dest_length]=0; // terminator
                    890:                return String::C((char*)dest_body, dest_length);
1.6       paf       891:        }
1.1       paf       892: }                      
                    893: 
1.58      misha     894: void Charset::store_Char(XMLByte*& outPtr, XMLCh src, XMLByte not_found){
1.59      misha     895:        if(isUTF8())
1.58      misha     896:                store_UTF8(src, outPtr);
1.59      misha     897:        else if(char ch=xlatOneTo(src, tables, not_found))
1.58      misha     898:                        *outPtr++=ch;
1.57      misha     899: }
                    900: 
1.1       paf       901: #ifdef XML
1.10      paf       902: 
1.35      paf       903: static const Charset::Tables* tables[MAX_CHARSETS];
                    904: 
1.46      paf       905: #ifdef PA_PATCHED_LIBXML_BACKWARD
                    906: 
                    907: #define declareXml256ioFuncs(i) \
                    908:        static int xml256CharEncodingInputFunc##i( \
                    909:                unsigned char *out, int *outlen, \
                    910:                const unsigned char *in, int *inlen, void*) { \
                    911:                return transcodeToUTF8( \
                    912:                        in, *(size_t*)inlen, \
                    913:                        out, *(size_t*)outlen, \
                    914:                        *tables[i]); \
                    915:        } \
                    916:        static int xml256CharEncodingOutputFunc##i( \
                    917:                unsigned char *out, int *outlen, \
                    918:                const unsigned char *in, int *inlen, void*) { \
                    919:                return transcodeFromUTF8( \
                    920:                        in, *(size_t*)inlen, \
                    921:                        out, *(size_t*)outlen, \
                    922:                        *tables[i]); \
                    923:        }
                    924: 
                    925: #else
                    926: 
1.35      paf       927: #define declareXml256ioFuncs(i) \
                    928:        static int xml256CharEncodingInputFunc##i( \
                    929:                unsigned char *out, int *outlen, \
                    930:                const unsigned char *in, int *inlen) { \
                    931:                return transcodeToUTF8( \
                    932:                        in, *(size_t*)inlen, \
                    933:                        out, *(size_t*)outlen, \
                    934:                        *tables[i]); \
                    935:        } \
                    936:        static int xml256CharEncodingOutputFunc##i( \
                    937:                unsigned char *out, int *outlen, \
                    938:                const unsigned char *in, int *inlen) { \
                    939:                return transcodeFromUTF8( \
                    940:                        in, *(size_t*)inlen, \
                    941:                        out, *(size_t*)outlen, \
                    942:                        *tables[i]); \
                    943:        }
                    944: 
1.46      paf       945: #endif
                    946: 
                    947: 
1.35      paf       948: declareXml256ioFuncs(0)        declareXml256ioFuncs(1)
                    949: declareXml256ioFuncs(2)        declareXml256ioFuncs(3)
                    950: declareXml256ioFuncs(4)        declareXml256ioFuncs(5)
                    951: declareXml256ioFuncs(6)        declareXml256ioFuncs(7)
                    952: declareXml256ioFuncs(8)        declareXml256ioFuncs(9)
                    953: 
                    954: static xmlCharEncodingInputFunc inputFuncs[MAX_CHARSETS]={
                    955:        xml256CharEncodingInputFunc0,   xml256CharEncodingInputFunc1,
                    956:        xml256CharEncodingInputFunc2,   xml256CharEncodingInputFunc3,
                    957:        xml256CharEncodingInputFunc4,   xml256CharEncodingInputFunc5,
                    958:        xml256CharEncodingInputFunc6,   xml256CharEncodingInputFunc7,
                    959:        xml256CharEncodingInputFunc8,   xml256CharEncodingInputFunc9
                    960: };
                    961: static xmlCharEncodingOutputFunc outputFuncs[MAX_CHARSETS]={
                    962:        xml256CharEncodingOutputFunc0,  xml256CharEncodingOutputFunc1,
                    963:        xml256CharEncodingOutputFunc2,  xml256CharEncodingOutputFunc3,
                    964:        xml256CharEncodingOutputFunc4,  xml256CharEncodingOutputFunc5,
                    965:        xml256CharEncodingOutputFunc6,  xml256CharEncodingOutputFunc7,
                    966:        xml256CharEncodingOutputFunc8,  xml256CharEncodingOutputFunc9
                    967: };
                    968: static size_t handlers_count=0;
1.10      paf       969: 
                    970: void Charset::addEncoding(char *name_cstr) {
1.35      paf       971:        if(handlers_count==MAX_CHARSETS)
                    972:                throw Exception(0,
                    973:                        0,
                    974:                        "already allocated %d handlers, no space for new encoding '%s'",
                    975:                                MAX_CHARSETS, name_cstr);
                    976: 
1.45      paf       977:        xmlCharEncodingHandler* handler=new(UseGC) xmlCharEncodingHandler;
1.35      paf       978:        {
                    979:                handler->name=name_cstr;
                    980:                handler->input=inputFuncs[handlers_count]; 
                    981:                handler->output=outputFuncs[handlers_count]; 
                    982:                ::tables[handlers_count]=&tables;
                    983:                handlers_count++;
                    984:        }
1.10      paf       985:        
                    986:        xmlRegisterCharEncodingHandler(handler);
1.35      paf       987: 
1.10      paf       988: }
                    989: 
1.37      paf       990: void Charset::initTranscoder(const String::Body NAME, const char* name_cstr) {
1.15      paf       991:        ftranscoder=xmlFindCharEncodingHandler(name_cstr);
1.35      paf       992:        transcoder(NAME); // check right way
1.15      paf       993: }
                    994: 
1.37      paf       995: xmlCharEncodingHandler& Charset::transcoder(const String::Body NAME) {
1.15      paf       996:        if(!ftranscoder)
1.56      misha     997:                throw Exception(PARSER_RUNTIME,
1.35      paf       998:                        new String(NAME, String::L_TAINTED),
1.10      paf       999:                        "unsupported encoding");
1.35      paf      1000:        return *ftranscoder;
1.10      paf      1001: }
                   1002: 
1.54      paf      1003: String::C Charset::transcode_cstr(const xmlChar* s) {
1.13      paf      1004:        if(!s)
1.35      paf      1005:                return String::C("", 0);
1.8       paf      1006: 
1.35      paf      1007:        int inlen=strlen((const char*)s);
1.51      paf      1008:        int outlen=inlen*6/*strlen("&#255;")*/; // max
1.35      paf      1009: #ifndef NDEBUG
                   1010:        int saved_outlen=outlen;
                   1011: #endif
                   1012:        char *out=new(PointerFreeGC) char[outlen+1];
1.8       paf      1013:        
1.30      paf      1014:        int error;
1.35      paf      1015:        if(xmlCharEncodingOutputFunc output=transcoder(FNAME).output) {
1.30      paf      1016:                error=output(
1.17      paf      1017:                        (unsigned char*)out, &outlen,
1.46      paf      1018:                        (const unsigned char*)s, &inlen
                   1019: #ifdef PA_PATCHED_LIBXML_BACKWARD
                   1020:                        ,0
                   1021: #endif
                   1022:                        );
1.30      paf      1023:        } else {
                   1024:                memcpy(out, s, outlen=inlen);
                   1025:                error=0;
                   1026:        }
                   1027:        if(error<0)
1.23      paf      1028:                throw Exception(0,
1.8       paf      1029:                        0,
1.30      paf      1030:                        "transcode_cstr failed (%d)", error);
1.8       paf      1031: 
1.35      paf      1032:        assert(outlen<=saved_outlen); out[outlen]=0;
                   1033:        return String::C(out, outlen);
1.14      paf      1034: }
1.54      paf      1035: const String& Charset::transcode(const xmlChar* s) { 
1.35      paf      1036:        String::C cstr=transcode_cstr(s);
                   1037:        return *new String(cstr.str, cstr.length, true);
1.1       paf      1038: }
                   1039: 
1.8       paf      1040: /// @test less memory using -maybe- xmlParserInputBufferCreateMem
1.35      paf      1041: xmlChar* Charset::transcode_buf2xchar(const char* buf, size_t buf_size) {
                   1042:        xmlChar* out;
1.30      paf      1043:        int outlen;
                   1044:        int error;
1.35      paf      1045: #ifndef NDEBUG
                   1046:        int saved_outlen;
                   1047: #endif
                   1048:        if(xmlCharEncodingInputFunc input=transcoder(FNAME).input) {
1.51      paf      1049:                outlen=buf_size*6/*max UTF8 bytes per char*/;
1.35      paf      1050: #ifndef NDEBUG
                   1051:                saved_outlen=outlen;
                   1052: #endif
1.47      paf      1053:                out=(xmlChar*)xmlMalloc(outlen+1);
1.30      paf      1054:                error=input(
1.17      paf      1055:                        out, &outlen,
1.46      paf      1056:                        (const unsigned char*)buf, (int*)&buf_size
                   1057: #ifdef PA_PATCHED_LIBXML_BACKWARD
                   1058:                        ,0
                   1059: #endif
                   1060:                        );
1.30      paf      1061:        } else {
                   1062:                outlen=buf_size;
1.35      paf      1063: #ifndef NDEBUG
                   1064:                saved_outlen=outlen;
                   1065: #endif
                   1066:                out=(xmlChar*)xmlMalloc(outlen+1);
1.30      paf      1067:                memcpy(out, buf, outlen);
                   1068:                error=0;
                   1069:        }
1.17      paf      1070:        
1.30      paf      1071:        if(error<0)
1.23      paf      1072:                throw Exception(0,
1.8       paf      1073:                        0,
1.30      paf      1074:                        "transcode_buf failed (%d)", error);
1.8       paf      1075: 
1.35      paf      1076:        assert(outlen<=saved_outlen); out[outlen]=0;
                   1077:        return out;
1.24      paf      1078: }
1.54      paf      1079: xmlChar* Charset::transcode(const String& s) { 
1.35      paf      1080:        const char* cstr=s.cstr(String::L_UNSPECIFIED);
1.1       paf      1081: 
1.54      paf      1082:        return transcode_buf2xchar(cstr, strlen(cstr)); 
1.1       paf      1083: }
1.54      paf      1084: xmlChar* Charset::transcode(const String::Body s) { 
1.35      paf      1085:        const char* cstr=s.cstr();
                   1086: 
1.54      paf      1087:        return transcode_buf2xchar(cstr, s.length()); 
1.35      paf      1088: }
1.36      paf      1089: #endif
1.34      paf      1090: 
1.37      paf      1091: String::Body Charset::transcode(const String::Body src, 
1.34      paf      1092:        const Charset& source_transcoder, 
1.35      paf      1093:        const Charset& dest_transcoder) {
1.34      paf      1094: 
1.35      paf      1095:        const char *src_ptr=src.cstr();
1.34      paf      1096:        size_t src_size=strlen(src_ptr);
                   1097: 
1.35      paf      1098:        String::C dest=Charset::transcode(String::C(src_ptr, src_size),
                   1099:                source_transcoder,
                   1100:                dest_transcoder);
1.34      paf      1101: 
1.37      paf      1102:        return String::Body(dest.str, dest.length);
1.35      paf      1103: }
                   1104: 
                   1105: String& Charset::transcode(const String& src, 
                   1106:        const Charset& source_transcoder, 
                   1107:        const Charset& dest_transcoder) {
                   1108:        if(!src.length())
                   1109:                return *new String("", 0, false);
1.34      paf      1110: 
1.37      paf      1111:        return *new String(transcode((String::Body)src, source_transcoder, dest_transcoder), String::L_CLEAN);
1.34      paf      1112: }
                   1113: 
1.35      paf      1114: void Charset::transcode(ArrayString& src,
1.34      paf      1115:        const Charset& source_transcoder, 
1.35      paf      1116:        const Charset& dest_transcoder) {
                   1117:        for(size_t i=0; i<src.count(); i++)
                   1118:                src.put(i, &transcode(*src[i], source_transcoder, dest_transcoder));
1.34      paf      1119: }
                   1120: 
                   1121: #ifndef DOXYGEN
                   1122: struct Transcode_pair_info {
                   1123:        const Charset* source_transcoder;
                   1124:        const Charset* dest_transcoder;
                   1125: };
                   1126: #endif
1.40      paf      1127: static void transcode_pair(const String::Body /*akey*/, 
1.37      paf      1128:                         String::Body& avalue, 
1.35      paf      1129:                         Transcode_pair_info* info) {
                   1130:        avalue=Charset::transcode(avalue,
                   1131:                *info->source_transcoder, 
                   1132:                *info->dest_transcoder);
1.34      paf      1133: }
1.61      misha    1134: 
1.35      paf      1135: void Charset::transcode(HashStringString& src,
1.34      paf      1136:        const Charset& source_transcoder, 
1.35      paf      1137:        const Charset& dest_transcoder) {
                   1138:        Transcode_pair_info info={&source_transcoder, &dest_transcoder};
1.55      paf      1139:        src.for_each_ref<Transcode_pair_info*>(transcode_pair, &info);
1.34      paf      1140: }
1.61      misha    1141: 
                   1142: size_t getUTF8BytePos(const XMLByte* srcBegin, const XMLByte* srcEnd, size_t charPos){
                   1143:        const XMLByte* ptr=srcBegin;
1.62      misha    1144:        while(charPos-- && skipChar(ptr, srcEnd));
1.61      misha    1145: 
                   1146:        return ptr-srcBegin;
                   1147: }
                   1148: 
                   1149: size_t getUTF8CharPos(const XMLByte* srcBegin, const XMLByte* srcEnd, size_t bytePos){
                   1150:        size_t charPos=0;
                   1151:        const XMLByte* ptr=srcBegin;
                   1152:        const XMLByte* ptrEnd=srcBegin+bytePos;
1.62      misha    1153:        while(skipChar(ptr, srcEnd)){
1.61      misha    1154:                if(ptr>ptrEnd)
                   1155:                        return charPos;
                   1156:                charPos++;
                   1157:        }
                   1158: 
                   1159:        // scan till end but position in bytes still too low
                   1160:        throw Exception(0,
                   1161:                                        0,
                   1162:                                        "Error convertion byte pos to char pos");
                   1163: }
                   1164: 
                   1165: size_t lengthUTF8(const XMLByte* srcBegin, const XMLByte* srcEnd){
                   1166:        size_t size=0;
1.62      misha    1167:        while(skipChar(srcBegin, srcEnd))
1.61      misha    1168:                size++;
                   1169: 
                   1170:        return size;
                   1171: }

E-mail: