--- parser3/src/main/pa_string.C 2026/11/01 14:41:57 1.288 +++ parser3/src/main/pa_string.C 2026/11/03 14:16:14 1.290 @@ -12,7 +12,7 @@ #include "pa_charset.h" #include "pa_vregex.h" -volatile const char * IDENT_PA_STRING_C="$Id: pa_string.C,v 1.288 2026/11/01 14:41:57 moko Exp $" IDENT_PA_STRING_H; +volatile const char * IDENT_PA_STRING_C="$Id: pa_string.C,v 1.290 2026/11/03 14:16:14 moko Exp $" IDENT_PA_STRING_H; const String String::Empty; @@ -404,11 +404,12 @@ String& String::mid(size_t substr_begin, return result; } -// from, to and helper_length in characters, not in bytes (it's important for utf-8) -String& String::mid(Charset& charset, size_t from, size_t to, size_t helper_length) const { +// from and to in characters, not in bytes (it's important for utf-8) +String& String::mid(Charset& charset, size_t from, size_t to) const { String& result=*new String; - size_t self_length=helper_length ? helper_length : length(charset); + // utf-8 length is not needed: converting to bytes stops at the end of the string by itself + size_t self_length=charset.isUTF8() ? to : length(); if(!self_length) return result; @@ -441,6 +442,34 @@ String& String::mid(Charset& charset, si return result; } +// n in characters, not in bytes (it's important for utf-8) +const String& String::right(Charset& charset, size_t n) const { + size_t self_length=body.length(); + size_t from; + + if(charset.isUTF8()){ + const XMLByte* src_begin=(const XMLByte*)cstr(); + const XMLByte* src_end=src_begin+self_length; + const XMLByte* ptr=src_end; + + // step back by n characters: continuation bytes (80-BF) belong to the leading byte before them, + // but only if it expects exactly that many, otherwise the byte is a character of its own (as length() counts it); + // the only exception is the last character cut off by the end of the string, length() counts it as a whole + while(n-- && ptr>src_begin) { + const XMLByte* lead=ptr-1; + while(lead>src_begin && (*lead & 0xC0)==0x80 && ptr-lead<6) // 6 bytes is the longest character + lead--; + size_t expected=lengthUTF8Char(*lead); + size_t present=ptr-lead; + ptr=(expected==present || (expected>present && ptr==src_end)) ? lead : ptr-1; + } + from=ptr-src_begin; + } else + from=self_length>n ? self_length-n : 0; + + return from ? mid(from, self_length) : *this; +} + size_t String::pos(const String::Body substr, size_t this_offset, Language lang) const { size_t substr_length=substr.length(); while(true) {