PLaSK library
Loading...
Searching...
No Matches
data.hpp
Go to the documentation of this file.
1/*
2 * This file is part of PLaSK (https://plask.app) by Photonics Group at TUL
3 * Copyright (c) 2022 Lodz University of Technology
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14#ifndef PLASK__DATA_H
15#define PLASK__DATA_H
16
21#include <iterator>
22#include <vector>
23#include <algorithm>
24#include <iostream>
25#include <initializer_list>
26#include <atomic>
27#include <type_traits>
28#include <memory> // std::unique_ptr
29#include <cassert>
30#include <type_traits> // std::is_trivially_destructible, std::false_type, std::true_type
31
32#include "memalloc.hpp"
33#include "math.hpp"
34#include "exceptions.hpp"
35#include "log/log.hpp"
36
37#include <boost/type_traits.hpp>
38
39namespace plask {
40
41namespace detail {
42
43 template <class T>
44 inline void _construct_array(T* first, T* last, const std::false_type&) {
45 T* current = first;
46 try {
47 for (; current != last; ++current)
48 ::new(static_cast<void*>(current)) T();
49 } catch (...) {
50 while (current != first)
51 (--current)->~T();
52 throw;
53 }
54 }
55
56 template <class T>
57 inline void _construct_array(T*, T*, const std::true_type&) {
58 }
59
60 template <class T>
61 inline void _destroy_array(T* first, T* last, const std::false_type&) {
62 while(last != first) {
63 --last;
64 last->~T();
65 }
66 }
67
68 template <class T>
69 inline void _destroy_array(T*, T*, const std::true_type&) {
70 }
71
72 template <class T>
73 inline void construct_array(T* first, T* last) {
74 _construct_array(first, last, std::is_trivially_default_constructible<T>());
75 }
76
77 template <class T>
78 inline void destroy_array(T* first, T* last) {
79 _destroy_array(first, last, std::is_trivially_destructible<T>());
80 }
81
82 // We consider dcomplex as POD (do not value-initialize memory)
83
84 template <>
85 inline void construct_array(dcomplex* first, dcomplex* last) {
86 _construct_array(first, last, std::true_type());
87 }
88
89 template <>
90 inline void destroy_array(dcomplex* first, dcomplex* last) {
91 _destroy_array(first, last, std::true_type());
92 }
93
94
96 struct DataVectorGC {
97 // Count is atomic so many threads can increment and decrement it at same time.
98 // If it is 0, it means that there has been only one DataVector object, so probably one thread uses it.
99 std::atomic<unsigned> count;
100
101 std::function<void(void*)>* deleter;
102
104
105 explicit DataVectorGC(unsigned initial, const std::function<void(void*)>& deleter):
106 count(initial), deleter(new std::function<void(void*)>(deleter)) {}
107
108 explicit DataVectorGC(unsigned initial, std::function<void(void*)>&& deleter):
109 count(initial), deleter(new std::function<void(void*)>(std::forward<std::function<void(void*)>>(deleter))) {}
110
111 void free(void* data) {
112 if (deleter) (*deleter)(data);
113 else aligned_free(data);
114 }
115
116 ~DataVectorGC() { delete deleter; }
117 };
118
119} // namespace detail
120
131template <typename T>
133
134 typedef typename std::remove_const<T>::type VT;
135 typedef const T CT;
136
138 private:
139
140 std::size_t size_;
141 Gc* gc_;
142 T* data_;
143
145 void dec_ref() { // see http://www.boost.org/doc/libs/1_53_0/doc/html/atomic/usage_examples.html "Reference counting" for optimal memory access description
146 if (gc_ && gc_->count.fetch_sub(1, std::memory_order_release) == 1) {
147 std::atomic_thread_fence(std::memory_order_acquire);
148 detail::destroy_array(data_, data_ + size_);
149 gc_->free(reinterpret_cast<void*>(const_cast<VT*>(data_)));
150 delete gc_;
151 }
152 }
153
155 void inc_ref() {
156 if (gc_) gc_->count.fetch_add(1, std::memory_order_relaxed);
157 }
158
159 // initialize constructs the elements and unwinds any partially constructed range on failure.
160 template <typename Initialize>
161 void resetOwned(std::size_t size, Initialize initialize) {
162 std::unique_ptr<Gc> gc(new Gc(1));
164 initialize(data.get());
165 dec_ref();
166 size_ = size;
167 gc_ = gc.release();
168 data_ = data.release();
169 }
170
171 template <typename InIterT>
172 void resetRange(InIterT begin, InIterT end, std::input_iterator_tag) {
173 std::vector<VT> values(begin, end);
174 resetRange(std::make_move_iterator(values.begin()), std::make_move_iterator(values.end()),
175 std::forward_iterator_tag{});
176 }
177
178 template <typename InIterT>
179 void resetRange(InIterT begin, InIterT end, std::forward_iterator_tag) {
180 resetOwned(std::distance(begin, end), [&](VT* data) { std::uninitialized_copy(begin, end, data); });
181 }
182
183 friend struct DataVector<VT>;
184 friend struct DataVector<CT>;
185
186 public:
187
188 typedef T value_type;
189
190 typedef T* iterator;
191 typedef const T* const_iterator;
192
194 DataVector(): size_(0), gc_(nullptr), data_(nullptr) {}
195
202 explicit DataVector(std::size_t size): DataVector() {
203 reset(size);
204 }
205
211 DataVector(std::size_t size, const T& value): DataVector() {
212 reset(size, value);
213 }
214
219 DataVector(const DataVector<CT>& src): size_(src.size_), gc_(src.gc_), data_(const_cast<T*>(src.data_)) { inc_ref(); }
220
225 DataVector(const DataVector<VT>& src): size_(src.size_), gc_(src.gc_), data_(const_cast<T*>(src.data_)) { inc_ref(); }
226
231 template <typename TS>
233 write_debug("copying data in constructor");
234 resetOwned(src.size(), [&](VT* data) { std::uninitialized_copy(src.begin(), src.end(), data); });
235 }
236
243 const_cast<DataVector<CT>&>(M).inc_ref(); // must be called before dec_ref in case of self-asigment with 1 reference
244 this->dec_ref(); // release old content, this can delete the old data
245 size_ = M.size_;
246 data_ = const_cast<T*>(M.data_);
247 gc_ = M.gc_;
248 return *this;
249 }
250
257 const_cast<DataVector<VT>&>(M).inc_ref(); // must be called before dec_ref in case of self-asigment with 1 reference
258 this->dec_ref(); // release old content, this can delete the old data
259 size_ = M.size_;
260 data_ = const_cast<T*>(M.data_);
261 gc_ = M.gc_;
262 return *this;
263 }
264
269 DataVector(DataVector<CT>&& src) noexcept: size_(src.size_), gc_(src.gc_), data_(const_cast<T*>(src.data_)) {
270 src.gc_ = nullptr;
271 }
272
277 DataVector(DataVector<VT>&& src) noexcept: size_(src.size_), gc_(src.gc_), data_(const_cast<T*>(src.data_)) {
278 src.gc_ = nullptr;
279 }
280
287 swap(src);
288 return *this;
289 }
290
296 template <typename TS>
298 size_(size), gc_(nullptr), data_(existing_data) {}
299
306 template <typename TS>
307 DataVector(TS* existing_data, std::size_t size, const std::function<void(void*)>& deleter):
308 size_(size), gc_(new Gc(1, deleter)), data_(existing_data) {
309 }
310
317 template <typename TS>
318 DataVector(TS* existing_data, std::size_t size, std::function<void(void*)>&& deleter):
319 size_(size), gc_(new Gc(1, std::forward<std::function<void(void*)>>(deleter))), data_(existing_data) {
320 }
321
326 DataVector(std::initializer_list<T> init): DataVector() {
327 resetOwned(init.size(), [&](VT* data) { std::uninitialized_copy(init.begin(), init.end(), data); });
328 }
329
334 template <typename TS>
335 DataVector(std::initializer_list<TS> init): DataVector() {
336 resetOwned(init.size(), [&](VT* data) { std::uninitialized_copy(init.begin(), init.end(), data); });
337 }
338
340 ~DataVector() { dec_ref(); }
341
347 void reset() {
348 dec_ref();
349 size_ = 0;
350 gc_ = nullptr;
351 data_ = nullptr;
352 }
353
359 template <typename TS>
360 void reset(TS* existing_data, std::size_t size) {
361 dec_ref();
362 gc_ = nullptr;
363 size_ = size;
364 data_ = existing_data;
365 }
366
373 template <typename TS>
374 void reset(TS* existing_data, std::size_t size, const std::function<void(void*)>& deleter) {
375 DataVector(existing_data, size, deleter).swap(*this);
376 }
377
384 template <typename TS>
385 void reset(TS* existing_data, std::size_t size, std::function<void(void*)>&& deleter) {
386 DataVector(existing_data, size, std::move(deleter)).swap(*this);
387 }
388
397 void reset(std::size_t size) {
398 resetOwned(size, [size](VT* data) { detail::construct_array(data, data + size); });
399 }
400
408 void reset(std::size_t size, const T& value) {
409 resetOwned(size, [&](VT* data) { std::uninitialized_fill_n(data, size, value); });
410 }
411
420 resetRange(begin, end, Category{});
421 }
422
427 const_iterator begin() const { return data_; }
428
433 iterator begin() { return data_; }
434
439 const_iterator end() const { return data_ + size_; }
440
445 iterator end() { return data_ + size_; }
446
448 std::size_t size() const { return size_; }
449
451 const T* data() const { return data_; }
452
454 T* data() { return data_; }
455
461 const T& operator[](std::size_t n) const { assert(n < size_); return data_[n]; }
462
468 T& operator[](std::size_t n) { assert(n < size_); return data_[n]; }
469
471 operator bool() const { return data_ != nullptr; }
472
479 std::copy(begin(), end(), new_data.begin());
480 return new_data;
481 }
482
487 bool unique() const {
488 return (gc_ != nullptr) && (gc_->count == 1);
489 }
490
496 DataVector<VT> result(const_cast<VT*>(this->data()), this->size());
497 result.gc_ = this->gc_;
498 result.inc_ref();
499 return result;
500 }
501
507 return (unique() && !gc_->deleter)? remove_const() : copy();
508 }
509
514 void swap(DataVector<T>& other) noexcept {
515 std::swap(size_, other.size_);
516 std::swap(gc_, other.gc_);
517 std::swap(data_, other.data_);
518 }
519
524 template <typename O>
525 void fill(const O& value) {
526 std::fill_n(data_, size_, value);
527 }
528
535 inline DataVector<T> getSubarrayRef(std::size_t begin_index, std::size_t subarray_size) {
536 assert(begin_index + subarray_size <= size_);
537 return DataVector<T>(data_ + begin_index, subarray_size);
538 }
539
546 inline DataVector<const T> getSubarrayRef(std::size_t begin_index, std::size_t subarray_size) const {
547 assert(begin_index + subarray_size <= size_);
549 }
550
557 inline DataVector<T> getSubarrayCopy(std::size_t begin_index, std::size_t subarray_size) const {
559 }
560
567 assert(this->begin() <= begin && begin <= end && end <= this->end());
568 return DataVector<T>(begin, end - begin);
569 }
570
580
587 assert(this->begin() <= begin && begin <= end && end <= this->end());
588 return getSubrangeRef(begin, end).copy();
589 }
590};
591
597template<class T1, class T2> inline
599{ return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); }
600
606template<class T1, class T2> inline
607bool operator!= ( DataVector<T1> const& a, DataVector<T2> const& b) { return !(a==b); }
608
614template<class T1, class T2> inline
616{ return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()); }
617
623template<class T1, class T2> inline
624bool operator> ( DataVector<T1> const& a, DataVector<T2> const& b) { return b < a; }
625
631template<class T1, class T2> inline
632bool operator<= ( DataVector<T1> const& a, DataVector<T2> const& b) { return !(b < a); }
633
639template<class T1, class T2> inline
640bool operator>= ( DataVector<T1> const& a, DataVector<T2> const& b) { return !(a < b); }
641
648template<class T>
649std::ostream& operator<<(std::ostream& out, DataVector<T> const& to_print) {
650 out << '[';
651 return print_seq(out, to_print.begin(), to_print.end()) << ']';
652}
653
660template<class T, class S>
662 if (to_inc.size() != inc_val.size())
663 throw DataError("data vectors sizes differ ([{0}] += [%2])", to_inc.size(), inc_val.size());
664 for (std::size_t i = 0; i < to_inc.size(); ++i)
665 to_inc[i] += inc_val[i];
666 return to_inc;
667}
668
675template<class T, class S>
677 if (to_dec.size() != dec_val.size())
678 throw DataError("data vectors sizes differ ([{0}] -= [%2])", to_dec.size(), dec_val.size());
679 for (std::size_t i = 0; i < to_dec.size(); ++i)
680 to_dec[i] -= dec_val[i];
681 return to_dec;
682}
683
690template<typename T, typename S>
692 for (std::size_t i = 0; i < vec.size(); ++i)
693 vec[i] *= a;
694 return vec;
695}
696
703template<typename T, typename S>
705 auto ia = 1. / a;
706 for (std::size_t i = 0; i < vec.size(); ++i)
707 vec[i] *= ia;
708 return vec;
709}
710
717template<typename T1, typename T2>
718DataVector<typename std::remove_cv<decltype(T1()+T2())>::type> operator+(DataVector<T1> const& vec1, DataVector<T2> const& vec2) {
719 if (vec1.size() != vec2.size())
720 throw DataError("data vectors sizes differ ([{0}] + [%2])", vec1.size(), vec2.size());
721 DataVector<typename std::remove_cv<decltype(T1()+T2())>::type> result(vec1.size());
722 for (std::size_t i = 0; i < vec1.size(); ++i)
723 result[i] = vec1[i] + vec2[i];
724 return result;
725}
726
733template<typename T1, typename T2>
734DataVector<typename std::remove_cv<decltype(T1()-T2())>::type> operator-(DataVector<T1> const& vec1, DataVector<T2> const& vec2) {
735 if (vec1.size() != vec2.size())
736 throw DataError("data vectors sizes differ ([{0}] - [%2])", vec1.size(), vec2.size());
737 DataVector<typename std::remove_cv<decltype(T1()-T2())>::type> result(vec1.size());
738 for (std::size_t i = 0; i < vec1.size(); ++i)
739 result [i] = vec1[i] - vec2[i];
740 return result;
741}
742
748template<class T>
751 for (std::size_t i = 0; i < vec.size(); ++i)
752 result [i] = -vec[i];
753 return result;
754}
755
762template<typename T, typename S>
763DataVector<typename std::remove_cv<decltype(T()*S())>::type> operator*(DataVector<T> const& vec, S a) {
764 DataVector<typename std::remove_cv<decltype(T()*S())>::type> result(vec.size());
765 for (std::size_t i = 0; i < vec.size(); ++i)
766 result[i] = vec[i] * a;
767 return result;
768}
769
776template<typename T, typename S>
777DataVector<typename std::remove_cv<decltype(S()*T())>::type> operator*(S a, DataVector<T> const& vec) {
778 DataVector<typename std::remove_cv<decltype(S()*T())>::type> result(vec.size());
779 for (std::size_t i = 0; i < vec.size(); ++i)
780 result[i] = a * vec[i];
781 return result;
782}
783
790template<typename T, typename S>
791DataVector<typename std::remove_cv<decltype(T()*(1./S()))>::type> operator/(DataVector<T> const& vec, S a) {
792 auto ia = 1. / a;
793 DataVector<typename std::remove_cv<decltype(T()*(1./S()))>::type> result(vec.size());
794 for (std::size_t i = 0; i < vec.size(); ++i)
795 result[i] = vec[i] * ia;
796 return result;
797}
798
799
800
807template <class T>
808typename std::remove_cv<T>::type accumulate(const DataVector<T>& to_accum, typename std::remove_cv<T>::type initial=typename std::remove_cv<T>::type()) {
809 for (std::size_t i = 0; i < to_accum.size(); ++i)
810 initial += to_accum[i];
811 return initial;
812}
813
818template <class T>
820 return accumulate(v) / v.size();
821}
822
829template<typename RT, typename T>
831 return src.remove_const();
832}
833
834/*
835PLASK_API_EXTERN_TEMPLATE_STRUCT(DataVector<double>)
836PLASK_API_EXTERN_TEMPLATE_STRUCT(DataVector<const double>)
837PLASK_API_EXTERN_TEMPLATE_STRUCT(PLASK_API DataVector<std::complex<double>>)
838PLASK_API_EXTERN_TEMPLATE_STRUCT(DataVector<const std::complex<double>>)
839*/
840
841} // namespace plask
842
843namespace std {
844 template <typename T>
846 s1.swap(s2);
847 }
848} // namespace std
849
850#if FMT_VERSION >= 90000
851template <typename T> struct fmt::formatter<plask::DataVector<T>> : ostream_formatter {};
852#endif
853
854#endif // PLASK__DATA_H