From 3a6b3a40643baa0e96ddd9e07d92049539567a9f Mon Sep 17 00:00:00 2001 From: Andrey Bychkov Date: Mon, 3 Jul 2023 19:10:36 +0300 Subject: [PATCH 1/3] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=20const=20=D0=B4=D0=BB=D1=8F=20=D1=87=D0=B0=D1=81=D1=82=D0=B8?= =?UTF-8?q?=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=B9=D0=BD=D0=B5=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=B8=20explicit=20=D0=B4=D0=BB=D1=8F=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/main/containers/picontainers.cpp | 3 +- libs/main/containers/picontainers.h | 2 +- libs/main/containers/pideque.h | 172 +++++++++++++++----------- libs/main/containers/pimap.h | 20 +-- libs/main/containers/pipair.h | 9 +- libs/main/containers/piset.h | 6 +- libs/main/containers/pivector.h | 105 ++++++++-------- libs/main/containers/pivector2d.h | 30 ++--- libs/main/types/pibytearray.cpp | 33 ++--- libs/main/types/pibytearray.h | 13 +- 10 files changed, 217 insertions(+), 176 deletions(-) diff --git a/libs/main/containers/picontainers.cpp b/libs/main/containers/picontainers.cpp index 1960b919..ff192559 100644 --- a/libs/main/containers/picontainers.cpp +++ b/libs/main/containers/picontainers.cpp @@ -24,7 +24,8 @@ const size_t minAlloc = 64; size_t _PIContainerConstantsBase::calcMinCountPoT(size_t szof) { - size_t ret = 0, elc = 1; + size_t ret = 0; + size_t elc = 1; while (elc * szof < minAlloc) { elc *= 2; ++ret; diff --git a/libs/main/containers/picontainers.h b/libs/main/containers/picontainers.h index b49c5e9b..b2f0e7e0 100644 --- a/libs/main/containers/picontainers.h +++ b/libs/main/containers/picontainers.h @@ -73,7 +73,7 @@ template class _PIContainerConstants { public: static size_t minCountPoT() { - static size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T)); + static const size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T)); return ret; } }; diff --git a/libs/main/containers/pideque.h b/libs/main/containers/pideque.h index 19488f0e..4414b063 100644 --- a/libs/main/containers/pideque.h +++ b/libs/main/containers/pideque.h @@ -75,9 +75,9 @@ //! if the number of elements is known beforehand. //! //! The complexity (efficiency) of common operations on PIDeque is as follows: -//! - Random access - constant 𝓞(1) -//! - Insertion or removal of elements at the end or begin - amortized constant 𝓞(1) -//! - Insertion or removal of elements - linear in the distance to the end of the array 𝓞(n) +//! - Random access - constant O(1) +//! - Insertion or removal of elements at the end or begin - amortized constant O(1) +//! - Insertion or removal of elements - linear in the distance to the end of the array O(n) //! //! \~russian //! Элементы хранятся непрерывно, а значит доступны не только через итераторы, @@ -109,9 +109,9 @@ //! если количество элементов известно заранее. //! //! Сложность (эффективность) обычных операций над PIDeque следующая: -//! - Произвольный доступ — постоянная 𝓞(1) -//! - Вставка и удаление элементов в конце или начале — амортизированная постоянная 𝓞(1) -//! - Вставка и удаление элементов — линейная по расстоянию до конца массива 𝓞(n) +//! - Произвольный доступ — постоянная O(1) +//! - Вставка и удаление элементов в конце или начале — амортизированная постоянная O(1) +//! - Вставка и удаление элементов — линейная по расстоянию до конца массива O(n) //! //! \~\sa \a PIVector, \a PIMap template @@ -164,7 +164,7 @@ public: //! \~english Contructs array with size `size` filled elements `e`. //! \~russian Создает массив из `size` элементов заполненных `e`. - inline PIDeque(size_t pid_size, const T & e = T()) { + inline explicit PIDeque(size_t pid_size, const T & e = T()) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) expand(pid_size, e); } @@ -249,7 +249,7 @@ public: return *this; } inline iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -258,7 +258,7 @@ public: return *this; } inline iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -328,7 +328,7 @@ public: return *this; } inline const_iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -337,7 +337,7 @@ public: return *this; } inline const_iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -409,7 +409,7 @@ public: return *this; } inline reverse_iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -418,7 +418,7 @@ public: return *this; } inline reverse_iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -487,7 +487,7 @@ public: return *this; } inline const_reverse_iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -496,7 +496,7 @@ public: return *this; } inline const_reverse_iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -729,7 +729,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a indexWhere() inline const T & atWhere(std::function test, ssize_t start = 0, const T & def = T()) const { - ssize_t i = indexWhere(test, start); + const ssize_t i = indexWhere(test, start); if (i < 0) return def; else @@ -743,7 +743,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a lastIndexWhere() inline const T & lastAtWhere(std::function test, ssize_t start = -1, const T & def = T()) const { - ssize_t i = lastIndexWhere(test, start); + const ssize_t i = lastIndexWhere(test, start); if (i < 0) return def; else @@ -1302,7 +1302,7 @@ public: //! \~\sa \a size(), \a capacity(), \a resize() inline PIDeque & reserve(size_t new_size) { if (new_size <= pid_rsize) return *this; - size_t os = pid_size; + const size_t os = pid_size; alloc_forward(new_size); pid_size = os; return *this; @@ -1322,17 +1322,21 @@ public: inline PIDeque & insert(size_t index, const T & e = T()) { if (index == pid_size) return push_back(e); PIINTROSPECTION_CONTAINER_USED(T, 1) - bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); + const bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { alloc_forward(pid_size + 1); if (index < pid_size - 1) { - size_t os = pid_size - index - 1; - memmove((void *)(pid_data + pid_start + index + 1), (const void *)(pid_data + pid_start + index), os * sizeof(T)); + const size_t os = pid_size - index - 1; + memmove(reinterpret_cast(pid_data + pid_start + index + 1), + reinterpret_cast(pid_data + pid_start + index), + os * sizeof(T)); } } else { alloc_backward(pid_size + 1, -1); if (index > 0) { - memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + 1), index * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start), + reinterpret_cast(pid_data + pid_start + 1), + index * sizeof(T)); } } elementNew(pid_data + pid_start + index, e); @@ -1348,17 +1352,21 @@ public: inline PIDeque & insert(size_t index, T && e) { if (index == pid_size) return push_back(e); PIINTROSPECTION_CONTAINER_USED(T, 1) - bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); + const bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { alloc_forward(pid_size + 1); if (index < pid_size - 1) { - size_t os = pid_size - index - 1; - memmove((void *)(pid_data + pid_start + index + 1), (const void *)(pid_data + pid_start + index), os * sizeof(T)); + const size_t os = pid_size - index - 1; + memmove(reinterpret_cast(pid_data + pid_start + index + 1), + reinterpret_cast(pid_data + pid_start + index), + os * sizeof(T)); } } else { alloc_backward(pid_size + 1, -1); if (index > 0) { - memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + 1), index * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start), + reinterpret_cast(pid_data + pid_start + 1), + index * sizeof(T)); } } elementNew(pid_data + pid_start + index, std::move(e)); @@ -1379,17 +1387,21 @@ public: } #endif assert(&v != this); - bool dir = v.size() > pid_size ? true : (index >= pid_rsize / 2 ? true : false); + const bool dir = v.size() > pid_size ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { - ssize_t os = pid_size - index; + const ssize_t os = pid_size - index; alloc_forward(pid_size + v.pid_size); if (os > 0) { - memmove((void *)(pid_data + pid_start + index + v.pid_size), (const void *)(pid_data + pid_start + index), os * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start + index + v.pid_size), + reinterpret_cast(pid_data + pid_start + index), + os * sizeof(T)); } } else { alloc_backward(pid_size + v.pid_size, -v.pid_size); if (index > 0) { - memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + v.pid_size), index * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start), + reinterpret_cast(pid_data + pid_start + v.pid_size), + index * sizeof(T)); } } newT(pid_data + pid_start + index, v.pid_data + v.pid_start, v.pid_size); @@ -1408,19 +1420,21 @@ public: //! \~\sa \a append(), \a prepend(), \a remove() inline PIDeque & insert(size_t index, std::initializer_list init_list) { if (init_list.size() == 0) return *this; - bool dir = init_list.size() > pid_size ? true : (index >= pid_rsize / 2 ? true : false); + const bool dir = init_list.size() > pid_size ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { - ssize_t os = ssize_t(pid_size) - index; + const ssize_t os = ssize_t(pid_size) - index; alloc_forward(pid_size + init_list.size()); if (os > 0) { - memmove((void *)(pid_data + pid_start + index + init_list.size()), - (const void *)(pid_data + pid_start + index), + memmove(reinterpret_cast(pid_data + pid_start + index + init_list.size()), + reinterpret_cast(pid_data + pid_start + index), os * sizeof(T)); } } else { alloc_backward(pid_size + init_list.size(), -init_list.size()); if (index > 0) { - memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + init_list.size()), index * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start), + reinterpret_cast(pid_data + pid_start + init_list.size()), + index * sizeof(T)); } } newT(pid_data + pid_start + index, init_list.begin(), init_list.size()); @@ -1444,13 +1458,17 @@ public: pid_size = index; } } else { - size_t os = pid_size - index - count; + const size_t os = pid_size - index - count; deleteT(pid_data + pid_start + index, count); if (os <= index) { - memmove((void *)(pid_data + pid_start + index), (const void *)(pid_data + pid_start + index + count), os * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start + index), + reinterpret_cast(pid_data + pid_start + index + count), + os * sizeof(T)); } else { if (index > 0) { - memmove((void *)(pid_data + pid_start + count), (const void *)(pid_data + pid_start), index * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start + count), + reinterpret_cast(pid_data + pid_start), + index * sizeof(T)); } pid_start += count; } @@ -1544,7 +1562,7 @@ public: //! \endcode //! \~\sa \a reversed() inline PIDeque & reverse() { - size_t s2 = pid_size / 2; + const size_t s2 = pid_size / 2; for (size_t i = 0; i < s2; ++i) { piSwap(pid_data[pid_start + i], pid_data[pid_start + pid_size - i - 1]); } @@ -1575,7 +1593,7 @@ public: //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. //! \~\sa \a resize() inline PIDeque & enlarge(ssize_t add_size, const T & e = T()) { - ssize_t ns = size_s() + add_size; + const ssize_t ns = size_s() + add_size; if (ns <= 0) clear(); else @@ -1698,7 +1716,7 @@ public: //! \~\sa \a push_back() inline PIDeque & push_back(std::initializer_list init_list) { if (init_list.size() == 0) return *this; - size_t ps = pid_size; + const size_t ps = pid_size; alloc_forward(pid_size + init_list.size()); newT(pid_data + pid_start + ps, init_list.begin(), init_list.size()); return *this; @@ -1718,7 +1736,7 @@ public: } #endif assert(&v != this); - size_t ps = pid_size; + const size_t ps = pid_size; alloc_forward(pid_size + v.pid_size); newT(pid_data + ps + pid_start, v.pid_data + v.pid_start, v.pid_size); return *this; @@ -1997,7 +2015,7 @@ public: //! \endcode //! \~\sa \a take_front(), \a pop_back(), \a pop_front() inline T take_back() { - T e(back()); + const T e(back()); pop_back(); return e; } @@ -2012,7 +2030,7 @@ public: //! \endcode //! \~\sa \a take_front(), \a pop_back(), \a pop_front() inline T take_front() { - T e(front()); + const T e(front()); pop_front(); return e; } @@ -2415,8 +2433,8 @@ public: inline PIDeque flatten(ReshapeOrder order = ReshapeByRow) const { PIDeque ret; if (isEmpty()) return ret; - size_t rows = size(); - size_t cols = at(0).size(); + const size_t rows = size(); + const size_t cols = at(0).size(); ret.reserve(rows * cols); if (order == ReshapeByRow) { for (size_t r = 0; r < rows; r++) { @@ -2487,11 +2505,11 @@ public: inline PIDeque> splitBySize(size_t sz) const { PIDeque> ret; if (isEmpty() || sz == 0) return ret; - size_t ch = pid_size / sz; + const size_t ch = pid_size / sz; for (size_t i = 0; i < ch; ++i) { ret << PIDeque(pid_data + pid_start + sz * i, sz); } - size_t t = ch * sz; + const size_t t = ch * sz; if (t < pid_size) { ret << PIDeque(pid_data + pid_start + t, pid_size - t); } @@ -2520,16 +2538,22 @@ public: if (index >= pid_size || count == 0) return ret; if (index + count > pid_size) count = pid_size - index; ret.alloc_forward(count); - memcpy((void *)(ret.pid_data + ret.pid_start), (const void *)(pid_data + pid_start + index), count * sizeof(T)); + memcpy(reinterpret_cast(ret.pid_data + ret.pid_start), + reinterpret_cast(pid_data + pid_start + index), + count * sizeof(T)); - size_t os = pid_size - index - count; + const size_t os = pid_size - index - count; if (os <= index) { if (os > 0) { - memmove((void *)(pid_data + pid_start + index), (const void *)(pid_data + pid_start + index + count), os * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start + index), + reinterpret_cast(pid_data + pid_start + index + count), + os * sizeof(T)); } } else { if (index > 0) { - memmove((void *)(pid_data + pid_start + count), (const void *)(pid_data + pid_start), index * sizeof(T)); + memmove(reinterpret_cast(pid_data + pid_start + count), + reinterpret_cast(pid_data + pid_start), + index * sizeof(T)); } pid_start += count; } @@ -2550,10 +2574,11 @@ private: if (pid_rsize * 2 >= size_t(s) && pid_rsize < size_t(s)) { return pid_rsize * 2; } - size_t t = _PIContainerConstants::minCountPoT(); - size_t s_ = s - 1; - while (s_ >> t) + size_t t = _PIContainerConstants::minCountPoT(); + s -= 1; + while (s >> t) { ++t; + } return (1 << t); } @@ -2568,7 +2593,7 @@ private: template::value, int>::type = 0> inline void newT(T * dst, const T * src, size_t s) { PIINTROSPECTION_CONTAINER_USED(T, s) - memcpy((void *)(dst), (const void *)(src), s * sizeof(T)); + memcpy(reinterpret_cast(dst), reinterpret_cast(src), s * sizeof(T)); } template::value, int>::type = 0> @@ -2616,7 +2641,7 @@ private: inline void dealloc() { if (pid_data != nullptr) { - free((void *)pid_data); + free(reinterpret_cast(pid_data)); pid_data = nullptr; } } @@ -2627,15 +2652,19 @@ private: if (pid_start < (pid_size * 2) || ssize_t(pid_start) > (ssize_t(pid_rsize) - (ssize_t(pid_size) * 2))) { size_t ns = (pid_rsize - pid_size) / 2; if (pid_start != ns) { - memmove((void *)(pid_data + ns), (const void *)(pid_data + pid_start), pid_size * sizeof(T)); + memmove(reinterpret_cast(pid_data + ns), + reinterpret_cast(pid_data + pid_start), + pid_size * sizeof(T)); pid_start = ns; } } } } else { - size_t ns = (pid_rsize - pid_size) / 2; + const size_t ns = (pid_rsize - pid_size) / 2; if (pid_start != ns) { - memmove((void *)(pid_data + ns), (const void *)(pid_data + pid_start), pid_size * sizeof(T)); + memmove(reinterpret_cast(pid_data + ns), + reinterpret_cast(pid_data + pid_start), + pid_size * sizeof(T)); pid_start = ns; } } @@ -2647,11 +2676,11 @@ private: if (pid_start > 0) checkMove(); return; } - pid_size = new_size; - size_t as = asize(pid_start + new_size); + pid_size = new_size; + const size_t as = asize(pid_start + new_size); if (as != pid_rsize) { PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize)) - T * p_d = (T *)(realloc((void *)(pid_data), as * sizeof(T))); + T * p_d = reinterpret_cast(realloc(reinterpret_cast(pid_data), as * sizeof(T))); #ifndef NDEBUG if (!p_d) { printf("error with PIDeque<%s>::alloc\n", __PIP_TYPENAME__(T)); @@ -2664,18 +2693,13 @@ private: } inline void alloc_backward(size_t new_size, ssize_t start_offset = 0) { - size_t as; - if (ssize_t(pid_start) + start_offset < 0) { - as = asize(pid_rsize - start_offset); - } else { - as = pid_rsize; - } + const size_t as = ssize_t(pid_start) + start_offset < 0 ? asize(pid_rsize - start_offset) : pid_rsize; if (as > pid_rsize) { - T * td = (T *)(malloc(as * sizeof(T))); - size_t ns = pid_start + as - pid_rsize; + T * td = reinterpret_cast(malloc(as * sizeof(T))); + const size_t ns = pid_start + as - pid_rsize; PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize)) if (pid_rsize > 0 && pid_data != 0) { - memcpy((void *)(td + ns), (const void *)(pid_data + pid_start), pid_size * sizeof(T)); + memcpy(reinterpret_cast(td + ns), reinterpret_cast(pid_data + pid_start), pid_size * sizeof(T)); dealloc(); } pid_data = td; @@ -2688,7 +2712,7 @@ private: } inline void expand(size_t new_size, const T & e = T()) { - size_t os = pid_size; + const size_t os = pid_size; alloc_forward(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size - os)) for (size_t i = os + pid_start; i < new_size + pid_start; ++i) { @@ -2697,7 +2721,7 @@ private: } inline void expand(size_t new_size, std::function f) { - size_t os = pid_size; + const size_t os = pid_size; alloc_forward(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size - os)) for (size_t i = os + pid_start; i < new_size + pid_start; ++i) { diff --git a/libs/main/containers/pimap.h b/libs/main/containers/pimap.h index e208e3a1..7cb8fa68 100644 --- a/libs/main/containers/pimap.h +++ b/libs/main/containers/pimap.h @@ -318,7 +318,7 @@ public: //! \~\sa \a insert(), \a value(), \a key() inline T & operator[](const Key & key) { bool f(false); - ssize_t i = _find(key, f); + const ssize_t i = _find(key, f); if (f) return pim_content[pim_index[i].index]; pim_content.push_back(T()); pim_index.insert(i, MapIndex(key, pim_content.size() - 1)); @@ -334,7 +334,7 @@ public: //! \~russian Удаляет элемент с ключом `key` из массива и возвращает его. inline T take(const Key & key, const T & default_ = T()) { bool f(false); - ssize_t i = _find(key, f); + const ssize_t i = _find(key, f); if (!f) return default_; T ret(pim_content[pim_index[i].index]); _remove(i); @@ -398,7 +398,7 @@ public: //! \~russian Удаляет элемент с ключом `key` из массива. inline PIMap & remove(const Key & key) { bool f(false); - ssize_t i = _find(key, f); + const ssize_t i = _find(key, f); if (f) _remove(i); return *this; } @@ -452,7 +452,7 @@ public: //! \~russian Если элемент с ключом `key` уже существует, то он будет перезаписан на значение `value`. inline PIMap & insert(const Key & key, const T & value) { bool f(false); - ssize_t i = _find(key, f); + const ssize_t i = _find(key, f); if (f) { pim_content[pim_index[i].index] = value; } else { @@ -464,7 +464,7 @@ public: inline PIMap & insert(const Key & key, T && value) { bool f(false); - ssize_t i = _find(key, f); + const ssize_t i = _find(key, f); if (f) { pim_content[pim_index[i].index] = std::move(value); } else { @@ -481,7 +481,7 @@ public: //! \~russian Первый элемент пары является ключом, а второй значением. inline PIMap & insert(const PIPair & pair) { bool f(false); - ssize_t i = _find(pair.first, f); + const ssize_t i = _find(pair.first, f); if (f) { pim_content[pim_index[i].index] = pair.second; } else { @@ -494,7 +494,7 @@ public: inline PIMap & insert(PIPair && pair) { bool f(false); Key k(std::move(pair.first)); - ssize_t i = _find(k, f); + const ssize_t i = _find(k, f); if (f) { pim_content[pim_index[i].index] = std::move(pair.second); } else { @@ -510,7 +510,7 @@ public: //! или `default_` если такого элемента нет. inline T value(const Key & key, const T & default_ = T()) const { bool f(false); - ssize_t i = _find(key, f); + const ssize_t i = _find(key, f); if (!f) return default_; return pim_content[pim_index[i].index]; } @@ -611,7 +611,7 @@ private: friend PIBinaryStream

