merged AI doc, some new pages

This commit is contained in:
2026-03-12 14:46:57 +03:00
parent 07ae277f9e
commit ed13838237
206 changed files with 14088 additions and 5152 deletions

View File

@@ -34,40 +34,64 @@
#define PIP_BINARY_STREAM
#define BINARY_STREAM_FRIEND(T) \
template<typename P> \
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v); \
template<typename P> \
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v);
#define BINARY_STREAM_WRITE(T) \
template<typename P> \
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v)
#define BINARY_STREAM_READ(T) \
template<typename P> \
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v)
#ifdef DOXYGEN
//! \ingroup Serialization
//! \relatesalso PIBinaryStream
//! \~\brief
//! \~english Binary serialization interface.
//! \~russian Интерфейс бинарной сериализации.
//! \~english Declares templated binary stream operators as friends of \c T.
//! \~russian Объявляет шаблонные операторы бинарного потока дружественными для \c T.
# define BINARY_STREAM_FRIEND(T)
//! \relatesalso PIBinaryStream
//! \~\brief
//! \~english Starts definition of a templated binary write operator for \c T.
//! \~russian Начинает определение шаблонного оператора записи в бинарный поток для \c T.
# define BINARY_STREAM_WRITE(T)
//! \relatesalso PIBinaryStream
//! \~\brief
//! \~english Starts definition of a templated binary read operator for \c T.
//! \~russian Начинает определение шаблонного оператора чтения из бинарного потока для \c T.
# define BINARY_STREAM_READ(T)
#else
# define BINARY_STREAM_FRIEND(T) \
template<typename P> \
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v); \
template<typename P> \
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v);
# define BINARY_STREAM_WRITE(T) \
template<typename P> \
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v)
# define BINARY_STREAM_READ(T) \
template<typename P> \
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v)
#endif
//! \~\ingroup Serialization
//! \~\brief
//! \~english CRTP interface for binary serialization streams.
//! \~russian CRTP-интерфейс для потоков бинарной сериализации.
//! \~\details
//! \~english In your class you should implement this methods:
//! \~russian В производном классе вы должны реализовать следующие методы:
//! \~english
//! Derived stream classes should implement:
//! \~\code
//! bool binaryStreamAppendImp (const void * d, size_t s);
//! bool binaryStreamTakeImp (void * d, size_t s);
//! ssize_t binaryStreamSizeImp () const;
//! \endcode
//! \~english Function binaryStreamSizeImp should return -1 if size unknown.
//! \~russian Функция binaryStreamSizeImp должна возвращать -1 если нет информации о размере.
//! \~english See details \ref iostream.
//! \~russian Подробнее \ref iostream.
//! \a binaryStreamSizeImp() should return \c -1 when the remaining size is unknown. See details \ref iostream.
//! \~russian
//! Производные классы потока должны реализовать методы из примера выше. \a binaryStreamSizeImp() должен возвращать \c -1, когда оставшийся
//! размер неизвестен. Подробнее \ref iostream.
template<typename P>
class PIBinaryStream {
public:
//! \~english Write data
//! \~russian Записать данные
//! \~english Writes raw bytes to the underlying stream.
//! \~russian Записывает сырые байты в нижележащий поток.
bool binaryStreamAppend(const void * d, size_t s) {
if (!static_cast<P *>(this)->binaryStreamAppendImp(d, s)) {
return false;
@@ -76,8 +100,8 @@ public:
return true;
}
//! \~english Read data
//! \~russian Прочитать данные
//! \~english Reads raw bytes from the underlying stream and sets read error state on short reads.
//! \~russian Читает сырые байты из нижележащего потока и устанавливает состояние ошибки чтения при неполном чтении.
bool binaryStreamTake(void * d, size_t s) {
if (!static_cast<P *>(this)->binaryStreamTakeImp(d, s)) {
_was_read_error_ = true;
@@ -87,22 +111,24 @@ public:
return true;
}
//! \~english Returns remain size
//! \~russian Возвращает оставшийся размер
//! \~english Returns remaining readable byte count.
//! \~russian Возвращает число байтов, доступных для чтения.
//! \~\details
//! \~english Returns -1 if no information about size
//! \~russian Возвращает -1 если нет информации о размере
//! \~english
//! Returns \c -1 when the stream cannot report its remaining size.
//! \~russian
//! Возвращает \c -1, если поток не может сообщить оставшийся размер.
ssize_t binaryStreamSize() const { return static_cast<const P *>(this)->binaryStreamSizeImp(); }
//! \~english Write data
//! \~russian Записать данные
//! \~english Writes one trivially copied value as raw bytes.
//! \~russian Записывает одно значение прямым копированием его байтов.
template<typename T>
void binaryStreamAppend(T v) {
binaryStreamAppend(&v, sizeof(v));
}
//! \~english Read int
//! \~russian Прочитать int
//! \~english Reads one \c int value from the stream.
//! \~russian Читает одно значение \c int из потока.
int binaryStreamTakeInt() {
int r = 0;
binaryStreamTake(&r, sizeof(r));
@@ -122,32 +148,50 @@ private:
};
// helper class to detect default operators
//! \~\ingroup Serialization
//! \~\brief
//! \~english Helper wrapper used to detect default trivial streaming operators.
//! \~russian Вспомогательная обертка для определения операторов потоковой обработки тривиальных типов по умолчанию.
//! \~english Helper class to detect default operators
//! \~russian Вспомогательный класс для обнаружения операторов по умолчанию
template<typename P>
class PIBinaryStreamTrivialRef {
public:
//! \~english Constructs helper reference for stream \a s.
//! \~russian Создает вспомогательную ссылку на поток \a s.
PIBinaryStreamTrivialRef(PIBinaryStream<P> & s): p(s) {}
//! \~english Referenced stream.
//! \~russian Связанный поток.
PIBinaryStream<P> & p;
};
template<typename P, typename T>
//! \~english Forwards write operation through %PIBinaryStreamTrivialRef.
//! \~russian Перенаправляет операцию записи через %PIBinaryStreamTrivialRef.
inline PIBinaryStream<P> & operator<<(PIBinaryStreamTrivialRef<P> s, const T & v) {
s.p << v;
return s.p;
}
template<typename P, typename T>
//! \~english Forwards read operation through %PIBinaryStreamTrivialRef.
//! \~russian Перенаправляет операцию чтения через %PIBinaryStreamTrivialRef.
inline PIBinaryStream<P> & operator>>(PIBinaryStreamTrivialRef<P> s, T & v) {
s.p >> v;
return s.p;
}
template<typename P>
//! \~english Forwards raw memory block write through %PIBinaryStreamTrivialRef.
//! \~russian Перенаправляет запись блока памяти через %PIBinaryStreamTrivialRef.
inline PIBinaryStream<P> & operator<<(PIBinaryStreamTrivialRef<P> s, const PIMemoryBlock v) {
s.p << v;
return s.p;
}
template<typename P>
//! \~english Forwards raw memory block read through %PIBinaryStreamTrivialRef.
//! \~russian Перенаправляет чтение блока памяти через %PIBinaryStreamTrivialRef.
inline PIBinaryStream<P> & operator>>(PIBinaryStreamTrivialRef<P> s, PIMemoryBlock v) {
s.p >> v;
return s.p;
@@ -156,11 +200,15 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStreamTrivialRef<P> s, PIMemoryBlo
// specify types
template<typename P>
//! \~english Stores \c bool as one unsigned byte.
//! \~russian Сохраняет \c bool как один беззнаковый байт.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const bool v) {
s.binaryStreamAppend((uchar)v);
return s;
}
template<typename P>
//! \~english Restores \c bool from one unsigned byte.
//! \~russian Восстанавливает \c bool из одного беззнакового байта.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, bool & v) {
uchar c = 0;
s.binaryStreamTake(&c, sizeof(c));
@@ -169,11 +217,15 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, bool & v) {
}
template<typename P>
//! \~english Writes raw bytes from %PIMemoryBlock.
//! \~russian Записывает сырые байты из %PIMemoryBlock.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIMemoryBlock v) {
s.binaryStreamAppend(v.data(), v.size());
return s;
}
template<typename P>
//! \~english Reads raw bytes into %PIMemoryBlock.
//! \~russian Читает сырые байты в %PIMemoryBlock.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMemoryBlock v) {
s.binaryStreamTake(v.data(), v.size());
return s;
@@ -184,6 +236,8 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMemoryBlock v) {
template<typename P, typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
//! \~english Stores enum values as \c int.
//! \~russian Сохраняет значения перечислений как \c int.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v) {
// piCout << "<< enum";
s.binaryStreamAppend((int)v);
@@ -195,14 +249,17 @@ template<typename P,
typename T,
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Stores trivially copyable values by raw memory copy and returns a helper marker for bulk container paths.
//! \~russian Сохраняет тривиально копируемые значения прямым копированием памяти и возвращает вспомогательный маркер для контейнерных путей
//! с пакетной записью.
inline PIBinaryStreamTrivialRef<P> operator<<(PIBinaryStream<P> & s, const T & v) {
s.binaryStreamAppend(&v, sizeof(v));
return s;
}
//! \~english Store operator for PIVector of any trivial copyable type
//! \~russian Оператор сохранения для PIVector тривиальных типов
//! \~english Stores %PIVector of trivial elements in bulk.
//! \~russian Сохраняет %PIVector из тривиальных элементов пакетно.
template<typename P,
typename T,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0,
@@ -221,6 +278,8 @@ template<typename P,
typename std::enable_if<
!std::is_same<decltype(std::declval<PIBinaryStream<P> &>() << std::declval<const T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Stores %PIVector element-by-element when the element type has custom binary streaming.
//! \~russian Сохраняет %PIVector поэлементно, когда тип элемента использует собственные операторы бинарного потока.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector<T> & v) {
// piCout << "<< vector trivial custom";
s.binaryStreamAppend((int)v.size());
@@ -230,14 +289,14 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector<T> &
}
//! \~english Store operator for PIDeque of any trivial copyable type
//! \~russian Оператор сохранения для PIDeque тривиальных типов
template<typename P,
typename T,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0,
typename std::enable_if<
std::is_same<decltype(std::declval<PIBinaryStream<P> &>() << std::declval<const T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Stores %PIDeque of trivial elements in bulk.
//! \~russian Сохраняет %PIDeque из тривиальных элементов пакетно.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIDeque<T> & v) {
// piCout << "<< deque trivial default";
s.binaryStreamAppend((int)v.size());
@@ -250,6 +309,8 @@ template<typename P,
typename std::enable_if<
!std::is_same<decltype(std::declval<PIBinaryStream<P> &>() << std::declval<const T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Stores %PIDeque element-by-element when the element type has custom binary streaming.
//! \~russian Сохраняет %PIDeque поэлементно, когда тип элемента использует собственные операторы бинарного потока.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIDeque<T> & v) {
// piCout << "<< deque trivial custom";
s.binaryStreamAppend((int)v.size());
@@ -259,14 +320,14 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIDeque<T> &
}
//! \~english Store operator for PIVector2D of any trivial copyable type
//! \~russian Оператор сохранения для PIVector2D тривиальных типов
template<typename P,
typename T,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0,
typename std::enable_if<
std::is_same<decltype(std::declval<PIBinaryStream<P> &>() << std::declval<const T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Stores %PIVector2D of trivial elements in bulk.
//! \~russian Сохраняет %PIVector2D из тривиальных элементов пакетно.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector2D<T> & v) {
// piCout << "<< vector2d trivial default";
s.binaryStreamAppend((int)v.rows());
@@ -280,6 +341,8 @@ template<typename P,
typename std::enable_if<
!std::is_same<decltype(std::declval<PIBinaryStream<P> &>() << std::declval<const T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Stores %PIVector2D row data through the element streaming path.
//! \~russian Сохраняет данные %PIVector2D через путь потоковой обработки элементов.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector2D<T> & v) {
// piCout << "<< vector2d trivial custom";
s.binaryStreamAppend((int)v.rows());
@@ -289,18 +352,18 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector2D<T>
}
//! \~english Store operator
//! \~russian Оператор сохранения
template<typename P>
//! \~english Stores %PIBitArray content.
//! \~russian Сохраняет содержимое %PIBitArray.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIBitArray & v) {
s << v.size_ << v.data_;
return s;
}
//! \~english Store operator
//! \~russian Оператор сохранения
template<typename P, typename Type0, typename Type1>
//! \~english Stores both members of %PIPair.
//! \~russian Сохраняет оба элемента %PIPair.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIPair<Type0, Type1> & v) {
s << v.first << v.second;
return s;
@@ -311,6 +374,8 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIPair<Type0,
template<typename P, typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
//! \~english Restores enum values from \c int.
//! \~russian Восстанавливает значения перечислений из \c int.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v) {
// piCout << ">> enum";
v = (T)s.binaryStreamTakeInt();
@@ -322,6 +387,9 @@ template<typename P,
typename T,
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Restores trivially copyable values by raw memory copy and returns a helper marker for bulk container paths.
//! \~russian Восстанавливает тривиально копируемые значения прямым копированием памяти и возвращает вспомогательный маркер для контейнерных
//! путей с пакетным чтением.
inline PIBinaryStreamTrivialRef<P> operator>>(PIBinaryStream<P> & s, T & v) {
if (!s.binaryStreamTake(&v, sizeof(v))) {
fprintf(stderr, "error with %s\n", __PIP_TYPENAME__(T));
@@ -330,14 +398,14 @@ inline PIBinaryStreamTrivialRef<P> operator>>(PIBinaryStream<P> & s, T & v) {
}
//! \~english Restore operator for PIVector of any trivial copyable type
//! \~russian Оператор извлечения для PIVector тривиальных типов
template<typename P,
typename T,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0,
typename std::enable_if<
std::is_same<decltype(std::declval<PIBinaryStream<P> &>() >> std::declval<T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Restores %PIVector of trivial elements in bulk.
//! \~russian Восстанавливает %PIVector из тривиальных элементов пакетно.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector<T> & v) {
// piCout << ">> vector trivial default";
int sz = s.binaryStreamTakeInt();
@@ -359,6 +427,8 @@ template<typename P,
typename std::enable_if<
!std::is_same<decltype(std::declval<PIBinaryStream<P> &>() >> std::declval<T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Restores %PIVector element-by-element when the element type has custom binary streaming.
//! \~russian Восстанавливает %PIVector поэлементно, когда тип элемента использует собственные операторы бинарного потока.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector<T> & v) {
// piCout << ">> vector trivial custom";
int sz = s.binaryStreamTakeInt();
@@ -380,14 +450,14 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector<T> & v) {
}
//! \~english Restore operator for PIDeque of any trivial copyable type
//! \~russian Оператор извлечения для PIDeque тривиальных типов
template<typename P,
typename T,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0,
typename std::enable_if<
std::is_same<decltype(std::declval<PIBinaryStream<P> &>() >> std::declval<T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Restores %PIDeque of trivial elements in bulk.
//! \~russian Восстанавливает %PIDeque из тривиальных элементов пакетно.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIDeque<T> & v) {
// piCout << ">> deque trivial default";
int sz = s.binaryStreamTakeInt();
@@ -409,6 +479,8 @@ template<typename P,
typename std::enable_if<
!std::is_same<decltype(std::declval<PIBinaryStream<P> &>() >> std::declval<T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Restores %PIDeque element-by-element when the element type has custom binary streaming.
//! \~russian Восстанавливает %PIDeque поэлементно, когда тип элемента использует собственные операторы бинарного потока.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIDeque<T> & v) {
// piCout << ">> deque trivial custom";
int sz = s.binaryStreamTakeInt();
@@ -430,14 +502,14 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIDeque<T> & v) {
}
//! \~english Restore operator for PIVector2D of any trivial copyable type
//! \~russian Оператор извлечения для PIVector2D тривиальных типов
template<typename P,
typename T,
typename std::enable_if<std::is_trivially_copyable<T>::value, int>::type = 0,
typename std::enable_if<
std::is_same<decltype(std::declval<PIBinaryStream<P> &>() >> std::declval<T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Restores %PIVector2D of trivial elements in bulk.
//! \~russian Восстанавливает %PIVector2D из тривиальных элементов пакетно.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector2D<T> & v) {
// piCout << ">> vector2d trivial default";
int r, c;
@@ -461,6 +533,8 @@ template<typename P,
typename std::enable_if<
!std::is_same<decltype(std::declval<PIBinaryStream<P> &>() >> std::declval<T &>()), PIBinaryStreamTrivialRef<P>>::value,
int>::type = 0>
//! \~english Restores %PIVector2D through the element streaming path.
//! \~russian Восстанавливает %PIVector2D через путь потоковой обработки элементов.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector2D<T> & v) {
// piCout << ">> vector2d trivial custom";
int r, c;
@@ -478,18 +552,18 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector2D<T> & v)
}
//! \~english Restore operator
//! \~russian Оператор извлечения
template<typename P>
//! \~english Restores %PIBitArray content.
//! \~russian Восстанавливает содержимое %PIBitArray.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIBitArray & v) {
s >> v.size_ >> v.data_;
return s;
}
//! \~english Restore operator
//! \~russian Оператор извлечения
template<typename P, typename Type0, typename Type1>
//! \~english Restores both members of %PIPair.
//! \~russian Восстанавливает оба элемента %PIPair.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIPair<Type0, Type1> & v) {
s >> v.first >> v.second;
return s;
@@ -499,9 +573,9 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIPair<Type0, Type1
// store complex types
//! \~english Store operator for PIVector of any compound type
//! \~russian Оператор сохранения для PIVector сложных типов
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Stores %PIVector of non-trivial elements one-by-one.
//! \~russian Сохраняет %PIVector из нетривиальных элементов по одному.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector<T> & v) {
// piCout << "<< vector complex";
s.binaryStreamAppend(int(v.size_s()));
@@ -511,9 +585,9 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector<T> &
}
//! \~english Store operator for PIDeque of any compound type
//! \~russian Оператор сохранения для PIDeque сложных типов
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Stores %PIDeque of non-trivial elements one-by-one.
//! \~russian Сохраняет %PIDeque из нетривиальных элементов по одному.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIDeque<T> & v) {
// piCout << "<< deque complex";
s.binaryStreamAppend(int(v.size_s()));
@@ -523,9 +597,9 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIDeque<T> &
}
//! \~english Store operator for PIVector2D of any compound type
//! \~russian Оператор сохранения для PIVector2D сложных типов
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Stores %PIVector2D of non-trivial elements via its plain vector representation.
//! \~russian Сохраняет %PIVector2D из нетривиальных элементов через его плоское векторное представление.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector2D<T> & v) {
// piCout << "<< vector2d complex";
s.binaryStreamAppend(int(v.rows()));
@@ -538,9 +612,9 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIVector2D<T>
// restore complex types
//! \~english Restore operator for PIVector of any compound type
//! \~russian Оператор извлечения для PIVector сложных типов
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Restores %PIVector of non-trivial elements one-by-one.
//! \~russian Восстанавливает %PIVector из нетривиальных элементов по одному.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector<T> & v) {
int sz = s.binaryStreamTakeInt();
if (s.wasReadError()) {
@@ -561,9 +635,9 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector<T> & v) {
}
//! \~english Restore operator for PIDeque of any compound type
//! \~russian Оператор извлечения для PIDeque сложных типов
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Restores %PIDeque of non-trivial elements one-by-one.
//! \~russian Восстанавливает %PIDeque из нетривиальных элементов по одному.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIDeque<T> & v) {
int sz = s.binaryStreamTakeInt();
if (s.wasReadError()) {
@@ -584,9 +658,9 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIDeque<T> & v) {
}
//! \~english Restore operator for PIVector2D of any compound type
//! \~russian Оператор извлечения для PIVector2D сложных типов
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Restores %PIVector2D of non-trivial elements via an intermediate plain vector.
//! \~russian Восстанавливает %PIVector2D из нетривиальных элементов через промежуточный плоский вектор.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector2D<T> & v) {
int r, c;
PIVector<T> tmp;
@@ -606,9 +680,9 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIVector2D<T> & v)
// other types
//! \~english Store operator
//! \~russian Оператор сохранения
template<typename P, typename Key, typename T>
//! \~english Stores %PIMap keys and values.
//! \~russian Сохраняет ключи и значения %PIMap.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIMap<Key, T> & v) {
s.binaryStreamAppend((int)v.pim_index.size_s());
for (uint i = 0; i < v.size(); ++i) {
@@ -620,9 +694,9 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIMap<Key, T>
}
//! \~english Restore operator
//! \~russian Оператор извлечения
template<typename P, typename Key, typename T>
//! \~english Restores %PIMap keys and values.
//! \~russian Восстанавливает ключи и значения %PIMap.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMap<Key, T> & v) {
int sz = s.binaryStreamTakeInt();
if (s.wasReadError()) {
@@ -656,9 +730,9 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMap<Key, T> & v)
}
//! \~english Store operator
//! \~russian Оператор сохранения
template<typename P, typename Key>
//! \~english Stores %PISet keys.
//! \~russian Сохраняет ключи %PISet.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PISet<Key> & v) {
s.binaryStreamAppend((int)v.pim_index.size_s());
for (uint i = 0; i < v.size(); ++i) {
@@ -669,9 +743,9 @@ inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PISet<Key> &
}
//! \~english Restore operator
//! \~russian Оператор извлечения
template<typename P, typename Key>
//! \~english Restores %PISet keys.
//! \~russian Восстанавливает ключи %PISet.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PISet<Key> & v) {
int sz = s.binaryStreamTakeInt();
if (s.wasReadError()) {
@@ -700,12 +774,16 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PISet<Key> & v) {
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Fallback overload that intentionally fails for unsupported non-trivial write types.
//! \~russian Резервная перегрузка, которая намеренно завершает компиляцию ошибкой для неподдерживаемых нетривиальных типов записи.
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T &) {
static_assert(std::is_trivially_copyable<T>::value, "[PIBinaryStream] Error: using undeclared operator << for complex type!");
return s;
}
template<typename P, typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, int>::type = 0>
//! \~english Fallback overload that intentionally fails for unsupported non-trivial read types.
//! \~russian Резервная перегрузка, которая намеренно завершает компиляцию ошибкой для неподдерживаемых нетривиальных типов чтения.
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T &) {
static_assert(std::is_trivially_copyable<T>::value, "[PIBinaryStream] Error: using undeclared operator >> for complex type!");
return s;

View File

@@ -29,52 +29,74 @@
#include "pibytearray.h"
//! \ingroup Serialization
//! \~\ingroup Serialization
//! \~\brief
//! \~english Class for binary de/serialization.
//! \~russian Класс для бинарной де/сериализации.
//! \~\details
//! \~english PIChunkStream provides a binary markup serialization stream that allows reading and writing structured data chunks with IDs.
//! \~russian PIChunkStream обеспечивает бинарный поток с разметкой для чтения и записи структурированных данных-чанков с ID.
class PIP_EXPORT PIChunkStream {
public:
//! \~english
//! Version of data packing. Read-access %PIChunkStream automatic detect version, but write-access
//! %PIChunkStream by default write in new version, be careful!
//! \~russian
//! Версия хранения данных. %PIChunkStream на чтение автоматически определяет версию, но для записи
//! использует по умолчанию новую, осторожно!
//! \~english Version of data packing.
//! \~russian Версия хранения данных.
//! \~\details
//! \~english Read-access %PIChunkStream automatic detect version, but write-access %PIChunkStream by default write in new version, be
//! careful!
//! \~russian %PIChunkStream на чтение автоматически определяет версию, но для записи использует по умолчанию новую, осторожно!
enum Version {
Version_1 /*! \~english First, old version \~russian Первая, старая версия */,
Version_2 /*! \~english Second, more optimized version \~russian Вторая, более оптимизированная версия */ = 2,
};
//! \~english Contructs stream for read from "data"
//! \~english Constructs stream for read from "data"
//! \~russian Создает поток на чтение из "data"
PIChunkStream(const PIByteArray & data): version_(Version_2) { setSource(data); }
//! \~english Contructs stream for read or write to/from "data", or empty stream for write if "data" = 0
//! \~english Constructs stream for read or write to/from "data", or empty stream for write if "data" = 0
//! \~russian Создает поток на чтение или запись из/в "data", или пустой поток на запись если "data" = 0
PIChunkStream(PIByteArray * data = 0, Version v = Version_2): version_(v) { setSource(data); }
//! \~english Contructs empty stream for write with version \"v\"
//! \~english Constructs empty stream for write with version \"v\"
//! \~russian Создает пустой поток на запись с версией \"v\"
PIChunkStream(Version v): version_(v) { setSource(0); }
//! \~english Destructor
//! \~russian Деструктор
~PIChunkStream();
//! \~english Nested template struct for chunk data
//! \~russian Вложенный шаблонный структура для данных чанка
template<typename T>
struct Chunk {
//! \~english Constructor with ID and data
//! \~russian Конструктор с ID и данными
Chunk(int i, const T & d): id(i), data(d) {}
//! \~english Chunk ID
//! \~russian ID чанка
int id;
//! \~english Chunk data
//! \~russian Данные чанка
T data;
};
//! \~english Nested template struct for constant chunk data
//! \~russian Вложенный шаблонный структура для константных данных чанка
template<typename T>
struct ChunkConst {
//! \~english Constructor with ID and data
//! \~russian Конструктор с ID и данными
ChunkConst(int i, const T & d): id(i), data(d) {}
//! \~english Chunk ID
//! \~russian ID чанка
int id;
//! \~english Constant chunk data reference
//! \~russian Константная ссылка на данные чанка
const T & data;
};
//! \~english Returns chunk with ID "id" and value "data" for write to stream
//! \~russian Возвращает чанк с ID "id" и значением "data" для записи в поток
//! \~\sa chunk()
template<typename T>
static ChunkConst<T> chunk(int id, const T & data) {
return ChunkConst<T>(id, data);
@@ -82,6 +104,7 @@ public:
//! \~english Add to this stream chunk with ID "id" and value "data"
//! \~russian Добавляет в этот поток чанк с ID "id" и значением "data"
//! \~\sa chunk()
template<typename T>
PIChunkStream & add(int id, const T & data) {
*this << ChunkConst<T>(id, data);
@@ -96,6 +119,9 @@ public:
//! Извлекает %PIByteArray из "stream" и инициализирует им поток.
//! Если указан "read_all", то вызывает \a readAll() после инициализации.
//! Возвращает если ли данные для чтения.
//! \~\note
//! \~english You should call \a readAll() before using \a getData() or \a get() methods
//! \~russian Перед использованием методов \a getData() или \a get() следует вызвать \a readAll()
template<typename T>
bool extract(PIBinaryStream<T> & stream, bool read_all = false) {
stream >> tmp_data;
@@ -106,7 +132,12 @@ public:
return true;
}
//! \~english Sets source buffer for read from "data"
//! \~russian Устанавливает исходный буфер для чтения из "data"
void setSource(const PIByteArray & data);
//! \~english Sets source buffer for read or write to/from "data", or empty stream for write if "data" = 0
//! \~russian Устанавливает исходный буфер для чтения или записи из/в "data", или пустой поток на запись если "data" = 0
void setSource(PIByteArray * data);
//! \~english Returns internal buffer with written data
@@ -122,20 +153,32 @@ public:
Version version() const { return (Version)version_; }
//! \~english Read one chunk from stream and returns its ID
//! \~english Reads one chunk from stream and returns its ID
//! \~russian Читает один чанк из потока и возвращает его ID
//! \~\details
//! \~english Reads the next chunk from the stream and stores its ID for subsequent \a getData() or \a get() calls
//! \~russian Читает следующий чанк из потока и сохраняет его ID для последующих вызовов \a getData() или \a get()
int read();
//! \~english Read all chunks from stream. This function just index input data
//! \~russian Читает все чанки из потока. Данный метод лишь индексирует данные
//! \~\details
//! \~english This function indexes input data to allow random access via \a getData(int id) and \a get(int id, T & v)
//! \~russian Эта функция индексирует входные данные для возможности случайного доступа через \a getData(int id) и \a get(int id, T & v)
void readAll();
//! \~english Returns last readed chunk ID
//! \~english Returns last read chunk ID
//! \~russian Возвращает ID последнего прочитанного чанка
//! \~\details
//! \~english Returns the ID of the last chunk read by \a read() method
//! \~russian Возвращает ID последнего чанка, прочитанного методом \a read()
int getID() { return last_id; }
//! \~english Returns value of last readed chunk
//! \~english Returns value of last read chunk
//! \~russian Возвращает значение последнего прочитанного чанка
//! \~\note
//! \~english Call \a read() first to read a chunk before using this method
//! \~russian Сначала вызовите \a read() для чтения чанка перед использованием этого метода
template<typename T>
T getData() const {
T ret{};
@@ -144,8 +187,11 @@ public:
return ret;
}
//! \~english Returns value of chunk with ID \"id\". You should call \a readAll() before using this function!
//! \~russian Возвращает значение чанка с ID \"id\". Необходимо вызвать \a readAll() перед использованием этого метода!
//! \~english Returns value of chunk with ID \"id\"
//! \~russian Возвращает значение чанка с ID \"id\"
//! \~\note
//! \~english You should call \a readAll() before using this function!
//! \~russian Необходимо вызвать \a readAll() перед использованием этого метода!
template<typename T>
T getData(int id) const {
T ret{};
@@ -156,15 +202,21 @@ public:
return ret;
}
//! \~english Place value of last readed chunk into \"v\"
//! \~english Places value of last read chunk into \"v\"
//! \~russian Записывает значение последнего прочитанного чанка в \"v\"
//! \~\note
//! \~english Call \a read() first to read a chunk before using this method
//! \~russian Сначала вызовите \a read() для чтения чанка перед использованием этого метода
template<typename T>
void get(T & v) const {
v = getData<T>();
}
//! \~english Place value of chunk with ID \"id\" into \"v\". You should call \a readAll() before using this function!
//! \~russian Записывает значение чанка с ID \"id\" в \"v\". Необходимо вызвать \a readAll() перед использованием этого метода!
//! \~english Places value of chunk with ID \"id\" into \"v\"
//! \~russian Записывает значение чанка с ID \"id\" в \"v\"
//! \~\note
//! \~english You should call \a readAll() before using this function!
//! \~russian Необходимо вызвать \a readAll() перед использованием этого метода!
template<typename T>
const PIChunkStream & get(int id, T & v) const {
CacheEntry pos = data_map.value(id);
@@ -174,8 +226,11 @@ public:
return *this;
}
//! \~english Replace value of chunk with ID \"id\" to \"v\". You should call \a readAll() before using this function!
//! \~russian Заменяет значение чанка с ID \"id\" на \"v\". Необходимо вызвать \a readAll() перед использованием этого метода!
//! \~english Replaces value of chunk with ID \"id\" to \"v\"
//! \~russian Заменяет значение чанка с ID \"id\" на \"v\"
//! \~\note
//! \~english You should call \a readAll() before using this function!
//! \~russian Необходимо вызвать \a readAll() перед использованием этого метода!
template<typename T>
PIChunkStream & set(int id, const T & v) {
PIByteArray ba;
@@ -211,6 +266,8 @@ private:
friend PIChunkStream & operator<<(PIChunkStream & s, const PIChunkStream::ChunkConst<T> & c);
};
//! \~english Stream output operator for Chunk
//! \~russian Оператор вывода в поток для Chunk
template<typename T>
PIChunkStream & operator<<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c) {
PIByteArray ba;
@@ -227,6 +284,9 @@ PIChunkStream & operator<<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c)
}
return s;
}
//! \~english Stream output operator for ChunkConst
//! \~russian Оператор вывода в поток для ChunkConst
template<typename T>
PIChunkStream & operator<<(PIChunkStream & s, const PIChunkStream::ChunkConst<T> & c) {
PIByteArray ba;

View File

@@ -1,9 +1,8 @@
/*! \file pijson.h
* \ingroup Serialization
* \brief
* \~english JSON class
* \~russian Класс JSON
*/
//! \~\file pijson.h
//! \~\ingroup Serialization
//! \~\brief
//! \~english JSON tree node type
//! \~russian Тип узла дерева JSON
/*
PIP - Platform Independent Primitives
JSON class
@@ -29,174 +28,200 @@
#include "pivariant.h"
//! \ingroup Serialization
//! \~\ingroup Serialization
//! \~\brief
//! \~english JSON class.
//! \~russian Класс JSON.
//! \~english JSON tree node.
//! \~russian Узел дерева JSON.
//! \~\details
//! \~english %PIJSON class provides a tree structure for JSON data representation.
//! Each element can be a value (with name), an array, or an object.
//! \~russian Класс %PIJSON предоставляет древовидную структуру для представления данных JSON.
//! Каждый элемент может быть значением (с именем), массивом или объектом.
class PIP_EXPORT PIJSON {
friend PICout operator<<(PICout s, const PIJSON & v);
public:
//! \~english
//! Type of JSON tree element
//! \~russian
//! Тип элемента дерева JSON
//! \~english Type of JSON node.
//! \~russian Тип узла JSON.
enum Type {
Invalid /*! \~english Invalid type \~russian Недействительный тип */,
Null /*! \~english Without value, null \~russian Без значения, null */,
Boolean /*! \~english Boolean, /b true or /b false \~russian Логическое, /b true или /b false */,
Boolean /*! \~english Boolean, \b true or \b false \~russian Логическое, \b true или \b false */,
Number /*! \~english Integer or floating-point number \~russian Целое либо число с плавающей точкой */,
String /*! \~english Text \~russian Текст */,
Object /*! \~english Object, {} \~russian Объект, {} */,
Array /*! \~english Array, [] \~russian Массив, [] */
};
//! \~english
//! Generate JSON variant
//! \~russian
//! Вариант генерации JSON
//! \~english Formatting mode for JSON text output.
//! \~russian Режим форматирования JSON-текста.
enum PrintType {
Compact /*! \~english Without spaces, minimum size \~russian Без пробелов, минимальный размер */,
Tree /*! \~english With spaces and new-lines, human-readable \~russian С пробелами и новыми строками, читаемый человеком */
};
//! \~english Contructs invalid %PIJSON.
//! \~english Constructs invalid %PIJSON.
//! \~russian Создает недействительный %PIJSON.
PIJSON() {}
//! \~english Copy constructor.
//! \~russian Конструктор копирования.
PIJSON(const PIJSON & o) = default;
//! \~english Returns name of element, or empty string if it doesn`t have name.
//! \~russian Возвращает имя элемента, либо пустую строку, если имени нет.
//! \~english Returns node name, or empty string for unnamed nodes.
//! \~russian Возвращает имя узла, либо пустую строку для безымянных узлов.
const PIString & name() const { return c_name; }
//! \~english Returns elements array of this element, or empty array if element is not \a PIJSON::Array.
//! \~russian Возвращает массив элементов этого элемента, либо пустой массив, если тип элемента не \a PIJSON::Array.
//! \~english Returns array children, or an empty array when the node is not \a PIJSON::Array.
//! \~russian Возвращает дочерние элементы массива, либо пустой массив, если узел не имеет тип \a PIJSON::Array.
const PIVector<PIJSON> & array() const;
//! \~english Returns elements map of this element, or empty map if element is not \a PIJSON::Object.
//! \~russian Возвращает словарь элементов этого элемента, либо пустой словарь, если тип элемента не \a PIJSON::Object.
//! \~english Returns object members, or an empty map when the node is not \a PIJSON::Object.
//! \~russian Возвращает поля объекта, либо пустой словарь, если узел не имеет тип \a PIJSON::Object.
const PIMap<PIString, PIJSON> & object() const;
//! \~english Returns element value.
//! \~russian Возвращает значение элемента.
//! \~english Returns scalar node value.
//! \~russian Возвращает скалярное значение узла.
const PIVariant & value() const { return c_value; }
//! \~english Returns element value as bool.
//! \~russian Возвращает значение элемента как логическое.
//! \~english Returns scalar value as bool.
//! \~russian Возвращает скалярное значение как логическое.
bool toBool() const { return c_value.toBool(); }
//! \~english Returns element value as integer number.
//! \~russian Возвращает значение элемента как целое число.
//! \~english Returns scalar value as integer.
//! \~russian Возвращает скалярное значение как целое число.
int toInt() const { return c_value.toInt(); }
//! \~english Returns element value as floating-point number.
//! \~russian Возвращает значение элемента как число с плавающей точкой.
//! \~english Returns scalar value as floating-point number.
//! \~russian Возвращает скалярное значение как число с плавающей точкой.
double toDouble() const { return c_value.toDouble(); }
//! \~english Returns element value as string, valid for all types.
//! \~russian Возвращает значение элемента как строка, действительно для всех типов.
//! \~english Returns scalar value as string.
//! \~russian Возвращает скалярное значение как строку.
PIString toString() const { return c_value.toString(); }
//! \~english Returns element type.
//! \~russian Возвращает тип элемента.
//! \~english Returns node type.
//! \~russian Возвращает тип узла.
Type type() const { return c_type; }
//! \~english Returns if element is valid.
//! \~russian Возвращает действителен ли элемент.
//! \~english Returns whether the node is valid.
//! \~russian Возвращает, является ли узел действительным.
bool isValid() const { return c_type != Invalid; }
//! \~english Returns if element is \a PIJSON::Object.
//! \~russian Возвращает является ли элемент \a PIJSON::Object.
//! \~english Returns whether the node is \a PIJSON::Object.
//! \~russian Возвращает, является ли узел \a PIJSON::Object.
bool isObject() const { return c_type == Object; }
//! \~english Returns if element is \a PIJSON::Array.
//! \~russian Возвращает является ли элемент \a PIJSON::Array.
//! \~english Returns whether the node is \a PIJSON::Array.
//! \~russian Возвращает, является ли узел \a PIJSON::Array.
bool isArray() const { return c_type == Array; }
//! \~english Set value and type of element from "v".
//! \~russian Устанавливает значение и тип элемента из "v".
//! \~english Sets scalar value and updates node type for bool, numeric and string variants.
//! \~russian Устанавливает скалярное значение и обновляет тип узла для логических, числовых и строковых вариантов.
void setValue(const PIVariant & v);
//! \~english Clear element and set it to \a PIJSON::Invalid.
//! \~russian Очищает элемент и устанавливает его в \a PIJSON::Invalid.
//! \~english Clears node content and sets type to \a PIJSON::Invalid.
//! \~russian Очищает содержимое узла и устанавливает тип \a PIJSON::Invalid.
void clear();
//! \~english Returns size of elements array if type is \a PIJSON::Array, size of elements map if type is \a PIJSON::Object, otherwise
//! returns 0.
//! \~russian Возвращает размер массива элементов если тип \a PIJSON::Array, размер словаря элементов если тип \a PIJSON::Object, иначе
//! возвращает 0.
//! \~english Returns array length or object member count. Other node types return 0.
//! \~russian Возвращает длину массива или число полей объекта. Для остальных типов возвращает 0.
int size() const;
//! \~english Returns if elements map contains key "key" if type is \a PIJSON::Object, otherwise returns \b false.
//! \~russian Возвращает содержит ли словарь элементов ключ "key" если тип \a PIJSON::Object, иначе возвращает \b false.
//! \~english Returns whether an object node contains key \a key.
//! \~russian Возвращает, содержит ли узел-объект ключ \a key.
bool contains(const PIString & key) const;
//! \~english Set element type to \a PIJSON::Array and resize elements array to "new_size".
//! \~russian Устанавливает тип элемента в \a PIJSON::Array и изменяет размер массива элементов на "new_size".
//! \~english Converts node to array and resizes it. New entries become empty strings.
//! \~russian Преобразует узел в массив и изменяет его размер. Новые элементы становятся пустыми строками.
void resize(int new_size);
//! \~english Synonim of \a setValue().
//! \~english Synonym of \a setValue().
//! \~russian Аналог \a setValue().
PIJSON & operator=(const PIVariant & v) {
setValue(v);
return *this;
}
//! \~english Copy assignment operator.
//! \~russian Оператор копирующего присваивания.
PIJSON & operator=(const PIJSON & v);
//! \~english Returns element from array with index "index" if type is \a PIJSON::Array, otherwise returns invalid %PIJSON.
//! \~russian Возвращает элемент из массива по индексу "index" если тип \a PIJSON::Array, иначе возвращает недействительный %PIJSON.
//! \~english Returns array element by index, or invalid %PIJSON when the node is not an array.
//! \~russian Возвращает элемент массива по индексу, либо недействительный %PIJSON, если узел не является массивом.
const PIJSON & operator[](int index) const;
//! \~english Set element type to \a PIJSON::Array, resize if necessary and returns element from array with index "index".
//! \~russian Устанавливает тип элемента в \a PIJSON::Array, изменяет размер массива при неоходимости и возвращает элемент из массива по
//! индексу "index".
//! \~english Converts node to array, grows it when needed and returns element by index.
//! \~russian Преобразует узел в массив, при необходимости увеличивает его и возвращает элемент по индексу.
PIJSON & operator[](int index);
//! \~english Set element type to \a PIJSON::Array and add element to the end of array.
//! \~russian Устанавливает тип элемента в \a PIJSON::Array и добавляет элемент в массив.
//! \~english Converts node to array and appends another JSON node.
//! \~russian Преобразует узел в массив и добавляет другой узел JSON.
PIJSON & operator<<(const PIJSON & element);
//! \~english Set element type to \a PIJSON::Array and add element to the end of array.
//! \~russian Устанавливает тип элемента в \a PIJSON::Array и добавляет элемент в массив.
//! \~english Converts node to array and appends a scalar value.
//! \~russian Преобразует узел в массив и добавляет скалярное значение.
PIJSON & operator<<(const PIVariant & value);
//! \~english Returns element from map with key "key" if type is \a PIJSON::Object, otherwise returns invalid %PIJSON.
//! \~russian Возвращает элемент из словаря по ключу "key" если тип \a PIJSON::Object, иначе возвращает недействительный %PIJSON.
//! \~english Returns object member by key, or invalid %PIJSON when the node is not an object or the key is absent.
//! \~russian Возвращает поле объекта по ключу, либо недействительный %PIJSON, если узел не является объектом или ключ отсутствует.
PIJSON operator[](const PIString & key) const;
//! \~english Set element type to \a PIJSON::Object and returns element from map with key "key". If element with this key doesn`t
//! exists, it will be created.
//! \~russian Устанавливает тип элемента в \a PIJSON::Object и возвращает элемент из словаря по ключу "key". Если элемента с таким
//! ключом не существует, он будет создан.
//! \~english Converts node to object and returns member by key, creating it when needed.
//! \~russian Преобразует узел в объект и возвращает поле по ключу, создавая его при необходимости.
PIJSON & operator[](const PIString & key);
//! \~english Convenience overload for UTF-8 key access.
//! \~russian Вспомогательная перегрузка для доступа по UTF-8 ключу.
PIJSON operator[](const char * key) const { return (*this)[PIString::fromUTF8(key)]; }
//! \~english Convenience overload for UTF-8 key access.
//! \~russian Вспомогательная перегрузка для доступа по UTF-8 ключу.
PIJSON & operator[](const char * key) { return (*this)[PIString::fromUTF8(key)]; }
//! \~english Returns text representation of JSON tree.
//! \~russian Возвращает текстовое представление дерева JSON.
//! \~english Returns JSON text representation of the node tree.
//! \~russian Возвращает JSON-текст для дерева узлов.
PIString toJSON(PrintType print_type = Compact, bool mask_unicode = true) const;
//! \~english Parse text representation of JSON "str" and returns it root element.
//! \~russian Разбирает текстовое представление JSON "str" и возвращает его корневой элемент.
//! \~english Parses JSON text and returns the root node.
//! \~russian Разбирает JSON-текст и возвращает корневой узел.
static PIJSON fromJSON(PIString str);
//! \~english Creates an object node initialized from variant fields.
//! \~russian Создает узел-объект, инициализированный из полей вариативного словаря.
static PIJSON newObject(const PIVariantMap & fields = {});
//! \~english Creates an array node initialized from variant elements.
//! \~russian Создает узел-массив, инициализированный из вариативных элементов.
static PIJSON newArray(const PIVariantVector & fields = {});
//! \~english Creates a string node.
//! \~russian Создает строковый узел.
static PIJSON newString(const PIString & v = PIString());
//! \~english Serializes value \a v with the overload set from \a pijsonserialization.h.
//! \~russian Сериализует значение \a v через набор перегрузок из \a pijsonserialization.h.
template<typename T>
static PIJSON serialize(const T & v);
//! \~english Deserializes value of type \c T with the overload set from \a pijsonserialization.h.
//! \~russian Десериализует значение типа \c T через набор перегрузок из \a pijsonserialization.h.
template<typename T>
static T deserialize(const PIJSON & json);
private:
static PIJSON & nullEntry();
static PIString parseName(PIString & s);
@@ -230,4 +255,4 @@ inline PICout operator<<(PICout s, const PIJSON & v) {
}
#endif // PICONSTCHARS_H
#endif // PIJSON_H

View File

@@ -1,12 +1,16 @@
/*! \file pijson.h
* \ingroup Serialization
* \brief
* \~english JSON serialization
* \~russian Сериализация JSON
*/
//! \~\file pijsonserialization.h
//! \~\ingroup Serialization
//! \~\brief
//! \~english Generic JSON serialization helpers
//! \~russian Вспомогательные шаблоны для сериализации JSON
//! \details
//! \~english
//! This file provides template functions for serializing and deserializing various types to and from PIJSON format.
//! \~russian
//! Этот файл предоставляет шаблонные функции для сериализации и десериализации различных типов в формат PIJSON и из него.
/*
PIP - Platform Independent Primitives
JSON serialization
Generic JSON serialization helpers
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
@@ -36,11 +40,15 @@
// enum & arithmetic
//! \~english Serializes enum values as JSON numbers.
//! \~russian Сериализует значения перечислений как JSON-числа.
template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
inline PIJSON piSerializeJSON(const T & v) {
return PIJSON() = (int)v;
}
//! \~english Serializes arithmetic values as JSON scalars.
//! \~russian Сериализует арифметические значения как JSON-скаляры.
template<typename T,
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
typename std::enable_if<std::is_arithmetic<T>::value, int>::type = 0>
@@ -48,6 +56,8 @@ inline PIJSON piSerializeJSON(const T & v) {
return PIJSON() = v;
}
//! \~english Fallback overload that intentionally fails for unsupported complex types.
//! \~russian Резервная перегрузка, которая намеренно завершает компиляцию ошибкой для неподдерживаемых сложных типов.
template<typename T,
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
typename std::enable_if<!std::is_arithmetic<T>::value, int>::type = 0>
@@ -60,14 +70,20 @@ inline PIJSON piSerializeJSON(const T & v) {
// known types
//! \~english Returns JSON node unchanged.
//! \~russian Возвращает JSON-узел без изменений.
inline PIJSON piSerializeJSON(const PIJSON & v) {
return v;
}
template<>
//! \~english Serializes %PIVariant as the matching scalar JSON node.
//! \~russian Сериализует %PIVariant в соответствующий скалярный JSON-узел.
inline PIJSON piSerializeJSON(const PIVariant & v) {
return PIJSON() = v;
}
template<typename T>
//! \~english Serializes complex number as array [real, imag].
//! \~russian Сериализует комплексное число как массив [real, imag].
inline PIJSON piSerializeJSON(const complex<T> & v) {
PIJSON ret;
ret << v.real() << v.imag();
@@ -75,26 +91,36 @@ inline PIJSON piSerializeJSON(const complex<T> & v) {
}
template<typename T>
//! \~english Serializes %PIFlags as an integer mask.
//! \~russian Сериализует %PIFlags как целочисленную маску.
inline PIJSON piSerializeJSON(const PIFlags<T> & v) {
return PIJSON() = (int)v;
}
template<>
//! \~english Serializes %PIString as JSON string.
//! \~russian Сериализует %PIString как JSON-строку.
inline PIJSON piSerializeJSON(const PIString & v) {
return PIJSON() = v;
}
template<>
//! \~english Serializes %PIConstChars as JSON string.
//! \~russian Сериализует %PIConstChars как JSON-строку.
inline PIJSON piSerializeJSON(const PIConstChars & v) {
return PIJSON() = v.toString();
}
template<>
//! \~english Serializes %PIByteArray as Base64 string.
//! \~russian Сериализует %PIByteArray как строку Base64.
inline PIJSON piSerializeJSON(const PIByteArray & v) {
return PIJSON() = PIStringAscii(v.toBase64());
}
template<>
//! \~english Serializes %PISystemTime as object with fields \c s and \c ns.
//! \~russian Сериализует %PISystemTime как объект с полями \c s и \c ns.
inline PIJSON piSerializeJSON(const PISystemTime & v) {
PIJSON ret;
ret["s"] = v.seconds;
@@ -103,6 +129,8 @@ inline PIJSON piSerializeJSON(const PISystemTime & v) {
}
template<>
//! \~english Serializes %PITime as object with fields \c h, \c m, \c s and \c z.
//! \~russian Сериализует %PITime как объект с полями \c h, \c m, \c s и \c z.
inline PIJSON piSerializeJSON(const PITime & v) {
PIJSON ret;
ret["h"] = v.hours;
@@ -113,6 +141,8 @@ inline PIJSON piSerializeJSON(const PITime & v) {
}
template<>
//! \~english Serializes %PIDate as object with fields \c y, \c M and \c d.
//! \~russian Сериализует %PIDate как объект с полями \c y, \c M и \c d.
inline PIJSON piSerializeJSON(const PIDate & v) {
PIJSON ret;
ret["y"] = v.year;
@@ -122,6 +152,8 @@ inline PIJSON piSerializeJSON(const PIDate & v) {
}
template<>
//! \~english Serializes %PIDateTime as object with fields \c y, \c M, \c d, \c h, \c m, \c s and \c z.
//! \~russian Сериализует %PIDateTime как объект с полями \c y, \c M, \c d, \c h, \c m, \c s и \c z.
inline PIJSON piSerializeJSON(const PIDateTime & v) {
PIJSON ret;
ret["y"] = v.year;
@@ -135,11 +167,15 @@ inline PIJSON piSerializeJSON(const PIDateTime & v) {
}
template<>
//! \~english Serializes %PINetworkAddress as string.
//! \~russian Сериализует %PINetworkAddress как строку.
inline PIJSON piSerializeJSON(const PINetworkAddress & v) {
return PIJSON() = v.toString();
}
template<typename T>
//! \~english Serializes %PIPoint as object with fields \c x and \c y.
//! \~russian Сериализует %PIPoint как объект с полями \c x и \c y.
inline PIJSON piSerializeJSON(const PIPoint<T> & v) {
PIJSON ret;
ret["x"] = piSerializeJSON(v.x);
@@ -148,6 +184,8 @@ inline PIJSON piSerializeJSON(const PIPoint<T> & v) {
}
template<typename T>
//! \~english Serializes %PILine as object with fields \c p0 and \c p1.
//! \~russian Сериализует %PILine как объект с полями \c p0 и \c p1.
inline PIJSON piSerializeJSON(const PILine<T> & v) {
PIJSON ret;
ret["p0"] = piSerializeJSON(v.p0);
@@ -156,6 +194,8 @@ inline PIJSON piSerializeJSON(const PILine<T> & v) {
}
template<typename T>
//! \~english Serializes %PIRect as object with fields \c bl and \c tr.
//! \~russian Сериализует %PIRect как объект с полями \c bl и \c tr.
inline PIJSON piSerializeJSON(const PIRect<T> & v) {
PIJSON ret;
ret["bl"] = piSerializeJSON(v.bottomLeft());
@@ -166,6 +206,8 @@ inline PIJSON piSerializeJSON(const PIRect<T> & v) {
// containers
//! \~english Serializes %PIPair as two-element array.
//! \~russian Сериализует %PIPair как массив из двух элементов.
template<typename T1, typename T2>
inline PIJSON piSerializeJSON(const PIPair<T1, T2> & v) {
PIJSON ret;
@@ -174,6 +216,8 @@ inline PIJSON piSerializeJSON(const PIPair<T1, T2> & v) {
}
template<typename T>
//! \~english Serializes %PIVector as JSON array.
//! \~russian Сериализует %PIVector как JSON-массив.
inline PIJSON piSerializeJSON(const PIVector<T> & v) {
if (v.isEmpty()) return PIJSON::newArray();
PIJSON ret;
@@ -183,6 +227,8 @@ inline PIJSON piSerializeJSON(const PIVector<T> & v) {
}
template<typename T>
//! \~english Serializes %PIDeque as JSON array.
//! \~russian Сериализует %PIDeque как JSON-массив.
inline PIJSON piSerializeJSON(const PIDeque<T> & v) {
if (v.isEmpty()) return PIJSON::newArray();
PIJSON ret;
@@ -192,6 +238,8 @@ inline PIJSON piSerializeJSON(const PIDeque<T> & v) {
}
template<typename T>
//! \~english Serializes %PIVector2D as object with \c rows, \c cols and flattened \c mat.
//! \~russian Сериализует %PIVector2D как объект с \c rows, \c cols и плоским массивом \c mat.
inline PIJSON piSerializeJSON(const PIVector2D<T> & v) {
PIJSON ret;
ret["cols"] = static_cast<uint>(v.cols());
@@ -201,6 +249,8 @@ inline PIJSON piSerializeJSON(const PIVector2D<T> & v) {
}
template<typename T>
//! \~english Serializes %PISet as JSON array.
//! \~russian Сериализует %PISet как JSON-массив.
inline PIJSON piSerializeJSON(const PISet<T> & v) {
if (v.isEmpty()) return PIJSON::newArray();
PIJSON ret;
@@ -210,6 +260,8 @@ inline PIJSON piSerializeJSON(const PISet<T> & v) {
}
template<typename K, typename T>
//! \~english Serializes %PIMap as JSON object with stringified keys.
//! \~russian Сериализует %PIMap как JSON-объект со строковыми ключами.
inline PIJSON piSerializeJSON(const PIMap<K, T> & v) {
if (v.isEmpty()) return PIJSON::newObject();
PIJSON ret;
@@ -220,6 +272,8 @@ inline PIJSON piSerializeJSON(const PIMap<K, T> & v) {
}
template<typename T>
//! \~english Serializes %PIMathVector as JSON array.
//! \~russian Сериализует %PIMathVector как JSON-массив.
inline PIJSON piSerializeJSON(const PIMathVector<T> & v) {
PIJSON ret;
for (uint i = 0; i < v.size(); ++i)
@@ -228,6 +282,8 @@ inline PIJSON piSerializeJSON(const PIMathVector<T> & v) {
}
template<uint Size, typename T>
//! \~english Serializes fixed-size %PIMathVectorT as JSON array.
//! \~russian Сериализует %PIMathVectorT фиксированного размера как JSON-массив.
inline PIJSON piSerializeJSON(const PIMathVectorT<Size, T> & v) {
PIJSON ret;
for (uint i = 0; i < v.size(); ++i)
@@ -243,11 +299,15 @@ inline PIJSON piSerializeJSON(const PIMathVectorT<Size, T> & v) {
// enum & arithmetic
//! \~english Deserializes enum value from JSON number.
//! \~russian Десериализует значение перечисления из JSON-числа.
template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
inline void piDeserializeJSON(T & v, const PIJSON & js) {
v = (T)js.toInt();
}
//! \~english Deserializes arithmetic value from JSON scalar.
//! \~russian Десериализует арифметическое значение из JSON-скаляра.
template<typename T,
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
typename std::enable_if<std::is_arithmetic<T>::value, int>::type = 0>
@@ -255,6 +315,8 @@ inline void piDeserializeJSON(T & v, const PIJSON & js) {
v = js.value().value<T>();
}
//! \~english Fallback overload that intentionally fails for unsupported complex types.
//! \~russian Резервная перегрузка, которая намеренно завершает компиляцию ошибкой для неподдерживаемых сложных типов.
template<typename T,
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
typename std::enable_if<!std::is_arithmetic<T>::value, int>::type = 0>
@@ -267,15 +329,21 @@ inline void piDeserializeJSON(T & v, const PIJSON & js) {
// known types
//! \~english Copies JSON node as-is.
//! \~russian Копирует JSON-узел без изменений.
inline void piDeserializeJSON(PIJSON & v, const PIJSON & js) {
v = js;
}
template<>
//! \~english Extracts scalar value from JSON node into %PIVariant.
//! \~russian Извлекает скалярное значение JSON-узла в %PIVariant.
inline void piDeserializeJSON(PIVariant & v, const PIJSON & js) {
v = js.value();
}
template<typename T>
//! \~english Deserializes complex number from array [real, imag].
//! \~russian Десериализует комплексное число из массива [real, imag].
inline void piDeserializeJSON(complex<T> & v, const PIJSON & js) {
if (!js.isArray()) return;
piDeserializeJSON(reinterpret_cast<T(&)[2]>(v)[0], js[0]);
@@ -283,27 +351,37 @@ inline void piDeserializeJSON(complex<T> & v, const PIJSON & js) {
}
template<typename T>
//! \~english Deserializes %PIFlags from integer mask.
//! \~russian Десериализует %PIFlags из целочисленной маски.
inline void piDeserializeJSON(PIFlags<T> & v, const PIJSON & js) {
v = js.toInt();
}
template<>
//! \~english Deserializes %PIString from JSON string representation.
//! \~russian Десериализует %PIString из строкового представления JSON.
inline void piDeserializeJSON(PIString & v, const PIJSON & js) {
v = js.toString();
}
template<>
//! \~english Deserializes %PIByteArray from Base64 string.
//! \~russian Десериализует %PIByteArray из строки Base64.
inline void piDeserializeJSON(PIByteArray & v, const PIJSON & js) {
v = PIByteArray::fromBase64(js.toString());
}
template<>
//! \~english Deserializes %PISystemTime from object with fields \c s and \c ns.
//! \~russian Десериализует %PISystemTime из объекта с полями \c s и \c ns.
inline void piDeserializeJSON(PISystemTime & v, const PIJSON & js) {
piDeserializeJSON(v.seconds, js["s"]);
piDeserializeJSON(v.nanoseconds, js["ns"]);
}
template<>
//! \~english Deserializes %PITime from object with fields \c h, \c m, \c s and \c z.
//! \~russian Десериализует %PITime из объекта с полями \c h, \c m, \c s и \c z.
inline void piDeserializeJSON(PITime & v, const PIJSON & js) {
v.hours = js["h"].toInt();
v.minutes = js["m"].toInt();
@@ -312,6 +390,8 @@ inline void piDeserializeJSON(PITime & v, const PIJSON & js) {
}
template<>
//! \~english Deserializes %PIDate from object with fields \c y, \c M and \c d.
//! \~russian Десериализует %PIDate из объекта с полями \c y, \c M и \c d.
inline void piDeserializeJSON(PIDate & v, const PIJSON & js) {
v.year = js["y"].toInt();
v.month = js["M"].toInt();
@@ -319,6 +399,8 @@ inline void piDeserializeJSON(PIDate & v, const PIJSON & js) {
}
template<>
//! \~english Deserializes %PIDateTime from object with fields \c y, \c M, \c d, \c h, \c m, \c s and \c z.
//! \~russian Десериализует %PIDateTime из объекта с полями \c y, \c M, \c d, \c h, \c m, \c s и \c z.
inline void piDeserializeJSON(PIDateTime & v, const PIJSON & js) {
v.year = js["y"].toInt();
v.month = js["M"].toInt();
@@ -330,23 +412,31 @@ inline void piDeserializeJSON(PIDateTime & v, const PIJSON & js) {
}
template<>
//! \~english Deserializes %PINetworkAddress from string.
//! \~russian Десериализует %PINetworkAddress из строки.
inline void piDeserializeJSON(PINetworkAddress & v, const PIJSON & js) {
v = PINetworkAddress(js.toString());
}
template<typename T>
//! \~english Deserializes %PIPoint from object with fields \c x and \c y.
//! \~russian Десериализует %PIPoint из объекта с полями \c x и \c y.
inline void piDeserializeJSON(PIPoint<T> & v, const PIJSON & js) {
piDeserializeJSON(v.x, js["x"]);
piDeserializeJSON(v.y, js["y"]);
}
template<typename T>
//! \~english Deserializes %PILine from object with fields \c p0 and \c p1.
//! \~russian Десериализует %PILine из объекта с полями \c p0 и \c p1.
inline void piDeserializeJSON(PILine<T> & v, const PIJSON & js) {
piDeserializeJSON(v.p0, js["p0"]);
piDeserializeJSON(v.p1, js["p1"]);
}
template<typename T>
//! \~english Deserializes %PIRect from object with fields \c bl and \c tr.
//! \~russian Десериализует %PIRect из объекта с полями \c bl и \c tr.
inline void piDeserializeJSON(PIRect<T> & v, const PIJSON & js) {
PIPoint<T> bl, tr;
piDeserializeJSON(bl, js["bl"]);
@@ -357,6 +447,8 @@ inline void piDeserializeJSON(PIRect<T> & v, const PIJSON & js) {
// containers
//! \~english Deserializes %PIPair from two-element array.
//! \~russian Десериализует %PIPair из массива из двух элементов.
template<typename T1, typename T2>
inline void piDeserializeJSON(PIPair<T1, T2> & v, const PIJSON & js) {
v = {};
@@ -366,6 +458,8 @@ inline void piDeserializeJSON(PIPair<T1, T2> & v, const PIJSON & js) {
}
template<typename T>
//! \~english Deserializes %PIVector from JSON array.
//! \~russian Десериализует %PIVector из JSON-массива.
inline void piDeserializeJSON(PIVector<T> & v, const PIJSON & js) {
v.clear();
if (!js.isArray()) return;
@@ -375,6 +469,8 @@ inline void piDeserializeJSON(PIVector<T> & v, const PIJSON & js) {
}
template<typename T>
//! \~english Deserializes %PIDeque from JSON array.
//! \~russian Десериализует %PIDeque из JSON-массива.
inline void piDeserializeJSON(PIDeque<T> & v, const PIJSON & js) {
v.clear();
if (!js.isArray()) return;
@@ -384,6 +480,8 @@ inline void piDeserializeJSON(PIDeque<T> & v, const PIJSON & js) {
}
template<typename T>
//! \~english Deserializes %PIVector2D from object with \c rows, \c cols and flattened \c mat.
//! \~russian Десериализует %PIVector2D из объекта с \c rows, \c cols и плоским массивом \c mat.
inline void piDeserializeJSON(PIVector2D<T> & v, const PIJSON & js) {
v.clear();
if (!js.isObject()) return;
@@ -394,6 +492,8 @@ inline void piDeserializeJSON(PIVector2D<T> & v, const PIJSON & js) {
}
template<typename T>
//! \~english Deserializes %PISet from JSON array.
//! \~russian Десериализует %PISet из JSON-массива.
inline void piDeserializeJSON(PISet<T> & v, const PIJSON & js) {
v.clear();
if (!js.isArray()) return;
@@ -405,6 +505,8 @@ inline void piDeserializeJSON(PISet<T> & v, const PIJSON & js) {
}
template<typename K, typename T>
//! \~english Deserializes %PIMap from JSON object with stringified keys.
//! \~russian Десериализует %PIMap из JSON-объекта со строковыми ключами.
inline void piDeserializeJSON(PIMap<K, T> & v, const PIJSON & js) {
v.clear();
if (!js.isObject()) return;
@@ -415,6 +517,8 @@ inline void piDeserializeJSON(PIMap<K, T> & v, const PIJSON & js) {
}
template<typename T>
//! \~english Deserializes dynamic %PIMathVector from JSON array.
//! \~russian Десериализует динамический %PIMathVector из JSON-массива.
inline void piDeserializeJSON(PIMathVector<T> & v, const PIJSON & js) {
v = {};
if (!js.isArray()) return;
@@ -424,6 +528,8 @@ inline void piDeserializeJSON(PIMathVector<T> & v, const PIJSON & js) {
}
template<uint Size, typename T>
//! \~english Deserializes fixed-size %PIMathVectorT from JSON array, truncating extra items.
//! \~russian Десериализует %PIMathVectorT фиксированного размера из JSON-массива, отбрасывая лишние элементы.
inline void piDeserializeJSON(PIMathVectorT<Size, T> & v, const PIJSON & js) {
v = PIMathVectorT<Size, T>();
if (!js.isArray()) return;
@@ -439,11 +545,15 @@ inline void piDeserializeJSON(PIMathVectorT<Size, T> & v, const PIJSON & js) {
template<typename T>
//! \~english Convenience wrapper around \a piSerializeJSON().
//! \~russian Вспомогательная обертка над \a piSerializeJSON().
PIJSON PIJSON::serialize(const T & v) {
return piSerializeJSON(v);
}
template<typename T>
//! \~english Convenience wrapper around \a piDeserializeJSON().
//! \~russian Вспомогательная обертка над \a piDeserializeJSON().
T PIJSON::deserialize(const PIJSON & json) {
T ret;
piDeserializeJSON(ret, json);

View File

@@ -1,3 +1,12 @@
//! \~\file piserializationmodule.h
//! \~\ingroup Serialization
//! \~\brief
//! \~english Serialization module include header
//! \~russian Заголовок подключения модуля Serialization
//!
//! \~\details
//! \~english Includes the public binary stream, JSON, and value tree serialization headers.
//! \~russian Подключает публичные заголовки бинарных потоков, JSON и сериализации дерева значений.
/*
PIP - Platform Independent Primitives
Module includes
@@ -34,10 +43,17 @@
//! \~russian \par Общее
//!
//! \~english
//!
//!
//! This module provides serialization support through:
//! - PIJSON class for JSON parsing and generation
//! - PIBinaryStream for binary serialization
//! - PIChunkStream for chunk-based binary serialization
//! - PIValueTree conversions for hierarchical data
//! \~russian
//!
//! Этот модуль предоставляет поддержку сериализации через:
//! - Класс PIJSON для разбора и генерации JSON
//! - PIBinaryStream для бинарной сериализации
//! - PIChunkStream для блочной бинарной сериализации
//! - Конверсии PIValueTree для иерархических данных
//!
//! \~\authors
//! \~english

View File

@@ -1,9 +1,8 @@
/*! \file pivaluetree_conversions.h
* \ingroup Serialization
* \brief
* \~english PIValueTree conversions
* \~russian Преобразования PIValueTree
*/
//! \~\file pivaluetree_conversions.h
//! \~\ingroup Serialization
//! \~\brief
//! \~english %PIValueTree conversion helpers
//! \~russian Вспомогательные преобразования %PIValueTree
/*
PIP - Platform Independent Primitives
PIValueTree conversions
@@ -32,31 +31,70 @@ class PIPropertyStorage;
class PIJSON;
class PIIODevice;
//! \relatesalso PIValueTree
//! \~english Namespace with conversions between %PIValueTree and other public serialization formats.
//! \~russian Пространство имен с преобразованиями между %PIValueTree и другими публичными форматами сериализации.
namespace PIValueTreeConversions {
//! \~english Conversion options.
//! \~russian Параметры преобразования.
enum Option {
WithAttributes = 0x1,
WithComment = 0x2,
WithType = 0x4,
WithAll = 0xFFF,
IncludeRoot = 0x1000,
Default = WithAll
WithAttributes = 0x1 /** \~english Include node attributes \~russian Включать атрибуты узлов */,
WithComment = 0x2 /** \~english Include node comments \~russian Включать комментарии узлов */,
WithType = 0x4 /** \~english Include textual value type information \~russian Включать текстовую информацию о типе значения */,
WithAll = 0xFFF /** \~english Enable all content flags \~russian Включать все флаги содержимого */,
IncludeRoot = 0x1000 /** \~english Serialize the passed root node itself instead of only its children \~russian Сериализовать сам
переданный корневой узел, а не только его дочерние элементы */
,
Default = WithAll /** \~english Default conversion options \~russian Параметры преобразования по умолчанию */
};
//! \~english Bit mask of %PIValueTree conversion options.
//! \~russian Набор флагов параметров преобразования %PIValueTree.
typedef PIFlags<Option> Options;
//! \~english Builds a tree from flat %PIPropertyStorage entries.
//! \~russian Создает дерево из плоского набора записей %PIPropertyStorage.
PIP_EXPORT PIValueTree fromPropertyStorage(const PIPropertyStorage & ps);
//! \~english Builds a tree whose top-level children come from a %PIVariantMap.
//! \~russian Создает дерево, в котором дочерние элементы верхнего уровня берутся из %PIVariantMap.
PIP_EXPORT PIValueTree fromVariantMap(const PIVariantMap & vm);
//! \~english Converts JSON tree representation produced by this module into %PIValueTree.
//! \~russian Преобразует JSON-представление дерева, создаваемое этим модулем, в %PIValueTree.
PIP_EXPORT PIValueTree fromJSON(const PIJSON & json);
//! \~english Parses PIP text configuration format from a device into %PIValueTree.
//! \~russian Разбирает текстовый конфигурационный формат PIP из устройства в %PIValueTree.
PIP_EXPORT PIValueTree fromText(PIIODevice * device);
//! \~english Parses PIP text configuration format from a string into %PIValueTree.
//! \~russian Разбирает текстовый конфигурационный формат PIP из строки в %PIValueTree.
PIP_EXPORT PIValueTree fromText(const PIString & str);
//! \~english Loads JSON tree text from file and merges an optional \c .override companion file when it exists.
//! \~russian Загружает JSON-представление дерева из файла и объединяет его с дополнительным файлом \c .override, если он существует.
PIP_EXPORT PIValueTree fromJSONFile(const PIString & path);
//! \~english Loads text tree configuration from file and merges an optional \c .override companion file when it exists.
//! \~russian Загружает текстовую конфигурацию дерева из файла и объединяет ее с дополнительным файлом \c .override, если он существует.
PIP_EXPORT PIValueTree fromTextFile(const PIString & path);
//! \~english Converts %PIValueTree to the module JSON tree representation.
//! \~russian Преобразует %PIValueTree в JSON-представление дерева этого модуля.
PIP_EXPORT PIJSON toJSON(const PIValueTree & root, Options options = Default);
//! \~english Converts %PIValueTree to the PIP text configuration format.
//! \~russian Преобразует %PIValueTree в текстовый конфигурационный формат PIP.
PIP_EXPORT PIString toText(const PIValueTree & root, Options options = Default);
//! \~english Writes JSON tree text to file. Returns \c true when the whole output was written.
//! \~russian Записывает JSON-представление дерева в файл. Возвращает \c true, если записан весь результат.
PIP_EXPORT bool toJSONFile(const PIString & path, const PIValueTree & root, Options options = Default);
//! \~english Writes text tree configuration to file. Returns \c true when the whole output was written.
//! \~russian Записывает текстовую конфигурацию дерева в файл. Возвращает \c true, если записан весь результат.
PIP_EXPORT bool toTextFile(const PIString & path, const PIValueTree & root, Options options = Default);
} // namespace PIValueTreeConversions