This commit is contained in:
2022-11-25 21:35:39 +03:00
parent a2256a3872
commit dc6fbbf7ec
37 changed files with 1498 additions and 1321 deletions

385
libs/main/text/pichar.cpp Normal file
View File

@@ -0,0 +1,385 @@
/*
PIP - Platform Independent Primitives
Unicode char
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piincludes_p.h"
#include "pistring.h"
#ifdef PIP_ICU
# define U_NOEXCEPT
# include "unicode/ucnv.h"
# include "unicode/ustring.h"
#endif
#ifdef WINDOWS
# include <stringapiset.h>
# include <winnls.h>
#endif
char * __syslocname__ = 0;
char * __sysoemname__ = 0;
char * __utf8name__ = 0;
#ifdef BLACKBERRY
# include <ctype.h>
#endif
#include <wchar.h>
//! \class PIChar pichar.h
//! \~\details
//! \~english
//! This class is wrapper around UTF16.
//! There are many contructors and information functions
//!
//! \~russian
//! %PIChar хранит один сивол в UTF16. Имеет много контрукторов, геттеров в различные
//! кодировки (системную, консольную, UTF8) и информационных функций.
//!
ushort charFromCodepage(const char * c, int size, const char * codepage, int * taken = 0) {
if (!c || size <= 0) return 0;
if (uchar(c[0]) < 0x80) return c[0];
int ret;
#ifdef PIP_ICU
UErrorCode e((UErrorCode)0);
UConverter * cc = ucnv_open(codepage, &e);
if (cc) {
UChar uc(0);
e = (UErrorCode)0;
ret = ucnv_toUChars(cc, &uc, 1, c, size, &e);
//printf("PIChar %d -> %d\n", c[0], uc);
if (taken) *taken = ret;
ucnv_close(cc);
return ushort(uc);
}
#else
# ifdef WINDOWS
wchar_t buffer;
ret = MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, size, &buffer, 1);
if (ret <= 0) return 0;
if (taken) *taken = ret;
return buffer;
# else
mbstate_t state;
memset(&state, 0, sizeof(state));
wchar_t wc;
ret = mbrtowc(&wc, c, size, &state);
//printf("mbtowc = %d\n", ret);
//piCout << errorString();
if (ret < 1) return 0;
return ushort(wc);
# endif
#endif
return ushort(c[0]);
}
int charCompare(const PIChar & f, const PIChar & s) {
if (f.isAscii() && s.isAscii())
return strncmp(f.toCharPtr(), s.toCharPtr(), 1);
return
#ifdef PIP_ICU
u_strCompare((const UChar*)f.toWCharPtr(), 1, (const UChar*)s.toWCharPtr(), 1, FALSE);
#else
# ifdef WINDOWS
CompareStringW(LOCALE_USER_DEFAULT, 0, (PCNZWCH)f.toWCharPtr(), 1, (PCNZWCH)s.toWCharPtr(), 1) - 2;
# else
wcsncmp((const wchar_t *)f.toWCharPtr(), (const wchar_t *)s.toWCharPtr(), 1);
# endif
#endif
}
bool winIsCharType(const ushort * ch, int type) {
#ifdef WINDOWS
WORD attr = 0;
if (GetStringTypeW(CT_CTYPE1, (LPCWCH)ch, 1, &attr) == 0) return false;
return ((attr & type) == type);
#endif
return false;
}
PIChar::PIChar(const char * c, int * bytes) {
ch = charFromCodepage(c, 4, __syslocname__, bytes);
}
PIChar PIChar::fromConsole(char c) {
PIChar ret;
ret.ch = charFromCodepage(&c, 1, __sysoemname__);
return ret;
}
PIChar PIChar::fromSystem(char c) {
PIChar ret;
ret.ch = charFromCodepage(&c, 1, __syslocname__);
return ret;
}
PIChar PIChar::fromUTF8(const char * c) {
PIChar ret;
int l = 0;
while (c[l] != '\0') ++l;
ret.ch = charFromCodepage(c, l, __utf8name__);
return ret;
}
bool PIChar::operator ==(const PIChar & o) const {
return ch == o.ch;
}
bool PIChar::operator >(const PIChar & o) const {
return charCompare(*this, o) > 0;
}
bool PIChar::operator <(const PIChar & o) const {
return charCompare(*this, o) < 0;
}
bool PIChar::operator >=(const PIChar & o) const {
return charCompare(*this, o) >= 0;
}
bool PIChar::operator <=(const PIChar & o) const {
return charCompare(*this, o) <= 0;
}
bool PIChar::isDigit() const {
if (isAscii()) return isdigit(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_DIGIT);
#else
return iswdigit(ch) != 0;
#endif
}
bool PIChar::isHex() const {
if (isAscii()) return isxdigit(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_XDIGIT);
#else
return iswxdigit(ch) != 0;
#endif
}
bool PIChar::isGraphical() const {
if (isAscii()) return isgraph(ch) != 0;
#ifdef WINDOWS
return !winIsCharType(&ch, C1_CNTRL);
#else
return iswgraph(ch) != 0;
#endif
}
bool PIChar::isControl() const {
if (isAscii()) return iscntrl(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_CNTRL);
#else
return iswcntrl(ch) != 0;
#endif
}
bool PIChar::isLower() const {
if (isAscii()) return islower(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_LOWER);
#else
return iswlower(ch) != 0;
#endif
}
bool PIChar::isUpper() const {
if (isAscii()) return isupper(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_UPPER);
#else
return iswupper(ch) != 0;
#endif
}
bool PIChar::isPrint() const {
if (isAscii()) return isprint(ch) != 0;
#ifdef WINDOWS
return !winIsCharType(&ch, C1_CNTRL);
#else
return iswprint(ch) != 0;
#endif
}
bool PIChar::isSpace() const {
if (isAscii()) return isspace(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_SPACE);
#else
return iswspace(ch) != 0;
#endif
}
bool PIChar::isAlpha() const {
if (isAscii()) return isalpha(ch) != 0;
#ifdef WINDOWS
return winIsCharType(&ch, C1_ALPHA);
#else
return iswalpha(ch) != 0;
#endif
}
bool PIChar::isAscii() const {
return isascii(ch) != 0;
}
const wchar_t * PIChar::toWCharPtr() const {
return reinterpret_cast<const wchar_t * >(&ch);
}
const char * PIChar::toCharPtr() const {
return reinterpret_cast<const char * >(&ch);
}
wchar_t PIChar::toWChar() const {
return wchar_t(ch);
}
char PIChar::toConsole1Byte() const {
if (ch < 0x80) return ch;
#ifdef PIP_ICU
UErrorCode e((UErrorCode)0);
UConverter * cc = ucnv_open(__sysoemname__, &e);
if (cc) {
char uc[8];
e = (UErrorCode)0;
ucnv_fromUChars(cc, uc, 8, (const UChar*)(&ch), 1, &e);
ucnv_close(cc);
return uc[0];
}
#endif
#ifdef WINDOWS
char ret[4] = {0,0,0,0};
WideCharToMultiByte(CP_OEMCP, 0, (LPCWCH)&ch, 1, ret, 4, NULL, NULL);
return ret[0];
#endif
return toAscii();
}
char PIChar::toSystem() const {
if (ch < 0x80) return ch;
#ifdef PIP_ICU
UErrorCode e((UErrorCode)0);
UConverter * cc = ucnv_open(__syslocname__, &e);
if (cc) {
char uc[8];
e = (UErrorCode)0;
ucnv_fromUChars(cc, uc, 8, (const UChar*)(&ch), 1, &e);
ucnv_close(cc);
return uc[0];
}
#endif
#ifdef WINDOWS
char ret[4] = {0,0,0,0};
WideCharToMultiByte(CP_ACP, 0, (LPCWCH)&ch, 1, ret, 4, NULL, NULL);
return ret[0];
#endif
return toAscii();
}
PIChar PIChar::toUpper() const {
if (isAscii()) return PIChar((ushort)toupper(ch));
#ifdef PIP_ICU
UChar c(0);
UErrorCode e((UErrorCode)0);
u_strToUpper(&c, 1, (const UChar*)(&ch), 1, 0, &e);
return PIChar((ushort)c);
#else
# ifdef WINDOWS
ushort wc = 0;
if (LCMapStringW(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, (LPCWSTR)&ch, 1, (LPWSTR)&wc, 1) == 1)
return PIChar(wc);
# endif
#endif
return PIChar((ushort)towupper(ch));
}
PIChar PIChar::toLower() const {
if (isAscii()) return PIChar((ushort)tolower(ch));
#ifdef PIP_ICU
UChar c(0);
UErrorCode e((UErrorCode)0);
u_strToLower(&c, 1, (const UChar*)(&ch), 1, 0, &e);
return PIChar((ushort)c);
#else
# ifdef WINDOWS
ushort wc = 0;
if (LCMapStringW(LOCALE_USER_DEFAULT, LCMAP_LOWERCASE, (LPCWSTR)&ch, 1, (LPWSTR)&wc, 1) == 1)
return PIChar(wc);
# endif
#endif
return PIChar((ushort)towlower(ch));
}
PICout operator <<(PICout s, const PIChar & v) {
s.space();
s.saveAndSetControls(0);
if (v.isAscii()) s << char(v.ch);
else {
#ifdef PIP_ICU
UErrorCode e((UErrorCode)0);
UConverter * cc = ucnv_open(__syslocname__, &e);
if (cc) {
char uc[8];
memset(uc, 0, 8);
e = (UErrorCode)0;
ucnv_fromUChars(cc, uc, 8, (const UChar*)(&v.ch), 1, &e);
ucnv_close(cc);
s << uc;
} else
#endif
#ifdef WINDOWS
s << v.toSystem();
#else
s << PIString(v);
#endif
}
s.restoreControls();
return s;
}

265
libs/main/text/pichar.h Normal file
View File

@@ -0,0 +1,265 @@
/*! \file pichar.h
* \ingroup Text
* \~\brief
* \~english Single string character
* \~russian Один символ строки
*/
/*
PIP - Platform Independent Primitives
Unicode char
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PICHAR_H
#define PICHAR_H
#include "piincludes.h"
extern PIP_EXPORT char * __syslocname__;
extern PIP_EXPORT char * __sysoemname__;
extern PIP_EXPORT char * __utf8name__;
//! \ingroup Text
//! \~\brief
//! \~english %PIChar represents a single character.
//! \~russian %PIChar представляет собой один символ строки.
class PIP_EXPORT PIChar
{
friend class PIString;
friend PICout operator <<(PICout s, const PIChar & v);
public:
//! \~english Contructs Ascii symbol
//! \~russian Создает символ Ascii
PIChar(char c) {ch = c;}
//! \~english Contructs ascii symbol
//! \~russian Создает символ Ascii
PIChar(uchar c) {ch = c;}
//! \~english Contructs 2-bytes symbol
//! \~russian Создает 2-байтный символ
PIChar(ushort c = 0) {ch = c;}
//! \~english Contructs 2-bytes symbol from `wchar_t`
//! \~russian Создает 2-байтный символ из `wchar_t`
PIChar(wchar_t c) {ch = c;}
//! \~english Contructs symbol from system locale and no more than 4 bytes of string
//! \~russian Создает символ из системной локали не более 4 байт длины
PIChar(const char * c, int * bytes = 0);
//! \~english Copy operator
//! \~russian Оператор присваивания
PIChar & operator =(const char v) {ch = v; return *this;}
//! \~english Copy operator
//! \~russian Оператор присваивания
PIChar & operator =(const wchar_t v) {ch = v; return *this;}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator ==(const PIChar & o) const;
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator !=(const PIChar & o) const {return !(o == *this);}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >(const PIChar & o) const;
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <(const PIChar & o) const;
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >=(const PIChar & o) const;
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <=(const PIChar & o) const;
//! \~english Returns \b true if symbol is digit ('0' to '9')
//! \~russian Возвращает \b true если символ является
bool isDigit() const;
//! \~english Returns \b true if symbol is HEX digit ('0' to '9', 'a' to 'f', 'A' to 'F')
//! \~russian Возвращает \b true если символ является HEX цифрой ('0' до '9', 'a' до 'f', 'A' до 'F')
bool isHex() const;
//! \~english Returns \b true if symbol is drawable (without space)
//! \~russian Возвращает \b true если символ является графическим (исключая пробельные)
bool isGraphical() const;
//! \~english Returns \b true if symbol is control byte (< 32 or 127)
//! \~russian Возвращает \b true если символ является контрольным (< 32 or 127)
bool isControl() const;
//! \~english Returns \b true if symbol is in lower case
//! \~russian Возвращает \b true если символ в нижнем регистре
bool isLower() const;
//! \~english Returns \b true if symbol is in upper case
//! \~russian Возвращает \b true если символ в верхнем регистре
bool isUpper() const;
//! \~english Returns \b true if symbol is printable (with space)
//! \~russian Возвращает \b true если символ является печатным (включая пробельные)
bool isPrint() const;
//! \~english Returns \b true if symbol is space or tab
//! \~russian Возвращает \b true если символ является пробельным или табуляцией
bool isSpace() const;
//! \~english Returns \b true if symbol is alphabetical letter
//! \~russian Возвращает \b true если символ является алфавитной буквой
bool isAlpha() const;
//! \~english Returns \b true if symbol is Ascii (< 128)
//! \~russian Возвращает \b true если символ является Ascii (< 128)
bool isAscii() const;
const wchar_t * toWCharPtr() const;
//! \~english Returns as `char *` string
//! \~russian Возвращает символ как указатель на `char *`
const char * toCharPtr() const;
wchar_t toWChar() const;
//! \~english Returns symbol as Ascii
//! \~russian Возвращает символ в Ascii
char toAscii() const {return ch % 256;}
//! \~english Returns symbol as console codepage
//! \~russian Возвращает символ в консольной кодировке
char toConsole1Byte() const;
//! \~english Returns symbol as system codepage
//! \~russian Возвращает символ в системной кодировке
char toSystem() const;
ushort unicode16Code() const {return ch;}
//! \~english Returns symbol in upper case
//! \~russian Возвращает символ в нижнем регистре
PIChar toUpper() const;
//! \~english Returns symbol in lower case
//! \~russian Возвращает символ в верхнем регистре
PIChar toLower() const;
//! \~english Returns symbol from console codepage
//! \~russian Возвращает символ из консольной кодировки
static PIChar fromConsole(char c);
//! \~english Returns symbol from system codepage
//! \~russian Возвращает символ из системной кодировки
static PIChar fromSystem(char c);
//! \~english Returns symbol from UTF8 codepage
//! \~russian Возвращает символ из UTF8 кодировки
static PIChar fromUTF8(const char * c);
private:
ushort ch;
};
//! \relatesalso PIChar
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
PIP_EXPORT PICout operator <<(PICout s, const PIChar & v);
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator ==(const char v, const PIChar & c) {return (PIChar(v) == c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >(const char v, const PIChar & c) {return (PIChar(v) > c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <(const char v, const PIChar & c) {return (PIChar(v) < c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >=(const char v, const PIChar & c) {return (PIChar(v) >= c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <=(const char v, const PIChar & c) {return (PIChar(v) <= c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator ==(const char * v, const PIChar & c) {return (PIChar(v) == c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >(const char * v, const PIChar & c) {return (PIChar(v) > c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <(const char * v, const PIChar & c) {return (PIChar(v) < c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >=(const char * v, const PIChar & c) {return (PIChar(v) >= c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <=(const char * v, const PIChar & c) {return (PIChar(v) <= c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator ==(const int v, const PIChar & c) {return (PIChar((ushort)v) == c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >(const int v, const PIChar & c) {return (PIChar((ushort)v) > c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <(const int v, const PIChar & c) {return (PIChar((ushort)v) < c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >=(const int v, const PIChar & c) {return (PIChar((ushort)v) >= c);}
//! \relatesalso PIChar
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <=(const int v, const PIChar & c) {return (PIChar((ushort)v) <= c);}
#endif // PICHAR_H

View File

@@ -0,0 +1,171 @@
/*
PIP - Platform Independent Primitives
C-String class
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piconstchars.h"
#include "pistring.h"
//! \~\class PIConstChars piconstchars.h
//! \~\details
//! \~english \section PIConstChars_sec0 Synopsis
//! \~russian \section PIConstChars_sec0 Краткий обзор
//! \~english
//! This is wrapper around \c const char * string. %PIConstChars doesn`t
//! copy string, just save pointer and size.
//!
//! Provides API similar to string, with information and compare methods.
//!
//! Used to more handly works with ordinary C-strings.
//!
//! \~russian
//! Это обертка вокруг \c const char * строки. %PIConstChars не скопирует
//! строку, а хранит только указатель и размер.
//!
//! Предоставляет API схожий с обычной строкой, с методами сравнения и информационными.
//!
//! Используется для более удобной работы с обычными C-строками.
//!
bool PIConstChars::contains(char c) const {
for (int i = 0; i < (int)len; ++i)
if (str[i] == c) return true;
return false;
}
bool PIConstChars::startsWith(const PIConstChars & str) const {
if (size() < str.size()) return false;
return str == left(str.size());
}
bool PIConstChars::startsWith(const char c) const {
if (size() < 1) return false;
return str[0] == c;
}
bool PIConstChars::endsWith(const PIConstChars & str) const {
if (size() < str.size()) return false;
return str == right(str.size());
}
bool PIConstChars::endsWith(const char c) const {
if (size() < 1) return false;
return str[len - 1] == c;
}
PIConstChars PIConstChars::mid(const int start, const int len) const {
int s = start, l = len;
if (l == 0 || s >= (int)size() || isEmpty()) return PIConstChars("");
if (s < 0) {
l += s;
s = 0;
}
if (l < 0) {
return PIConstChars(str + s, (int)size() - s);
} else {
if (l > (int)size() - s)
l = (int)size() - s;
return PIConstChars(str + s, l);
}
return PIConstChars("");
}
PIConstChars PIConstChars::left(const int l) const {
if (l <= 0) return PIConstChars("");
return mid(0, l);
}
PIConstChars PIConstChars::right(const int l) const {
if (l <= 0) return PIConstChars("");
return mid((int)size() - l, l);
}
PIConstChars & PIConstChars::cutLeft(const int l) {
if (l <= 0) return *this;
if (l >= (int)size())
*this = PIConstChars("");
else {
str += l;
len -= l;
}
return *this;
}
PIConstChars & PIConstChars::cutRight(const int l) {
if (l <= 0) return *this;
if (l >= (int)size())
*this = PIConstChars("");
else {
len -= l;
}
return *this;
}
PIConstChars PIConstChars::takeLeft(const int len) {
PIConstChars ret(left(len));
cutLeft(len);
return ret;
}
PIConstChars PIConstChars::takeRight(const int len) {
PIConstChars ret(right(len));
cutRight(len);
return ret;
}
PIConstChars & PIConstChars::trim() {
if (isEmpty()) return *this;
int st = -1, fn = 0;
for (int i = 0; i < (int)len; ++i) {
if (at(i) != ' ' && at(i) != '\t' && at(i) != '\n' && at(i) != '\r' && at(i) != char(12) && at(i) != uchar(0)) {
st = i;
break;
}
}
if (st < 0) {
*this = PIConstChars("");
return *this;
}
for (int i = (int)len - 1; i >= 0; --i) {
if (at(i) != ' ' && at(i) != '\t' && at(i) != '\n' && at(i) != '\r' && at(i) != char(12) && at(i) != uchar(0)) {
fn = i;
break;
}
}
if (fn < (int)len - 1) cutRight((int)len - fn - 1);
if (st > 0) cutLeft(st);
return *this;
}
PIString PIConstChars::toString() const {
if (isEmpty()) return PIString();
return PIString::fromAscii(str, len);
}

View File

@@ -0,0 +1,266 @@
/*! \file piconstchars.h
* \ingroup Text
* \brief
* \~english C-String class
* \~russian Класс C-строки
*/
/*
PIP - Platform Independent Primitives
C-String class
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PICONSTCHARS_H
#define PICONSTCHARS_H
#include "picout.h"
//! \ingroup Text
//! \~\brief
//! \~english C-String class.
//! \~russian Класс C-строки.
class PIP_EXPORT PIConstChars {
public:
//! \~english Contructs an null string.
//! \~russian Создает нулевую строку.
PIConstChars() {}
//! \~english Contructs string from C-string "string".
//! \~russian Создает строку из C-строки "string".
PIConstChars(const char * string) {
str = string;
len = strlen(string);
}
//! \~english Contructs string from "size" characters of buffer "data".
//! \~russian Создает строку из "size" символов массива "data".
PIConstChars(const char * data, size_t size) {
str = data;
len = size;
}
//! \~english Contructs a copy of string.
//! \~russian Создает копию строки.
PIConstChars(const PIConstChars & o) {
str = o.str;
len = o.len;
}
//! \~english Read-only access to character by `index`.
//! \~russian Доступ на чтение к символу по индексу `index`.
inline char operator [](size_t index) const {return str[index];}
//! \~english Read-only access to character by `index`.
//! \~russian Доступ на чтение к символу по индексу `index`.
inline char at(size_t index) const {return str[index];}
//! \~english Returns \c char * string pointer.
//! \~russian Возвращает \c char * указатель строки.
inline const char * data() const {return str;}
//! \~english Returns \c true if string doesn`t have any data.
//! \~russian Возвращает \c true если строка не имеет данных.
inline bool isNull() const {return !str;}
//! \~english Returns \c true if string is empty, i.e. length = 0, or null.
//! \~russian Возвращает \c true если строка пустая, т.е. длина = 0, или нулевая.
inline bool isEmpty() const {return len == 0;}
//! \~english Returns \c true if string is not empty, i.e. length > 0.
//! \~russian Возвращает \c true если строка непустая, т.е. длина > 0.
inline bool isNotEmpty() const {return len > 0;}
//! \~english Returns \c true if string contains character "c".
//! \~russian Возвращает \c true если строка содержит символ "c".
bool contains(char c) const;
//! \~english Returns characters length of string.
//! \~russian Возвращает длину строки в символах.
inline size_t length() const {return len;}
//! \~english Returns characters length of string.
//! \~russian Возвращает длину строки в символах.
inline size_t size() const {return len;}
//! \~english Returns characters length of string.
//! \~russian Возвращает длину строки в символах.
inline ssize_t size_s() const {return len;}
//! \~english Returns if string starts with "str".
//! \~russian Возвращает начинается ли строка со "str".
bool startsWith(const PIConstChars & str) const;
//! \~english Returns if string starts with "c".
//! \~russian Возвращает начинается ли строка с "c".
bool startsWith(const char c) const;
//! \~english Returns if string ends with "str".
//! \~russian Возвращает оканчивается ли строка на "str".
bool endsWith(const PIConstChars & str) const;
//! \~english Returns if string ends with "c".
//! \~russian Возвращает оканчивается ли строка "c".
bool endsWith(const char c) const;
//! \~english Returns part of string from character at index "start" and maximum length "len".
//! \~russian Возвращает подстроку от символа "start" и максимальной длиной "len".
//! \~\sa \a left(), \a right()
PIConstChars mid(const int start, const int len = -1) const;
//! \~english Returns part of string from start and maximum length "len".
//! \~russian Возвращает подстроку от начала и максимальной длиной "len".
//! \~\sa \a mid(), \a right()
PIConstChars left(const int len) const;
//! \~english Returns part of string at end and maximum length "len".
//! \~russian Возвращает подстроку максимальной длиной "len" и до конца.
//! \~\sa \a mid(), \a left()
PIConstChars right(const int len) const;
//! \~english Remove part of string from start and maximum length "len" and return this string.
//! \~russian Удаляет часть строки от начала и максимальной длины "len", возвращает эту строку.
//! \~\sa \a cutRight()
PIConstChars & cutLeft(const int len);
//! \~english Remove part of string at end and maximum length "len" and return this string.
//! \~russian Удаляет часть строки максимальной длины "len" от конца, возвращает эту строку.
//! \~\sa \a cutLeft()
PIConstChars & cutRight(const int len);
//! \~english Take a part from the begin of string with maximum length "len" and return it.
//! \~russian Извлекает часть строки от начала максимальной длины "len" и возвращает её.
//! \~\sa \a takeRight()
PIConstChars takeLeft(const int len);
//! \~english Take a part from the end of string with maximum length "len" and return it.
//! \~russian Извлекает часть строки с конца максимальной длины "len" и возвращает её.
//! \~\sa \a takeLeft()
PIConstChars takeRight(const int len);
//! \~english Remove spaces at the start and at the end of string and return this string.
//! \~russian Удаляет пробельные символы с начала и конца строки и возвращает эту строку.
//! \~\sa \a trimmed()
PIConstChars & trim();
//! \~english Returns copy of this string without spaces at the start and at the end.
//! \~russian Возвращает копию этой строки без пробельных символов с начала и конца.
//! \~\sa \a trim()
PIConstChars trimmed() const {return PIConstChars(*this).trim();}
//! \~english Returns as PIString.
//! \~russian Возвращает как PIString.
PIString toString() const;
//! \~english Assign operator.
//! \~russian Оператор присваивания.
inline PIConstChars & operator =(const PIConstChars & s) {
if (this == &s) return *this;
len = s.len;
str = s.str;
return *this;
}
//! \~english Assign move operator.
//! \~russian Оператор перемещающего присваивания.
inline PIConstChars & operator =(PIConstChars && s) {
swap(s);
return *this;
}
//! \~english Assign operator.
//! \~russian Оператор присваивания.
inline PIConstChars & operator =(const char * s) {
str = s;
len = strlen(s);
return *this;
}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
inline bool operator ==(const PIConstChars & s) const {
if (isNull() && s.isNull()) return true;
if (isNull() xor s.isNull()) return false;
if (size() != s.size()) return false;
return strcmp(str, s.str) == 0;
}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
inline bool operator !=(const PIConstChars & s) const {return !(*this == s);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
inline bool operator <(const PIConstChars & s) const {
if ( isNull() && s.isNull()) return false;
if ( isNull() && !s.isNull()) return true ;
if (!isNull() && s.isNull()) return false;
if (size() == s.size())
return strcmp(str, s.str) < 0;
return size() < s.size();
}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
inline bool operator >(const PIConstChars & s) const {
if ( isNull() && s.isNull()) return false;
if ( isNull() && !s.isNull()) return false;
if (!isNull() && s.isNull()) return true ;
if (size() == s.size())
return strcmp(str, s.str) > 0;
return size() > s.size();
}
//! \~english Returns hash of string content.
//! \~russian Возвращает хэш содержимого строки.
inline uint hash() const {
if (isEmpty()) return 0;
return piHashData((const uchar *)str, len);
}
inline void swap(PIConstChars& v) {
piSwap<const char *>(str, v.str);
piSwap<size_t>(len, v.len);
}
private:
const char * str = nullptr;
size_t len = 0;
};
//! \relatesalso PICout
//! \~english Output operator to \a PICout.
//! \~russian Оператор вывода в \a PICout.
inline PICout operator <<(PICout s, const PIConstChars & v) {
s.space();
if (v.isNull())
s.write("(null)");
else {
s.quote();
s.write(v.data(), v.size());
s.quote();
}
return s;
}
template<> inline uint piHash(const PIConstChars & s) {return s.hash();}
#endif // PICONSTCHARS_H

1799
libs/main/text/pistring.cpp Normal file
View File

@@ -0,0 +1,1799 @@
/*
PIP - Platform Independent Primitives
String
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piincludes_p.h"
#include "pistring.h"
#include "pistringlist.h"
#include "pimathbase.h"
#ifdef PIP_ICU
# define U_NOEXCEPT
# include "unicode/ucnv.h"
#endif
#ifdef WINDOWS
# include <stringapiset.h>
#endif
#include <string>
#include <locale>
#include <codecvt>
//! \class PIString pistring.h
//! \~\details
//! \~english \section PIString_sec0 Synopsis
//! \~russian \section PIString_sec0 Краткий обзор
//!
//! \~english
//! String is a sequence of \a PIChar. Real memory size of string is symbols count * 2.
//! String can be constucted from many types of data and can be converted
//! to many types. There are many operators and handly functions to use
//! string as you wish.
//!
//! \~russian
//! Строка состоит из последовательности \a PIChar. Реальный объем памяти,
//! занимаемый строкой, равен количеству символов * 2. Строка может быть
//! создана из множества типов и преобразована в несколько типов.
//! Имеет множество методов для манипуляций.
//!
const char PIString::toBaseN[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^'};
const char PIString::fromBaseN[] = {(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char) 0, (char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7, (char) 8, (char) 9, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24,
(char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, (char)32, (char)33, (char)34, (char)35, (char)36, (char)37, (char)38, (char)39, (char)-1,
(char)-1, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24,
(char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, (char)32, (char)33, (char)34, (char)35, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
(char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1};
const float PIString::ElideLeft = 0.f;
const float PIString::ElideCenter = .5f;
const float PIString::ElideRight = 1.f;
template <typename T>
T toDecimal(const PIString & s) {
int part = 0, exp = 0;
bool negative = false, negative_exp = false, err = false, has_digit = false;
T ret = 0., frac = 0., frac_delim = 1.;
for (const PIChar pc: s) {
char c = pc.toAscii();
switch (part) {
case 0: // sign
if (pc.isSpace()) continue;
if (c >= '0' && c <= '9') {
has_digit = true;
ret = c - '0';
part = 1;
continue;
}
if (c == '+') {
part = 1;
continue;
}
if (c == '-') {
negative = true;
part = 1;
continue;
}
if (c == '.' || c == ',') {
part = 2;
continue;
}
err = true;
break;
case 1: // integer
if (c >= '0' && c <= '9') {
has_digit = true;
ret = ret * 10 + (c - '0');
continue;
}
if (c == '.' || c == ',') {
part = 2;
continue;
}
if ((c == 'e' || c == 'E') && has_digit) {
part = 3;
continue;
}
err = true;
break;
case 2: // fractional
if (c >= '0' && c <= '9') {
has_digit = true;
frac = frac * 10 + (c - '0');
frac_delim *= 10.;
continue;
}
if ((c == 'e' || c == 'E') && has_digit) {
part = 3;
continue;
}
err = true;
break;
case 3: // exponent with sign
if (c == '+') {
part = 4;
continue;
}
if (c == '-') {
negative_exp = true;
part = 4;
continue;
}
case 4: // exponent
if (c >= '0' && c <= '9') {
exp = (exp * 10) + (c - '0');
continue;
}
err = true;
break;
}
if (err) break;
}
frac /= frac_delim;
ret += frac;
if (negative && has_digit) ret = -ret;
if (exp > 0) {
if (negative_exp) ret /= pow10((T)exp);
else ret *= pow10((T)exp);
}
return ret;
}
#define pisprintf(f, v) char ch[256]; memset(ch, 0, 256); snprintf(ch, 256, f, v); return PIStringAscii(ch);
PIString PIString::itos(const int num) {pisprintf("%d", num);}
PIString PIString::ltos(const long num) {pisprintf("%ld", num);}
PIString PIString::lltos(const llong num) {pisprintf("%lld", num);}
PIString PIString::uitos(const uint num) {pisprintf("%u", num);}
PIString PIString::ultos(const ulong num) {pisprintf("%lu", num);}
PIString PIString::ulltos(const ullong num) {pisprintf("%llu", num);}
PIString PIString::dtos(const double num, char format, int precision) {
char f[8] = "%.";
int wr = snprintf(&(f[2]), 4, "%d", precision);
if (wr > 4) wr = 4;
f[2 + wr] = format;
f[3 + wr] = 0;
pisprintf(f, num);
}
#undef pisprintf
PIString PIString::fromNumberBaseS(const llong value, int base, bool * ok) {
if (value == 0LL) return PIString('0');
if ((base < 2) || (base > 40)) {
if (ok != 0) *ok = false;
return PIString();
}
if (ok != 0) *ok = true;
if (base == 10) return lltos(value);
PIString ret;
llong v = value < 0 ? -value : value, cn;
int b = base;
while (v >= llong(base)) {
cn = v % b;
v /= b;
//cout << int(cn) << ", " << int(v) << endl;
ret.push_front(PIChar(toBaseN[cn]));
}
if (v > 0) ret.push_front(PIChar(toBaseN[v]));
if (value < 0) ret.push_front('-');
return ret;
}
PIString PIString::fromNumberBaseU(const ullong value, int base, bool * ok) {
if (value == 0ULL) return PIString('0');
if ((base < 2) || (base > 40)) {
if (ok != 0) *ok = false;
return PIString();
}
if (ok != 0) *ok = true;
if (base == 10) return ulltos(value);
PIString ret;
ullong v = value, cn;
int b = base;
while (v >= ullong(base)) {
cn = v % b;
v /= b;
//cout << int(cn) << ", " << int(v) << endl;
ret.push_front(PIChar(toBaseN[cn]));
}
if (v > 0) ret.push_front(PIChar(toBaseN[v]));
return ret;
}
llong PIString::toNumberBase(const PIString & value, int base, bool * ok) {
static const PIString s_0x = PIStringAscii("0x");
PIString v = value.trimmed();
if (base < 0) {
int ind = v.find(s_0x);
if (ind == 0 || ind == 1) {
v.remove(ind, 2);
base = 16;
} else {
base = 10;
}
} else if ((base < 2) || (base > 40)) {
if (ok != 0) *ok = false;
return 0;
}
if (ok) *ok = true;
PIVector<int> digits;
llong ret = 0, m = 1;
bool neg = false;
char cs;
for (int i = 0; i < v.size_s(); ++i) {
if (v[i] == PIChar('-')) {
neg = !neg;
continue;
}
cs = fromBaseN[int(v[i].toAscii())];
if (cs < 0 || cs >= base) {
if (ok) *ok = false;
break;
}
digits << cs;
}
for (int i = digits.size_s() - 1; i >= 0; --i) {
ret += digits[i] * m;
m *= base;
}
if (neg) ret = -ret;
return ret;
}
void PIString::appendFromChars(const char * c, int s, const char * codepage) {
// piCout << "appendFromChars";
if (s == 0) return;
int old_sz = size_s();
if (s == -1) s = strlen(c);
#ifdef PIP_ICU
UErrorCode e((UErrorCode)0);
UConverter * cc = ucnv_open(codepage, &e);
if (cc) {
d.enlarge(s);
e = (UErrorCode)0;
int sz = ucnv_toUChars(cc, (UChar*)(d.data(old_sz)), s, c, s, &e);
d.resize(old_sz+sz);
ucnv_close(cc);
return;
}
#else
# ifdef WINDOWS
int sz = MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, s, 0, 0);
if (sz <= 0) return;
d.enlarge(sz);
MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, s, (LPWSTR)d.data(old_sz), sz);
# else
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> ucs2conv;
std::u16string ucs2 = ucs2conv.from_bytes(c, c+s);
d.enlarge(ucs2.size());
ucs2.copy((char16_t *)d.data(old_sz), ucs2.size());
# endif
#endif
}
PIString PIString::fromConsole(const PIByteArray & ba) {
PIString ret;
if (ba.isNotEmpty()) ret.appendFromChars((const char*)ba.data(), ba.size(), __sysoemname__);
return ret;
}
PIString PIString::fromConsole(const char * s) {
PIString ret;
if (!s) return ret;
if (s[0] != '\0') ret.appendFromChars(s, -1, __sysoemname__);
return ret;
}
PIString PIString::fromSystem(const PIByteArray & ba) {
PIString ret;
if (ba.isNotEmpty()) ret.appendFromChars((const char*)ba.data(), ba.size(), __syslocname__);
return ret;
}
PIString PIString::fromSystem(const char * s) {
PIString ret;
if (!s) return ret;
if (s[0] != '\0') ret.appendFromChars(s, -1, __syslocname__);
return ret;
}
PIString PIString::fromUTF8(const char * s) {
PIString ret;
if (!s) return ret;
if (s[0] != '\0') {
if ((uchar)s[0] == 0xEF && (uchar)s[1] == 0xBB && (uchar)s[2] == 0xBF) {
s += 3;
if (s[0] == '\0') return ret;
}
ret.appendFromChars(s, -1, __utf8name__);
}
return ret;
}
PIString PIString::fromUTF8(const PIByteArray & ba) {
PIString ret;
if (ba.isNotEmpty()) {
const char * data = (const char*)ba.data();
int size = ba.size();
if (ba.size() >= 3) {
if (ba[0] == 0xEF && ba[1] == 0xBB && ba[2] == 0xBF) {
data += 3;
size -= 3;
if (size == 0) return ret;
}
}
ret.appendFromChars(data, size, __utf8name__);
}
return ret;
}
PIString PIString::fromAscii(const char * s) {
return fromAscii(s, strlen(s));
}
PIString PIString::fromAscii(const char * s, int len) {
PIString ret;
ret.resize(len);
for (int l = 0; l < len; ++l) {
ret[l] = s[l];
}
return ret;
}
PIString PIString::fromCodepage(const char * s, const char * c) {
PIString ret;
if (s[0] > '\0') ret.appendFromChars(s, -1
#ifdef PIP_ICU
, c
#else
# ifdef WINDOWS
, __utf8name__
# endif
#endif
);
return ret;
}
//! \~\details
//! \~english
//! Example:
//! \~russian
//! Пример:
//! \~\code
//! piCout << PIString::readableSize(512); // 512 B
//! piCout << PIString::readableSize(5120); // 5.0 kB
//! piCout << PIString::readableSize(512000); // 500.0 kB
//! piCout << PIString::readableSize(5120000); // 4.8 MB
//! piCout << PIString::readableSize(512000000); // 488.2 MB
//! piCout << PIString::readableSize(51200000000); // 47.6 GB
//! \endcode
PIString PIString::readableSize(llong bytes) {
PIString s;
s.setReadableSize(bytes);
return s;
}
void PIString::buildData(const char * cp) const {
deleteData();
#ifdef PIP_ICU
UErrorCode e((UErrorCode)0);
UConverter * cc = ucnv_open(cp, &e);
if (cc) {
const size_t len = MB_CUR_MAX*size()+1;
data_ = (char *)malloc(len);
int sz = ucnv_fromUChars(cc, data_, len, (const UChar*)(d.data()), d.size_s(), &e);
ucnv_close(cc);
data_[sz] = '\0';
return;
}
#else
# ifdef WINDOWS
int sz = WideCharToMultiByte((uint)(uintptr_t)cp, 0, (LPCWCH)d.data(), d.size_s(), 0, 0, NULL, NULL);
if (sz <= 0) {
data_ = (char *)malloc(1);
data_[0] = '\0';
return;
}
data_ = (char *)malloc(sz+1);
WideCharToMultiByte((uint)(uintptr_t)cp, 0, (LPCWCH)d.data(), d.size_s(), (LPSTR)data_, sz, NULL, NULL);
data_[sz] = '\0';
return;
# else
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> ucs2conv;
std::string u8str = ucs2conv.to_bytes((char16_t*)d.data(), (char16_t*)d.data() + d.size());
data_ = (char *)malloc(u8str.size()+1);
strcpy(data_, u8str.c_str());
# endif
#endif
}
void PIString::deleteData() const {
if (!data_) return;
free(data_);
data_ = nullptr;
}
void PIString::trimsubstr(int &st, int &fn) const {
for (int i = 0; i < d.size_s(); ++i) {
if (at(i) != ' ' && at(i) != '\t' && at(i) != '\n' && at(i) != '\r' && at(i) != char(12) && at(i) != uchar(0)) {
st = i;
break;
}
}
if (st < 0) return;
for (int i = d.size_s() - 1; i >= 0; --i) {
if (at(i) != ' ' && at(i) != '\t' && at(i) != '\n' && at(i) != '\r' && at(i) != char(12) && at(i) != uchar(0)) {
fn = i;
break;
}
}
}
uint PIString::hash() const {
return piHashData((const uchar*)d.data(), d.size() * sizeof(PIChar));
}
PIByteArray PIString::toSystem() const {
if (isEmpty()) return PIByteArray();
buildData(__syslocname__);
return PIByteArray(data_, strlen(data_));
}
PIByteArray PIString::toUTF8() const {
if (isEmpty()) return PIByteArray();
buildData(__utf8name__);
return PIByteArray(data_, strlen(data_));
}
PIByteArray PIString::toCharset(const char * c) const {
if (isEmpty()) return PIByteArray();
buildData(
#ifdef PIP_ICU
c
#else
# ifdef WINDOWS
__utf8name__
# endif
#endif
);
return PIByteArray(data_, strlen(data_));
}
PIString PIString::simplified() const {
PIString ret(*this);
for (int i = 0; i < ret.size_s(); ++i)
if (!ret[i].isAscii())
ret[i] = '?';
return ret;
}
PIString & PIString::operator +=(const char * str) {
if (!str) return *this;
appendFromChars(str, -1, __syslocname__);
return *this;
}
PIString & PIString::operator +=(const PIByteArray & ba) {
appendFromChars((const char * )ba.data(), ba.size_s(), __utf8name__);
return *this;
}
PIString::~PIString() {
deleteData();
}
PIString & PIString::operator +=(const wchar_t * str) {
if (!str) return *this;
int i = -1;
while (str[++i]) {
d.push_back(PIChar(str[i]));
}
return *this;
}
PIString & PIString::operator +=(const PIString & str) {
d.append(str.d);
return *this;
}
PIString & PIString::operator +=(const PIConstChars & str) {
if (!str.isEmpty()) {
size_t os = d.size();
d.enlarge(str.size());
for (size_t l = 0; l < d.size(); ++l) {
d[os + l] = str[l];
}
}
return *this;
}
bool PIString::operator ==(const PIString & str) const {
return d == str.d;
}
bool PIString::operator !=(const PIString & str) const {
return d != str.d;
}
bool PIString::operator <(const PIString & str) const {
size_t l = str.size();
if (size() < l) return true;
if (size() > l) return false;
for (size_t i = 0; i < l; ++i) {
if (at(i) == str.at(i)) continue;
if (at(i) < str.at(i)) return true;
else return false;
}
return false;
}
bool PIString::operator >(const PIString & str) const {
size_t l = str.size();
if (size() < l) return false;
if (size() > l) return true;
for (size_t i = 0; i < l; ++i) {
if (at(i) == str.at(i)) continue;
if (at(i) < str.at(i)) return false;
else return true;
}
return false;
}
//! \~\details
//! \~english
//! If "len" < 0 then returns substring from symbol "start" to end.
//! "start" should be >= 0.
//! \~russian
//! Если "len" < 0 тогда возвращается подстрока от символа "start" и до конца.
//! "start" должен быть >= 0.
//! \~\code
//! PIString s("0123456789");
//! piCout << s.mid(0, -1); // s = "0123456789"
//! piCout << s.mid(0, 2); // s = "01"
//! piCout << s.mid(3); // s = "3456789"
//! piCout << s.mid(3, 4); // s = "3456"
//! piCout << s.mid(7, 1); // s = "7"
//! piCout << s.mid(7, 4); // s = "789"
//! piCout << s.mid(-1); // s = ""
//! \endcode
//! \~\sa \a left(), \a right()
PIString PIString::mid(int start, int len) const {
if (len == 0 || start >= length()) return PIString();
if (start < 0) {
return PIString();
}
if (len < 0) {
return PIString(d.data(start), size_s() - start);
} else {
if (len > length() - start) len = length() - start;
return PIString(d.data(start), len);
}
return PIString();
}
//! \~\details
//! \~english
//! If "len" < 0 then remove substring from symbol "start" to end.
//! "start" should be >= 0.
//! \~russian
//! Если "len" < 0 тогда удаляется подстрока от символа "start" и до конца.
//! "start" должен быть >= 0.
//! \~\code
//! PIString s("0123456789");
//! s.cutMid(1, 3);
//! piCout << s; // s = "0456789"
//! s.cutMid(0, 2);
//! piCout << s; // s = "56789"
//! s.cutMid(3, -1);
//! piCout << s; // s = "567"
//! s.cutMid(-1, -1);
//! piCout << s; // s = "567"
//! \endcode
//! \~\sa \a cutLeft(), \a cutRight()
PIString & PIString::cutMid(int start, int len) {
if (len == 0) return *this;
if (start < 0) {
return *this;
}
if (len < 0) {
d.remove(start, size() - start);
} else {
if (len > length() - start) len = length() - start;
d.remove(start, len);
}
return *this;
}
//! \~\details
//! \~english Remove spaces, tabulations, line feeds and null symbols:
//! \~russian Удаляет пробелы, табуляцию, переводы строк и нулевые символы:
//! \~ ' ', '\\n', '\\r', '\\t', '\\0'
//! \~\code
//! PIString s(" \t string \n");
//! s.trim();
//! piCout << s; // s = "string"
//! \endcode
//! \~\sa \a trimmed()
PIString & PIString::trim() {
int st = -1, fn = 0;
trimsubstr(st, fn);
if (st < 0) {
clear();
return *this;
}
if (fn < size_s() - 1) cutRight(size_s() - fn - 1);
if (st > 0) cutLeft(st);
return *this;
}
PIString PIString::trimmed() const {
int st = -1, fn = 0;
trimsubstr(st, fn);
if (st < 0) return PIString();
return mid(st, fn - st + 1);
}
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! s.replace(2, 3, "_cut_");
//! piCout << s; // s = "01_cut_56789"
//! s.replace(0, 1, "one_");
//! piCout << s; // s = "one_1_cut_56789"
//! \endcode
//! \~\sa \a replaced(), \a replaceAll()
PIString & PIString::replace(int from, int count, const PIString & with) {
count = piMini(count, length() - from);
if (count == with.size_s()) {
memcpy(d.data(from), with.d.data(), count * sizeof(PIChar));
} else {
d.remove(from, count);
d.insert(from, with.d);
}
return *this;
}
//! \~\details
//! \~english If "ok" is not null, it set to "true" if something was replaced
//! \~russian Если "ok" не null, то устанавливает в "true" если замена произведена
//! \~\code
//! PIString s("pip string");
//! bool ok;
//! s.replace("string", "conf", &ok);
//! piCout << s << ok; // s = "pip conf", true
//! s.replace("PIP", "PlInPr", &ok);
//! piCout << s << ok; // s = "pip conf", false
//! \endcode
//! \~\sa \a replaced(), \a replaceAll()
PIString & PIString::replace(const PIString & what, const PIString & with, bool * ok) {
if (what.isEmpty()) {
if (ok != 0) *ok = false;
return *this;
}
int s = find(what);
if (s >= 0) replace(s, what.length(), with);
if (ok != 0) *ok = (s >= 0);
return *this;
}
//! \~\details
//! \~\code
//! PIString s("substrings");
//! s.replaceAll("s", "_");
//! piCout << s; // s = "_ub_tring_"
//! \endcode
//! \~\sa \a replace(), \a replaced(), \a replacedAll()
PIString & PIString::replaceAll(const PIString & what, const PIString & with) {
if (what.isEmpty() || what == with) return *this;
if (with.isEmpty()) {
removeAll(what);
} else {
int l = what.length(), dl = with.length() - what.length();
for (int i = 0; i < length() - l + 1; ++i) {
bool match = true;
for (int j = 0; j < l; ++j) {
if (at(j + i) != what[j]) {
match = false;
break;
}
}
if (!match) continue;
if (dl > 0) d.insert(i, PIDeque<PIChar>((size_t)dl));
if (dl < 0) d.remove(i, -dl);
memcpy(d.data(i), with.d.data(), with.size() * sizeof(PIChar));
}
}
return *this;
}
//! \~\details
//! \~\code
//! PIString s("substrings");
//! s.replaceAll("s", '_');
//! piCout << s; // s = "_ub_tring_"
//! \endcode
//! \~\sa \a replace(), \a replaced(), \a replacedAll()
PIString & PIString::replaceAll(const PIString & what, const char with) {
if (what.isEmpty()) return *this;
int l = what.length(), dl = what.length() - 1;
for (int i = 0; i < length() - l + 1; ++i) {
bool match = true;
for (int j = 0; j < l; ++j) {
if (at(j + i) != what[j]) {
match = false;
break;
}
}
if (!match) continue;
if (dl > 0) d.remove(i, dl);
d[i] = PIChar(with);
}
return *this;
}
//! \~\details
//! \~\code
//! PIString s("substrings");
//! s.replaceAll('s', '_');
//! piCout << s; // s = "_ub_tring_"
//! \endcode
//! \~\sa \a replace(), \a replaced(), \a replacedAll()
PIString & PIString::replaceAll(const char what, const char with) {
int l = length();
for (int i = 0; i < l; ++i) {
if (at(i) == what) d[i] = with;
}
return *this;
}
PIString & PIString::removeAll(const PIString & str) {
if (str.isEmpty()) return *this;
int l = str.length();
for (int i = 0; i < length() - l + 1; ++i) {
bool match = true;
for (int j = 0; j < l; ++j) {
if (d.at(j + i) != str.at(j)) {
match = false;
break;
}
}
if (!match) continue;
d.remove(i, l);
i -= l;
}
return *this;
}
PIString & PIString::insert(int index, const PIString & str) {
d.insert(index, str.d);
return *this;
}
PIString & PIString::elide(int size, float pos) {
static const PIString s_dotdot = PIStringAscii("..");
if (length() <= size) return *this;
if (length() <= 2) {
fill('.');
return *this;
}
pos = piClampf(pos, 0.f, 1.f);
int ns = size - 2;
int ls = piRoundf(ns * pos);
d.remove(ls, length() - ns);
d.insert(ls, s_dotdot.d);
return *this;
}
PIStringList PIString::split(const PIString & delim) const {
PIStringList sl;
if (isEmpty() || delim.isEmpty()) return sl;
PIString ts(*this);
int ci = ts.find(delim);
while (ci >= 0) {
sl << ts.left(ci);
ts.cutLeft(ci + delim.length());
ci = ts.find(delim);
}
if (ts.length() > 0) sl << ts;
return sl;
}
//! \~\details
//! \~\code
//! PIString s("012345012345");
//! piCout << s.find('-'); // -1
//! piCout << s.find('3'); // 3
//! piCout << s.find('3', 4); // 9
//! piCout << s.find('3', 10); // -1
//! \endcode
//! \~\sa \a findAny(), \a findLast(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int PIString::find(const char c, const int start) const {
for (int i = start; i < length(); ++i) {
if (at(i) == c) return i;
}
return -1;
}
//! \~\details
//! \~\code
//! PIString s("012345012345");
//! piCout << s.find("-"); // -1
//! piCout << s.find("34"); // 3
//! piCout << s.find("3", 4); // 9
//! piCout << s.find("3", 10); // -1
//! \endcode
//! \~\sa \a findAny(), \a findLast(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int PIString::find(const PIString & str, const int start) const {
int l = str.length();
for (int i = start; i < length() - l + 1; ++i) {
if (mid(i, l) == str) return i;
}
return -1;
}
//! \~\details
//! \~\code
//! piCout << PIString("1.str").findAny(".,:"); // 1
//! piCout << PIString("1,str").findAny(".,:"); // 1
//! piCout << PIString("1:str").findAny(".,:"); // 1
//! \endcode
//! \~\sa \a find(), \a findLast(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int PIString::findAny(const PIString & str, const int start) const {
for (int i = start; i < length(); ++i) {
if (str.contains(at(i))) return i;
}
return -1;
}
//! \~\details
//! \~\code
//! PIString s("012345012345");
//! piCout << s.findLast('-'); // -1
//! piCout << s.findLast('3'); // 9
//! piCout << s.findLast('3', 4); // 9
//! piCout << s.findLast('3', 10); // -1
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int PIString::findLast(const char c, const int start) const {
for (int i = length() - 1; i >= start; --i) {
if (at(i) == c) return i;
}
return -1;
}
int PIString::findLast(PIChar c, const int start) const
{
for (int i = length() - 1; i >= start; --i) {
if (at(i) == c) return i;
}
return -1;
}
//! \~\details
//! \~\code
//! PIString s("012345012345");
//! piCout << s.findLast("-"); // -1
//! piCout << s.findLast("34"); // 9
//! piCout << s.findLast("3", 4); // 9
//! piCout << s.findLast("3", 10); // -1
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int PIString::findLast(const PIString & str, const int start) const {
int l = str.length();
for (int i = length() - l; i >= start; --i) {
if (mid(i, l) == str) return i;
}
return -1;
}
//! \~\details
//! \~\code
//! piCout << PIString(".str.0").findAnyLast(".,:"); // 4
//! piCout << PIString(".str,0").findAnyLast(".,:"); // 4
//! piCout << PIString(".str:0").findAnyLast(".,:"); // 4
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findLast(), \a findWord(), \a findCWord(), \a findRange()
int PIString::findAnyLast(const PIString & str, const int start) const {
for (int i = length() - 1; i >= start; --i) {
if (str.contains(at(i))) return i;
}
return -1;
}
//! \~\details
//! \~\code
//! PIString s("this is <PIP>");
//! piCout << s.findWord("this"); // 0
//! piCout << s.findWord("is"); // 5
//! piCout << s.findWord("PIP", 4); // -1
//! piCout << s.findWord("<PIP>", 4); // 8
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findLast(), \a findAnyLast(), \a findCWord(), \a findRange()
int PIString::findWord(const PIString & word, const int start) const {
int f = start - 1, tl = length(), wl = word.length();
while ((f = find(word, f + 1)) >= 0) {
bool ok = true;
PIChar c;
if (f > 0) {
c = at(f - 1);
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r')) {
ok = false;
continue;
}
}
if (f + wl < tl) {
c = at(f + wl);
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r')) {
ok = false;
continue;
}
}
if (ok) return f;
}
return -1;
}
//! \~\details
//! \~\code
//! PIString s("this::is <PIP>");
//! piCout << s.findCWord("this"); // 0
//! piCout << s.findCWord("is"); // 6
//! piCout << s.findCWord("PIP", 4); // 10
//! piCout << s.findCWord("<PIP>", 4); // 9
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findLast(), \a findAnyLast(), \a findWord(), \a findRange()
int PIString::findCWord(const PIString & word, const int start) const {
int f = start - 1, tl = length(), wl = word.length();
while ((f = find(word, f + 1)) >= 0) {
bool ok = true;
PIChar c;
if (f > 0) {
c = at(f - 1);
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r' || (c != '_' && !c.isAlpha() && !c.isDigit()))) {
ok = false;
continue;
}
}
if (f + wl < tl) {
c = at(f + wl);
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r' || (c != '_' && !c.isAlpha() && !c.isDigit()))) {
ok = false;
continue;
}
}
if (ok) return f;
}
return -1;
}
//! \~\details
//! \~\code
//! PIString s(" {figures{inside}}");
//! int len = -1;
//! piCout << s.findRange('{', '}', '\\', 0, &len) << len << s.mid(2, len); // 2 15 figures{inside}
//! s = "\"text\\\"shielded\" next";
//! piCout << s.findRange('"', '"', '\\', 0, &len) << len << s.mid(1, len); // 1 14 text\"shielded
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findLast(), \a findAnyLast(), \a findWord(), \a findCWord()
int PIString::findRange(const PIChar start, const PIChar end, const PIChar shield, const int start_index, int * len) const {
if (len) *len = 0;
bool trim_ = (start != ' ' && start != '\t' && start != '\n' && start != '\r'), eq = (start == end);
int sz = size_s(), ls = -1, le = -1, cnt = 0;
for (int i = start_index; i < sz; ++i) {
PIChar c = at(i);
if (c == shield) {
++i;
continue;
}
if (trim_) {
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
continue;
trim_ = false;
}
if (eq) {
if (c == start) {
if (cnt == 0) ls = i;
else {le = i; cnt = 0; break;}
cnt++;
}
} else {
if (c == start) {
if (cnt == 0) ls = i;
cnt++;
}
if (c == end) {
cnt--;
if (cnt == 0) le = i;
}
}
if (cnt <= 0) break;
}
//piCout << ls << le << cnt;
if (le < ls || ls < 0 || le < 0 || cnt != 0) return -1;
if (len) *len = le - ls - 1;
return ls + 1;
}
int PIString::entries(const PIChar c) const {
int sz = size_s(), ret = 0;
for (int i = 0; i < sz; ++i) {
if (at(i) == c) ++ret;
}
return ret;
}
bool PIString::startsWith(const PIString & str) const {
if (size() < str.size()) return false;
return str == left(str.size());
}
bool PIString::endsWith(const PIString & str) const {
if (size() < str.size()) return false;
return str == right(str.size());
}
//! \~\details
//! \~\code
//! piCout << PIString("true").toBool(); // true
//! piCout << PIString("Yes").toBool(); // true
//! piCout << PIString(" TRUE ").toBool(); // true
//! piCout << PIString(" 1 ").toBool(); // true
//! piCout << PIString("0").toBool(); // false
//! piCout << PIString("0.1").toBool(); // true
//! piCout << PIString("-1").toBool(); // false
//! piCout << PIString("").toBool(); // false
//! \endcode
bool PIString::toBool() const {
static const PIString s_true = PIStringAscii("true");
static const PIString s_yes = PIStringAscii("yes" );
static const PIString s_on = PIStringAscii("on" );
static const PIString s_ok = PIStringAscii("ok" );
PIString s(*this);
s = s.trimmed().toLowerCase();
if (s == s_true || s == s_yes || s == s_on || s == s_ok) return true;
if (toDouble() > 0.) return true;
return false;
}
//! \~\details
//! \~\code
//! PIString s("\t ! word");
//! piCout << s.takeSymbol(); // "!"
//! piCout << s.takeSymbol(); // "w"
//! piCout << s.takeSymbol(); // "o"
//! piCout << s; // "rd"
//! \endcode
//! \~\sa \a takeWord(), \a takeCWord(), \a takeLine(), \a takeNumber(), \a takeRange()
PIString PIString::takeSymbol() {
PIString ret;
int sz = size_s(), ss = -1;
for (int i = 0; i < sz; ++i) {
PIChar c = at(i);
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
ss = i;
break;
}
if (ss < 0) return ret;
ret = mid(ss, 1);
cutLeft(ss + 1);
return ret;
}
//! \~\details
//! \~\code
//! PIString s("some words\nnew line ");
//! piCout << s.takeWord(); // "some"
//! piCout << s.takeWord(); // "words"
//! piCout << s.takeWord(); // "new"
//! piCout << s; // " line "
//! \endcode
//! \~\sa \a takeSymbol(), \a takeCWord(), \a takeLine(), \a takeNumber(), \a takeRange()
PIString PIString::takeWord() {
int sz = size_s(), ws = -1, we = -1;
for (int i = 0; i < sz; ++i) {
PIChar c = at(i);
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
if (we < 0 && ws >= 0) {
we = i;
break;
}
} else {
if (ws < 0) ws = i;
if (we >= 0) break;
}
}
PIString ret = mid(ws, we - ws);
cutLeft(we < 0 ? sz : we);
return ret;
}
//! \~\details
//! \~\code
//! \endcode
//! \~\sa \a takeSymbol(), \a takeWord(), \a takeLine(), \a takeNumber(), \a takeRange()
PIString PIString::takeCWord() {
PIString ret;
int sz = size_s(), ws = -1, we = -1;
for (int i = 0; i < sz; ++i) {
PIChar c = at(i);
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
if (we < 0 && ws >= 0) {
we = i;
break;
}
} else {
if (ws < 0) {
if (c.isAlpha() || c == '_') {
ws = i;
} else {
return ret;
}
} else {
if (!c.isAlpha() && !c.isDigit() && c != '_') {
we = i;
break;
}
}
if (we >= 0) break;
}
}
ret = mid(ws, we - ws);
cutLeft(we < 0 ? sz : we);
return ret;
}
//! \~\details
//! \~\code
//! PIString s("some words\nnew line \n\nend");
//! piCout << s.takeLine(); // "some words"
//! piCout << s.takeLine(); // "new line "
//! piCout << s.takeLine(); // ""
//! piCout << s; // "end"
//! \endcode
//! \~\sa \a takeSymbol(), \a takeWord(), \a takeCWord(), \a takeNumber(), \a takeRange()
PIString PIString::takeLine() {
int sz = size_s(), le = -1;
for (int i = 0; i < sz; ++i) {
PIChar c = at(i);
if (c == '\n') {
le = i;
break;
}
}
PIString ret = left(le);
if (!ret.isEmpty()) {
if (ret.back() == '\r') {
ret.cutRight(1);
}
}
cutLeft(le < 0 ? sz : le + 1);
return ret;
}
//! \~\details
//! \~\code
//! PIString s(" 0xFF -99 1.2E+5f 1000L");
//! piCout << s.takeNumber(); // "0xFF"
//! piCout << s.takeNumber(); // "-99"
//! piCout << s.takeNumber(); // "1.2E+5f"
//! piCout << s.takeNumber(); // "1000L"
//! piCout << s; // ""
//! \endcode
//! \~\sa \a takeSymbol(), \a takeWord(), \a takeCWord(), \a takeLine(), \a takeRange()
PIString PIString::takeNumber() {
PIString ret;
int sz = size_s(), ls = -1, le = -1, phase = 0;
for (int i = 0; i < sz; ++i) {
if (phase > 7) break;
PIChar c = at(i);
//piCout << "char " << c << "phase" << phase;
switch (phase) {
case 0: // trim
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
continue;
}
phase = 7;
case 7: // sign
if (c == '-' || c == '+') {
ls = i;
phase = 1;
break;
}
case 1: // search start
if ((c >= '0' && c <= '9') || c == '.') {
le = i;
if (ls < 0) ls = i;
if (c == '.') phase = 3;
else phase = 2;
break;
}
phase = 9;
break;
case 2: // integer
if (c == '.') {
le = i;
phase = 3;
break;
}
if (c == 'e' || c == 'E') {
le = i;
phase = 4;
break;
}
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c == 'x') {
le = i;
break;
}
phase = 6;
break;
case 3: // point
if (c == 'e' || c == 'E') {
le = i;
phase = 4;
break;
}
if (c >= '0' && c <= '9') {
le = i;
break;
}
phase = 6;
break;
case 4: // exp
if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
le = i;
phase = 5;
break;
}
phase = 6;
break;
case 5: // power
if (c >= '0' && c <= '9') {
le = i;
break;
}
phase = 6;
break;
case 6: // suffix
if (c == 'f' || c == 's' || c == 'u' || c == 'l' || c == 'L') {
le = i;
break;
}
phase = 9;
break;
}
if (phase == 6) {
if (c == 'f' || c == 's' || c == 'u' || c == 'l' || c == 'L') le = i;
else phase = 9;
}
}
//piCout << ls << le;
if (le < ls) return ret;
ret = mid(ls, le - ls + 1);
cutLeft(le + 1);
return ret;
}
//! \~\details
//! \~english "shield" symbol prevent analysis of the next symbol
//! \~russian Символ "shield" экранирует следующий символ
//! \~\code
//! PIString s(" {figures{inside}}");
//! piCout << s.takeRange('{', '}'); // "figures{inside}"
//! piCout << s; // ""
//! s = "\"text\\\"shielded\" next";
//! piCout << s.takeRange('"', '"'); // "text\"shielded"
//! piCout << s; // " next"
//! \endcode
//! \~\sa \a takeSymbol(), \a takeWord(), \a takeLine(), \a takeNumber()
PIString PIString::takeRange(const PIChar start, const PIChar end, const PIChar shield) {
PIString ret;
bool trim_ = (start != ' ' && start != '\t' && start != '\n' && start != '\r'), eq = (start == end);
int sz = size_s(), ls = -1, le = -1, cnt = 0;
for (int i = 0; i < sz; ++i) {
PIChar c = at(i);
if (c == shield) {
++i;
continue;
}
if (trim_) {
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
continue;
}
trim_ = false;
}
if (eq) {
if (c == start) {
if (cnt == 0) {
ls = i;
} else {
le = i;
cnt = 0;
break;
}
cnt++;
}
} else {
if (c == start) {
if (cnt == 0) ls = i;
cnt++;
}
if (c == end) {
cnt--;
if (cnt == 0) le = i;
}
}
if (cnt <= 0) break;
}
//piCout << ls << le << cnt;
if (le < ls || ls < 0 || le < 0 || cnt != 0) return ret;
ret = mid(ls + 1, le - ls - 1);
cutLeft(le + 1);
return ret;
}
//! \~\details
//! \~\code
//! PIString s("a(b(c)d)e");
//! piCout << s.inBrackets('(', ')'); // "b(c)d"
//! piCout << s; // s = "a(b(c)d)e"
//! \endcode
PIString PIString::inBrackets(const PIChar start, const PIChar end) const {
int slen = length();
int st = -1, bcnt = 0;
PIChar cc;
for (int i = 0; i < slen; i++) {
cc = at(i);
if (cc == start) {
if (bcnt == 0) st = i;
bcnt++;
}
if (cc == end && st >= 0) {
bcnt--;
if (bcnt == 0) return mid(st+1, i-st-1);
}
}
return PIString();
}
//! \~\details
//! \~english
//! This function fill internal buffer by sequence of chars.
//! Length of this buffer is count of symbols + end byte '\0'.
//! Returned pointer is valid until next execution of this function.
//! \~russian
//! Этот метод заполняет внутренный байтовый буфер. Размер
//! этого буфера равен количеству символов строки + завершающий байт '\0'.
//! Возвращаемый указатель действителен до следующего вызова этого метода.
//! \~\code
//! piCout << PIString("0123456789").data(); // 0123456789
//! piCout << PIString("№1").data(); // №1
//! \endcode
//! \~\sa \a dataConsole(), \a dataUTF8()
const char * PIString::data() const {
if (isEmpty()) return "";
buildData(__syslocname__);
return data_;
}
//! \~\details
//! \~english
//! This function fill internal buffer by sequence of chars.
//! Length of this buffer is count of symbols + end byte '\0'.
//! Returned pointer is valid until next execution of this function.
//! \~russian
//! Этот метод заполняет внутренный байтовый буфер. Размер
//! этого буфера равен количеству символов строки + завершающий байт '\0'.
//! Возвращаемый указатель действителен до следующего вызова этого метода.
//! \~\sa \a data(), \a dataUTF8()
const char * PIString::dataConsole() const {
if (isEmpty()) return "";
buildData(__sysoemname__ );
return data_;
}
//! \~\details
//! \~english
//! This function fill internal buffer by sequence of chars.
//! Length of this buffer is count of symbols + end byte '\0'.
//! Returned pointer is valid until next execution of this function.
//! \~russian
//! Этот метод заполняет внутренный байтовый буфер. Размер
//! этого буфера равен количеству символов строки + завершающий байт '\0'.
//! Возвращаемый указатель действителен до следующего вызова этого метода.
//! \~\sa \a data(), \a dataConsole()
const char * PIString::dataUTF8() const {
if (isEmpty()) return "";
buildData(__utf8name__);
return data_;
}
//! \~\details
//! \~english
//! This function fill internal buffer by sequence of chars.
//! Length of this buffer is count of symbols + end byte '\0'.
//! Returned pointer is valid until next execution of this function.
//! \~russian
//! Этот метод заполняет внутренный байтовый буфер. Размер
//! этого буфера равен количеству символов строки + завершающий байт '\0'.
//! Возвращаемый указатель действителен до следующего вызова этого метода.
//! \~\sa \a dataConsole(), \a dataUTF8()
const char * PIString::dataAscii() const {
if (isEmpty()) return "";
deleteData();
data_ = (char*)malloc(size()+1);
for (int i = 0; i < size_s(); ++i) {
data_[i] = uchar(at(i).ch);
}
data_[size()] = '\0';
return data_;
}
PIString PIString::toUpperCase() const {
PIString str(*this);
int l = str.size();
for (int i = 0; i < l; ++i) {
str.d[i] = str.d[i].toUpper();
}
return str;
}
PIString PIString::toLowerCase() const {
PIString str(*this);
int l = str.size();
for (int i = 0; i < l; ++i) {
str.d[i] = str.d[i].toLower();
}
return str;
}
char PIString::toChar() const {
char v;
sscanf(dataAscii(), "%c", &v);
return v;
}
float PIString::toFloat() const {
return toDecimal<float>(*this);
}
double PIString::toDouble() const {
return toDecimal<double>(*this);
}
ldouble PIString::toLDouble() const {
return toDecimal<ldouble>(*this);
}
//! \~\details
//! \~english
//! Example:
//! \~russian
//! Пример:
//! \~\code
//! PIString s;
//! s.setReadableSize(512);
//! piCout << s; // 512 B
//! s.setReadableSize(5120);
//! piCout << s; // 5.0 kB
//! s.setReadableSize(512000);
//! piCout << s; // 500.0 kB
//! s.setReadableSize(5120000);
//! piCout << s; // 4.8 MB
//! s.setReadableSize(512000000);
//! piCout << s; // 488.2 MB
//! s.setReadableSize(51200000000);
//! piCout << s; // 47.6 GB
//! \endcode
PIString & PIString::setReadableSize(llong bytes) {
clear();
if (bytes < 1024) {
*this += (PIString::fromNumber(bytes) + PIStringAscii(" B"));
return *this;
}
double fres = bytes / 1024.;
llong res = bytes / 1024;
fres -= res;
if (res < 1024) {
*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" kB"));
return *this;
}
fres = res / 1024.;
res /= 1024;
fres -= res;
if (res < 1024) {
*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" MB"));
return *this;
}
fres = res / 1024.;
res /= 1024;
fres -= res;
if (res < 1024) {
*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" GB"));
return *this;
}
fres = res / 1024.;
res /= 1024;
fres -= res;
if (res < 1024) {
*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" TB"));
return *this;
}
fres = res / 1024.;
res /= 1024;
fres -= res;
*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" PB"));
return *this;
}
const static PIString _versionDelims_ = PIStringAscii("._-+");
void parseVersion(PIString s, PIVector<int> & codes, PIStringList & strs) {
s.trim();
if (s.isEmpty()) {
codes.resize(3, 0);
return;
}
int mccnt = 2 - s.entries('.');
if (mccnt > 0) {
int ind = s.findLast('.') + 1;
while (!_versionDelims_.contains(s[ind])) {
++ind;
if (ind > s.size_s() - 1) break;
}
for (int i = 0; i < mccnt; ++i) {
s.insert(ind, PIStringAscii(".0"));
}
}
PIStringList comps;
while (!s.isEmpty()) {
int ind = s.findAny(_versionDelims_);
if (ind >= 0) {
comps << s.takeLeft(ind);
s.cutLeft(1).trim();
} else {
comps << s;
s.clear();
}
}
for (int i = 0; i < comps.size_s(); ++i) {
if (comps[i].isEmpty()) comps[i] = '0';
bool ok = false;
int val = comps[i].toInt(-1, &ok);
if (ok) {
codes << val;
} else {
strs << comps[i];
}
}
//piCout << codes << strs;
}
int versionLabelValue(PIString s) {
int ret = -10000;
if (s.isEmpty()) return 0;
if (s.startsWith(PIStringAscii("pre"))) {
s.cutLeft(3);
ret -= 1;
}
if (s.startsWith(PIStringAscii("rc"))) {
s.cutLeft(2);
ret += s.toInt();
}
if (s.startsWith(PIStringAscii("r"))) {
s.cutLeft(1);
ret += 10000 + s.toInt();
}
if (s == PIStringAscii("alpha")) ret -= 4;
if (s == PIStringAscii("beta" )) ret -= 2;
return ret;
}
//! \relatesalso PIString
//! \~\details
//! \~english
//! This function parse version to number codes and labels. Then it
//! compare no more than "components" codes. If there is no difference, compare
//! labels. Each label has corresponding integer value, so
//! "prealpha" < "alpha" < "prebeta" < "beta" < "rc[N]" < "" < "r[N]".
//! Example:
//! \~russian
//! Этот метод разбирает версии на числовые части и метку. Затем сравнивает
//! не более чем "components" частей. Если различий нет, то сравниваются
//! метки. Каждой метке соответствует своё значение так, что
//! "prealpha" < "alpha" < "prebeta" < "beta" < "rc[N]" < "" < "r[N]".
//! Пример:
//! \~\code
//! piCout << versionCompare("1.0.0_rc2-999", "1.0.1_rc2-999"); // -1, <
//! piCout << versionCompare("1.0.0", "0.9.2"); // 1, >
//! piCout << versionCompare("1.0.0_r1", "1.0.0"); // 1, >
//! piCout << versionCompare("1.0.0_r1", "1.0.0", 3); // 0, =
//! piCout << versionCompare("1.0.0_r2", "1.0.0", 3); // 0, =
//! piCout << versionCompare(".2-alpha", "0.2_alpha"); // 0, =
//! piCout << versionCompare("1_prebeta", "1.0_alpha"); // 1, >
//! \endcode
//! \~\return
//! \~english
//! * 0 - equal
//! * 1 - v0 > v1
//! * -1 - v0 < v1
//! \~russian
//! * 0 - равны
//! * 1 - v0 > v1
//! * -1 - v0 < v1
int versionCompare(const PIString & v0, const PIString & v1, int components) {
PIStringList strs[2]; PIVector<int> codes[2];
parseVersion(v0.toLowerCase(), codes[0], strs[0]);
parseVersion(v1.toLowerCase(), codes[1], strs[1]);
//piCout << codes[0] << strs[0];
int mc = piMaxi(codes[0].size_s(), codes[1].size_s());
if (codes[0].size_s() < mc) codes[0].resize(mc, 0);
if (codes[1].size_s() < mc) codes[1].resize(mc, 0);
mc = piMaxi(strs[0].size_s(), strs[1].size_s());
if (strs[0].size_s() < mc) strs[0].resize(mc, "");
if (strs[1].size_s() < mc) strs[1].resize(mc, "");
int comps = piMini(components, codes[0].size_s(), codes[1].size_s());
if (comps < 1) return (v0 == v1 ? 0 : (v0 > v1 ? 1 : -1));
for (int c = 0; c < comps; ++c) {
if (codes[0][c] > codes[1][c]) return 1;
if (codes[0][c] < codes[1][c]) return -1;
}
mc = piClampi(mc, 0, components - comps);
for (int c = 0; c < mc; ++c) {
int lv0 = versionLabelValue(strs[0][c]);
int lv1 = versionLabelValue(strs[1][c]);
if (lv0 > lv1) return 1;
if (lv0 < lv1) return -1;
}
return 0;
}
//! \relatesalso PIString
//! \~\details
//! \~english
//! Parse version as described in \a versionCompare() and returns
//! classic view of codes and labels: major.minor.revision[-build][_label].
//! Example:
//! \~russian
//! Разбирает версию по описанию \a versionCompare() и возвращает
//! классическое представление версии и метки: major.minor.revision[-build][_label].
//! Пример:
//! \~\code
//! piCout << versionNormalize(""); // 0.0.0
//! piCout << versionNormalize("1"); // 1.0.0
//! piCout << versionNormalize("1.2"); // 1.2.0
//! piCout << versionNormalize("1.2.3"); // 1.2.3
//! piCout << versionNormalize("1.2+rc1.99"); // 1.2.99_rc1
//! piCout << versionNormalize("1.2-alpha"); // 1.2.0_alpha
//! piCout << versionNormalize("1..4_rc2-999"); // 1.0.4-999_rc2
//! \endcode
PIString versionNormalize(const PIString & v) {
PIStringList strs; PIVector<int> codes;
parseVersion(v.toLowerCase(), codes, strs);
PIString ret;
for (int i = 0; i < codes.size_s(); ++i) {
if (i > 0) {
if (i < 3) ret += '.';
else ret += '-';
}
ret += PIString::fromNumber(codes[i]);
}
for (int i = 0; i < strs.size_s(); ++i) {
ret += '_';
ret += strs[i];
}
return ret;
}

1570
libs/main/text/pistring.h Normal file
View File

@@ -0,0 +1,1570 @@
/*! \file pistring.h
* \ingroup Text
* \brief
* \~english String class
* \~russian Класс строки
*/
/*
PIP - Platform Independent Primitives
String
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PISTRING_H
#define PISTRING_H
#include "pibytearray.h"
#include "piconstchars.h"
#define PIStringAscii PIString::fromAscii
class PIStringList;
//! \ingroup Text
//! \~\brief
//! \~english String class.
//! \~russian Класс строки.
class PIP_EXPORT PIString
{
BINARY_STREAM_FRIEND(PIString);
public:
typedef PIDeque<PIChar>::iterator iterator;
typedef PIDeque<PIChar>::const_iterator const_iterator;
typedef PIDeque<PIChar>::reverse_iterator reverse_iterator;
typedef PIDeque<PIChar>::const_reverse_iterator const_reverse_iterator;
typedef PIChar value_type;
typedef PIChar* pointer;
typedef const PIChar* const_pointer;
typedef PIChar& reference;
typedef const PIChar& const_reference;
typedef size_t size_type;
//! \~english Contructs an empty string.
//! \~russian Создает пустую строку.
PIString() {}
//! \~english Value for elide at left.
//! \~russian Значение для пропуска слева.
static const float ElideLeft ;
//! \~english Value for elide at center.
//! \~russian Значение для пропуска в середине.
static const float ElideCenter;
//! \~english Value for elide at right.
//! \~russian Значение для пропуска справа.
static const float ElideRight ;
PIString & operator +=(const PIChar & c) {d.push_back(c); return *this;}
PIString & operator +=(const char c) {d.push_back(PIChar(c)); return *this;}
PIString & operator +=(const char * str);
PIString & operator +=(const wchar_t * str);
PIString & operator +=(const PIByteArray & ba);
PIString & operator +=(const PIString & str);
PIString & operator +=(const PIConstChars & str);
PIString(uchar ) = delete;
PIString( short) = delete;
PIString(ushort) = delete;
PIString( int ) = delete;
PIString(uint ) = delete;
PIString( long ) = delete;
PIString(ulong ) = delete;
PIString( llong) = delete;
PIString(ullong) = delete;
PIString & operator +=(uchar ) = delete;
PIString & operator +=( short) = delete;
PIString & operator +=(ushort) = delete;
PIString & operator +=( int ) = delete;
PIString & operator +=(uint ) = delete;
PIString & operator +=( long ) = delete;
PIString & operator +=(ulong ) = delete;
PIString & operator +=( llong) = delete;
PIString & operator +=(ullong) = delete;
//! \~english Contructs a copy of string.
//! \~russian Создает копию строки.
PIString(const PIString & o) {d = o.d;}
//! \~english Move constructor.
//! \~russian Перемещающий конструктор.
PIString(PIString && o): d(std::move(o.d)) {piSwap(data_, o.data_);}
//! \~english Contructs string with single character "c".
//! \~russian Создает строку из одного символа "c".
PIString(const PIChar c) {d.push_back(c);}
//! \~english Contructs string with single character "c".
//! \~russian Создает строку из одного символа "c".
PIString(const char c) {d.push_back(PIChar(c));}
//! \~english Contructs string from C-string "str" (system codepage).
//! \~russian Создает строку из C-строки "str" (кодировка системы).
//! \~\details
//! \~english
//! "str" should be null-terminated\n
//! \~russian
//! "str" должна заканчиваться нулевым байтом\n
//! \~\code
//! PIString s("string");
//! \endcode
PIString(const char * str) {*this += str;}
//! \~english Contructs string from \c wchar_t C-string "str".
//! \~russian Создает строку из \c wchar_t C-строки "str".
//! \~\details
//! \~english
//! "str" should be null-terminated
//! \~russian
//! "str" должна заканчиваться нулевым \c wchar_t
//! \~\code
//! PIString s(L"string");
//! \endcode
PIString(const wchar_t * str) {*this += str;}
//! \~english Contructs string from byte array "ba" (as UTF-8).
//! \~russian Создает строку из байтового массива "ba" (как UTF-8).
PIString(const PIByteArray & ba) {*this += ba;}
//! \~english Contructs string from "len" characters of buffer "str".
//! \~russian Создает строку из "len" символов массива "str".
PIString(const PIChar * str, const int len): d(str, size_t(len)) {}
//! \~english Contructs string from "len" characters of buffer "str" (system codepage).
//! \~russian Создает строку из "len" символов массива "str" (кодировка системы).
//! \~\details
//! \~\code
//! PIString s("string", 3); // s = "str"
//! \endcode
PIString(const char * str, const int len) {appendFromChars(str, len);}
//! \~english Contructs string as sequence of characters "c" of buffer with length "len".
//! \~russian Создает строку как последовательность длиной "len" символа "c".
//! \~\details
//! \~\code
//! PIString s(5, 'p'); // s = "ppppp"
//! \endcode
PIString(const int len, const char c) {for (int i = 0; i < len; ++i) d.push_back(PIChar(c));}
//! \~english Contructs string as sequence of characters "c" of buffer with length "len".
//! \~russian Создает строку как последовательность длиной "len" символа "c".
//! \~\details
//! \~\code
//! PIString s(5, "№"); // s = "№№№№№"
//! \endcode
PIString(const int len, const PIChar c) {for (int i = 0; i < len; ++i) d.push_back(c);}
PIString(const PIConstChars & c) {*this += c;}
~PIString();
//! \~english Assign operator.
//! \~russian Оператор присваивания.
PIString & operator =(const PIString & o) {if (this == &o) return *this; d = o.d; return *this;}
//! \~english Assign move operator.
//! \~russian Оператор перемещающего присваивания.
PIString & operator =(PIString && o) {d.swap(o.d); piSwap(data_, o.data_); return *this;}
//! \~english Assign operator.
//! \~russian Оператор присваивания.
PIString & operator =(const PIConstChars & o) {d.clear(); *this += o; return *this;}
//! \~english Assign operator.
//! \~russian Оператор присваивания.
PIString & operator =(const char * o) {d.clear(); *this += o; return *this;}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator ==(const PIString & str) const;
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator ==(const PIChar c) const {if (d.size() != 1) return false; return d.at(0) == c;}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator ==(const char * str) const {return *this == PIString(str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator !=(const PIString & str) const;
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator !=(const PIChar c) const {if (d.size() != 1) return true; return d.at(0) != c;}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator !=(const char * str) const {return *this != PIString(str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator <(const PIString & str) const;
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator <(const PIChar c) const {if (d.size() != 1) return d.size() < 1; return d.at(0) < c;}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator <(const char * str) const {return *this < PIString(str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator >(const PIString & str) const;
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator >(const PIChar c) const {if (d.size() != 1) return d.size() > 1; return d.at(0) > c;}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator >(const char * str) const {return *this > PIString(str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator <=(const PIString & str) const {return !(*this > str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator <=(const PIChar c) const {return !(*this > c);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator <=(const char * str) const {return *this <= PIString(str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator >=(const PIString & str) const {return !(*this < str);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator >=(const PIChar c) const {return !(*this < c);}
//! \~english Compare operator.
//! \~russian Оператор сравнения.
bool operator >=(const char * str) const {return *this >= PIString(str);}
//! \~english Iterator to the first element.
//! \~russian Итератор на первый элемент.
//! \~\details
//! \~\return \ref stl_iterators
//! \~\sa \a end(), \a rbegin(), \a rend()
inline iterator begin() {return d.begin();}
//! \~english Iterator to the element following the last element.
//! \~russian Итератор на элемент, следующий за последним элементом.
//! \~\details
//! \~\return \ref stl_iterators
//! \~\sa \a begin(), \a rbegin(), \a rend()
inline iterator end() {return d.end();}
inline const_iterator begin() const {return d.begin();}
inline const_iterator end() const {return d.end();}
//! \~english Returns a reverse iterator to the first element of the reversed array.
//! \~russian Обратный итератор на первый элемент.
//! \~\details
//! \~english It corresponds to the last element of the non-reversed array.
//! \~russian Итератор для прохода массива в обратном порядке.
//! Указывает на последний элемент.
//! \~\return \ref stl_iterators
//! \~\sa \a rend(), \a begin(), \a end()
inline reverse_iterator rbegin() {return d.rbegin();}
//! \~english Returns a reverse iterator to the element.
//! following the last element of the reversed array.
//! \~russian Обратный итератор на элемент, следующий за последним элементом.
//! \~\details
//! \~english It corresponds to the element preceding the first element of the non-reversed array.
//! \~russian Итератор для прохода массива в обратном порядке.
//! Указывает на элемент, предшествующий первому элементу.
//! \~\return \ref stl_iterators
//! \~\sa \a rbegin(), \a begin(), \a end()
inline reverse_iterator rend() {return d.rend();}
inline const_reverse_iterator rbegin() const {return d.rbegin();}
inline const_reverse_iterator rend() const {return d.rend();}
//! \~english Full access to character by `index`.
//! \~russian Полный доступ к символу по индексу `index`.
//! \~\details
//! \~english Сharacter index starts from `0`.
//! Сharacter index must be in range from `0` to `size()-1`.
//! Otherwise will be undefined behavior.
//! \~russian Индекс элемента считается от `0`.
//! Индекс символа должен лежать в пределах от `0` до `size()-1`.
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
inline PIChar & operator [](size_t index) {return d[index];}
inline PIChar operator [](size_t index) const {return d[index];}
//! \~english Read only access to character by `index`.
//! \~russian Доступ исключительно на чтение к символу по индексу `index`.
//! \~\details
//! \~english Сharacter index starts from `0`.
//! Сharacter index must be in range from `0` to `size()-1`.
//! Otherwise will be undefined behavior.
//! \~russian Индекс символа считается от `0`.
//! Индекс символа должен лежать в пределах от `0` до `size()-1`.
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
inline const PIChar at(size_t index) const {return d.at(index);}
//! \~english Returns the last character of the string.
//! \~russian Возвращает последний символ строки.
inline PIChar & back() {return d.back();}
inline PIChar back() const {return d.back();}
inline PIChar & front() {return d.front();}
inline PIChar front() const {return d.front();}
//! \~english Sets size of the string, new characters are copied from `c`.
//! \~russian Устанавливает размер строки, новые символы копируются из `c`.
//! \~\details
//! \~english If `new_size` is greater than the current \a size(),
//! characters are added to the end; the new characters are initialized from `c`.
//! If `new_size` is less than the current \a size(), characters are removed from the end.
//! \~russian Если `new_size` больше чем текущий размер строки \a size(),
//! новые символы добавляются в конец строки и создаются из `с`.
//! Если `new_size` меньше чем текущий размер строки \a size(),
//! лишние символы удаляются с конца строки.
//! \~\sa \a size(), \a clear()
inline PIString & resize(size_t new_size, PIChar c = PIChar()) {d.resize(new_size, c); return *this;}
//! \~english Delete one character at the end of string.
//! \~russian Удаляет один символ с конца строки.
inline PIString & pop_back() {d.pop_back(); return *this;}
//! \~english Delete one character at the benig of string.
//! \~russian Удаляет один символ с начала строки.
inline PIString & pop_front() {d.pop_front(); return *this;}
//! \~english Removes `count` characters from the string, starting at `index` position.
//! \~russian Удаляет символы из строки, начиная с позиции `index` в количестве `count`.
inline PIString & remove(size_t index, size_t count = 1) {d.remove(index, count); return *this;}
//! \~english Assigns character 'c' to all string characters.
//! \~russian Заполняет всю строку символами `c`.
inline PIString & fill(PIChar c = PIChar()) {d.fill(c); return *this;}
//! \~english Insert string "str" at the begin of string.
//! \~russian Вставляет "str" в начало строки.
PIString & prepend(const char * str) {insert(0, str); return *this;}
//! \~english Insert string "str" at the begin of string.
//! \~russian Вставляет "str" в начало строки.
PIString & prepend(const PIString & str) {d.prepend(str.d); return *this;}
//! \~english Insert character `c` at the begin of string.
//! \~russian Вставляет символ `c` в начало строки.
PIString & prepend(const PIChar c) {d.prepend(c); return *this;}
//! \~english Insert character `c` at the begin of string.
//! \~russian Вставляет символ `c` в начало строки.
PIString & prepend(const char c) {d.prepend(PIChar(c)); return *this;}
//! \~english Insert string "str" at the begin of string.
//! \~russian Вставляет "str" в начало строки.
PIString & push_front(const char * str) {insert(0, str); return *this;}
//! \~english Insert string "str" at the begin of string.
//! \~russian Вставляет "str" в начало строки.
PIString & push_front(const PIString & str) {d.push_front(str.d); return *this;}
//! \~english Insert character `c` at the begin of string.
//! \~russian Вставляет символ `c` в начало строки.
PIString & push_front(const PIChar c) {d.push_front(c); return *this;}
//! \~english Insert character `c` at the begin of string.
//! \~russian Вставляет символ `c` в начало строки.
PIString & push_front(const char c) {d.push_front(PIChar(c)); return *this;}
//! \~english Insert string "str" at the end of string.
//! \~russian Вставляет "str" в конец строки.
PIString & append(const char * str) {*this += str; return *this;}
//! \~english Insert string "str" at the end of string.
//! \~russian Вставляет "str" в конец строки.
PIString & append(const PIString & str) {d.append(str.d); return *this;}
PIString & append(const PIConstChars & str) {*this += str; return *this;}
//! \~english Insert character `c` at the end of string.
//! \~russian Вставляет символ `c` в конец строки.
PIString & append(const PIChar c) {d.append(c); return *this;}
//! \~english Insert character `c` at the end of string.
//! \~russian Вставляет символ `c` в конец строки.
PIString & append(const char c) {d.append(PIChar(c)); return *this;}
//! \~english Insert string "str" at the end of string.
//! \~russian Вставляет "str" в конец строки.
PIString & push_back(const char * str) {*this += str; return *this;}
//! \~english Insert string "str" at the end of string.
//! \~russian Вставляет "str" в конец строки.
PIString & push_back(const PIString & str) {d.push_back(str.d); return *this;}
PIString & push_back(const PIConstChars & str) {*this += str; return *this;}
//! \~english Insert character `c` at the end of string.
//! \~russian Вставляет символ `c` в конец строки.
PIString & push_back(const PIChar c) {d.push_back(c); return *this;}
//! \~english Insert character `c` at the end of string.
//! \~russian Вставляет символ `c` в конец строки.
PIString & push_back(const char c) {d.push_back(PIChar(c)); return *this;}
//! \~english Returns part of string from character at index "start" and maximum length "len".
//! \~russian Возвращает подстроку от символа "start" и максимальной длиной "len".
PIString mid(int start, int len = -1) const;
//! \~english Synonym of \a mid().
//! \~russian Аналог \a mid().
PIString subString(int start, int len = -1) const {return mid(start, len);}
//! \~english Returns part of string from start and maximum length "len".
//! \~russian Возвращает подстроку от начала и максимальной длиной "len".
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.left(-1); // s = ""
//! piCout << s.left(1); // s = "0"
//! piCout << s.left(5); // s = "01234"
//! piCout << s.left(15); // s = "0123456789"
//! \endcode
//! \~\sa \a mid(), \a right()
PIString left(int len) const {return len <= 0 ? PIString() : mid(0, len);}
//! \~english Returns part of string at end and maximum length "len".
//! \~russian Возвращает подстроку максимальной длиной "len" и до конца.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.right(-1); // s = ""
//! piCout << s.right(1); // s = "9"
//! piCout << s.right(5); // s = "56789"
//! piCout << s.right(15); // s = "0123456789"
//! \endcode
//! \~\sa \a mid(), \a left()
PIString right(int len) const {return len <= 0 ? PIString() : mid(size() - len, len);}
//! \~english Remove part of string from character as index "start" and maximum length "len" and return this string.
//! \~russian Удаляет часть строки от символа "start" и максимальной длины "len", возвращает эту строку.
PIString & cutMid(int start, int len);
//! \~english Remove part of string from start and maximum length "len" and return this string.
//! \~russian Удаляет часть строки от начала и максимальной длины "len", возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! s.cutLeft(1);
//! piCout << s; // s = "123456789"
//! s.cutLeft(3);
//! piCout << s; // s = "456789"
//! s.cutLeft(30);
//! piCout << s; // s = ""
//! \endcode
//! \~\sa \a cutMid(), \a cutRight()
PIString & cutLeft(int len) {return len <= 0 ? *this : cutMid(0, len);}
//! \~english Remove part of string at end and maximum length "len" and return this string.
//! \~russian Удаляет часть строки максимальной длины "len" от конца, возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! s.cutRight(1);
//! piCout << s; // s = "012345678"
//! s.cutRight(3);
//! piCout << s; // s = "012345"
//! s.cutRight(30);
//! piCout << s; // s = ""
//! \endcode
//! \~\sa \a cutMid(), \a cutLeft()
PIString & cutRight(int len) {return len <= 0 ? *this : cutMid(size() - len, len);}
//! \~english Remove spaces at the start and at the end of string and return this string.
//! \~russian Удаляет пробельные символы с начала и конца строки и возвращает эту строку.
PIString & trim();
//! \~english Returns copy of this string without spaces at the start and at the end.
//! \~russian Возвращает копию этой строки без пробельных символов с начала и конца.
//! \~\details
//! \~\code
//! PIString s(" \t string \n");
//! piCout << s.trimmed(); // s = "string"
//! piCout << s; // s = " string "
//! \endcode
//! \~\sa \a trim()
PIString trimmed() const;
//! \~english Replace part of string from index "from" and maximum length "len" with string "with" and return this string.
//! \~russian Заменяет часть строки от символа "from" и максимальной длины "len" строкой "with", возвращает эту строку.
PIString & replace(const int from, const int count, const PIString & with);
//! \~english Replace part copy of this string from index "from" and maximum length "len" with string "with".
//! \~russian Заменяет часть копии этой строки от символа "from" и максимальной длины "len" строкой "with".
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.replaced(2, 3, "_cut_"); // s = "01_cut_56789"
//! piCout << s.replaced(0, 1, "one_"); // s = "one_123456789"
//! \endcode
//! \~\sa \a replace(), \a replaceAll()
PIString replaced(const int from, const int count, const PIString & with) const {PIString str(*this); str.replace(from, count, with); return str;}
//! \~english Replace first founded substring "what" with string "with" and return this string.
//! \~russian Заменяет первую найденную подстроку "what" строкой "with", возвращает эту строку.
PIString & replace(const PIString & what, const PIString & with, bool * ok = 0);
//! \~english Replace in string copy first founded substring "what" with string "with".
//! \~russian Заменяет в копии строки первую найденную подстроку "what" строкой "with".
//! \~\details
//! \~english If "ok" is not null, it set to "true" if something was replaced.
//! \~russian Если "ok" не null, то устанавливает в "true" если замена произведена.
//! \~\code
//! PIString s("pip string");
//! bool ok;
//! piCout << s.replace("string", "conf", &ok); // s = "pip conf", true
//! piCout << s.replace("PIP", "PlInPr", &ok); // s = "pip string", false
//! \endcode
//! \~\sa \a replaced(), \a replaceAll()
PIString replaced(const PIString & what, const PIString & with, bool * ok = 0) const {PIString str(*this); str.replace(what, with, ok); return str;}
//! \~english Replace all founded substrings "what" with strings "with" and return this string.
//! \~russian Заменяет все найденные подстроки "what" строками "with", возвращает эту строку.
PIString & replaceAll(const PIString & what, const PIString & with);
//! \~english Replace all founded substrings "what" with characters "with" and return this string.
//! \~russian Заменяет все найденные подстроки "what" символами "with", возвращает эту строку.
PIString & replaceAll(const PIString & what, const char with);
//! \~english Replace all founded characters "what" with characters "with" and return this string.
//! \~russian Заменяет все найденные символы "what" символами "with", возвращает эту строку.
PIString & replaceAll(const char what, const char with);
//! \~english Replace all founded substrings "what" with strings "with" in string copy.
//! \~russian Заменяет в копии строки все найденные подстроки "what" строками "with".
//! \~\sa \a replaceAll()
PIString replacedAll(const PIString & what, const PIString & with) const {PIString str(*this); str.replaceAll(what, with); return str;}
//! \~english Replace all founded substrings "what" with characters "with" in string copy.
//! \~russian Заменяет в копии строки все найденные подстроки "what" символами "with".
//! \~\sa \a replaceAll()
PIString replacedAll(const PIString & what, const char with) const {PIString str(*this); str.replaceAll(what, with); return str;}
//! \~english Replace all founded characters "what" with characters "with" in string copy.
//! \~russian Заменяет в копии строки все найденные символы "what" символами "with".
//! \~\sa \a replaceAll()
PIString replacedAll(const char what, const char with) const {PIString str(*this); str.replaceAll(what, with); return str;}
//! \~english Remove all founded substrings "what" and return this string.
//! \~russian Удаляет все найденные подстроки "what", возвращает эту строку.
PIString & removeAll(const PIString & str);
//! \~english Remove all founded characters "what" and return this string.
//! \~russian Удаляет все найденные символы "what", возвращает эту строку.
PIString & removeAll(char c) {d.removeAll(PIChar(c)); return *this;}
//! \~english Repeat content of string "times" times and return this string.
//! \~russian Повторяет содержимое строки "times" раз и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s(" :-) ");
//! s.repeat(3);
//! piCout << s; // :-) :-) :-)
//! \endcode
//! \~\sa \a repeated()
PIString & repeat(int times) {PIString ss(*this); times--; piForTimes (times) *this += ss; return *this;}
//! \~english Returns repeated "times" times string.
//! \~russian Возвращает повторённую "times" раз строку.
//! \~\details
//! \~\code
//! PIString s(" :-) ");
//! piCout << s.repeated(3); // :-) :-) :-)
//! piCout << s; // :-)
//! \endcode
//! \~\sa \a repeat()
PIString repeated(int times) const {PIString ss(*this); return ss.repeat(times);}
//! \~english Insert character "c" after index "index" and return this string.
//! \~russian Вставляет символ "c" после позиции "index" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("pp");
//! s.insert(1, "i");
//! piCout << s; // s = "pip"
//! \endcode
PIString & insert(const int index, const PIChar c) {d.insert(index, c); return *this;}
//! \~english Insert character "c" after index "index" and return this string.
//! \~russian Вставляет символ "c" после позиции "index" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("pp");
//! s.insert(1, 'i');
//! piCout << s; // s = "pip"
//! \endcode
PIString & insert(const int index, const char c) {return insert(index, PIChar(c));}
//! \~english Insert string "str" after index "index" and return this string.
//! \~russian Вставляет строку "str" после позиции "index" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("stg");
//! s.insert(2, "rin");
//! piCout << s; // s = "string"
//! \endcode
PIString & insert(const int index, const PIString & str);
//! \~english Insert string "str" after index "index" and return this string.
//! \~russian Вставляет строку "str" после позиции "index" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("stg");
//! s.insert(2, "rin");
//! piCout << s; // s = "string"
//! \endcode
PIString & insert(const int index, const char * c) {return insert(index, PIString(c));}
//! \~english Enlarge string to length "len" by addition characters "c" at the end, and return this string.
//! \~russian Увеличивает длину строки до "len" добавлением символов "c" в конец и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("str");
//! s.expandRightTo(2, "_");
//! piCout << s; // s = "str"
//! s.expandRightTo(6, "_");
//! piCout << s; // s = "str___"
//! \endcode
//! \~\sa \a expandLeftTo(), \a expandedRightTo(), \a expandedLeftTo()
PIString & expandRightTo(const int len, const PIChar c) {if (len > d.size_s()) d.resize(len, c); return *this;}
//! \~english Enlarge string to length "len" by addition characters "c" at the begin, and return this string.
//! \~russian Увеличивает длину строки до "len" добавлением символов "c" в начало и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("str");
//! s.expandLeftTo(2, "_");
//! piCout << s; // s = "str"
//! s.expandLeftTo(6, "_");
//! piCout << s; // s = "___str"
//! \endcode
//! \~\sa \a expandRightTo(), \a expandedRightTo(), \a expandedLeftTo()
PIString & expandLeftTo(const int len, const PIChar c) {if (len > d.size_s()) insert(0, PIString(len - d.size_s(), c)); return *this;}
//! \~english Enlarge copy of this string to length "len" by addition characters "c" at the end.
//! \~russian Увеличивает длину копии этой строки до "len" добавлением символов "c" в конец.
//! \~\details
//! \~\code
//! PIString s("str");
//! piCouy << s.expandedRightTo(5, "_"); // s = "str__"
//! piCout << s; // s = "str"
//! \endcode
//! \~\sa \a expandRightTo(), \a expandLeftTo(), \a expandedLeftTo()
PIString expandedRightTo(const int len, const PIChar c) const {return PIString(*this).expandRightTo(len, c);}
//! \~english Enlarge copy of this string to length "len" by addition characters "c" at the begin.
//! \~russian Увеличивает длину копии этой строки до "len" добавлением символов "c" в начало.
//! \~\details
//! \~\code
//! PIString s("str");
//! piCouy << s.expandedLeftTo(5, "_"); // s = "__str"
//! piCout << s; // s = "str"
//! \endcode
//! \~\sa \a expandRightTo(), \a expandLeftTo(), \a expandedRightTo()
PIString expandedLeftTo(const int len, const PIChar c) const {return PIString(*this).expandLeftTo(len, c);}
//! \~english Add "c" characters at the beginning and end, and return this string.
//! \~russian Добавляет символ "c" в начало и конец и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("str");
//! s.quote();
//! piCout << s; // s = ""str""
//! \endcode
//! \~\sa \a quoted()
PIString & quote(PIChar c = PIChar('"')) {d.prepend(c); d.append(c); return *this;}
//! \~english Returns quoted copy of this string.
//! \~russian Возвращает копию строки с добавленным в начало и конец символом "c".
//! \~\details
//! \~\code
//! PIString s("str");
//! piCout << s.quoted(); // s = ""str""
//! piCout << s; // s = "str"
//! \endcode
//! \~\sa \a quote()
PIString quoted(PIChar c = PIChar('"')) {return PIString(*this).quote(c);}
//! \~english Reverse string and return this string.
//! \~russian Разворачивает и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! s.reverse();
//! piCout << s; // s = "9876543210"
//! \endcode
//! \~\sa \a reversed()
PIString & reverse() {d.reverse(); return *this;}
//! \~english Reverse copy of this string.
//! \~russian Разворачивает копию этой строки.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.reversed(); // s = "9876543210"
//! piCout << s; // s = "0123456789"
//! \endcode
//! \~\sa \a reverse()
PIString reversed() const {PIString ret(*this); return ret.reverse();}
//! \~english Fit string to maximum size "size" by inserting ".." at position "pos" and return this string.
//! \~russian Уменьшает строку до размера "size", вставляя ".." в положение "pos" и возвращает эту строку.
//! \~\sa \a elided()
PIString & elide(int size, float pos = ElideCenter);
//! \~english Fit copy of this string to maximum size "size" by inserting ".." at position "pos".
//! \~russian Уменьшает копию этой строки до размера "size", вставляя ".." в положение "pos".
//! \~\details
//! \~\code
//! piCout << PIString("123456789ABCDEF").elided(8, PIString::ElideLeft); // ..ABCDEF
//! piCout << PIString("123456789ABCDEF").elided(8, PIString::ElideCenter); // 123..DEF
//! piCout << PIString("123456789ABCDEF").elided(8, PIString::ElideRight); // 123456..
//! piCout << PIString("123456789ABCDEF").elided(8, 0.25); // 12..CDEF
//! \endcode
//! \~\sa \a elide()
PIString elided(int size, float pos = ElideCenter) const {PIString str(*this); str.elide(size, pos); return str;}
//! \~english Take a part of string from character at index "start" and maximum length "len" and return it.
//! \~russian Извлекает часть строки от символа "start" максимальной длины "len" и возвращает её.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.takeMid(1, 3); // "123"
//! piCout << s; // s = "0456789"
//! \endcode
//! \~\sa \a takeLeft, \a takeRight()
PIString takeMid(const int start, const int len = -1) {PIString ret(mid(start, len)); cutMid(start, len); return ret;}
//! \~english Take a part from the begin of string with maximum length "len" and return it.
//! \~russian Извлекает часть строки от начала максимальной длины "len" и возвращает её.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.takeLeft(3); // "012"
//! piCout << s; // s = "3456789"
//! \endcode
//! \~\sa \a takeMid(), \a takeRight()
PIString takeLeft(const int len) {PIString ret(left(len)); cutLeft(len); return ret;}
//! \~english Take a part from the end of string with maximum length "len" and return it.
//! \~russian Извлекает часть строки с конца максимальной длины "len" и возвращает её.
//! \~\details
//! \~\code
//! PIString s("0123456789");
//! piCout << s.takeRight(3); // "789"
//! piCout << s; // s = "0123456"
//! \endcode
//! \~\sa \a takeMid(), \a takeLeft()
PIString takeRight(const int len) {PIString ret(right(len)); cutRight(len); return ret;}
//! \~english Take a character from the begin of this string and return it.
//! \~russian Извлекает символ с начала строки и возвращает его как строку.
PIString takeSymbol();
//! \~english Take a word from the begin of this string and return it.
//! \~russian Извлекает слово с начала строки и возвращает его.
PIString takeWord();
//! \~english Take a word with letters, numbers and '_' characters from the begin of this string and return it.
//! \~russian Извлекает слово из букв, цифр и симолов '_' с начала строки и возвращает его.
PIString takeCWord();
//! \~english Take a line from the begin of this string and return it.
//! \~russian Извлекает строку текста (до новой строки) с начала строки и возвращает её.
PIString takeLine();
//! \~english Take a number with C-format from the begin of this string and return it.
//! \~russian Извлекает число в C-формате с начала строки и возвращает его как строку.
PIString takeNumber();
//! \~english Take a range between "start" and "end" characters from the begin of this string and return it.
//! \~russian Извлекает диапазон между символами "start" и "end" с начала строки и возвращает его.
PIString takeRange(const PIChar start, const PIChar end, const PIChar shield = '\\');
//! \~english Returns string in brackets "start" and "end" characters from the beginning.
//! \~russian Возвращает строку между символами "start" и "end" с начала строки.
PIString inBrackets(const PIChar start, const PIChar end) const;
//! \~english Returns \c char * representation of this string in system codepage.
//! \~russian Возвращает \c char * представление строки в системной кодировке.
const char * data() const;
//! \~english Returns \c char * representation of this string in terminal codepage.
//! \~russian Возвращает \c char * представление строки в кодировке консоли.
const char * dataConsole() const;
//! \~english Returns \c char * representation of this string in UTF-8.
//! \~russian Возвращает \c char * представление строки в кодировке UTF-8.
const char * dataUTF8() const;
//! \~english Returns \c char * representation of this string in ASCII.
//! \~russian Возвращает \c char * представление строки в кодировке ASCII.
const char * dataAscii() const;
//! \~english Returns hash of string
//! \~russian Возвращает хэш строки
uint hash() const;
//! \~english Same as \a toUTF8().
//! \~russian Тоже самое, что \a toUTF8().
PIByteArray toByteArray() const {return toUTF8();}
//! \~english Returns \a PIByteArray contains \a data() of this string without terminating null-char.
//! \~russian Возвращает \a PIByteArray содержащий \a data() строки без завершающего нулевого байта.
PIByteArray toSystem() const;
//! \~english Returns \a PIByteArray contains \a dataUTF8() of this string without terminating null-char.
//! \~russian Возвращает \a PIByteArray содержащий \a dataUTF8() строки без завершающего нулевого байта.
PIByteArray toUTF8() const;
//! \~english Returns \a PIByteArray contains custom charset representation of this string without terminating null-char.
//! \~russian Возвращает \a PIByteArray содержащий строку в указанной кодировке без завершающего нулевого байта.
PIByteArray toCharset(const char * c) const;
//! \~english Returns \a PIString with non-ASCII symbols replaced with '?'.
//! \~russian Возвращает \a PIString с заменёнными '?' не-ASCII символами.
PIString simplified() const;
//! \~english Split string with delimiter "delim" to \a PIStringList.
//! \~russian Разделяет строку в \a PIStringList через разделитель "delim".
//! \~\details
//! \~\code
//! PIString s("1 2 3");
//! piCout << s.split(" "); // {"1", "2", "3"}
//! \endcode
PIStringList split(const PIString & delim) const;
//! \~english Convert each character in copied string to upper case.
//! \~russian Преобразует каждый символ в скопированной строке в верхний регистр.
PIString toUpperCase() const;
//! \~english Convert each character in copied string to lower case.
//! \~russian Преобразует каждый символ в скопированной строке в нижний регистр.
PIString toLowerCase() const;
//! \~english Returns if string contains character "c".
//! \~russian Возвращает содержит ли строка символ "c".
bool contains(const char c) const {return d.contains(PIChar(c));}
//! \~english Returns if string contains substring "str".
//! \~russian Возвращает содержит ли строка подстроку "str".
bool contains(const char * str) const {return contains(PIString(str));}
//! \~english Returns if string contains substring "str".
//! \~russian Возвращает содержит ли строка подстроку "str".
bool contains(const PIString & str) const {return find(str) >= 0;}
//! \~english Search character "c" from character at index "start" and return first occur position.
//! \~russian Ищет символ "c" от символа "start" и возвращает первое вхождение.
int find(const char c, const int start = 0) const;
//! \~english Search character "c" from character at index "start" and return first occur position.
//! \~russian Ищет символ "c" от символа "start" и возвращает первое вхождение.
int find(PIChar c, const int start = 0) const {return d.indexOf(c, start);}
//! \~english Search substring "str" from character at index "start" and return first occur position.
//! \~russian Ищет подстроку "str" от символа "start" и возвращает первое вхождение.
int find(const PIString & str, const int start = 0) const;
//! \~english Search substring "str" from character at index "start" and return first occur position.
//! \~russian Ищет подстроку "str" от символа "start" и возвращает первое вхождение.
//! \~\details
//! \~\code
//! PIString s("012345012345");
//! piCout << s.find("-"); // -1
//! piCout << s.find("34"); // 3
//! piCout << s.find("3", 4); // 9
//! piCout << s.find("3", 10); // -1
//! \endcode
//! \~\sa \a findAny(), \a findLast(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int find(const char * str, const int start = 0) const {return find(PIString(str), start);}
//! \~english Search any character of "str" from character at index "start" and return first occur position.
//! \~russian Ищет любой символ строки "str" от симола "start" и возвращает первое вхождение.
int findAny(const PIString & str, const int start = 0) const;
//! \~english Search any character of "str" from character at index "start" and return first occur position.
//! \~russian Ищет любой символ строки "str" от симола "start" и возвращает первое вхождение.
//! \~\details
//! \~\code
//! piCout << PIString("1.str").findAny(".,:"); // 1
//! piCout << PIString("1,str").findAny(".,:"); // 1
//! piCout << PIString("1:str").findAny(".,:"); // 1
//! \endcode
//! \~\sa \a find(), \a findLast(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int findAny(const char * str, const int start = 0) const {return findAny(PIString(str), start);}
//! \~english Search character "c" from character at index "start" and return last occur position.
//! \~russian Ищет символ "c" от символа "start" и возвращает последнее вхождение.
int findLast(const char c, const int start = 0) const;
//! \~english Search character "c" from character at index "start" and return last occur position.
//! \~russian Ищет символ "c" от символа "start" и возвращает последнее вхождение.
int findLast(PIChar c, const int start = 0) const;
//! \~english Search substring "str" from character at index "start" and return last occur position.
//! \~russian Ищет подстроку "str" от символа "start" и возвращает последнее вхождение.
int findLast(const PIString & str, const int start = 0) const;
//! \~english Search substring "str" from character at index "start" and return last occur position.
//! \~russian Ищет подстроку "str" от символа "start" и возвращает последнее вхождение.
//! \~\details
//! \~\code
//! PIString s("012345012345");
//! piCout << s.findLast("-"); // -1
//! piCout << s.findLast("34"); // 9
//! piCout << s.findLast("3", 4); // 9
//! piCout << s.findLast("3", 10); // -1
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findAnyLast(), \a findWord(), \a findCWord(), \a findRange()
int findLast(const char * str, const int start = 0) const {return findLast(PIString(str), start);}
//! \~english Search any character of "str" from character at index "start" and return last occur position.
//! \~russian Ищет любой символ строки "str" от символа "start" и возвращает последнее вхождение.
int findAnyLast(const PIString & str, const int start = 0) const;
//! \~english Search any character of "str" from character at index "start" and return last occur position.
//! \~russian Ищет любой символ строки "str" от символа "start" и возвращает последнее вхождение.
//! \~\details
//! \~\code
//! piCout << PIString(".str.0").findAnyLast(".,:"); // 4
//! piCout << PIString(".str,0").findAnyLast(".,:"); // 4
//! piCout << PIString(".str:0").findAnyLast(".,:"); // 4
//! \endcode
//! \~\sa \a find(), \a findAny(), \a findLast(), \a findWord(), \a findCWord(), \a findRange()
int findAnyLast(const char * str, const int start = 0) const {return findAnyLast(PIString(str), start);}
//! \~english Search word "word" from character at index "start" and return first occur position.
//! \~russian Ищет слово "word" от симола "start" и возвращает первое вхождение.
int findWord(const PIString & word, const int start = 0) const;
//! \~english Search C-word "word" from character at index "start" and return first occur position.
//! \~russian Ищет C-слово "word" от симола "start" и возвращает первое вхождение.
int findCWord(const PIString & word, const int start = 0) const;
//! \~english Search range start between "start" and "end" characters at index "start_index" and return first occur position.
//! \~russian Ищет начало диапазона между символами "start" и "end" от симола "start" и возвращает первое вхождение.
int findRange(const PIChar start, const PIChar end, const PIChar shield = '\\', const int start_index = 0, int * len = 0) const;
//! \~english Returns number of occurrences of character "c".
//! \~russian Возвращает число вхождений символа "c".
//! \~\details
//! \~\code
//! piCout << PIString(".str.0").entries("."); // 2
//! piCout << PIString(".str.0").entries("0"); // 1
//! \endcode
int entries(const PIChar c) const;
//! \~english Returns number of occurrences of character "c".
//! \~russian Возвращает число вхождений символа "c".
//! \~\details
//! \~\code
//! piCout << PIString(".str.0").entries('.'); // 2
//! piCout << PIString(".str.0").entries('0'); // 1
//! \endcode
int entries(char c) const {return entries(PIChar(c));}
//! \~english Returns if string starts with "str".
//! \~russian Возвращает начинается ли строка со "str".
bool startsWith(const PIString & str) const;
//! \~english Returns if string ends with "str".
//! \~russian Возвращает оканчивается ли строка на "str".
bool endsWith(const PIString & str) const;
//! \~english Returns characters length of string.
//! \~russian Возвращает длину строки в символах.
int length() const {return d.size_s();}
//! \~english Returns characters length of string.
//! \~russian Возвращает длину строки в символах.
size_t size() const {return d.size();}
//! \~english Returns characters length of string.
//! \~russian Возвращает длину строки в символах.
ssize_t size_s() const {return d.size_s();}
//! \~english Returns \c true if string is empty, i.e. length = 0.
//! \~russian Возвращает \c true если строка пустая, т.е. длина = 0.
bool isEmpty() const {if (d.isEmpty()) return true; if (d.at(0) == PIChar()) return true; return false;}
//! \~english Returns \c true if string is not empty, i.e. length > 0.
//! \~russian Возвращает \c true если строка непустая, т.е. длина > 0.
bool isNotEmpty() const {return !isEmpty();}
//! \~english Clear string, will be empty string.
//! \~russian Очищает строку, строка становится пустой.
//! \~\details
//! \~\note
//! \~english Reserved memory will not be released.
//! \~russian Зарезервированная память не освободится.
//! \~\sa \a resize()
void clear() {d.clear();}
//! \~english Returns \c true if string equal "true", "yes", "on" or positive not null numeric value.
//! \~russian Возвращает \c true если строка равна "true", "yes", "on" или числу > 0.
bool toBool() const;
//! \~english Returns \c char numeric value of string.
//! \~russian Возвращает \c char числовое значение строки.
char toChar() const;
//! \~english Returns \c short numeric value of string in base "base".
//! \~russian Возвращает \c short числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toShort(); // 123
//! piCout << PIString("123").toShort(16); // 291
//! piCout << PIString("0x123").toShort(); // 291
//! piCout << PIString("1001").toShort(2); // 9
//! \endcode
short toShort(int base = -1, bool * ok = 0) const {return short(toNumberBase(*this, base, ok));}
//! \~english Returns \c ushort numeric value of string in base "base".
//! \~russian Возвращает \c ushort числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toUShort(); // 123
//! piCout << PIString("123").toUShort(16); // 291
//! piCout << PIString("0x123").toUShort(); // 291
//! piCout << PIString("1001").toUShort(2); // 9
//! \endcode
ushort toUShort(int base = -1, bool * ok = 0) const {return ushort(toNumberBase(*this, base, ok));}
//! \~english Returns \c int numeric value of string in base "base".
//! \~russian Возвращает \c int числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toInt(); // 123
//! piCout << PIString("123").toInt(16); // 291
//! piCout << PIString("0x123").toInt(); // 291
//! piCout << PIString("1001").toInt(2); // 9
//! \endcode
int toInt(int base = -1, bool * ok = 0) const {return int(toNumberBase(*this, base, ok));}
//! \~english Returns \c uint numeric value of string in base "base".
//! \~russian Возвращает \c uint числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toUInt(); // 123
//! piCout << PIString("123").toUInt(16); // 291
//! piCout << PIString("0x123").toUInt(); // 291
//! piCout << PIString("1001").toUInt(2); // 9
//! \endcode
uint toUInt(int base = -1, bool * ok = 0) const {return uint(toNumberBase(*this, base, ok));}
//! \~english Returns \c long numeric value of string in base "base".
//! \~russian Возвращает \c long числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toLong(); // 123
//! piCout << PIString("123").toLong(16); // 291
//! piCout << PIString("0x123").toLong(); // 291
//! piCout << PIString("1001").toLong(2); // 9
//! \endcode
long toLong(int base = -1, bool * ok = 0) const {return long(toNumberBase(*this, base, ok));}
//! \~english Returns \c ulong numeric value of string in base "base".
//! \~russian Возвращает \c ulong числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toULong(); // 123
//! piCout << PIString("123").toULong(16); // 291
//! piCout << PIString("0x123").toULong(); // 291
//! piCout << PIString("1001").toULong(2); // 9
//! \endcode
ulong toULong(int base = -1, bool * ok = 0) const {return ulong(toNumberBase(*this, base, ok));}
//! \~english Returns \c llong numeric value of string in base "base".
//! \~russian Возвращает \c llong числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toLLong(); // 123
//! piCout << PIString("123").toLLong(16); // 291
//! piCout << PIString("0x123").toLLong(); // 291
//! piCout << PIString("1001").toLLong(2); // 9
//! \endcode
llong toLLong(int base = -1, bool * ok = 0) const {return toNumberBase(*this, base, ok);}
//! \~english Returns \c ullong numeric value of string in base "base".
//! \~russian Возвращает \c ullong числовое значение строки по основанию "base".
//! \~\details
//! \~english If "base" < 0 then base automatically select 16 if string start with "0x", therwise 10.
//! \~russian Если "base" < 0 тогда основание автоматически принимается 16 если строка начинается с "0x", иначе 10.
//! \~\code
//! piCout << PIString("123").toULLong(); // 123
//! piCout << PIString("123").toULLong(16); // 291
//! piCout << PIString("0x123").toULLong(); // 291
//! piCout << PIString("1001").toULLong(2); // 9
//! \endcode
ullong toULLong(int base = -1, bool * ok = 0) const {return ullong(toNumberBase(*this, base, ok));}
//! \~english Returns \c float numeric value of string.
//! \~russian Возвращает \c float числовое значение строки.
//! \~\details
//! \~\code
//! piCout << PIString("123").toFloat(); // 123
//! piCout << PIString("1.2E+2").toFloat(); // 120
//! piCout << PIString("0.01").toFloat(); // 0.01
//! \endcode
float toFloat() const;
//! \~english Returns \c double numeric value of string.
//! \~russian Возвращает \c double числовое значение строки.
//! \~\details
//! \~\code
//! piCout << PIString("123").toDouble(); // 123
//! piCout << PIString("1.2E+2").toDouble(); // 120
//! piCout << PIString("0.01").toDouble(); // 0.01
//! \endcode
double toDouble() const;
//! \~english Returns \c ldouble numeric value of string.
//! \~russian Возвращает \c ldouble числовое значение строки.
//! \~\details
//! \~\code
//! piCout << PIString("123").toLDouble(); // 123
//! piCout << PIString("1.2E+2").toLDouble(); // 120
//! piCout << PIString("0.01").toLDouble(); // 0.01
//! \endcode
ldouble toLDouble() const;
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const short value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const ushort value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const int value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const uint value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const long value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const ulong value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const llong & value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" in base "base" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" по основанию "base" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(123);
//! piCout << s; // 123
//! s.setNumber(123, 16);
//! piCout << s; // 7B
//! \endcode
PIString & setNumber(const ullong & value, int base = 10, bool * ok = 0) {*this = PIString::fromNumber(value, base, ok); return *this;}
//! \~english Set string content to text representation of "value" with format "format" and precision "precision" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" в формате "format" и точностью "precision" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(12.3);
//! piCout << s; // 12.30000000
//! s.setNumber(12.3, 'f', 3);
//! piCout << s; // 12.300
//! s.setNumber(12.123456, 'f', 3);
//! piCout << s; // 12.123
//! s.setNumber(123456789., 'g', 2);
//! piCout << s; // 1.2e+08
//! s.setNumber(123456789., 'f', 0);
//! piCout << s; // 123456789
//! \endcode
PIString & setNumber(const float value, char format = 'f', int precision = 8) {*this = PIString::fromNumber(value, format, precision); return *this;}
//! \~english Set string content to text representation of "value" with format "format" and precision "precision" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" в формате "format" и точностью "precision" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(12.3);
//! piCout << s; // 12.30000000
//! s.setNumber(12.3, 'f', 3);
//! piCout << s; // 12.300
//! s.setNumber(12.123456, 'f', 3);
//! piCout << s; // 12.123
//! s.setNumber(123456789., 'g', 2);
//! piCout << s; // 1.2e+08
//! s.setNumber(123456789., 'f', 0);
//! piCout << s; // 123456789
//! \endcode
PIString & setNumber(const double & value, char format = 'f', int precision = 8) {*this = PIString::fromNumber(value, format, precision); return *this;}
//! \~english Set string content to text representation of "value" with format "format" and precision "precision" and return this string.
//! \~russian Устанавливает содержимое строки в текстовое представление "value" в формате "format" и точностью "precision" и возвращает эту строку.
//! \~\details
//! \~\code
//! PIString s;
//! s.setNumber(12.3);
//! piCout << s; // 12.30000000
//! s.setNumber(12.3, 'f', 3);
//! piCout << s; // 12.300
//! s.setNumber(12.123456, 'f', 3);
//! piCout << s; // 12.123
//! s.setNumber(123456789., 'g', 2);
//! piCout << s; // 1.2e+08
//! s.setNumber(123456789., 'f', 0);
//! piCout << s; // 123456789
//! \endcode
PIString & setNumber(const ldouble & value, char format = 'f', int precision = 8) {*this = PIString::fromNumber(value, format, precision); return *this;}
//! \~english Set string content to human readable size in B/kB/MB/GB/TB/PB.
//! \~russian Устанавливает содержимое в строку с читаемым размером B/kB/MB/GB/TB/PB.
//! \~\sa PIString::readableSize()
PIString & setReadableSize(llong bytes);
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const short value, int base = 10, bool * ok = 0) {return fromNumberBaseS(llong(value), base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const ushort value, int base = 10, bool * ok = 0) {return fromNumberBaseU(ullong(value), base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const int value, int base = 10, bool * ok = 0) {return fromNumberBaseS(llong(value), base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const uint value, int base = 10, bool * ok = 0) {return fromNumberBaseU(ullong(value), base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const long value, int base = 10, bool * ok = 0) {return fromNumberBaseS(llong(value), base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const ulong value, int base = 10, bool * ok = 0) {return fromNumberBaseU(ullong(value), base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const llong & value, int base = 10, bool * ok = 0) {return fromNumberBaseS(value, base, ok);}
//! \~english Returns string contains numeric representation of "value" in base "base".
//! \~russian Возвращает строковое представление числа "value" по основанию "base".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(123); // 123
//! piCout << PIString::fromNumber(123, 16); // 7B
//! \endcode
static PIString fromNumber(const ullong & value, int base = 10, bool * ok = 0) {return fromNumberBaseU(value, base, ok);}
//! \~english Returns string contains numeric representation of "value" with format "format" and precision "precision".
//! \~russian Возвращает строковое представление числа "value" в формате "format" и точностью "precision".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(12.3); // 12.30000000
//! piCout << PIString::fromNumber(12.3, 'f', 3); // 12.300
//! piCout << PIString::fromNumber(12.123456, 'f', 3); // 12.123
//! piCout << PIString::fromNumber(123456789., 'g', 2); // 1.2e+08
//! piCout << PIString::fromNumber(123456789., 'f', 0); // 123456789
//! \endcode
static PIString fromNumber(const float value, char format = 'f', int precision = 8) {return dtos(value, format, precision);}
//! \~english Returns string contains numeric representation of "value" with format "format" and precision "precision".
//! \~russian Возвращает строковое представление числа "value" в формате "format" и точностью "precision".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(12.3); // 12.30000000
//! piCout << PIString::fromNumber(12.3, 'f', 3); // 12.300
//! piCout << PIString::fromNumber(12.123456, 'f', 3); // 12.123
//! piCout << PIString::fromNumber(123456789., 'g', 2); // 1.2e+08
//! piCout << PIString::fromNumber(123456789., 'f', 0); // 123456789
//! \endcode
static PIString fromNumber(const double & value, char format = 'f', int precision = 8) {return dtos(value, format, precision);}
//! \~english Returns string contains numeric representation of "value" with format "format" and precision "precision".
//! \~russian Возвращает строковое представление числа "value" в формате "format" и точностью "precision".
//! \~\details
//! \~\code
//! piCout << PIString::fromNumber(12.3); // 12.30000000
//! piCout << PIString::fromNumber(12.3, 'f', 3); // 12.300
//! piCout << PIString::fromNumber(12.123456, 'f', 3); // 12.123
//! piCout << PIString::fromNumber(123456789., 'g', 2); // 1.2e+08
//! piCout << PIString::fromNumber(123456789., 'f', 0); // 123456789
//! \endcode
static PIString fromNumber(const ldouble & value, char format = 'f', int precision = 8) {return dtos(value, format, precision);}
//! \~english Returns "true" or "false"
//! \~russian Возвращает "true" или "false"
static PIString fromBool(const bool value) {return PIString(value ? PIStringAscii("true") : PIStringAscii("false"));}
//! \~english Returns string constructed from terminal codepage.
//! \~russian Возвращает строку созданную из кодировки консоли.
static PIString fromConsole(const PIByteArray & s);
//! \~english Returns string constructed from terminal codepage.
//! \~russian Возвращает строку созданную из кодировки консоли.
static PIString fromConsole(const char * s);
//! \~english Returns string constructed from system codepage.
//! \~russian Возвращает строку созданную из кодировки системы.
static PIString fromSystem(const PIByteArray & s);
//! \~english Returns string constructed from system codepage.
//! \~russian Возвращает строку созданную из кодировки системы.
static PIString fromSystem(const char * s);
//! \~english Returns string constructed from UTF-8.
//! \~russian Возвращает строку созданную из UTF-8.
static PIString fromUTF8(const char * s);
//! \~english Returns string constructed from UTF-8.
//! \~russian Возвращает строку созданную из UTF-8.
static PIString fromUTF8(const PIByteArray & utf);
//! \~english Returns string constructed from ASCII.
//! \~russian Возвращает строку созданную из ASCII.
static PIString fromAscii(const char * s);
//! \~english Returns string constructed from "len" chars ASCII.
//! \~russian Возвращает строку созданную из "len" символов ASCII.
static PIString fromAscii(const char * s, int len);
//! \~english Returns string constructed from "cp" codepage.
//! \~russian Возвращает строку созданную из кодировки "cp".
static PIString fromCodepage(const char * s, const char * cp);
//! \~english Returns string contains human readable size in B/kB/MB/GB/TB/PB.
//! \~russian Возвращает строку с читаемым размером B/kB/MB/GB/TB/PB.
//! \~\sa PIString::setReadableSize()
static PIString readableSize(llong bytes);
//! \~english Swaps string `str` other with this string.
//! \~russian Меняет строку `str` с этой строкой.
//! \~\details
//! \~english This operation is very fast and never fails.
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
void swap(PIString & str) {
d.swap(str.d);
piSwap(data_, str.data_);
}
private:
static const char toBaseN[];
static const char fromBaseN[];
static PIString itos(const int num);
static PIString ltos(const long num);
static PIString lltos(const llong num);
static PIString uitos(const uint num);
static PIString ultos(const ulong num);
static PIString ulltos(const ullong num);
static PIString dtos(const double num, char format = 'f', int precision = 8);
static PIString fromNumberBaseS(const llong value, int base = 10, bool * ok = 0);
static PIString fromNumberBaseU(const ullong value, int base = 10, bool * ok = 0);
static llong toNumberBase(const PIString & value, int base = -1, bool * ok = 0);
void appendFromChars(const char * c, int s, const char * cp = __syslocname__);
void buildData(const char * cp = __syslocname__) const;
void deleteData() const;
void trimsubstr(int &st, int &fn) const;
PIDeque<PIChar> d;
mutable char * data_ = nullptr;
};
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIString) {s << v.d; return s;}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ(PIString) {s >> v.d; return s;}
//! \~english Returns concatenated string.
//! \~russian Возвращает соединение строк.
inline PIString operator +(const PIString & str, const PIString & f) {PIString s(str); s += f; return s;}
//! \~english Returns concatenated string.
//! \~russian Возвращает соединение строк.
inline PIString operator +(const PIString & f, const char * str) {PIString s(f); s += str; return s;}
//! \~english Returns concatenated string.
//! \~russian Возвращает соединение строк.
inline PIString operator +(const char * str, const PIString & f) {return PIString(str) + f;}
//! \~english Returns concatenated string.
//! \~russian Возвращает соединение строк.
inline PIString operator +(const char c, const PIString & f) {return PIString(c) + f;}
//! \~english Returns concatenated string.
//! \~russian Возвращает соединение строк.
inline PIString operator +(const PIString & f, const char c) {PIString s(f); s.push_back(c); return s;}
//! \relatesalso PIString
//! \~english Compare two version strings in free notation and returns 0, -1 or 1.
//! \~russian Сравнивает две строки с версиями в произвольной форме и возвращает 0, -1 или 1.
int PIP_EXPORT versionCompare(const PIString & v0, const PIString & v1, int components = 6);
//! \relatesalso PIString
//! \~english Converts version string in free notation to classic view.
//! \~russian Преобразует строку с версией в произвольной форме к классическому виду.
PIString PIP_EXPORT versionNormalize(const PIString & v);
template<> inline uint piHash(const PIString & s) {return s.hash();}
template<> inline void piSwap(PIString & f, PIString & s) {
f.swap(s);
}
#endif // PISTRING_H

View File

@@ -0,0 +1,131 @@
/*! \file pistring_std.h
* \ingroup Text
* \brief
* \~english STD convertions for PIString
* \~russian Преобразования в/из STD для строки
*/
/*
PIP - Platform Independent Primitives
STD for PIString
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PISTRING_STD_H
#define PISTRING_STD_H
#include <string>
#ifdef QNX
typedef std::basic_string<wchar_t> wstring;
#endif
#include "pistringlist.h"
inline std::string PIString2StdString(const PIString & v) {
std::string s;
ushort wc;
uchar tc;
if (v.size() > 0) {
for (int i = 0; i < v.length(); ++i) {
wc = v[i].unicode16Code();
while (tc = wc & 0xFF, tc) {
s.push_back(tc);
wc >>= 8;
}
}
}
return s;
}
inline PIString StdString2PIString(const std::string & v) {
return PIString(v.c_str(), v.length());
}
#ifdef HAS_LOCALE
inline std::wstring PIString2StdWString(const PIString & v) {
std::wstring s;
for (int i = 0; i < v.length(); ++i) {
s.push_back(v[i].toWChar());
}
return s;
}
inline PIString StdWString2PIString(const std::wstring & v) {
PIString s;
uint l = v.size();
for (uint i = 0; i < l; ++i) {
s.push_back(PIChar(v[i]));
}
return s;
}
#endif
//! \relatesalso PIChar \brief Output operator to \c std::ostream
inline std::ostream & operator <<(std::ostream & s, const PIChar & v) {
s << v.toCharPtr();
return s;
}
//! \relatesalso PIString \brief Return concatenated string
inline PIString operator +(const PIString & f, const std::string & str) {
PIString s(f);
s += StdString2PIString(str);
return s;
}
//! \relatesalso PIString \brief Return concatenated string
inline PIString operator +(const std::string & str, const PIString & f) {
return StdString2PIString(str) + f;
}
//! \relatesalso PIString \brief Output operator to std::ostream (cout)
inline std::ostream & operator <<(std::ostream & s, const PIString & v) {
for (int i = 0; i < v.length(); ++i) {
s << v[i];
}
return s;
}
//! \relatesalso PIString \brief Input operator from std::istream (cin)
inline std::istream & operator >>(std::istream & s, PIString & v) {
std::string ss;
s >> ss;
v = StdString2PIString(ss);
return s;
}
//! \relatesalso PIStringList \brief Output operator to std::ostream (cout)
inline std::ostream & operator <<(std::ostream & s, const PIStringList & v) {
s << PIChar("{");
for (uint i = 0; i < v.size(); ++i) {
s << PIChar("\"") << v[i] << PIChar("\"");
if (i < v.size() - 1) s << PIStringAscii(", ");
}
s << PIChar("}");
return s;
}
#endif // PISTRING_STD_H

View File

@@ -0,0 +1,110 @@
/*
PIP - Platform Independent Primitives
Strings array class
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pistringlist.h"
//! \~\class PIStringList pistringlist.h
//! \~\details
//!
//! \details
//! \~english Example:
//! \~russian Пример:
//! \~\code
//! PIStringList sl("1", "2");
//! sl << "3";
//! piCout << sl.join(" < "); // 1 < 2 < 3
//! \endcode
PIString PIStringList::join(const PIString & delim) const {
PIString s;
for (uint i = 0; i < size(); ++i) {
s += at(i);
if (i < size() - 1)
s += delim;
}
return s;
}
//! \details
//! \~english Example:
//! \~russian Пример:
//! \~\code
//! PIStringList sl("1", "2");
//! sl << "1" << "2" << "3";
//! piCout << sl; // {"1", "2", "1", "2", "3"}
//! piCout << sl.removeStrings("1"); // {"2", "2", "3"}
//! \endcode
PIStringList & PIStringList::removeStrings(const PIString & value) {
for (uint i = 0; i < size(); ++i) {
if (at(i) == value) {
remove(i);
--i;
}
}
return *this;
}
//! \details
//! \~english Example:
//! \~russian Пример:
//! \~\code
//! PIStringList sl("1", "2");
//! sl << "1" << "2" << "3";
//! piCout << sl; // {"1", "2", "1", "2", "3"}
//! piCout << sl.removeDuplicates(); // {"1", "2", "3"}
//! \endcode
PIStringList& PIStringList::removeDuplicates() {
PIStringList l;
PIString s;
bool ae;
for (int i = 0; i < size_s(); ++i) {
ae = false;
s = at(i);
for (int j = 0; j < l.size_s(); ++j) {
if (s != l[j]) continue;
ae = true; break;
}
if (!ae) {
l << s;
continue;
}
remove(i);
--i;
}
return *this;
}
//! \details
//! \~english Example:
//! \~russian Пример:
//! \~\code
//! PIStringList sl(" 1 ", "\t2", " 3\n");
//! piCout << sl; // {" 1 ", " 2", " 3\n"}
//! piCout << sl.trim(); // {"1", "2", "3"}
//! \endcode
PIStringList & PIStringList::trim() {
for (uint i = 0; i < size(); ++i)
(*this)[i].trim();
return *this;
}

View File

@@ -0,0 +1,151 @@
/*! \file pistringlist.h
* \ingroup Text
* \~\brief
* \~english Based on \a PIDeque<PIString> strings list
* \~russian Основанный на \a PIDeque<PIString> массив строк
*/
/*
PIP - Platform Independent Primitives
Strings array class
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PISTRINGLIST_H
#define PISTRINGLIST_H
#include "pistring.h"
//! \ingroup Text
//! \~\brief
//! \~english Based on \a PIDeque<PIString> strings list.
//! \~russian Основанный на \a PIDeque<PIString> массив строк.
class PIP_EXPORT PIStringList: public PIDeque<PIString>
{
public:
//! \~english Contructs an empty strings list
//! \~russian Создает пустой список строк
PIStringList() {;}
//! \~english Contructs strings list with one string "str"
//! \~russian Создает список строк с одной строкой "str"
PIStringList(const PIString & str) {push_back(str);}
PIStringList(PIString && str) {push_back(std::move(str));}
//! \~english Contructs strings list with strings "s0" and "s1"
//! \~russian Создает список строк со строками "s0" и "s1"
PIStringList(const PIString & s0, const PIString & s1) {push_back(s0); push_back(s1);}
PIStringList(PIString && s0, PIString && s1) {push_back(std::move(s0)); push_back(std::move(s1));}
//! \~english Contructs strings list with strings "s0", "s1" and "s2"
//! \~russian Создает список строк со строками "s0", "s1" и "s2"
PIStringList(const PIString & s0, const PIString & s1, const PIString & s2) {push_back(s0); push_back(s1); push_back(s2);}
PIStringList(PIString && s0, PIString && s1, PIString && s2) {push_back(std::move(s0)); push_back(std::move(s1)); push_back(std::move(s2));}
//! \~english Contructs strings list with strings "s0", "s1", "s2" and "s3"
//! \~russian Создает список строк со строками "s0", "s1", "s2" и "s3"
PIStringList(const PIString & s0, const PIString & s1, const PIString & s2, const PIString & s3) {push_back(s0); push_back(s1); push_back(s2); push_back(s3);}
PIStringList(PIString && s0, PIString && s1, PIString && s2, PIString && s3) {push_back(std::move(s0)); push_back(std::move(s1)); push_back(std::move(s2)); push_back(std::move(s3));}
//! \~english Contructs strings list with strings "o"
//! \~russian Создает список строк со строками "o"
PIStringList(const PIStringList & o): PIDeque<PIString>(o) {}
PIStringList(PIStringList && o): PIDeque<PIString>(std::move(o)) {}
//! \~english Contructs strings list with strings "o"
//! \~russian Создает список строк со строками "o"
PIStringList(const PIVector<PIString> & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];}
//! \~english Contructs strings list with strings "o"
//! \~russian Создает список строк со строками "o"
PIStringList(const PIDeque<PIString> & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];}
//! \~english Contructs strings list with strings "init_list" in std::initializer_list format
//! \~russian Создает список строк со строками "init_list" в формате std::initializer_list
PIStringList(std::initializer_list<PIString> init_list): PIDeque<PIString>(init_list) {}
//! \~english Join all strings in one with delimiter "delim" and returns it
//! \~russian Соединяет все строки в одну через разделитель "delim" и возвращает её
PIString join(const PIString & delim) const;
//! \~english Remove all strings equal "value" and returns reference to this
//! \~russian Удаляет все строки равные "value" и возвращает ссылку на этот список строк
PIStringList & removeStrings(const PIString & value);
PIStringList & remove(uint num) {PIDeque<PIString>::remove(num); return *this;}
PIStringList & remove(uint num, uint count) {PIDeque<PIString>::remove(num, count); return *this;}
//! \~english Remove duplicated strings and returns reference to this
//! \~russian Удаляет все дублированные строки и возвращает ссылку на этот список строк
PIStringList & removeDuplicates();
//! \~english Trim all strings and returns reference to this
//! \~russian Подчищает у всех строк пробельные символы в начале и в конце и возвращает ссылку на этот список строк
PIStringList & trim();
//! \~english Returns sum of lengths of all strings
//! \~russian Возвращает сумму длин всех строк
uint contentSize() {uint s = 0; for (uint i = 0; i < size(); ++i) s += at(i).size(); return s;}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator ==(const PIStringList & o) const {if (size() != o.size()) return false; for (size_t i = 0; i < size(); ++i) if (o[i] != (*this)[i]) return false; return true;}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator !=(const PIStringList & o) const {return !(o == (*this));}
//! \~english Assign operator
//! \~russian Оператор присваивания
PIStringList & operator =(const PIStringList & o) {PIDeque<PIString>::operator=(o); return *this;}
//! \~english Append string "str"
//! \~russian Добавляет строку "str"
PIStringList & operator <<(const PIString & str) {append(str); return *this;}
PIStringList & operator <<(PIString && str) {append(std::move(str)); return *this;}
//! \~english Append strings list "sl"
//! \~russian Добавляет список строк "sl"
PIStringList & operator <<(const PIStringList & sl) {append(sl); return *this;}
};
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIStringList) {
s << static_cast<const PIDeque<PIString> &>(v);
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ(PIStringList) {
s >> static_cast<PIDeque<PIString> &>(v);
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIStringList & v) {s.space(); s.saveAndSetControls(0); s << "{"; for (uint i = 0; i < v.size(); ++i) {s << "\"" << v[i] << "\""; if (i < v.size() - 1) s << ", ";} s << "}"; s.restoreControls(); return s;}
#endif // PISTRINGLIST_H

View File

@@ -0,0 +1,58 @@
/*
PIP - Platform Independent Primitives
Module includes
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! \defgroup Text Text
//! \~\brief
//! \~english String classes.
//! \~russian Классы строк.
//!
//! \~\details
//! \~english \section cmake_module_Text Building with CMake
//! \~russian \section cmake_module_Text Сборка с использованием CMake
//!
//! \~\code
//! find_package(PIP REQUIRED)
//! target_link_libraries([target] PIP)
//! \endcode
//!
//! \~english \par Common
//! \~russian \par Общее
//!
//! \~english
//!
//!
//! \~russian
//!
//!
//! \~\authors
//! \~english
//! Ivan Pelipenko peri4ko@yandex.ru;
//! Andrey Bychkov work.a.b@yandex.ru;
//! \~russian
//! Иван Пелипенко peri4ko@yandex.ru;
//! Андрей Бычков work.a.b@yandex.ru;
//!
#ifndef PITEXTMODULE_H
#define PITEXTMODULE_H
#include "pistringlist.h"
#include "piconstchars.h"
#include "pitextstream.h"
#endif // PITEXTMODULE_H

View File

@@ -0,0 +1,341 @@
/*! \file pitextstream.h
* \ingroup Text
* \~\brief
* \~english Text serialization functionality over PIBinaryStream
* \~russian Функциональность текстовой сериализации поверх PIBinaryStream
*/
/*
PIP - Platform Independent Primitives
Text serialization functionality over PIBinaryStream
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PITEXTSTREAM_H
#define PITEXTSTREAM_H
#include "pistring.h"
//! \ingroup Text
//! \~\brief
//! \~english Text serialization functionality over PIBinaryStream.
//! \~russian Функциональность текстовой сериализации поверх PIBinaryStream.
template<typename P>
class PITextStream {
public:
//! \~english Floating-point numbers write format
//! \~russian Формат записи чисел с плавающей точкой
enum FloatFormat {
DecimalFormat /** \~english Decimal format, "*.*" \~russian Десятичный формат, "*.*" */ = 'f',
ExponentFormat /** \~english Exponential format, "*e+-<E>" \~russian Экспонентный формат, "*e+-<E>" */ = 'e'
};
//! \~english String encoding
//! \~russian Кодировка строк
enum Encoding {
System /** \~english System encoding \~russian Системная кодировка */,
UTF8 /** \~english UTF-8 encoding \~russian Кодировка UTF-8 */,
};
//! \~english Construct text stream binded to "stream_"
//! \~russian Возвращает привязанный к "stream_" текстовый поток
PITextStream(PIBinaryStream<P> * stream_) {setStream(stream_);}
//! \~english Returns binded PIBinaryStream
//! \~russian Возвращает привязанный PIBinaryStream
PIBinaryStream<P> * stream() const {return s;}
void setStream(PIBinaryStream<P> * stream_) {
s = stream_;
is_end = false;
}
//! \~english Returns if end of stream reached
//! \~russian Возвращает достигнут ли конец потока
bool isEnd() const {return is_end;}
//! \~english Returns read/write encoding
//! \~russian Возвращает кодировку чтения/записи
Encoding encoding() const {return enc;}
//! \~english Set read/write encoding, default UTF8
//! \~russian Устанавливает кодировку чтения/записи, по умолчанию UTF8
void setEncoding(Encoding e) {enc = e;}
//! \~english Returns float numbers write format
//! \~russian Возвращает формат записи чисел с плавающей точкой
FloatFormat floatFormat() const {return format_;}
//! \~english Set float numbers write format, default DecimalFormat
//! \~russian Устанавливает формат записи чисел с плавающей точкой, по умолчанию DecimalFormat
void setFloatFormat(FloatFormat format) {format_ = format;}
//! \~english Returns float numbers write precision
//! \~russian Возвращает точность записи чисел с плавающей точкой
int floatPrecision() const {return prec_;}
//! \~english Set float numbers write precision to "prec_" digits, default 5
//! \~russian Устанавливает точность записи чисел с плавающей точкой, по умолчанию 5
void setFloatPrecision(int prec) {prec_ = prec;}
//! \~english Append space
//! \~russian Добавляет пробел
PITextStream<P> & space() {s->binaryStreamAppend(' '); return *this;}
//! \~english Append new line
//! \~russian Добавляет новую строку
PITextStream<P> & newLine() {s->binaryStreamAppend('\n'); return *this;}
//! \~english Append "v" string
//! \~russian Добавляет строку "v"
void append(const PIString & v) {
if (v.isEmpty()) return;
PIByteArray d;
switch (enc) {
case System: d = v.toSystem(); break;
case UTF8 : d = v.toUTF8(); break;
}
s->binaryStreamAppend(d.data(), d.size());
}
//! \~english Append "v" as ASCII
//! \~russian Добавляет "v" как ASCII
void append(const PIConstChars & v) {if (!v.isEmpty()) s->binaryStreamAppend(v.data(), v.size());}
//! \~english Append "v" char as character
//! \~russian Добавляет "v" как символ
void append(char v) {s->binaryStreamAppend(v);}
//! \~english Append "v" as ASCII
//! \~russian Добавляет "v" как ASCII
void append(const char * v) {append(PIConstChars(v));}
//! \~english Append boolean, "true" of "false"
//! \~russian Добавляет логическое, "true" of "false"
void append(bool v) {append(v ? "true" : "false");}
//! \~english Append integer
//! \~russian Добавляет целое
void append(int v) {append(PIString::fromNumber(v));}
//! \~english Append integer
//! \~russian Добавляет целое
void append(llong v) {append(PIString::fromNumber(v));}
//! \~english Append floating-point number, using \a floatFormat() and \a floatPrecision()
//! \~russian Добавляет число с плавающей точкой, используя \a floatFormat() и \a floatPrecision()
void append(float v) {append(PIString::fromNumber(v, (char)format_, prec_));}
//! \~english Append floating-point number, using \a floatFormat() and \a floatPrecision()
//! \~russian Добавляет число с плавающей точкой, используя \a floatFormat() и \a floatPrecision()
void append(double v) {append(PIString::fromNumber(v, (char)format_, prec_));}
//! \~english Read character
//! \~russian Читает символ
char readChar(bool * rok) {
char ret;
bool ok = s->binaryStreamTake(&ret, sizeof(ret));
if (!ok) is_end = true;
if (rok) *rok = ok;
return ret;
}
//! \~english Read line
//! \~russian Читает строку
PIString readLine() {
PIByteArray ret;
bool ok = true;
for (;;) {
char b = readChar(&ok);
if (!ok || b == '\n') break;
if (b != '\r')
ret.append((uchar)b);
}
return fromBytes(ret);
}
//! \~english Read word, skip leading whitespaces, until next whitespace
//! \~russian Читает слово, пропуская начальные пробельные символы, до следующего пробельного символа
PIString readWord() {
static PIConstChars spaces(" \t\n\r");
return readUntil(spaces);
}
//! \~english Read C-word, skip leading and until non C-identifier
//! \~russian Читает C-слово, пропуская начальные и до следующих символов, не являющихся C-идентификаторами
PIString readCWord() {
static PIConstChars chars(" \t\n\r:;%$&#@!?~/*-+=.,\\\"'`[](){}<>");
return readUntil(chars);
}
private:
PIString fromBytes(const PIByteArray & ba) {
switch (enc) {
case System: return PIString::fromSystem(ba);
case UTF8 : return PIString::fromUTF8(ba);
}
return PIString();
}
PIString readUntil(const PIConstChars & chars) {
//static PIConstChars spaces(" \t\n\r");
bool ok = true;
char c = skipWhile(chars, &ok);
if (!ok) return PIString();
PIByteArray ret;
ret.append((uchar)c);
for (;;) {
c = readChar(&ok);
if (!ok || chars.contains(c)) break;
ret.append((uchar)c);
}
return fromBytes(ret);
}
// returns first non-"chars" char
char skipWhile(const PIConstChars & chars, bool * rok) {
bool ok = true;
char c = 0;
for (;;) {
c = readChar(&ok);
if (!ok || !chars.contains(c)) break;
}
if (rok) *rok = ok;
return c;
}
PIBinaryStream<P> * s;
Encoding enc = UTF8;
FloatFormat format_ = DecimalFormat;
bool is_end = false;
int prec_ = 5;
};
//! \~english Returns PITextStream for binary stream "stream"
//! \~russian Возвращает PITextStream для бинарного потока "stream"
template<typename P>
inline PITextStream<P> createPITextStream(PIBinaryStream<P> * stream) {return PITextStream<P>(stream);}
//! \~english Append boolean
//! \~russian Добавляет логическое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, bool v) {s.append(v); return s;}
//! \~english Append character
//! \~russian Добавляет символ
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, char v) {s.append(v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, uchar v) {s.append((int)v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, short v) {s.append((int)v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, ushort v) {s.append((int)v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, int v) {s.append((int)v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, uint v) {s.append((int)v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, llong v) {s.append((llong)v); return s;}
//! \~english Append integer
//! \~russian Добавляет целое
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, ullong v) {s.append((llong)v); return s;}
//! \~english Append floating-point number
//! \~russian Добавляет число с плавающей точкой
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, float v) {s.append(v); return s;}
//! \~english Append floating-point number
//! \~russian Добавляет число с плавающей точкой
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, double v) {s.append(v); return s;}
//! \~english Append string
//! \~russian Добавляет строку
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, const char * v) {s.append(v); return s;}
//! \~english Append string
//! \~russian Добавляет строку
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, const PIConstChars & v) {s.append(v); return s;}
//! \~english Append string
//! \~russian Добавляет строку
template<typename P> inline PITextStream<P> & operator <<(PITextStream<P> & s, const PIString & v) {s.append(v); return s;}
//! \~english Read word as bool
//! \~russian Читает слово как логическое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, bool & v) {v = s.readWord().toBool(); return s;}
//! \~english Read character
//! \~russian Читает символ
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, char & v) {v = s.readChar(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, uchar & v) {v = s.readWord().toUInt(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, short & v) {v = s.readWord().toInt(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, ushort & v) {v = s.readWord().toUInt(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, int & v) {v = s.readWord().toInt(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, uint & v) {v = s.readWord().toUInt(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, llong & v) {v = s.readWord().toLLong(); return s;}
//! \~english Read word as integer
//! \~russian Читает слово как целое
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, ullong & v) {v = s.readWord().toULLong(); return s;}
//! \~english Read word as floating-point number
//! \~russian Читает слово как число с плавающей точкой
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, float & v) {v = s.readWord().toFloat(); return s;}
//! \~english Read word as floating-point number
//! \~russian Читает слово как число с плавающей точкой
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, double & v) {v = s.readWord().toDouble(); return s;}
//! \~english Read word
//! \~russian Читает слово
template<typename P> inline PITextStream<P> & operator >>(PITextStream<P> & s, PIString & v) {v = s.readWord(); return s;}
#endif