& operator<<(PIBinaryStream

& s, const PIDeque::MapIndex> & v); inline ssize_t _binarySearch(ssize_t first, ssize_t last, const Key & key, bool & found) const { - ssize_t mid; + ssize_t mid = 0; while (first <= last) { mid = (first + last) / 2; if (key > pim_index[mid].key) @@ -636,7 +636,7 @@ private: } inline void _remove(ssize_t index) { - size_t ci = pim_index[index].index, bi = pim_index.size() - 1; + const size_t ci = pim_index[index].index, bi = pim_index.size() - 1; pim_index.remove(index); for (size_t i = 0; i < pim_index.size(); ++i) { if (pim_index[i].index == bi) { diff --git a/libs/main/containers/pipair.h b/libs/main/containers/pipair.h index d1cb18d8..cfdee8d7 100644 --- a/libs/main/containers/pipair.h +++ b/libs/main/containers/pipair.h @@ -54,11 +54,18 @@ public: //! \~english Constructs PIPair from [std::tuple](https://en.cppreference.com/w/cpp/utility/tuple). //! \~russian Создает PIPair из [std::tuple](https://ru.cppreference.com/w/cpp/utility/tuple). - PIPair(std::tuple tuple) { + explicit PIPair(std::tuple tuple) { first = std::get<0>(tuple); second = std::get<1>(tuple); } + //! \~english Constructs PIPair from [std::pair](https://en.cppreference.com/w/cpp/utility/pair). + //! \~russian Создает PIPair из [std::pair](https://ru.cppreference.com/w/cpp/utility/pair). + explicit PIPair(std::pair pair) { + first = pair.first; + second = pair.second; + } + //! \~english Constructs PIPair from values `value0` and `value1`. //! \~russian Создает PIPair из `value0` и `value1`. PIPair(const Type0 & value0, const Type1 & value1) { diff --git a/libs/main/containers/piset.h b/libs/main/containers/piset.h index aecd4e0f..cf126b3d 100644 --- a/libs/main/containers/piset.h +++ b/libs/main/containers/piset.h @@ -43,7 +43,7 @@ public: PISet() {} //! Contructs set with one element "value" - PISet(const T & value) { _CSet::insert(value, 0); } + explicit PISet(const T & value) { _CSet::insert(value, 0); } //! Contructs set with elements "v0" and "v1" PISet(const T & v0, const T & v1) { @@ -67,7 +67,7 @@ public: } //! Contructs set from vector of elements - PISet(const PIVector & values) { + explicit PISet(const PIVector & values) { if (values.isEmpty()) return; for (int i = 0; i < values.size_s(); ++i) { _CSet::insert(values[i], 0); @@ -75,7 +75,7 @@ public: } //! Contructs set from deque of elements - PISet(const PIDeque & values) { + explicit PISet(const PIDeque & values) { if (values.isEmpty()) return; for (int i = 0; i < values.size_s(); ++i) { _CSet::insert(values[i], 0); diff --git a/libs/main/containers/pivector.h b/libs/main/containers/pivector.h index d69397cf..910f6cc9 100644 --- a/libs/main/containers/pivector.h +++ b/libs/main/containers/pivector.h @@ -74,9 +74,9 @@ //! if the number of elements is known beforehand. //! //! The complexity (efficiency) of common operations on PIVector is as follows: -//! - Random access - constant 𝓞(1) -//! - Insertion or removal of elements at the end - amortized constant 𝓞(1) -//! - Insertion or removal of elements - linear in the distance to the end of the array 𝓞(n) +//! - Random access - constant O(1) +//! - Insertion or removal of elements at the end - amortized constant O(1) +//! - Insertion or removal of elements - linear in the distance to the end of the array O(n) //! //! \~russian //! Элементы хранятся непрерывно, а значит доступны не только через итераторы, @@ -109,9 +109,9 @@ //! если количество элементов известно заранее. //! //! Сложность (эффективность) обычных операций над PIVector следующая: -//! - Произвольный доступ — постоянная 𝓞(1) -//! - Вставка и удаление элементов в конце — амортизированная постоянная 𝓞(1) -//! - Вставка и удаление элементов — линейная по расстоянию до конца массива 𝓞(n) +//! - Произвольный доступ — постоянная O(1) +//! - Вставка и удаление элементов в конце — амортизированная постоянная O(1) +//! - Вставка и удаление элементов — линейная по расстоянию до конца массива O(n) //! //! \~\sa \a PIDeque, \a PIMap template @@ -164,7 +164,7 @@ public: //! \~english Contructs array with size `size` filled elements `e`. //! \~russian Создает массив из `size` элементов заполненных `e`. - inline PIVector(size_t size, const T & e = T()) { + inline explicit PIVector(size_t size, const T & e = T()) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) expand(size, e); } @@ -248,7 +248,7 @@ public: return *this; } inline iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -257,7 +257,7 @@ public: return *this; } inline iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -327,7 +327,7 @@ public: return *this; } inline const_iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -336,7 +336,7 @@ public: return *this; } inline const_iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -408,7 +408,7 @@ public: return *this; } inline reverse_iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -417,7 +417,7 @@ public: return *this; } inline reverse_iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -486,7 +486,7 @@ public: return *this; } inline const_reverse_iterator operator++(int) { - auto tmp = *this; + const auto tmp = *this; --*this; return tmp; } @@ -495,7 +495,7 @@ public: return *this; } inline const_reverse_iterator operator--(int) { - auto tmp = *this; + const auto tmp = *this; ++*this; return tmp; } @@ -725,7 +725,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a indexWhere() inline const T & atWhere(std::function test, ssize_t start = 0, const T & def = T()) const { - ssize_t i = indexWhere(test, start); + const ssize_t i = indexWhere(test, start); if (i < 0) return def; else @@ -739,7 +739,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a lastIndexWhere() inline const T & lastAtWhere(std::function test, ssize_t start = -1, const T & def = T()) const { - ssize_t i = lastIndexWhere(test, start); + const ssize_t i = lastIndexWhere(test, start); if (i < 0) return def; else @@ -1286,7 +1286,7 @@ public: //! \~\sa \a size(), \a capacity(), \a resize() inline PIVector & reserve(size_t new_size) { if (new_size <= piv_rsize) return *this; - size_t os = piv_size; + const size_t os = piv_size; alloc(new_size); piv_size = os; return *this; @@ -1306,8 +1306,8 @@ public: inline PIVector & insert(size_t index, const T & e = T()) { alloc(piv_size + 1); if (index < piv_size - 1) { - size_t os = piv_size - index - 1; - memmove((void *)(piv_data + index + 1), (const void *)(piv_data + index), os * sizeof(T)); + const size_t os = piv_size - index - 1; + memmove(reinterpret_cast(piv_data + index + 1), reinterpret_cast(piv_data + index), os * sizeof(T)); } PIINTROSPECTION_CONTAINER_USED(T, 1) elementNew(piv_data + index, e); @@ -1323,8 +1323,8 @@ public: inline PIVector & insert(size_t index, T && e) { alloc(piv_size + 1); if (index < piv_size - 1) { - size_t os = piv_size - index - 1; - memmove((void *)(piv_data + index + 1), (const void *)(piv_data + index), os * sizeof(T)); + const size_t os = piv_size - index - 1; + memmove(reinterpret_cast(piv_data + index + 1), reinterpret_cast(piv_data + index), os * sizeof(T)); } PIINTROSPECTION_CONTAINER_USED(T, 1) elementNew(piv_data + index, std::move(e)); @@ -1345,10 +1345,12 @@ public: } #endif assert(&v != this); - ssize_t os = piv_size - index; + const ssize_t os = piv_size - index; alloc(piv_size + v.piv_size); if (os > 0) { - memmove((void *)(piv_data + index + v.piv_size), (const void *)(piv_data + index), os * sizeof(T)); + memmove(reinterpret_cast(piv_data + index + v.piv_size), + reinterpret_cast(piv_data + index), + os * sizeof(T)); } newT(piv_data + index, v.piv_data, v.piv_size); return *this; @@ -1366,10 +1368,12 @@ public: //! \~\sa \a append(), \a prepend(), \a remove() inline PIVector & insert(size_t index, std::initializer_list init_list) { if (init_list.size() == 0) return *this; - ssize_t os = piv_size - index; + const ssize_t os = piv_size - index; alloc(piv_size + init_list.size()); if (os > 0) { - memmove((void *)(piv_data + index + init_list.size()), (const void *)(piv_data + index), os * sizeof(T)); + memmove(reinterpret_cast(piv_data + index + init_list.size()), + reinterpret_cast(piv_data + index), + os * sizeof(T)); } newT(piv_data + index, init_list.begin(), init_list.size()); return *this; @@ -1392,9 +1396,9 @@ public: piv_size = index; } } else { - size_t os = piv_size - index - count; + const size_t os = piv_size - index - count; deleteT(piv_data + index, count); - memmove((void *)(piv_data + index), (const void *)(piv_data + index + count), os * sizeof(T)); + memmove(reinterpret_cast(piv_data + index), reinterpret_cast(piv_data + index + count), os * sizeof(T)); piv_size -= count; } return *this; @@ -1483,7 +1487,7 @@ public: //! \endcode //! \~\sa \a reversed() inline PIVector & reverse() { - size_t s2 = piv_size / 2; + const size_t s2 = piv_size / 2; for (size_t i = 0; i < s2; ++i) { piSwap(piv_data[i], piv_data[piv_size - i - 1]); } @@ -1514,7 +1518,7 @@ public: //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. //! \~\sa \a resize() inline PIVector & enlarge(ssize_t add_size, const T & e = T()) { - ssize_t ns = size_s() + add_size; + const ssize_t ns = size_s() + add_size; if (ns <= 0) clear(); else @@ -1637,7 +1641,7 @@ public: //! \~\sa \a push_back() inline PIVector & push_back(std::initializer_list init_list) { if (init_list.size() == 0) return *this; - size_t ps = piv_size; + const size_t ps = piv_size; alloc(piv_size + init_list.size()); newT(piv_data + ps, init_list.begin(), init_list.size()); return *this; @@ -1657,7 +1661,7 @@ public: } #endif assert(&v != this); - size_t ps = piv_size; + const size_t ps = piv_size; alloc(piv_size + v.piv_size); newT(piv_data + ps, v.piv_data, v.piv_size); return *this; @@ -1909,7 +1913,7 @@ public: //! \endcode //! \~\sa \a take_front(), \a pop_back(), \a pop_front() inline T take_back() { - T e(back()); + const T e(back()); pop_back(); return e; } @@ -1924,7 +1928,7 @@ public: //! \endcode //! \~\sa \a take_front(), \a pop_back(), \a pop_front() inline T take_front() { - T e(front()); + const T e(front()); pop_front(); return e; } @@ -2327,8 +2331,8 @@ public: inline PIVector flatten(ReshapeOrder order = ReshapeByRow) const { PIVector ret; if (isEmpty()) return ret; - size_t rows = size(); - size_t cols = at(0).size(); + const size_t rows = size(); + const size_t cols = at(0).size(); ret.reserve(rows * cols); if (order == ReshapeByRow) { for (size_t r = 0; r < rows; r++) { @@ -2399,11 +2403,11 @@ public: inline PIVector> splitBySize(size_t sz) const { PIVector> ret; if (isEmpty() || sz == 0) return ret; - size_t ch = piv_size / sz; + const size_t ch = piv_size / sz; for (size_t i = 0; i < ch; ++i) { ret << PIVector(piv_data + sz * i, sz); } - size_t t = ch * sz; + const size_t t = ch * sz; if (t < piv_size) { ret << PIVector(piv_data + t, piv_size - t); } @@ -2431,10 +2435,10 @@ public: if (index >= piv_size || count == 0) return ret; if (index + count > piv_size) count = piv_size - index; ret.alloc(count); - memcpy((void *)ret.piv_data, (const void *)(piv_data + index), count * sizeof(T)); - size_t os = piv_size - index - count; + memcpy(reinterpret_cast(ret.piv_data), reinterpret_cast(piv_data + index), count * sizeof(T)); + const size_t os = piv_size - index - count; if (os > 0) { - memmove((void *)(piv_data + index), (const void *)(piv_data + index + count), os * sizeof(T)); + memmove(reinterpret_cast(piv_data + index), reinterpret_cast(piv_data + index + count), os * sizeof(T)); piv_size -= count; } else { piv_size = index; @@ -2454,8 +2458,9 @@ private: if (piv_rsize * 2 >= s && piv_rsize < s) { return piv_rsize * 2; } - ssize_t t = _PIContainerConstants::minCountPoT(), s_ = s - 1; - while (s_ >> t) + ssize_t t = _PIContainerConstants::minCountPoT(); + s -= 1; + while (s >> t) ++t; return (1 << t); } @@ -2471,7 +2476,7 @@ private: template::value, int>::type = 0> inline void newT(T * dst, const T * src, size_t s) { PIINTROSPECTION_CONTAINER_USED(T, s) - memcpy((void *)(dst), (const void *)(src), s * sizeof(T)); + memcpy(reinterpret_cast(dst), reinterpret_cast(src), s * sizeof(T)); } template::value, int>::type = 0> @@ -2519,13 +2524,13 @@ private: inline void dealloc() { if (piv_data != nullptr) { - free((void *)piv_data); + free(reinterpret_cast(piv_data)); piv_data = nullptr; } } inline void expand(size_t new_size, const T & e = T()) { - size_t os = piv_size; + const size_t os = piv_size; alloc(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size - os)) for (size_t i = os; i < new_size; ++i) { @@ -2534,7 +2539,7 @@ private: } inline void expand(size_t new_size, std::function f) { - size_t os = piv_size; + const size_t os = piv_size; alloc(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size - os)) for (size_t i = os; i < new_size; ++i) { @@ -2547,11 +2552,11 @@ private: piv_size = new_size; return; } - piv_size = new_size; - size_t as = asize(new_size); + piv_size = new_size; + const size_t as = asize(new_size); if (as == piv_rsize) return; PIINTROSPECTION_CONTAINER_ALLOC(T, (as - piv_rsize)) - T * p_d = (T *)(realloc((void *)(piv_data), as * sizeof(T))); + T * p_d = reinterpret_cast(realloc(reinterpret_cast(piv_data), as * sizeof(T))); #ifndef NDEBUG if (!p_d) { printf("error with PIVector<%s>::alloc\n", __PIP_TYPENAME__(T)); diff --git a/libs/main/containers/pivector2d.h b/libs/main/containers/pivector2d.h index 7695b2f6..85524325 100644 --- a/libs/main/containers/pivector2d.h +++ b/libs/main/containers/pivector2d.h @@ -98,12 +98,12 @@ public: inline const T * data(size_t index = 0) const { return p_->data(st_ + index); } inline Row & operator=(const Row & other) { if (p_ == other.p_ && st_ == other.st_) return *this; - size_t sz = piMin(sz_, other.sz_); + const size_t sz = piMin(sz_, other.sz_); p_->_copyRaw(p_->data(st_), other.data(), sz); return *this; } inline Row & operator=(const PIVector & other) { - size_t sz = piMin(sz, other.size()); + const size_t sz = piMin(sz, other.size()); p_->_copyRaw(p_->data(st_), other.data(), sz); return *this; } @@ -130,13 +130,13 @@ public: inline const T * data(size_t index = 0) const { return p_->data(index * step_ + row_); } inline Col & operator=(const Col & other) { if (p_ == other.p_ && row_ == other.row_) return *this; - size_t sz = piMin(sz_, other.sz_); + const size_t sz = piMin(sz_, other.sz_); for (int i = 0; i < sz; ++i) (*p_)[i * step_ + row_] = other[i]; return *this; } inline Row & operator=(const PIVector & other) { - size_t sz = piMin(sz_, other.size()); + const size_t sz = piMin(sz_, other.size()); for (int i = 0; i < sz; ++i) (*p_)[i * step_ + row_] = other[i]; return *this; @@ -206,24 +206,24 @@ public: inline Col col(size_t index) { return Col(this, index); } inline ColConst col(size_t index) const { return ColConst(this, index); } inline PIVector2D & setRow(size_t row, const Row & other) { - size_t sz = piMin(cols_, other.sz_); + const size_t sz = piMin(cols_, other.sz_); mat._copyRaw(mat.data(cols_ * row), other.data(), sz); return *this; } inline PIVector2D & setRow(size_t row, const RowConst & other) { - size_t sz = piMin(cols_, other.sz_); + const size_t sz = piMin(cols_, other.sz_); mat._copyRaw(mat.data(cols_ * row), other.data(), sz); return *this; } inline PIVector2D & setRow(size_t row, const PIVector & other) { - size_t sz = piMin(cols_, other.size()); + const size_t sz = piMin(cols_, other.size()); mat._copyRaw(mat.data(cols_ * row), other.data(), sz); return *this; } inline PIVector2D & addRow(const Row & other) { if (cols_ == 0) cols_ = other.sz_; - size_t sz = piMin(cols_, other.sz_); - size_t ps = mat.size(); + const size_t sz = piMin(cols_, other.sz_); + const size_t ps = mat.size(); mat.resize(mat.size() + cols_); mat._copyRaw(mat.data(ps), other.data(), sz); rows_++; @@ -231,8 +231,8 @@ public: } inline PIVector2D & addRow(const RowConst & other) { if (cols_ == 0) cols_ = other.sz_; - size_t sz = piMin(cols_, other.sz_); - size_t ps = mat.size(); + const size_t sz = piMin(cols_, other.sz_); + const size_t ps = mat.size(); mat.resize(mat.size() + cols_); mat._copyRaw(mat.data(ps), other.data(), sz); rows_++; @@ -240,8 +240,8 @@ public: } inline PIVector2D & addRow(const PIVector & other) { if (cols_ == 0) cols_ = other.size(); - size_t sz = piMin(cols_, other.size()); - size_t ps = mat.size(); + const size_t sz = piMin(cols_, other.size()); + const size_t ps = mat.size(); mat.resize(mat.size() + cols_); mat._copyRaw(mat.data(ps), other.data(), sz); rows_++; @@ -250,8 +250,8 @@ public: inline PIVector2D & resize(size_t rows, size_t cols, const T & f = T()) { mat.resize(rows * cols_, f); - rows_ = rows; - int cs = (cols - cols_); + rows_ = rows; + const int cs = (cols - cols_); if (cs < 0) { for (size_t r = 0; r < rows; ++r) { mat.remove(r * cols + cols, -cs); diff --git a/libs/main/types/pibytearray.cpp b/libs/main/types/pibytearray.cpp index eab6793d..d88d1459 100644 --- a/libs/main/types/pibytearray.cpp +++ b/libs/main/types/pibytearray.cpp @@ -143,7 +143,8 @@ PIByteArray PIByteArray::toBase64() const { if (isEmpty()) return PIByteArray(); base64HelpStruct hs; PIByteArray ret; - int sz = (size_s() / 3) * 3, ri = -1; + const int sz = (size_s() / 3) * 3; + int ri = -1; uchar t[4]; ret.resize(((size_s() - 1) / 3 + 1) * 4); for (int i = 0; i < sz; i += 3) { @@ -154,7 +155,7 @@ PIByteArray PIByteArray::toBase64() const { ret[++ri] = (t[2]); ret[++ri] = (t[3]); } - int der = size_s() % 3; + const int der = size_s() % 3; switch (der) { case 1: hs.setBytes(data(sz), 1); @@ -182,7 +183,8 @@ PIByteArray PIByteArray::fromBase64(const PIByteArray & base64) { if (base64.isEmpty()) return PIByteArray(); base64HelpStruct hs; PIByteArray ret; - int sz = base64.size_s(), ind = -1; + const int sz = base64.size_s(); + int ind = -1; uchar t[4]; ret.resize(sz / 4 * 3); for (int i = 0; i < sz; i += 4) { @@ -206,7 +208,9 @@ PIByteArray PIByteArray::fromBase64(const PIString & base64) { PIByteArray & PIByteArray::compressRLE(uchar threshold) { PIByteArray t; - uchar fb, clen, mlen = 255 - threshold; + uchar fb; + uchar clen; + const uchar mlen = 255 - threshold; for (uint i = 0; i < size();) { fb = at(i); clen = 1; @@ -232,7 +236,8 @@ PIByteArray & PIByteArray::compressRLE(uchar threshold) { PIByteArray & PIByteArray::decompressRLE(uchar threshold) { PIByteArray t; - uchar fb, clen; + uchar fb; + uchar clen; for (uint i = 0; i < size(); ++i) { fb = at(i); if (fb >= threshold) { @@ -263,8 +268,8 @@ PIByteArray & PIByteArray::decompressRLE(uchar threshold) { //! else return sum; //! \endcode uchar PIByteArray::checksumPlain8(bool inverse) const { - uchar c = 0; - int sz = size_s(); + uchar c = 0; + const int sz = size_s(); for (int i = 0; i < sz; ++i) c += at(i); if (inverse) c = ~(c + 1); @@ -299,8 +304,8 @@ uint PIByteArray::checksumCRC32() const { //! else return sum; //! \endcode uint PIByteArray::checksumPlain32(bool inverse) const { - uint c = 0; - int sz = size_s(); + uint c = 0; + const int sz = size_s(); for (int i = 0; i < sz; ++i) c += at(i) * (i + 1); if (inverse) c = ~(c + 1); @@ -315,7 +320,7 @@ uint PIByteArray::hash() const { PIString PIByteArray::toString(int base) const { PIString ret; - int sz = size_s(); + const int sz = size_s(); for (int i = 0; i < sz; ++i) { if (i > 0) ret += " "; if (base == 2) ret += "b"; @@ -351,10 +356,10 @@ PIByteArray PIByteArray::fromUserInput(PIString str) { PIByteArray ret; if (str.trim().isEmpty()) return ret; str.replaceAll("\n", " ").replaceAll("\t", " ").replaceAll(" ", " "); - PIStringList bl(str.split(" ")); + const PIStringList bl(str.split(" ")); bool ok(false); - piForeachC(PIString & b, bl) { - int bv = b.toInt(-1, &ok); + for (const auto & b: bl) { + const int bv = b.toInt(-1, &ok); if (ok) ret << uchar(bv); } return ret; @@ -362,7 +367,7 @@ PIByteArray PIByteArray::fromUserInput(PIString str) { PIByteArray PIByteArray::fromHex(PIString str) { - PIByteArray hexEncoded = str.toByteArray(); + const PIByteArray hexEncoded = str.toByteArray(); PIByteArray res((hexEncoded.size() + 1) / 2); uchar * result = res.data() + res.size(); bool odd_digit = true; diff --git a/libs/main/types/pibytearray.h b/libs/main/types/pibytearray.h index 94ff84cd..f7f434aa 100644 --- a/libs/main/types/pibytearray.h +++ b/libs/main/types/pibytearray.h @@ -53,14 +53,14 @@ public: //! \~english Constructs copy of byte array "o" //! \~russian Создает копию байтового массива "o" - PIByteArray(const PIDeque & o): d(o) {} + explicit PIByteArray(const PIDeque & o): d(o) {} PIByteArray(PIByteArray && o): d(std::move(o.d)) {} PIByteArray(PIDeque && o): d(std::move(o)) {} //! \~english Constructs 0-filled byte array with size "size" //! \~russian Создает заполненный "0" байтовый массив размером "size" - PIByteArray(const uint size) { resize(size); } + explicit PIByteArray(const uint size) { resize(size); } //! \~english Constructs byte array from data "data" and size "size" //! \~russian Создает байтовый массив из данных по указателю "data" размером "size" @@ -784,7 +784,7 @@ public: //! \~english Add to the end data "data" with size "size" //! \~russian Добавляет в конец массива данные по указателю "data" размером "size" PIByteArray & push_back(const void * data_, int size_) { - uint ps = size(); + const uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this; @@ -1083,7 +1083,7 @@ public: //! \~english Add to the end data "data" with size "size" //! \~russian Добавляет в конец массива данные по указателю "data" размером "size" PIByteArray & append(const void * data_, int size_) { - uint ps = size(); + const uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this; @@ -1092,7 +1092,7 @@ public: //! \~english Add to the end byte array "data" //! \~russian Добавляет в конец массива содержимое массива "data" PIByteArray & append(const PIByteArray & data_) { - uint ps = size(); + const uint ps = size(); enlarge(data_.size_s()); memcpy(data(ps), data_.data(), data_.size()); return *this; @@ -1176,8 +1176,7 @@ public: return true; } bool binaryStreamTakeImp(void * d_, size_t s) { - size_t rs = size(); - if (rs > s) rs = s; + const size_t rs = s < size() ? s : size(); memcpy(d_, data(), rs); remove(0, rs); return rs == s; From 8ad2503c5add08b643dfda41c6a5759044333ef3 Mon Sep 17 00:00:00 2001 From: Andrey Bychkov Date: Thu, 6 Jul 2023 18:37:42 +0300 Subject: [PATCH 2/3] pichar and pistring explicit test --- libs/main/core/picli.h | 2 +- libs/main/io_devices/piusb.h | 4 ++-- libs/main/text/pichar.h | 24 ++++++++++----------- libs/main/text/pistring.h | 17 ++++----------- tests/core/pistringTest.cpp | 42 ++++++++++++++++++------------------ utils/deploy_tool/main.cpp | 9 ++++---- 6 files changed, 44 insertions(+), 54 deletions(-) diff --git a/libs/main/core/picli.h b/libs/main/core/picli.h index 4bb0073c..5a71db20 100644 --- a/libs/main/core/picli.h +++ b/libs/main/core/picli.h @@ -135,7 +135,7 @@ public: //! \~russian Возвращает короткий ключ аргумента "name" или пустую строку, если аргумента нет. PIString argumentShortKey(const PIString & name) { piForeach(Argument & i, _args) - if (i.name == name) return i.short_key; + if (i.name == name) return PIString(i.short_key); return PIString(); } diff --git a/libs/main/io_devices/piusb.h b/libs/main/io_devices/piusb.h index c80a059b..839f2382 100644 --- a/libs/main/io_devices/piusb.h +++ b/libs/main/io_devices/piusb.h @@ -175,11 +175,11 @@ public: void setVendorID(ushort vid) { vid_ = vid; - setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, "0") + ":" + PIString::fromNumber(pid_, 16).expandLeftTo(4, "0")); + setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, '0') + ':' + PIString::fromNumber(pid_, 16).expandLeftTo(4, '0')); } void setProductID(ushort pid) { pid_ = pid; - setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, "0") + ":" + PIString::fromNumber(pid_, 16).expandLeftTo(4, "0")); + setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, '0') + ':' + PIString::fromNumber(pid_, 16).expandLeftTo(4, '0')); } bool setConfiguration(uchar value); diff --git a/libs/main/text/pichar.h b/libs/main/text/pichar.h index 22977c2f..2d39742a 100644 --- a/libs/main/text/pichar.h +++ b/libs/main/text/pichar.h @@ -59,7 +59,7 @@ public: //! \~english Contructs symbol from system locale and no more than 4 bytes of string //! \~russian Создает символ из системной локали не более 4 байт длины - PIChar(const char * c, int * bytes = 0); + explicit PIChar(const char * c, int * bytes = 0); //! \~english Copy operator //! \~russian Оператор присваивания @@ -81,7 +81,7 @@ public: //! \~english Compare operator //! \~russian Оператор сравнения - bool operator!=(const PIChar & o) const { return !(o == *this); } + bool operator!=(const PIChar & o) const { return !(*this == o); } //! \~english Compare operator //! \~russian Оператор сравнения @@ -265,36 +265,36 @@ inline bool operator<=(const char * v, const PIChar & c) { //! \relatesalso PIChar //! \~english Compare operator //! \~russian Оператор сравнения -inline bool operator==(const int v, const PIChar & c) { - return (PIChar((ushort)v) == c); +inline bool operator==(ushort 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); +inline bool operator>(ushort 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); +inline bool operator<(ushort 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); +inline bool operator>=(ushort 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); +inline bool operator<=(ushort v, const PIChar & c) { + return (PIChar(v) <= c); } #endif // PICHAR_H diff --git a/libs/main/text/pistring.h b/libs/main/text/pistring.h index 2a3f7d28..e81fa4d1 100644 --- a/libs/main/text/pistring.h +++ b/libs/main/text/pistring.h @@ -113,11 +113,11 @@ public: //! \~english Contructs string with single character "c". //! \~russian Создает строку из одного символа "c". - PIString(const PIChar c) { d.push_back(c); } + explicit 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)); } + explicit PIString(const char c) { d.push_back(PIChar(c)); } //! \~english Contructs string from C-string "str" (system codepage). //! \~russian Создает строку из C-строки "str" (кодировка системы). @@ -145,7 +145,7 @@ public: //! \~english Contructs string from byte array "ba" (as UTF-8). //! \~russian Создает строку из байтового массива "ba" (как UTF-8). - PIString(const PIByteArray & ba) { *this += ba; } + explicit PIString(const PIByteArray & ba) { *this += ba; } //! \~english Contructs string from "len" characters of buffer "str". //! \~russian Создает строку из "len" символов массива "str". @@ -181,7 +181,7 @@ public: d.push_back(c); } - PIString(const PIConstChars & c) { *this += c; } + explicit PIString(const PIConstChars & c) { *this += c; } ~PIString(); @@ -1184,15 +1184,6 @@ public: //! \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; diff --git a/tests/core/pistringTest.cpp b/tests/core/pistringTest.cpp index 4597c157..981e373b 100644 --- a/tests/core/pistringTest.cpp +++ b/tests/core/pistringTest.cpp @@ -12,7 +12,7 @@ TEST(PIString_Tests, constructor_empty) { TEST(PIString_Tests, operator_concatenation_pichar) { PIString str1 = "AB C"; - const PIChar str2 = " "; + const PIChar str2 = ' '; str1 += str2; PIString res = "AB C "; ASSERT_EQ(str1, res); @@ -20,7 +20,7 @@ TEST(PIString_Tests, operator_concatenation_pichar) { TEST(PIString_Tests, operator_concatenation_pichar_zero1) { PIString str1 = ""; - const PIChar str2 = "D"; + const PIChar str2 = 'D'; str1 += str2; ASSERT_EQ(str1, "D"); } @@ -120,7 +120,7 @@ TEST(PIString_Tests, construct_pistring) { TEST(PIString_Tests, construct_pistring_move) { PIString str1 = "New"; PIString res = str1; - PIString str(move(str1)); + PIString str(std::move(str1)); ASSERT_EQ(res, str); } @@ -192,14 +192,14 @@ TEST(PIString_Tests, operator_assignment) { TEST(PIString_Tests, operator_assignment_move) { PIString str1 = "testing"; PIString str; - str = move(str1); + str = std::move(str1); ASSERT_EQ(PIString("testing"), str); ASSERT_TRUE(str1.isEmpty()); } TEST(PIString_Tests, operator_symbol) { PIString str1 = "testing"; - PIChar symbo = "i"; + PIChar symbo = 'i'; ASSERT_EQ(symbo, str1[4]); } @@ -217,13 +217,13 @@ TEST(PIString_Tests, operator_equal_pistring_false) { TEST(PIString_Tests, operator_equal_pichar_true) { PIString str1 = "t"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_TRUE(str1 == str2); } TEST(PIString_Tests, operator_equal_pichar_false) { PIString str1 = "t"; - PIChar str2 = "p"; + PIChar str2 = 'p'; ASSERT_FALSE(str1 == str2); } @@ -253,13 +253,13 @@ TEST(PIString_Tests, operator_not_equal_pistring_true) { TEST(PIString_Tests, operator_not_equal_pichar_false) { PIString str1 = "t"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_FALSE(str1 != str2); } TEST(PIString_Tests, operator_not_equal_pichar_true) { PIString str1 = "t"; - PIChar str2 = "p"; + PIChar str2 = 'p'; ASSERT_TRUE(str1 != str2); } @@ -295,19 +295,19 @@ TEST(PIString_Tests, operator_less_pistring_false_equal) { TEST(PIString_Tests, operator_less_pichar_true) { PIString str1 = "a"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_TRUE(str1 < str2); } TEST(PIString_Tests, operator_less_pichar_false) { PIString str1 = "t"; - PIChar str2 = "a"; + PIChar str2 = 'a'; ASSERT_FALSE(str1 < str2); } TEST(PIString_Tests, operator_less_pichar_false_equal) { PIString str1 = "t"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_FALSE(str1 < str2); } @@ -349,19 +349,19 @@ TEST(PIString_Tests, operator_grater_pistring_false_equal) { TEST(PIString_Tests, operator_grater_pichar_true) { PIString str1 = "t"; - PIChar str2 = "a"; + PIChar str2 = 'a'; ASSERT_TRUE(str1 > str2); } TEST(PIString_Tests, operator_grater_pichar_false) { PIString str1 = "a"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_FALSE(str1 > str2); } TEST(PIString_Tests, operator_grater_pichar_false_equal) { PIString str1 = "t"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_FALSE(str1 > str2); } @@ -403,19 +403,19 @@ TEST(PIString_Tests, operator_less_eq_pistring_true_equal) { TEST(PIString_Tests, operator_less_eq_pichar_true) { PIString str1 = "a"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_TRUE(str1 <= str2); } TEST(PIString_Tests, operator_less_eq_pichar_false) { PIString str1 = "t"; - PIChar str2 = "a"; + PIChar str2 = 'a'; ASSERT_FALSE(str1 <= str2); } TEST(PIString_Tests, operator_less_eq_pichar_true_equal) { PIString str1 = "t"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_TRUE(str1 <= str2); } @@ -457,19 +457,19 @@ TEST(PIString_Tests, operator_grater_eq_pistring_true_equal) { TEST(PIString_Tests, operator_grater_eq_pichar_true) { PIString str1 = "t"; - PIChar str2 = "a"; + PIChar str2 = 'a'; ASSERT_TRUE(str1 >= str2); } TEST(PIString_Tests, operator_grater_eq_pichar_false) { PIString str1 = "a"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_FALSE(str1 >= str2); } TEST(PIString_Tests, operator_grater_eq_pichar_true_equal) { PIString str1 = "t"; - PIChar str2 = "t"; + PIChar str2 = 't'; ASSERT_TRUE(str1 >= str2); } diff --git a/utils/deploy_tool/main.cpp b/utils/deploy_tool/main.cpp index afa4421b..4a5e2c07 100644 --- a/utils/deploy_tool/main.cpp +++ b/utils/deploy_tool/main.cpp @@ -20,7 +20,6 @@ #include "picli.h" #include "pidir.h" #include "piiostream.h" -#include "piprocess.h" #define DELIM "::" @@ -251,7 +250,7 @@ void checkQtLib(PIString lib) { for (int i = 0;; ++i) { if (qt_deps[i].lib.isEmpty()) break; if (qt_deps[i].lib == base) { - qt_plugins << qt_deps[i].plugins; + qt_plugins << PISet(qt_deps[i].plugins); // piCout << "add qt plugins" << qt_deps[i].plugins << "now" << qt_plugins; need_qt = true; qt_libs << lib; @@ -269,8 +268,8 @@ void checkQtLib(PIString lib) { void procLdd(PIString file, bool ext_lib = false, int cur_depth = 0) { ++cur_depth; if (cur_depth > depth) return; - static PIStringList ignore_ext = {"png", "jpg", "jpeg", "gif", "bmp", "svg", "tif", "tiff", "ico", "pdf", - "txt", "cfg", "conf", "json", "qml", "glsl", "fraq", "vert", "geom", "qmltypes", + static PIStringList ignore_ext = {"png", "jpg", "jpeg", "gif", "bmp", "svg", "tif", "tiff", "ico", "pdf", + "txt", "cfg", "conf", "json", "qml", "glsl", "fraq", "vert", "geom", "qmltypes", "metainfo", "ts", "qm", "ttf", "htm", "html", "md", "sms", "smsee", "blockmodel"}; PIString ext = PIFile::FileInfo(file).extension(); if (ignore_ext.contains(ext.toLowerCase())) return; @@ -615,7 +614,7 @@ int main(int argc, char * argv[]) { out_dir = cli.argumentValue("output"); lib_dirs = cli.argumentValue("search_path").split(DELIM); add_libs = cli.argumentValue("add_libs").split(DELIM); - ignore_libs = cli.argumentValue("ignore").split(DELIM); + ignore_libs = PISet(cli.argumentValue("ignore").split(DELIM)); qt_dir = cli.argumentValue("qtdir"); ldd = cli.argumentValue("ldd"); readelf = cli.argumentValue("Lreadelf"); From 61f1a34c14f1588628154187aae9f1668465a6f9 Mon Sep 17 00:00:00 2001 From: peri4 Date: Thu, 6 Jul 2023 19:59:26 +0300 Subject: [PATCH 3/3] PIString/PIChar explicit, support char16_t --- libs/crypt/piauth.cpp | 2 +- libs/main/core/picli.h | 4 +- libs/main/text/pichar.cpp | 19 +++++---- libs/main/text/pichar.h | 47 ++++----------------- libs/main/text/pistring.cpp | 38 ++++++++++++++--- libs/main/text/pistring.h | 74 +++++++++++++++++++++++++++++---- libs/main/text/pistring_std.h | 9 ++-- libs/main/types/pibytearray.cpp | 2 +- libs/opencl/piopencl.cpp | 2 +- main_picloud_test.cpp | 4 +- utils/crypt_tool/main.cpp | 4 +- 11 files changed, 132 insertions(+), 73 deletions(-) diff --git a/libs/crypt/piauth.cpp b/libs/crypt/piauth.cpp index f5643f24..8ce5f329 100644 --- a/libs/crypt/piauth.cpp +++ b/libs/crypt/piauth.cpp @@ -238,7 +238,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) { rinfo = crypt.decrypt(rinfo, secret_key, &ok); if (!ok) return disconnect(ba, "Error while exchange keys"); state = Connected; - connected(rinfo); + connected(PIString::fromUTF8(rinfo)); ba << (int)state << crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE); return state; } diff --git a/libs/main/core/picli.h b/libs/main/core/picli.h index 5a71db20..19325ab1 100644 --- a/libs/main/core/picli.h +++ b/libs/main/core/picli.h @@ -57,7 +57,7 @@ public: //! \~english Add argument with name "name", short key = "shortKey" and full key = name. //! \~russian Добавляет аргумент с именем "name", коротким ключом = "shortKey" и полным ключом = имени. void addArgument(const PIString & name, const char * shortKey, bool value = false) { - _args << Argument(name, PIChar(shortKey), name, value); + _args << Argument(name, PIChar::fromUTF8(shortKey), name, value); needParse = true; } @@ -71,7 +71,7 @@ public: //! \~english Add argument with name "name", short key = "shortKey" and full key = "fullKey". //! \~russian Добавляет аргумент с именем "name", коротким ключом = "shortKey" и полным ключом = "fullKey". void addArgument(const PIString & name, const char * shortKey, const PIString & fullKey, bool value = false) { - _args << Argument(name, PIChar(shortKey), fullKey, value); + _args << Argument(name, PIChar::fromUTF8(shortKey), fullKey, value); needParse = true; } diff --git a/libs/main/text/pichar.cpp b/libs/main/text/pichar.cpp index 64eef9de..ac75b930 100644 --- a/libs/main/text/pichar.cpp +++ b/libs/main/text/pichar.cpp @@ -90,7 +90,7 @@ 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, 0); + u_strCompare((const UChar *)f.toWCharPtr(), 1, (const UChar *)s.toWCharPtr(), 1, 0); #else # ifdef WINDOWS CompareStringW(LOCALE_USER_DEFAULT, 0, (PCNZWCH)f.toWCharPtr(), 1, (PCNZWCH)s.toWCharPtr(), 1) - 2; @@ -111,11 +111,6 @@ bool winIsCharType(const ushort * ch, int type) { } -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__); @@ -130,10 +125,20 @@ PIChar PIChar::fromSystem(char c) { } +PIChar PIChar::fromSystem(const char * c) { + PIChar ret; + int l = 0; + while (c[l] != '\0' && l < 4) + ++l; + ret.ch = charFromCodepage(c, l, __syslocname__); + return ret; +} + + PIChar PIChar::fromUTF8(const char * c) { PIChar ret; int l = 0; - while (c[l] != '\0') + while (c[l] != '\0' && l < 4) ++l; ret.ch = charFromCodepage(c, l, __utf8name__); return ret; diff --git a/libs/main/text/pichar.h b/libs/main/text/pichar.h index 2d39742a..0fe96237 100644 --- a/libs/main/text/pichar.h +++ b/libs/main/text/pichar.h @@ -57,9 +57,9 @@ public: //! \~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 байт длины - explicit PIChar(const char * c, int * bytes = 0); + //! \~english Contructs 2-bytes symbol from `char16_t` + //! \~russian Создает 2-байтный символ из `char16_t` + PIChar(char16_t c) { ch = c; } //! \~english Copy operator //! \~russian Оператор присваивания @@ -177,6 +177,10 @@ public: //! \~russian Возвращает символ из системной кодировки static PIChar fromSystem(char c); + //! \~english Returns symbol from system codepage + //! \~russian Возвращает символ из системной кодировки + static PIChar fromSystem(const char * c); + //! \~english Returns symbol from UTF8 codepage //! \~russian Возвращает символ из UTF8 кодировки static PIChar fromUTF8(const char * c); @@ -225,43 +229,6 @@ 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 Оператор сравнения diff --git a/libs/main/text/pistring.cpp b/libs/main/text/pistring.cpp index 715c50df..09fc76eb 100644 --- a/libs/main/text/pistring.cpp +++ b/libs/main/text/pistring.cpp @@ -404,6 +404,16 @@ PIString PIString::fromAscii(const char * s, int len) { } +PIString PIString::fromAscii(const PIByteArray & ascii) { + PIString ret; + ret.resize(ascii.size()); + for (int l = 0; l < ret.size_s(); ++l) { + ret[l] = PIChar(ascii[l]); + } + return ret; +} + + PIString PIString::fromCodepage(const char * s, const char * c) { PIString ret; if (s[0] > '\0') @@ -572,12 +582,6 @@ PIString & PIString::operator+=(const char * str) { } -PIString & PIString::operator+=(const PIByteArray & ba) { - appendFromChars((const char *)ba.data(), ba.size_s(), __utf8name__); - return *this; -} - - PIString::~PIString() { deleteData(); } @@ -593,6 +597,16 @@ PIString & PIString::operator+=(const wchar_t * str) { } +PIString & PIString::operator+=(const char16_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; @@ -1161,12 +1175,24 @@ int PIString::entries(const PIChar c) const { } +bool PIString::startsWith(const PIChar c) const { + if (isEmpty()) return false; + return front() == c; +} + + bool PIString::startsWith(const PIString & str) const { if (size() < str.size()) return false; return str == left(str.size()); } +bool PIString::endsWith(const PIChar c) const { + if (isEmpty()) return false; + return back() == c; +} + + bool PIString::endsWith(const PIString & str) const { if (size() < str.size()) return false; return str == right(str.size()); diff --git a/libs/main/text/pistring.h b/libs/main/text/pistring.h index e81fa4d1..c9494b1a 100644 --- a/libs/main/text/pistring.h +++ b/libs/main/text/pistring.h @@ -79,7 +79,7 @@ public: } PIString & operator+=(const char * str); PIString & operator+=(const wchar_t * str); - PIString & operator+=(const PIByteArray & ba); + PIString & operator+=(const char16_t * str); PIString & operator+=(const PIString & str); PIString & operator+=(const PIConstChars & str); @@ -113,11 +113,11 @@ public: //! \~english Contructs string with single character "c". //! \~russian Создает строку из одного символа "c". - explicit PIString(const PIChar c) { d.push_back(c); } + PIString(const PIChar c) { d.push_back(c); } //! \~english Contructs string with single character "c". //! \~russian Создает строку из одного символа "c". - explicit PIString(const char c) { d.push_back(PIChar(c)); } + PIString(const char c) { d.push_back(PIChar(c)); } //! \~english Contructs string from C-string "str" (system codepage). //! \~russian Создает строку из C-строки "str" (кодировка системы). @@ -143,9 +143,17 @@ public: //! \endcode PIString(const wchar_t * str) { *this += str; } - //! \~english Contructs string from byte array "ba" (as UTF-8). - //! \~russian Создает строку из байтового массива "ba" (как UTF-8). - explicit PIString(const PIByteArray & ba) { *this += ba; } + //! \~english Contructs string from \c char16_t C-string "str". + //! \~russian Создает строку из \c char16_t C-строки "str". + //! \~\details + //! \~english + //! "str" should be null-terminated + //! \~russian + //! "str" должна заканчиваться нулевым \c char16_t + //! \~\code + //! PIString s(u"string"); + //! \endcode + PIString(const char16_t * str) { *this += str; } //! \~english Contructs string from "len" characters of buffer "str". //! \~russian Создает строку из "len" символов массива "str". @@ -181,7 +189,7 @@ public: d.push_back(c); } - explicit PIString(const PIConstChars & c) { *this += c; } + PIString(const PIConstChars & c) { *this += c; } ~PIString(); @@ -217,6 +225,14 @@ public: return *this; } + //! \~english Assign operator. + //! \~russian Оператор присваивания. + PIString & operator=(const char16_t * o) { + d.clear(); + *this += o; + return *this; + } + //! \~english Compare operator. //! \~russian Оператор сравнения. bool operator==(const PIString & str) const; @@ -452,6 +468,13 @@ public: return *this; } + //! \~english Insert string "str" at the begin of string. + //! \~russian Вставляет "str" в начало строки. + PIString & push_front(const char16_t * str) { + insert(0, str); + return *this; + } + //! \~english Insert string "str" at the begin of string. //! \~russian Вставляет "str" в начало строки. PIString & push_front(const PIString & str) { @@ -480,6 +503,13 @@ public: return *this; } + //! \~english Insert string "str" at the end of string. + //! \~russian Вставляет "str" в конец строки. + PIString & append(const char16_t * str) { + *this += str; + return *this; + } + //! \~english Insert string "str" at the end of string. //! \~russian Вставляет "str" в конец строки. PIString & append(const PIString & str) { @@ -787,6 +817,16 @@ public: //! \endcode PIString & insert(const int index, const char * c) { return insert(index, PIString(c)); } + //! \~english Insert string "str" after index "index" and return this string. + //! \~russian Вставляет строку "str" после позиции "index" и возвращает эту строку. + //! \~\details + //! \~\code + //! PIString s("stg"); + //! s.insert(2, u"rin"); + //! piCout << s; // s = "string" + //! \endcode + PIString & insert(const int index, const char16_t * 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 @@ -1184,10 +1224,26 @@ public: //! \endcode int entries(const PIChar c) const; + //! \~english Returns if string starts with "c". + //! \~russian Возвращает начинается ли строка с "c". + bool startsWith(const char c) const { return startsWith(PIChar(c)); } + + //! \~english Returns if string starts with "c". + //! \~russian Возвращает начинается ли строка с "c". + bool startsWith(const PIChar c) const; + //! \~english Returns if string starts with "str". //! \~russian Возвращает начинается ли строка со "str". bool startsWith(const PIString & str) const; + //! \~english Returns if string ends with "c". + //! \~russian Возвращает оканчивается ли строка на "c". + bool endsWith(const char c) const { return endsWith(PIChar(c)); } + + //! \~english Returns if string ends with "c". + //! \~russian Возвращает оканчивается ли строка на "c". + bool endsWith(const PIChar c) const; + //! \~english Returns if string ends with "str". //! \~russian Возвращает оканчивается ли строка на "str". bool endsWith(const PIString & str) const; @@ -1705,6 +1761,10 @@ public: //! \~russian Возвращает строку созданную из "len" символов ASCII. static PIString fromAscii(const char * s, int len); + //! \~english Returns string constructed from ASCII. + //! \~russian Возвращает строку созданную из ASCII. + static PIString fromAscii(const PIByteArray & ascii); + //! \~english Returns string constructed from "cp" codepage. //! \~russian Возвращает строку созданную из кодировки "cp". static PIString fromCodepage(const char * s, const char * cp); diff --git a/libs/main/text/pistring_std.h b/libs/main/text/pistring_std.h index 4b760eba..873fd227 100644 --- a/libs/main/text/pistring_std.h +++ b/libs/main/text/pistring_std.h @@ -30,6 +30,7 @@ #ifdef QNX typedef std::basic_string wstring; #endif +#include "piliterals.h" #include "pistringlist.h" @@ -117,12 +118,12 @@ inline std::istream & operator>>(std::istream & s, PIString & v) { //! \relatesalso PIStringList \brief Output operator to std::ostream (cout) inline std::ostream & operator<<(std::ostream & s, const PIStringList & v) { - s << PIChar("{"); + s << PIChar('{'); for (uint i = 0; i < v.size(); ++i) { - s << PIChar("\"") << v[i] << PIChar("\""); - if (i < v.size() - 1) s << PIStringAscii(", "); + s << PIChar('"') << v[i] << PIChar('"'); + if (i < v.size() - 1) s << ", "_a; } - s << PIChar("}"); + s << PIChar('}'); return s; } diff --git a/libs/main/types/pibytearray.cpp b/libs/main/types/pibytearray.cpp index d88d1459..6207c9ea 100644 --- a/libs/main/types/pibytearray.cpp +++ b/libs/main/types/pibytearray.cpp @@ -348,7 +348,7 @@ PIString PIByteArray::toHex() const { else hexData[i * 2 + 1] = (j + 'a' - 10); } - return PIString(hex); + return PIString::fromAscii(hex); } diff --git a/libs/opencl/piopencl.cpp b/libs/opencl/piopencl.cpp index 2879bfd4..8b368d87 100644 --- a/libs/opencl/piopencl.cpp +++ b/libs/opencl/piopencl.cpp @@ -139,7 +139,7 @@ void PIOpenCL::Initializer::init() { PIOpenCL::Context::Context() { - PRIVATE->complex_src = PIResources::get("3rd/clcomplex.h") + "\n"; + PRIVATE->complex_src = PIString::fromUTF8(PIResources::get("3rd/clcomplex.h")) + "\n"; zero(); } diff --git a/main_picloud_test.cpp b/main_picloud_test.cpp index b1d3108c..35dedfe0 100644 --- a/main_picloud_test.cpp +++ b/main_picloud_test.cpp @@ -31,7 +31,7 @@ int main(int argc, char * argv[]) { CONNECTL(&c, threadedReadEvent, ([&](const uchar * readed, ssize_t size) { PIByteArray ba(readed, size); if (size < 1024) { - PIString str = PIString(ba); + PIString str = PIString::fromUTF8(ba); piCout << "[Client] data:" << str; if (str == "ping_S") c.write(PIString("pong_S").toByteArray()); } else @@ -44,7 +44,7 @@ int main(int argc, char * argv[]) { clients->append(cl); CONNECTL(cl, threadedReadEvent, ([cl, &rnd](const uchar * readed, ssize_t size) { PIByteArray ba(readed, size); - PIString str = PIString(ba); + PIString str = PIString::fromUTF8(ba); piCout << "[Server] data from" << cl << ":" << str; if (str == "ping") { cl->write(PIString("pong").toByteArray()); diff --git a/utils/crypt_tool/main.cpp b/utils/crypt_tool/main.cpp index dd9fcebb..8d4ec3b7 100644 --- a/utils/crypt_tool/main.cpp +++ b/utils/crypt_tool/main.cpp @@ -30,7 +30,7 @@ void usage() { piCout << Cyan << "Version" << Bold << PIPVersion() << NewLine; piCout << Green << Bold << "Usage:" << Default << "\"picrypt [-thr] [-g ] [-o ] [{[-c ] [-d ]} {[-p ] [-s ] [-k ] [-x " - "]}]\"" + "]}]\"" << NewLine; piCout << Green << Bold << "Details:"; piCout << "-h --help " << Green << "- display this message and exit"; @@ -96,7 +96,7 @@ int main(int argc, char * argv[]) { } if (cli.hasArgument("pass")) secret = crypt.hash(cli.argumentValue("pass")); if (cli.hasArgument("secret")) secret = PIByteArray::fromBase64(cli.argumentValue("secret").toByteArray()); - if (cli.hasArgument("hex")) secret = PIByteArray::fromHex(cli.argumentValue("hex").toByteArray()); + if (cli.hasArgument("hex")) secret = PIByteArray::fromHex(PIString::fromAscii(cli.argumentValue("hex").toByteArray())); if (secret.size() == crypt.sizeKey()) { PIFile inf; PIString in_file;