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

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

E-mail: