diff --git a/examples/listdir.cc b/examples/listdir.cc index 8864c78..5664582 100644 --- a/examples/listdir.cc +++ b/examples/listdir.cc @@ -1,5 +1,6 @@ #include #include +#include using namespace ostd; @@ -7,16 +8,19 @@ void list_dirs(ConstCharRange path, int off = 0) { DirectoryStream ds{path}; /* iterate all items in directory */ for (auto v: ds.iter()) { - if (v.type() != FileType::directory) + if (v.type() != FileType::directory) { continue; - for (int i = 0; i < off; ++i) write(' '); + } + for_each(range(off), [](int) { write(' '); }); writeln(v.filename()); list_dirs(v.path(), off + 1); } } int main(int argc, char **argv) { - if (argc < 1) return 1; + if (argc < 1) { + return 1; + } list_dirs(argv[1]); return 0; } diff --git a/examples/range.cc b/examples/range.cc index 2a08e04..5541ca9 100644 --- a/examples/range.cc +++ b/examples/range.cc @@ -7,19 +7,22 @@ using namespace ostd; int main() { /* range iter - prints 0 to 9 each on new line */ writeln("range iter test"); - for (int i: range(10)) + for (int i: range(10)) { writeln(i); + } /* algorithm: map - prints 0.5 to 9.5 each on new line */ writeln("range map test"); - for (float f: map(range(10), [](int v) { return v + 0.5f; })) + for (float f: map(range(10), [](int v) { return v + 0.5f; })) { writeln(f); + } /* algorithm: filter - prints 10, 15, 8 each on new line */ writeln("range filter test"); auto il = { 5, 5, 5, 5, 5, 10, 15, 4, 8, 2 }; - for (int i: filter(iter(il), [](int v) { return v > 5; })) + for (int i: filter(iter(il), [](int v) { return v > 5; })) { writeln(i); + } /* prints ABCDEF (ASCII 65, 66, 67, 68, 69, 70) */ writeln("string gen test"); @@ -31,8 +34,9 @@ int main() { auto x = { 11, 22, 33 }; auto y = { 44, 55, 66 }; auto z = { 77, 88, 99 }; - for (auto i: iter(x).join(iter(y), iter(z))) + for (auto i: iter(x).join(iter(y), iter(z))) { writeln(i); + } /* chunk a range into subranges - prints * {11, 22, 33} @@ -41,21 +45,25 @@ int main() { */ writeln("range chunk test"); auto cr = { 11, 22, 33, 44, 55, 66, 77, 88, 99 }; - for (auto r: iter(cr).chunks(3)) + for (auto r: iter(cr).chunks(3)) { writeln(r); + } /* take test, prints only first 4 */ writeln("range take test"); - for (auto r: iter(cr).take(4)) + for (auto r: iter(cr).take(4)) { writeln(r); + } /* {11, 44, 77}, {22, 55, 88}, {33, 66, 99} */ writeln("range zip test"); - for (auto v: iter(x).zip(iter(y), iter(z))) + for (auto v: iter(x).zip(iter(y), iter(z))) { writeln(v); + } /* 2-tuple zip uses Pair */ writeln("2-tuple range zip"); - for (auto v: iter({ 5, 10, 15, 20 }).zip(iter({ 6, 11, 16, 21 }))) + for (auto v: iter({ 5, 10, 15, 20 }).zip(iter({ 6, 11, 16, 21 }))) { writeln(v.first, ", ", v.second); + } } diff --git a/examples/range_pipe.cc b/examples/range_pipe.cc index ddc434e..516de1e 100644 --- a/examples/range_pipe.cc +++ b/examples/range_pipe.cc @@ -10,14 +10,16 @@ using namespace ostd; int main() { /* algorithm: map - prints 0.5 to 9.5 each on new line */ writeln("range map test"); - for (float f: range(10) | map([](int v) { return v + 0.5f; })) + for (float f: range(10) | map([](int v) { return v + 0.5f; })) { writeln(f); + } /* algorithm: filter - prints 10, 15, 8 each on new line */ writeln("range filter test"); auto il = { 5, 5, 5, 5, 5, 10, 15, 4, 8, 2 }; - for (int i: iter(il) | filter([](int v) { return v > 5; })) + for (int i: iter(il) | filter([](int v) { return v > 5; })) { writeln(i); + } /* prints ABCDEF (ASCII 65, 66, 67, 68, 69, 70) */ writeln("string gen test"); @@ -29,8 +31,9 @@ int main() { auto x = { 11, 22, 33 }; auto y = { 44, 55, 66 }; auto z = { 77, 88, 99 }; - for (auto i: iter(x) | join(iter(y), iter(z))) + for (auto i: iter(x) | join(iter(y), iter(z))) { writeln(i); + } /* chunk a range into subranges - prints * {11, 22, 33} @@ -39,23 +42,27 @@ int main() { */ writeln("range chunk test"); auto cr = { 11, 22, 33, 44, 55, 66, 77, 88, 99 }; - for (auto r: iter(cr) | chunks(3)) + for (auto r: iter(cr) | chunks(3)) { writeln(r); + } /* take test, prints only first 4 */ writeln("range take test"); - for (auto r: iter(cr) | take(4)) + for (auto r: iter(cr) | take(4)) { writeln(r); + } /* {11, 44, 77}, {22, 55, 88}, {33, 66, 99} */ writeln("range zip test"); - for (auto v: iter(x) | zip(iter(y), iter(z))) + for (auto v: iter(x) | zip(iter(y), iter(z))) { writeln(v); + } /* 2-tuple zip uses Pair */ writeln("2-tuple range zip"); - for (auto v: iter({ 5, 10, 15, 20 }) | zip(iter({ 6, 11, 16, 21 }))) + for (auto v: iter({ 5, 10, 15, 20 }) | zip(iter({ 6, 11, 16, 21 }))) { writeln(v.first, ", ", v.second); + } /* more complex pipe */ writeln("several piped algorithms"); @@ -65,16 +72,19 @@ int main() { generate(arr.iter(), []() { return rand() % 128; }); auto r = arr.iter() - | sort() + | sort () | filter([](auto v) { return v >= 65 && v <= 90; }) - | map([](auto v) { return char(v); }); + | map ([](auto v) { return char(v); }); writeln(String(r)); /* "list comprehensions" */ writeln("list initialization"); - Vector test(range(20) | filter([](int v) { return v % 2 == 0; }) - | map([](int v) { return v * 2; })); + Vector test( + range(20) + | filter([](int v) { return v % 2 == 0; }) + | map ([](int v) { return v * 2; }) + ); writeln(test); } diff --git a/examples/signal.cc b/examples/signal.cc index 4db7f91..8a5e70f 100644 --- a/examples/signal.cc +++ b/examples/signal.cc @@ -48,8 +48,9 @@ int main() { /* we can connect lambdas, including closures * this callback can access "test" easily and it will still work */ - auto idx = st.on_simple.connect([&](SignalTest const &, int v, - ConstCharRange str) { + auto idx = st.on_simple.connect([&]( + SignalTest const &, int v, ConstCharRange str + ) { writefln("and lambda test: %d, %s (%d)", v, str, test); }); @@ -69,13 +70,16 @@ int main() { /* the reference to SignalTest here is mutable */ st.on_param.connect([](SignalTest &self, float oldval) { writeln("value changed..."); - writefln(" old value: %f, new value: %f", oldval, - self.get_param()); + writefln( + " old value: %f, new value: %f", oldval, self.get_param() + ); /* when we have a mutable reference we can change the original * object, for example re-emit its own signal once again */ - if (self.get_param() > 140.0f) return; + if (self.get_param() > 140.0f) { + return; + } self.set_param(self.get_param() + 1.0f); }); diff --git a/examples/stream1.cc b/examples/stream1.cc index 50e4f93..07e0329 100644 --- a/examples/stream1.cc +++ b/examples/stream1.cc @@ -9,14 +9,18 @@ void print_result(Uint32 x) { int main() { FileStream wtest{"test.bin", StreamMode::write}; - copy(iter({ 0xABCD1214, 0xBADC3264, 0xDEADBEEF, 0xBEEFDEAD }), wtest.iter()); + copy( + iter({ 0xABCD1214, 0xBADC3264, 0xDEADBEEF, 0xBEEFDEAD }), + wtest.iter() + ); wtest.close(); FileStream rtest{"test.bin"}; writefln("stream size: %d", rtest.size()); - for (Uint32 x: map(rtest.iter(), FromBigEndian())) + for (Uint32 x: map(rtest.iter(), FromBigEndian())) { print_result(x); + } return 0; } diff --git a/examples/stream2.cc b/examples/stream2.cc index ba6f709..3592adc 100644 --- a/examples/stream2.cc +++ b/examples/stream2.cc @@ -9,12 +9,13 @@ int main() { FileStream wtest{"test.txt", StreamMode::write}; - String smpl = "This is a test file for later read.\n" - "It contains some sample text in order to see whether " - "things actually read correctly.\n\n\n" - "" - "This is after a few newlines. The file continues here.\n" - "The file ends here.\n"; + String smpl = + "This is a test file for later read.\n" + "It contains some sample text in order to see whether " + "things actually read correctly.\n\n\n" + "" + "This is after a few newlines. The file continues here.\n" + "The file ends here.\n"; copy(smpl.iter(), wtest.iter()); wtest.close(); diff --git a/ostd/algorithm.hh b/ostd/algorithm.hh index 34c0743..5b03657 100644 --- a/ostd/algorithm.hh +++ b/ostd/algorithm.hh @@ -39,8 +39,11 @@ inline auto partition(F &&func) { template inline bool is_partitioned(R range, P pred) { for (; !range.empty() && pred(range.front()); range.pop_front()); - for (; !range.empty(); range.pop_front()) - if (pred(range.front())) return false; + for (; !range.empty(); range.pop_front()) { + if (pred(range.front())) { + return false; + } + } return true; } @@ -69,20 +72,25 @@ namespace detail { } template - static void hs_sift_down(R range, RangeSize s, - RangeSize e, C &compare) { + static void hs_sift_down( + R range, RangeSize s, RangeSize e, C &compare + ) { RangeSize r = s; while ((r * 2 + 1) <= e) { RangeSize ch = r * 2 + 1; RangeSize sw = r; - if (compare(range[sw], range[ch])) + if (compare(range[sw], range[ch])) { sw = ch; - if (((ch + 1) <= e) && compare(range[sw], range[ch + 1])) + } + if (((ch + 1) <= e) && compare(range[sw], range[ch + 1])) { sw = ch + 1; + } if (sw != r) { detail::swap_adl(range[r], range[sw]); r = sw; - } else return; + } else { + return; + } } } @@ -92,7 +100,9 @@ namespace detail { RangeSize st = (len - 2) / 2; for (;;) { detail::hs_sift_down(range, st, len - 1, compare); - if (st-- == 0) break; + if (st-- == 0) { + break; + } } RangeSize e = len - 1; while (e > 0) { @@ -117,19 +127,23 @@ namespace detail { R pr = range; pr.pop_back(); for (; !pr.empty(); pr.pop_front()) { - if (compare(pr.front(), range.back())) + if (compare(pr.front(), range.back())) { detail::swap_adl(pr.front(), range[pi++]); + } } detail::swap_adl(range[pi], range.back()); detail::introloop(range.slice(0, pi), compare, depth - 1); - detail::introloop(range.slice(pi + 1, range.size()), compare, - depth - 1); + detail::introloop( + range.slice(pi + 1, range.size()), compare, depth - 1 + ); } template inline void introsort(R range, C &compare) { - detail::introloop(range, compare, RangeSize(2 - * (log(range.size()) / log(2)))); + detail::introloop( + range, compare, + static_cast>(2 * (log(range.size()) / log(2))) + ); } } /* namespace detail */ @@ -176,17 +190,21 @@ inline T const &max_cmp(T const &a, T const &b, C compare) { template inline R min_element(R range) { R r = range; - for (; !range.empty(); range.pop_front()) - if (ostd::min(r.front(), range.front()) == range.front()) + for (; !range.empty(); range.pop_front()) { + if (ostd::min(r.front(), range.front()) == range.front()) { r = range; + } + } return r; } template inline R min_element_cmp(R range, C compare) { R r = range; - for (; !range.empty(); range.pop_front()) - if (ostd::min_cmp(r.front(), range.front(), compare) == range.front()) + for (; !range.empty(); range.pop_front()) { + if (ostd::min_cmp(r.front(), range.front(), compare) == range.front()) { r = range; + } + } return r; } inline auto min_element() { @@ -202,17 +220,21 @@ inline auto min_element_cmp(C &&compare) { template inline R max_element(R range) { R r = range; - for (; !range.empty(); range.pop_front()) - if (ostd::max(r.front(), range.front()) == range.front()) + for (; !range.empty(); range.pop_front()) { + if (ostd::max(r.front(), range.front()) == range.front()) { r = range; + } + } return r; } template inline R max_element_cmp(R range, C compare) { R r = range; - for (; !range.empty(); range.pop_front()) - if (ostd::max_cmp(r.front(), range.front(), compare) == range.front()) + for (; !range.empty(); range.pop_front()) { + if (ostd::max_cmp(r.front(), range.front(), compare) == range.front()) { r = range; + } + } return r; } inline auto max_element() { @@ -261,8 +283,12 @@ inline T clamp(T const &v, U const &lo, U const &hi, C compare) { template inline bool lexicographical_compare(R1 range1, R2 range2) { while (!range1.empty() && !range2.empty()) { - if (range1.front() < range2.front()) return true; - if (range2.front() < range1.front()) return false; + if (range1.front() < range2.front()) { + return true; + } + if (range2.front() < range1.front()) { + return false; + } range1.pop_front(); range2.pop_front(); } @@ -271,15 +297,21 @@ inline bool lexicographical_compare(R1 range1, R2 range2) { template inline auto lexicographical_compare(R &&range) { return [range = forward(range)](auto &&obj) mutable { - return lexicographical_compare(forward(obj), forward(range)); + return lexicographical_compare( + forward(obj), forward(range) + ); }; } template inline bool lexicographical_compare_cmp(R1 range1, R2 range2, C compare) { while (!range1.empty() && !range2.empty()) { - if (compare(range1.front(), range2.front())) return true; - if (compare(range2.front(), range1.front())) return false; + if (compare(range1.front(), range2.front())) { + return true; + } + if (compare(range2.front(), range1.front())) { + return false; + } range1.pop_front(); range2.pop_front(); } @@ -287,9 +319,12 @@ inline bool lexicographical_compare_cmp(R1 range1, R2 range2, C compare) { } template inline auto lexicographical_compare_cmp(R &&range, C &&compare) { - return [range = forward(range), compare = forward(compare)](auto &&obj) mutable { - return lexicographical_compare_cmp(forward(obj), - forward(range), forward(compare)); + return [ + range = forward(range), compare = forward(compare) + ](auto &&obj) mutable { + return lexicographical_compare_cmp( + forward(obj), forward(range), forward(compare) + ); }; } @@ -297,8 +332,9 @@ inline auto lexicographical_compare_cmp(R &&range, C &&compare) { template inline F for_each(R range, F func) { - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { func(range.front()); + } return move(func); } @@ -311,8 +347,11 @@ inline auto for_each(F &&func) { template inline bool all_of(R range, P pred) { - for (; !range.empty(); range.pop_front()) - if (!pred(range.front())) return false; + for (; !range.empty(); range.pop_front()) { + if (!pred(range.front())) { + return false; + } + } return true; } @@ -353,9 +392,11 @@ inline auto none_of(F &&func) { template inline R find(R range, T const &v) { - for (; !range.empty(); range.pop_front()) - if (range.front() == v) + for (; !range.empty(); range.pop_front()) { + if (range.front() == v) { break; + } + } return range; } @@ -369,13 +410,16 @@ inline auto find(T &&v) { template inline R find_last(R range, T const &v) { range = find(range, v); - if (!range.empty()) for (;;) { - R prev = range; - prev.pop_front(); - R r = find(prev, v); - if (r.empty()) - break; - range = r; + if (!range.empty()) { + for (;;) { + R prev = range; + prev.pop_front(); + R r = find(prev, v); + if (r.empty()) { + break; + } + range = r; + } } return range; } @@ -389,9 +433,11 @@ inline auto find_last(T &&v) { template inline R find_if(R range, P pred) { - for (; !range.empty(); range.pop_front()) - if (pred(range.front())) + for (; !range.empty(); range.pop_front()) { + if (pred(range.front())) { break; + } + } return range; } @@ -404,9 +450,11 @@ inline auto find_if(F &&func) { template inline R find_if_not(R range, P pred) { - for (; !range.empty(); range.pop_front()) - if (!pred(range.front())) + for (; !range.empty(); range.pop_front()) { + if (!pred(range.front())) { break; + } + } return range; } @@ -419,26 +467,35 @@ inline auto find_if_not(F &&func) { template inline R1 find_one_of_cmp(R1 range, R2 values, C compare) { - for (; !range.empty(); range.pop_front()) - for (R2 rv = values; !rv.empty(); rv.pop_front()) - if (compare(range.front(), rv.front())) + for (; !range.empty(); range.pop_front()) { + for (R2 rv = values; !rv.empty(); rv.pop_front()) { + if (compare(range.front(), rv.front())) { return range; + } + } + } return range; } template inline auto find_one_of_cmp(R &&values, C &&compare) { - return [values = forward(values), compare = forward(compare)](auto &&obj) mutable { - return find_one_of_cmp(forward(obj), - forward(values), forward(compare)); + return [ + values = forward(values), compare = forward(compare) + ](auto &&obj) mutable { + return find_one_of_cmp( + forward(obj), forward(values), forward(compare) + ); }; } template inline R1 find_one_of(R1 range, R2 values) { - for (; !range.empty(); range.pop_front()) - for (R2 rv = values; !rv.empty(); rv.pop_front()) - if (range.front() == rv.front()) + for (; !range.empty(); range.pop_front()) { + for (R2 rv = values; !rv.empty(); rv.pop_front()) { + if (range.front() == rv.front()) { return range; + } + } + } return range; } template @@ -451,9 +508,11 @@ inline auto find_one_of(R &&values) { template inline RangeSize count(R range, T const &v) { RangeSize ret = 0; - for (; !range.empty(); range.pop_front()) - if (range.front() == v) + for (; !range.empty(); range.pop_front()) { + if (range.front() == v) { ++ret; + } + } return ret; } @@ -467,9 +526,11 @@ inline auto count(T &&v) { template inline RangeSize count_if(R range, P pred) { RangeSize ret = 0; - for (; !range.empty(); range.pop_front()) - if (pred(range.front())) + for (; !range.empty(); range.pop_front()) { + if (pred(range.front())) { ++ret; + } + } return ret; } @@ -483,9 +544,11 @@ inline auto count_if(F &&func) { template inline RangeSize count_if_not(R range, P pred) { RangeSize ret = 0; - for (; !range.empty(); range.pop_front()) - if (!pred(range.front())) + for (; !range.empty(); range.pop_front()) { + if (!pred(range.front())) { ++ret; + } + } return ret; } @@ -499,8 +562,9 @@ inline auto count_if_not(F &&func) { template inline bool equal(R range1, R range2) { for (; !range1.empty(); range1.pop_front()) { - if (range2.empty() || (range1.front() != range2.front())) + if (range2.empty() || (range1.front() != range2.front())) { return false; + } range2.pop_front(); } return range2.empty(); @@ -529,31 +593,37 @@ inline auto slice_until(R &&range) { template inline R2 copy(R1 irange, R2 orange) { - for (; !irange.empty(); irange.pop_front()) + for (; !irange.empty(); irange.pop_front()) { orange.put(irange.front()); + } return orange; } template inline R2 copy_if(R1 irange, R2 orange, P pred) { - for (; !irange.empty(); irange.pop_front()) - if (pred(irange.front())) + for (; !irange.empty(); irange.pop_front()) { + if (pred(irange.front())) { orange.put(irange.front()); + } + } return orange; } template inline R2 copy_if_not(R1 irange, R2 orange, P pred) { - for (; !irange.empty(); irange.pop_front()) - if (!pred(irange.front())) + for (; !irange.empty(); irange.pop_front()) { + if (!pred(irange.front())) { orange.put(irange.front()); + } + } return orange; } template inline R2 move(R1 irange, R2 orange) { - for (; !irange.empty(); irange.pop_front()) + for (; !irange.empty(); irange.pop_front()) { orange.put(move(irange.front())); + } return orange; } @@ -568,21 +638,24 @@ inline void reverse(R range) { template inline R2 reverse_copy(R1 irange, R2 orange) { - for (; !irange.empty(); irange.pop_back()) + for (; !irange.empty(); irange.pop_back()) { orange.put(irange.back()); + } return orange; } template inline void fill(R range, T const &v) { - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { range.front() = v; + } } template inline void generate(R range, F gen) { - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { range.front() = gen(); + } } template @@ -597,21 +670,24 @@ inline Pair swap_ranges(R1 range1, R2 range2) { template inline void iota(R range, T value) { - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { range.front() = value++; + } } template inline T foldl(R range, T init) { - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { init = init + range.front(); + } return init; } template inline T foldl_f(R range, T init, F func) { - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { init = func(init, range.front()); + } return init; } @@ -623,22 +699,28 @@ inline auto foldl(T &&init) { } template inline auto foldl_f(T &&init, F &&func) { - return [init = forward(init), func = forward(func)](auto &&obj) mutable { - return foldl_f(forward(obj), forward(init), forward(func)); + return [ + init = forward(init), func = forward(func) + ](auto &&obj) mutable { + return foldl_f( + forward(obj), forward(init), forward(func) + ); }; } template inline T foldr(R range, T init) { - for (; !range.empty(); range.pop_back()) + for (; !range.empty(); range.pop_back()) { init = init + range.back(); + } return init; } template inline T foldr_f(R range, T init, F func) { - for (; !range.empty(); range.pop_back()) + for (; !range.empty(); range.pop_back()) { init = func(init, range.back()); + } return init; } @@ -650,8 +732,12 @@ inline auto foldr(T &&init) { } template inline auto foldr_f(T &&init, F &&func) { - return [init = forward(init), func = forward(func)](auto &&obj) mutable { - return foldr_f(forward(obj), forward(init), forward(func)); + return [ + init = forward(init), func = forward(func) + ](auto &&obj) mutable { + return foldr_f( + forward(obj), forward(init), forward(func) + ); }; } @@ -734,8 +820,8 @@ public: }; namespace detail { - template using MapReturnType - = decltype(declval()(declval>())); + template + using MapReturnType = decltype(declval()(declval>())); } template @@ -760,22 +846,27 @@ private: Decay p_pred; void advance_valid() { - while (!p_range.empty() && !p_pred(front())) p_range.pop_front(); + while (!p_range.empty() && !p_pred(front())) { + p_range.pop_front(); + } } public: FilterRange() = delete; template - FilterRange(T const &range, P &&pred): p_range(range), - p_pred(forward

(pred)) { + FilterRange(T const &range, P &&pred): + p_range(range), p_pred(forward

(pred)) + { advance_valid(); } - FilterRange(FilterRange const &it): p_range(it.p_range), - p_pred(it.p_pred) { + FilterRange(FilterRange const &it): + p_range(it.p_range), p_pred(it.p_pred) + { advance_valid(); } - FilterRange(FilterRange &&it): p_range(move(it.p_range)), - p_pred(move(it.p_pred)) { + FilterRange(FilterRange &&it): + p_range(move(it.p_range)), p_pred(move(it.p_pred)) + { advance_valid(); } @@ -808,10 +899,10 @@ public: }; namespace detail { - template using FilterPred - = EnableIf()(declval>())), bool - >, P>; + template + using FilterPred = EnableIf< + IsSame()(declval>())), bool>, P + >; } template diff --git a/ostd/array.hh b/ostd/array.hh index e7d7ea1..e5503d7 100644 --- a/ostd/array.hh +++ b/ostd/array.hh @@ -31,11 +31,15 @@ struct Array { T const &operator[](Size i) const { return p_buf[i]; } T *at(Size i) { - if (!in_range(i)) return nullptr; + if (!in_range(i)) { + return nullptr; + } return &p_buf[i]; } T const *at(Size i) const { - if (!in_range(i)) return nullptr; + if (!in_range(i)) { + return nullptr; + } return &p_buf[i]; } diff --git a/ostd/atomic.hh b/ostd/atomic.hh index a6b4471..12c844a 100644 --- a/ostd/atomic.hh +++ b/ostd/atomic.hh @@ -31,7 +31,8 @@ namespace detail { T p_value; }; - template T atomic_create(); + template + T atomic_create(); template EnableIfvalue = atomic_create()), char> @@ -41,8 +42,8 @@ namespace detail { int test_atomic_assignable(...); template - constexpr bool CanAtomicAssign - = (sizeof(test_atomic_assignable(1)) == sizeof(char)); + constexpr bool CanAtomicAssign = + (sizeof(test_atomic_assignable(1)) == sizeof(char)); template static inline EnableIf< @@ -59,7 +60,9 @@ namespace detail { char volatile *to = reinterpret_cast(&a->p_value); char volatile *end = to + sizeof(T); char *from = reinterpret_cast(&v); - while (to != end) *to++ =*from++; + while (to != end) { + *to++ =*from++; + } } template @@ -88,21 +91,25 @@ static constexpr Size AtomicPointerLockFree = __GCC_ATOMIC_POINTER_LOCK_FREE; namespace detail { static inline constexpr int to_gcc_order(MemoryOrder ord) { - return ((ord == MemoryOrder::relaxed) ? __ATOMIC_RELAXED : - ((ord == MemoryOrder::acquire) ? __ATOMIC_ACQUIRE : - ((ord == MemoryOrder::release) ? __ATOMIC_RELEASE : - ((ord == MemoryOrder::seq_cst) ? __ATOMIC_SEQ_CST : - ((ord == MemoryOrder::acq_rel) ? __ATOMIC_ACQ_REL : - __ATOMIC_CONSUME))))); + return ( + ((ord == MemoryOrder::relaxed) ? __ATOMIC_RELAXED : + ((ord == MemoryOrder::acquire) ? __ATOMIC_ACQUIRE : + ((ord == MemoryOrder::release) ? __ATOMIC_RELEASE : + ((ord == MemoryOrder::seq_cst) ? __ATOMIC_SEQ_CST : + ((ord == MemoryOrder::acq_rel) ? __ATOMIC_ACQ_REL : + __ATOMIC_CONSUME))))) + ); } static inline constexpr int to_gcc_failure_order(MemoryOrder ord) { - return ((ord == MemoryOrder::relaxed) ? __ATOMIC_RELAXED : - ((ord == MemoryOrder::acquire) ? __ATOMIC_ACQUIRE : - ((ord == MemoryOrder::release) ? __ATOMIC_RELAXED : - ((ord == MemoryOrder::seq_cst) ? __ATOMIC_SEQ_CST : - ((ord == MemoryOrder::acq_rel) ? __ATOMIC_ACQUIRE : - __ATOMIC_CONSUME))))); + return ( + ((ord == MemoryOrder::relaxed) ? __ATOMIC_RELAXED : + ((ord == MemoryOrder::acquire) ? __ATOMIC_ACQUIRE : + ((ord == MemoryOrder::release) ? __ATOMIC_RELAXED : + ((ord == MemoryOrder::seq_cst) ? __ATOMIC_SEQ_CST : + ((ord == MemoryOrder::acq_rel) ? __ATOMIC_ACQUIRE : + __ATOMIC_CONSUME))))) + ); } static inline void atomic_thread_fence(MemoryOrder ord) { @@ -119,8 +126,9 @@ namespace detail { } template - static inline void atomic_store(AtomicBase volatile *a, - T v, MemoryOrder ord) { + static inline void atomic_store( + AtomicBase volatile *a, T v, MemoryOrder ord + ) { __atomic_store(&a->p_value, &v, to_gcc_order(ord)); } @@ -163,8 +171,10 @@ namespace detail { AtomicBase volatile *a, T *expected, T v, MemoryOrder success, MemoryOrder failure ) { - return __atomic_compare_exchange(&a->p_value, expected, &v, false, - to_gcc_order(success), to_gcc_failure_order(failure)); + return __atomic_compare_exchange( + &a->p_value, expected, &v, false, + to_gcc_order(success), to_gcc_failure_order(failure) + ); } template @@ -172,8 +182,10 @@ namespace detail { AtomicBase *a, T *expected, T v, MemoryOrder success, MemoryOrder failure ) { - return __atomic_compare_exchange(&a->p_value, expected, &v, false, - to_gcc_order(success), to_gcc_failure_order(failure)); + return __atomic_compare_exchange( + &a->p_value, expected, &v, false, + to_gcc_order(success), to_gcc_failure_order(failure) + ); } template @@ -181,8 +193,10 @@ namespace detail { AtomicBase volatile *a, T *expected, T v, MemoryOrder success, MemoryOrder failure ) { - return __atomic_compare_exchange(&a->p_value, expected, &v, true, - to_gcc_order(success), to_gcc_failure_order(failure)); + return __atomic_compare_exchange( + &a->p_value, expected, &v, true, + to_gcc_order(success), to_gcc_failure_order(failure) + ); } template @@ -190,8 +204,10 @@ namespace detail { AtomicBase *a, T *expected, T v, MemoryOrder success, MemoryOrder failure ) { - return __atomic_compare_exchange(&a->p_value, expected, &v, true, - to_gcc_order(success), to_gcc_failure_order(failure)); + return __atomic_compare_exchange( + &a->p_value, expected, &v, true, + to_gcc_order(success), to_gcc_failure_order(failure) + ); } template @@ -200,84 +216,96 @@ namespace detail { template struct SkipAmt { static constexpr Size value = sizeof(T); }; - template struct SkipAmt {}; - template struct SkipAmt {}; + template + struct SkipAmt {}; + + template + struct SkipAmt {}; template - static inline T atomic_fetch_add(AtomicBase volatile *a, - U d, MemoryOrder ord) { - return __atomic_fetch_add(&a->p_value, d * SkipAmt::value, - to_gcc_order(ord)); + static inline T atomic_fetch_add( + AtomicBase volatile *a, U d, MemoryOrder ord + ) { + return __atomic_fetch_add( + &a->p_value, d * SkipAmt::value, to_gcc_order(ord) + ); } template - static inline T atomic_fetch_add(AtomicBase *a, - U d, MemoryOrder ord) { - return __atomic_fetch_add(&a->p_value, d * SkipAmt::value, - to_gcc_order(ord)); + static inline T atomic_fetch_add( + AtomicBase *a, U d, MemoryOrder ord + ) { + return __atomic_fetch_add( + &a->p_value, d * SkipAmt::value, to_gcc_order(ord) + ); } template - static inline T atomic_fetch_sub(AtomicBase volatile *a, - U d, MemoryOrder ord) { - return __atomic_fetch_sub(&a->p_value, d * SkipAmt::value, - to_gcc_order(ord)); + static inline T atomic_fetch_sub( + AtomicBase volatile *a, U d, MemoryOrder ord + ) { + return __atomic_fetch_sub( + &a->p_value, d * SkipAmt::value, to_gcc_order(ord) + ); } template - static inline T atomic_fetch_sub(AtomicBase *a, - U d, MemoryOrder ord) { - return __atomic_fetch_sub(&a->p_value, d * SkipAmt::value, - to_gcc_order(ord)); + static inline T atomic_fetch_sub( + AtomicBase *a, U d, MemoryOrder ord + ) { + return __atomic_fetch_sub( + &a->p_value, d * SkipAmt::value, to_gcc_order(ord) + ); } template - static inline T atomic_fetch_and(AtomicBase volatile *a, - T pattern, MemoryOrder ord) { - return __atomic_fetch_and(&a->p_value, pattern, - to_gcc_order(ord)); + static inline T atomic_fetch_and( + AtomicBase volatile *a, T pattern, MemoryOrder ord + ) { + return __atomic_fetch_and(&a->p_value, pattern, to_gcc_order(ord)); } template - static inline T atomic_fetch_and(AtomicBase *a, - T pattern, MemoryOrder ord) { - return __atomic_fetch_and(&a->p_value, pattern, - to_gcc_order(ord)); + static inline T atomic_fetch_and( + AtomicBase *a, T pattern, MemoryOrder ord + ) { + return __atomic_fetch_and(&a->p_value, pattern, to_gcc_order(ord)); } template - static inline T atomic_fetch_or(AtomicBase volatile *a, - T pattern, MemoryOrder ord) { - return __atomic_fetch_or(&a->p_value, pattern, - to_gcc_order(ord)); + static inline T atomic_fetch_or( + AtomicBase volatile *a, T pattern, MemoryOrder ord + ) { + return __atomic_fetch_or(&a->p_value, pattern, to_gcc_order(ord)); } template - static inline T atomic_fetch_or(AtomicBase *a, - T pattern, MemoryOrder ord) { - return __atomic_fetch_or(&a->p_value, pattern, - to_gcc_order(ord)); + static inline T atomic_fetch_or( + AtomicBase *a, T pattern, MemoryOrder ord + ) { + return __atomic_fetch_or(&a->p_value, pattern, to_gcc_order(ord)); } template - static inline T atomic_fetch_xor(AtomicBase volatile *a, - T pattern, MemoryOrder ord) { - return __atomic_fetch_xor(&a->p_value, pattern, - to_gcc_order(ord)); + static inline T atomic_fetch_xor( + AtomicBase volatile *a, T pattern, MemoryOrder ord + ) { + return __atomic_fetch_xor(&a->p_value, pattern, to_gcc_order(ord)); } template - static inline T atomic_fetch_xor(AtomicBase *a, - T pattern, MemoryOrder ord) { - return __atomic_fetch_xor(&a->p_value, pattern, - to_gcc_order(ord)); + static inline T atomic_fetch_xor( + AtomicBase *a, T pattern, MemoryOrder ord + ) { + return __atomic_fetch_xor(&a->p_value, pattern, to_gcc_order(ord)); } } /* namespace detail */ #else # error Unsupported compiler #endif -template inline T kill_dependency(T v) { +template +inline T kill_dependency(T v) { return v; } @@ -330,45 +358,47 @@ namespace detail { return atomic_exchange(&p_a, v, ord); } - bool compare_exchange_weak(T &e, T v, MemoryOrder s, - MemoryOrder f) volatile { + bool compare_exchange_weak( + T &e, T v, MemoryOrder s, MemoryOrder f + ) volatile { return atomic_compare_exchange_weak(&p_a, &e, v, s, f); } - bool compare_exchange_weak(T &e, T v, MemoryOrder s, - MemoryOrder f) { + bool compare_exchange_weak(T &e, T v, MemoryOrder s, MemoryOrder f) { return atomic_compare_exchange_weak(&p_a, &e, v, s, f); } - bool compare_exchange_strong(T &e, T v, MemoryOrder s, - MemoryOrder f) volatile { + bool compare_exchange_strong( + T &e, T v, MemoryOrder s, MemoryOrder f + ) volatile { return atomic_compare_exchange_strong(&p_a, &e, v, s, f); } - bool compare_exchange_strong(T &e, T v, MemoryOrder s, - MemoryOrder f) { + bool compare_exchange_strong(T &e, T v, MemoryOrder s, MemoryOrder f) { return atomic_compare_exchange_strong(&p_a, &e, v, s, f); } - bool compare_exchange_weak(T &e, T v, MemoryOrder ord - = MemoryOrder::seq_cst) - volatile { + bool compare_exchange_weak( + T &e, T v, MemoryOrder ord = MemoryOrder::seq_cst + ) volatile { return atomic_compare_exchange_weak(&p_a, &e, v, ord, ord); } - bool compare_exchange_weak(T &e, T v, MemoryOrder ord - = MemoryOrder::seq_cst) { + bool compare_exchange_weak( + T &e, T v, MemoryOrder ord = MemoryOrder::seq_cst + ) { return atomic_compare_exchange_weak(&p_a, &e, v, ord, ord); } - bool compare_exchange_strong(T &e, T v, MemoryOrder ord - = MemoryOrder::seq_cst) - volatile { + bool compare_exchange_strong( + T &e, T v, MemoryOrder ord = MemoryOrder::seq_cst + ) volatile { return atomic_compare_exchange_strong(&p_a, &e, v, ord, ord); } - bool compare_exchange_strong(T &e, T v, MemoryOrder ord - = MemoryOrder::seq_cst) { + bool compare_exchange_strong( + T &e, T v, MemoryOrder ord = MemoryOrder::seq_cst + ) { return atomic_compare_exchange_strong(&p_a, &e, v, ord, ord); } }; @@ -421,10 +451,10 @@ namespace detail { return atomic_fetch_xor(&this->p_a, op, ord); } - T operator++(int) volatile { return fetch_add(T(1)); } - T operator++(int) { return fetch_add(T(1)); } - T operator--(int) volatile { return fetch_sub(T(1)); } - T operator--(int) { return fetch_sub(T(1)); } + T operator++(int) volatile { return fetch_add(T(1)); } + T operator++(int) { return fetch_add(T(1)); } + T operator--(int) volatile { return fetch_sub(T(1)); } + T operator--(int) { return fetch_sub(T(1)); } T operator++( ) volatile { return fetch_add(T(1)) + T(1); } T operator++( ) { return fetch_add(T(1)) + T(1); } T operator--( ) volatile { return fetch_sub(T(1)) - T(1); } @@ -581,20 +611,17 @@ inline T atomic_exchange(Atomic *a, T v) { } template -inline T atomic_exchange_explicit(Atomic volatile *a, T v, - MemoryOrder ord) { +inline T atomic_exchange_explicit(Atomic volatile *a, T v, MemoryOrder ord) { return a->exchange(v, ord); } template -inline T atomic_exchange_explicit(Atomic *a, T v, - MemoryOrder ord) { +inline T atomic_exchange_explicit(Atomic *a, T v, MemoryOrder ord) { return a->exchange(v, ord); } template -inline bool atomic_compare_exchange_weak(Atomic volatile *a, - T *e, T v) { +inline bool atomic_compare_exchange_weak(Atomic volatile *a, T *e, T v) { return a->compare_exchange_weak(*e, v); } @@ -604,8 +631,7 @@ inline bool atomic_compare_exchange_weak(Atomic *a, T *e, T v) { } template -inline bool atomic_compare_exchange_strong(Atomic volatile *a, - T *e, T v) { +inline bool atomic_compare_exchange_strong(Atomic volatile *a, T *e, T v) { return a->compare_exchange_strong(*e, v); } @@ -615,46 +641,44 @@ inline bool atomic_compare_exchange_strong(Atomic *a, T *e, T v) { } template -inline bool atomic_compare_exchange_weak_explicit(Atomic volatile *a, - T *e, T v, - MemoryOrder s, - MemoryOrder f) { +inline bool atomic_compare_exchange_weak_explicit( + Atomic volatile *a, T *e, T v, MemoryOrder s, MemoryOrder f +) { return a->compare_exchange_weak(*e, v, s, f); } template -inline bool atomic_compare_exchange_weak_explicit(Atomic *a, T *e, - T v, - MemoryOrder s, - MemoryOrder f) { +inline bool atomic_compare_exchange_weak_explicit( + Atomic *a, T *e, T v, MemoryOrder s, MemoryOrder f +) { return a->compare_exchange_weak(*e, v, s, f); } template -inline bool atomic_compare_exchange_strong_explicit(Atomic volatile *a, - T *e, T v, - MemoryOrder s, - MemoryOrder f) { +inline bool atomic_compare_exchange_strong_explicit( + Atomic volatile *a, T *e, T v, MemoryOrder s, MemoryOrder f +) { return a->compare_exchange_strong(*e, v, s, f); } template -inline bool atomic_compare_exchange_strong_explicit(Atomic *a, T *e, - T v, - MemoryOrder s, - MemoryOrder f) { +inline bool atomic_compare_exchange_strong_explicit( + Atomic *a, T *e, T v, MemoryOrder s, MemoryOrder f +) { return a->compare_exchange_strong(*e, v, s, f); } template -inline EnableIf && !IsSame, T> -atomic_fetch_add(Atomic volatile *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_add( + Atomic volatile *a, T op +) { return a->fetch_add(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_add(Atomic *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_add( + Atomic *a, T op +) { return a->fetch_add(op); } @@ -669,39 +693,44 @@ inline T *atomic_fetch_add(Atomic *a, Ptrdiff op) { } template -inline EnableIf && !IsSame, T> -atomic_fetch_add_explicit(Atomic volatile *a, T op, - MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_add_explicit( + Atomic volatile *a, T op, MemoryOrder ord +) { return a->fetch_add(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_add_explicit(Atomic *a, T op, MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_add_explicit( + Atomic *a, T op, MemoryOrder ord +) { return a->fetch_add(op, ord); } template -inline T *atomic_fetch_add_explicit(Atomic volatile *a, - Ptrdiff op, MemoryOrder ord) { +inline T *atomic_fetch_add_explicit( + Atomic volatile *a, Ptrdiff op, MemoryOrder ord +) { return a->fetch_add(op, ord); } template -inline T *atomic_fetch_add_explicit(Atomic *a, Ptrdiff op, - MemoryOrder ord) { +inline T *atomic_fetch_add_explicit( + Atomic *a, Ptrdiff op, MemoryOrder ord +) { return a->fetch_add(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_sub(Atomic volatile *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_sub( + Atomic volatile *a, T op +) { return a->fetch_sub(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_sub(Atomic *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_sub( + Atomic *a, T op +) { return a->fetch_sub(op); } @@ -716,102 +745,114 @@ inline T *atomic_fetch_sub(Atomic *a, Ptrdiff op) { } template -inline EnableIf && !IsSame, T> -atomic_fetch_sub_explicit(Atomic volatile *a, T op, - MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_sub_explicit( + Atomic volatile *a, T op, MemoryOrder ord +) { return a->fetch_sub(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_sub_explicit(Atomic *a, T op, MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_sub_explicit( + Atomic *a, T op, MemoryOrder ord +) { return a->fetch_sub(op, ord); } template -inline T *atomic_fetch_sub_explicit(Atomic volatile *a, - Ptrdiff op, MemoryOrder ord) { +inline T *atomic_fetch_sub_explicit( + Atomic volatile *a, Ptrdiff op, MemoryOrder ord +) { return a->fetch_sub(op, ord); } template -inline T *atomic_fetch_sub_explicit(Atomic *a, Ptrdiff op, - MemoryOrder ord) { +inline T *atomic_fetch_sub_explicit( + Atomic *a, Ptrdiff op, MemoryOrder ord +) { return a->fetch_sub(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_and(Atomic volatile *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_and( + Atomic volatile *a, T op +) { return a->fetch_and(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_and(Atomic *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_and( + Atomic *a, T op +) { return a->fetch_and(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_and_explicit(Atomic volatile *a, T op, - MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_and_explicit( + Atomic volatile *a, T op, MemoryOrder ord +) { return a->fetch_and(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_and_explicit(Atomic *a, T op, MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_and_explicit( + Atomic *a, T op, MemoryOrder ord +) { return a->fetch_and(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_or(Atomic volatile *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_or( + Atomic volatile *a, T op +) { return a->fetch_or(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_or(Atomic *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_or( + Atomic *a, T op +) { return a->fetch_or(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_or_explicit(Atomic volatile *a, T op, - MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_or_explicit( + Atomic volatile *a, T op, MemoryOrder ord +) { return a->fetch_or(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_or_explicit(Atomic *a, T op, MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_or_explicit( + Atomic *a, T op, MemoryOrder ord +) { return a->fetch_or(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_xor(Atomic volatile *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_xor( + Atomic volatile *a, T op +) { return a->fetch_xor(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_xor(Atomic *a, T op) { +inline EnableIf && !IsSame, T> atomic_fetch_xor( + Atomic *a, T op +) { return a->fetch_xor(op); } template -inline EnableIf && !IsSame, T> -atomic_fetch_xor_explicit(Atomic volatile *a, T op, - MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_xor_explicit( + Atomic volatile *a, T op, MemoryOrder ord +) { return a->fetch_xor(op, ord); } template -inline EnableIf && !IsSame, T> -atomic_fetch_xor_explicit(Atomic *a, T op, MemoryOrder ord) { +inline EnableIf && !IsSame, T> atomic_fetch_xor_explicit( + Atomic *a, T op, MemoryOrder ord +) { return a->fetch_xor(op, ord); } @@ -852,13 +893,13 @@ inline bool atomic_flag_test_and_set(AtomicFlag *a) { return a->test_and_set(); } -inline bool atomic_flag_test_and_set_explicit(AtomicFlag volatile *a, - MemoryOrder ord) { +inline bool atomic_flag_test_and_set_explicit( + AtomicFlag volatile *a, MemoryOrder ord +) { return a->test_and_set(ord); } -inline bool atomic_flag_test_and_set_explicit(AtomicFlag *a, - MemoryOrder ord) { +inline bool atomic_flag_test_and_set_explicit(AtomicFlag *a, MemoryOrder ord) { return a->test_and_set(ord); } @@ -870,8 +911,7 @@ inline void atomic_flag_clear(AtomicFlag *a) { a->clear(); } -inline void atomic_flag_clear_explicit(AtomicFlag volatile *a, - MemoryOrder ord) { +inline void atomic_flag_clear_explicit(AtomicFlag volatile *a, MemoryOrder ord) { a->clear(ord); } diff --git a/ostd/environ.hh b/ostd/environ.hh index 20749f6..d3e5bdc 100644 --- a/ostd/environ.hh +++ b/ostd/environ.hh @@ -24,14 +24,19 @@ inline Maybe env_get(ConstCharRange name) { auto tbuf = to_temp_cstr(name, buf, sizeof(buf)); #ifndef OSTD_PLATFORM_WIN32 char const *ret = getenv(tbuf.get()); - if (!ret) return ostd::nothing; + if (!ret) { + return ostd::nothing; + } return ostd::move(String(ret)); #else String rbuf; for (;;) { - auto ret = GetEnvironmentVariable(tbuf.get(), rbuf.data(), - rbuf.capacity() + 1); - if (!ret) return ostd::nothing; + auto ret = GetEnvironmentVariable( + tbuf.get(), rbuf.data(), rbuf.capacity() + 1 + ); + if (!ret) { + return ostd::nothing; + } if (ret <= rbuf.capacity()) { rbuf.advance(ret); break; @@ -42,13 +47,15 @@ inline Maybe env_get(ConstCharRange name) { #endif } -inline bool env_set(ConstCharRange name, ConstCharRange value, - bool update = true) { +inline bool env_set( + ConstCharRange name, ConstCharRange value, bool update = true +) { char sbuf[2048]; char *buf = sbuf; bool alloc = (name.size() + value.size() + 2) > sizeof(sbuf); - if (alloc) + if (alloc) { buf = new char[name.size() + value.size() + 2]; + } memcpy(buf, name.data(), name.size()); buf[name.size()] = '\0'; memcpy(&buf[name.size() + 1], value.data(), value.size()); @@ -56,12 +63,14 @@ inline bool env_set(ConstCharRange name, ConstCharRange value, #ifndef OSTD_PLATFORM_WIN32 bool ret = !setenv(buf, &buf[name.size() + 1], update); #else - if (!update && GetEnvironmentVariable(buf, nullptr, 0)) + if (!update && GetEnvironmentVariable(buf, nullptr, 0)) { return true; + } bool ret = !!SetEnvironmentVariable(buf, &buf[name.size() + 1]); #endif - if (alloc) + if (alloc) { delete[] buf; + } return ret; } @@ -79,7 +88,7 @@ inline bool env_unset(ConstCharRange name) { #ifndef OSTD_PLATFORM_WIN32 return !unsetenv(String(name).data()); #else - return !!SetEnvironmentVariable(String(name).data(), nullptr); + return !!SetEnvironmentVariable(String(name).data(), nullptr); #endif } diff --git a/ostd/event.hh b/ostd/event.hh index 7088888..4a60e6a 100644 --- a/ostd/event.hh +++ b/ostd/event.hh @@ -16,8 +16,9 @@ namespace detail { struct SignalBase { SignalBase(C *cl): p_class(cl), p_funcs(nullptr), p_nfuncs(0) {} - SignalBase(SignalBase const &ev): p_class(ev.p_class), - p_nfuncs(ev.p_nfuncs) { + SignalBase(SignalBase const &ev): + p_class(ev.p_class), p_nfuncs(ev.p_nfuncs) + { using Func = Function; byte *bufp = new byte[sizeof(Func) * p_nfuncs]; Func *nbuf = reinterpret_cast(bufp); @@ -26,8 +27,9 @@ namespace detail { p_funcs = nbuf; } - SignalBase(SignalBase &&ev): p_class(nullptr), p_funcs(nullptr), - p_nfuncs(0) { + SignalBase(SignalBase &&ev): + p_class(nullptr), p_funcs(nullptr), p_nfuncs(0) + { swap(ev); } @@ -37,8 +39,9 @@ namespace detail { p_nfuncs = ev.p_nfuncs; byte *bufp = new byte[sizeof(Func) * p_nfuncs]; Func *nbuf = reinterpret_cast(bufp); - for (Size i = 0; i < p_nfuncs; ++i) + for (Size i = 0; i < p_nfuncs; ++i) { new (&nbuf[i]) Func(ev.p_funcs[i]); + } p_funcs = nbuf; return *this; } @@ -51,8 +54,9 @@ namespace detail { ~SignalBase() { clear(); } void clear() { - for (Size i = 0; i < p_nfuncs; ++i) + for (Size i = 0; i < p_nfuncs; ++i) { p_funcs[i].~Function(); + } delete[] reinterpret_cast(p_funcs); p_funcs = nullptr; p_nfuncs = 0; @@ -80,16 +84,23 @@ namespace detail { } bool disconnect(Size idx) { - if ((idx >= p_nfuncs) || !p_funcs[idx]) return false; + if ((idx >= p_nfuncs) || !p_funcs[idx]) { + return false; + } p_funcs[idx] = nullptr; return true; } template void emit(Args &&...args) const { - if (!p_class) return; - for (Size i = 0; i < p_nfuncs; ++i) - if (p_funcs[i]) p_funcs[i](*p_class, args...); + if (!p_class) { + return; + } + for (Size i = 0; i < p_nfuncs; ++i) { + if (p_funcs[i]) { + p_funcs[i](*p_class, args...); + } + } } C *get_class() const { diff --git a/ostd/ext/sdl_rwops.hh b/ostd/ext/sdl_rwops.hh index 6119488..c0985a6 100644 --- a/ostd/ext/sdl_rwops.hh +++ b/ostd/ext/sdl_rwops.hh @@ -29,28 +29,41 @@ inline SDL_RWops *stream_to_rwops(Stream &s) { if (!rwr) { return nullptr; } + rwr->hidden.unknown.data1 = &s; + rwr->size = [](SDL_RWops *rw) -> SDLRWopsOffset { Stream *is = static_cast(rw->hidden.unknown.data1); return static_cast(is->size()); }; - rwr->seek = [](SDL_RWops *rw, SDLRWopsOffset pos, int whence) -> SDLRWopsOffset { + + rwr->seek = [](SDL_RWops *rw, SDLRWopsOffset pos, int whence) -> + SDLRWopsOffset + { Stream *is = static_cast(rw->hidden.unknown.data1); - if (!pos && whence == SEEK_CUR) + if (!pos && whence == SEEK_CUR) { return static_cast(is->tell()); - if (is->seek(((StreamOffset)pos, (StreamSeek)whence)) + } + if (is->seek(((StreamOffset)pos, (StreamSeek)whence)) { return static_cast(is->tell()); + } return -1; }; + rwr->read = [](SDL_RWops *rw, void *buf, Size size, Size nb) -> Size { Stream *is = static_cast(rw->hidden.unknown.data1); return is->read_bytes(buf, size * nb) / size; }; + rwr->write = [](SDL_RWops *rw, const void *buf, Size size, Size nb) -> Size { Stream *is = static_cast(rw->hidden.unknown.data1); return is->write_bytes(buf, size * nb) / size; }; - rwr->close = [](SDL_RWops *) -> int { return 0; }; + + rwr->close = [](SDL_RWops *) -> int { + return 0; + }; + return rwr; } diff --git a/ostd/filesystem.hh b/ostd/filesystem.hh index a2f0c48..683904a 100644 --- a/ostd/filesystem.hh +++ b/ostd/filesystem.hh @@ -59,12 +59,14 @@ struct FileInfo { FileInfo(FileInfo const &i): p_slash(i.p_slash), p_dot(i.p_dot), p_type(i.p_type), p_path(i.p_path), p_atime(i.p_atime), p_mtime(i.p_mtime), - p_ctime(i.p_ctime) {} + p_ctime(i.p_ctime) + {} FileInfo(FileInfo &&i): p_slash(i.p_slash), p_dot(i.p_dot), p_type(i.p_type), p_path(move(i.p_path)), p_atime(i.p_atime), p_mtime(i.p_mtime), - p_ctime(i.p_ctime) { + p_ctime(i.p_ctime) + { i.p_slash = i.p_dot = npos; i.p_type = FileType::unknown; i.p_atime = i.p_ctime = i.p_mtime = 0; @@ -93,18 +95,22 @@ struct FileInfo { ConstCharRange path() const { return p_path.iter(); } ConstCharRange filename() const { - return path().slice((p_slash == npos) ? 0 : (p_slash + 1), - p_path.size()); + return path().slice( + (p_slash == npos) ? 0 : (p_slash + 1), p_path.size() + ); } ConstCharRange stem() const { - return path().slice((p_slash == npos) ? 0 : (p_slash + 1), - (p_dot == npos) ? p_path.size() : p_dot); + return path().slice( + (p_slash == npos) ? 0 : (p_slash + 1), + (p_dot == npos) ? p_path.size() : p_dot + ); } ConstCharRange extension() const { - return (p_dot == npos) ? ConstCharRange() - : path().slice(p_dot, p_path.size()); + return (p_dot == npos) + ? ConstCharRange() + : path().slice(p_dot, p_path.size()); } FileType type() const { return p_type; } @@ -150,53 +156,55 @@ private: ConstCharRange r = p_path.iter(); ConstCharRange found = find_last(r, PathSeparator); - if (found.empty()) + if (found.empty()) { p_slash = npos; - else + } else { p_slash = r.distance_front(found); + } found = find(filename(), '.'); - if (found.empty()) + if (found.empty()) { p_dot = npos; - else + } else { p_dot = r.distance_front(found); + } #ifdef OSTD_PLATFORM_WIN32 - if (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + if (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { p_type = FileType::directory; - else if (attr.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) + } else if (attr.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { p_type = FileType::symlink; - else if (attr.dwFileAttributes & (FILE_ATTRIBUTE_ARCHIVE | - FILE_ATTRIBUTE_COMPRESSED | - FILE_ATTRIBUTE_COMPRESSED | - FILE_ATTRIBUTE_HIDDEN | - FILE_ATTRIBUTE_NORMAL | - FILE_ATTRIBUTE_SPARSE_FILE | - FILE_ATTRIBUTE_TEMPORARY)) + } else if (attr.dwFileAttributes & ( + FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_COMPRESSED | + FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_NORMAL | + FILE_ATTRIBUTE_SPARSE_FILE | FILE_ATTRIBUTE_TEMPORARY + )) { p_type = FileType::regular; - else + } else { p_type = FileType::unknown; + } p_atime = detail::filetime_to_time_t(attr.ftLastAccessTime); p_mtime = detail::filetime_to_time_t(attr.ftLastWriteTime); p_ctime = detail::filetime_to_time_t(attr.ftCreationTime); #else - if (S_ISREG(st.st_mode)) + if (S_ISREG(st.st_mode)) { p_type = FileType::regular; - else if (S_ISDIR(st.st_mode)) + } else if (S_ISDIR(st.st_mode)) { p_type = FileType::directory; - else if (S_ISCHR(st.st_mode)) + } else if (S_ISCHR(st.st_mode)) { p_type = FileType::character; - else if (S_ISBLK(st.st_mode)) + } else if (S_ISBLK(st.st_mode)) { p_type = FileType::block; - else if (S_ISFIFO(st.st_mode)) + } else if (S_ISFIFO(st.st_mode)) { p_type = FileType::fifo; - else if (S_ISLNK(st.st_mode)) + } else if (S_ISLNK(st.st_mode)) { p_type = FileType::symlink; - else if (S_ISSOCK(st.st_mode)) + } else if (S_ISSOCK(st.st_mode)) { p_type = FileType::socket; - else + } else { p_type = FileType::unknown; + } p_atime = st.st_atime; p_mtime = st.st_mtime; @@ -219,9 +227,9 @@ struct DirectoryStream { DirectoryStream(): p_d(), p_de(), p_dev(), p_path() {} DirectoryStream(DirectoryStream const &) = delete; - DirectoryStream(DirectoryStream &&s): p_d(s.p_d), p_de(s.p_de), - p_dev(s.p_dev), - p_path(move(s.p_path)) { + DirectoryStream(DirectoryStream &&s): + p_d(s.p_d), p_de(s.p_de), p_dev(s.p_dev), p_path(move(s.p_path)) + { s.p_d = nullptr; s.p_de = nullptr; memset(&s.p_dev, 0, sizeof(s.p_dev)); @@ -241,7 +249,9 @@ struct DirectoryStream { } bool open(ConstCharRange path) { - if (p_d || (path.size() > FILENAME_MAX)) return false; + if (p_d || (path.size() > FILENAME_MAX)) { + return false; + } char buf[FILENAME_MAX + 1]; memcpy(buf, &path[0], path.size()); buf[path.size()] = '\0'; @@ -263,20 +273,27 @@ struct DirectoryStream { } long size() const { - if (!p_d) return -1; + if (!p_d) { + return -1; + } DIR *td = opendir(p_path.data()); - if (!td) return -1; + if (!td) { + return -1; + } long ret = 0; struct dirent rdv; struct dirent *rd; - while (pop_front(td, &rdv, &rd)) + while (pop_front(td, &rdv, &rd)) { ret += strcmp(rd->d_name, ".") && strcmp(rd->d_name, ".."); + } closedir(td); return ret; } bool rewind() { - if (!p_d) return false; + if (!p_d) { + return false; + } rewinddir(p_d); if (!pop_front()) { close(); @@ -290,8 +307,9 @@ struct DirectoryStream { } FileInfo read() { - if (!pop_front()) + if (!pop_front()) { return FileInfo(); + } return front(); } @@ -311,10 +329,12 @@ private: /* order of . and .. in the stream is not guaranteed, apparently... * gotta check every time because of that */ - while (*de && (!strcmp((*de)->d_name, ".") || - !strcmp((*de)->d_name, ".."))) { - if (readdir_r(d, dev, de)) + while (*de && ( + !strcmp((*de)->d_name, ".") || !strcmp((*de)->d_name, "..") + )) { + if (readdir_r(d, dev, de)) { return false; + } } return !!*de; } @@ -324,8 +344,9 @@ private: } FileInfo front() const { - if (!p_de) + if (!p_de) { return FileInfo(); + } String ap = p_path; ap += PathSeparator; ap += static_cast(p_de->d_name); @@ -345,9 +366,9 @@ struct DirectoryStream { DirectoryStream(): p_handle(INVALID_HANDLE_VALUE), p_data(), p_path() {} DirectoryStream(DirectoryStream const &) = delete; - DirectoryStream(DirectoryStream &&s): p_handle(s.p_handle), - p_data(s.p_data), - p_path(move(s.p_path)) { + DirectoryStream(DirectoryStream &&s): + p_handle(s.p_handle), p_data(s.p_data), p_path(move(s.p_path)) + { s.p_handle = INVALID_HANDLE_VALUE; memset(&s.p_data, 0, sizeof(s.p_data)); } @@ -366,10 +387,12 @@ struct DirectoryStream { } bool open(ConstCharRange path) { - if (p_handle != INVALID_HANDLE_VALUE) + if (p_handle != INVALID_HANDLE_VALUE) { return false; - if ((path.size() >= 1024) || !path.size()) + } + if ((path.size() >= 1024) || !path.size()) { return false; + } char buf[1026]; memcpy(buf, &path[0], path.size()); char *bptr = &buf[path.size()]; @@ -378,10 +401,12 @@ struct DirectoryStream { /* include trailing zero */ memcpy(bptr, "\\*", 3); p_handle = FindFirstFile(buf, &p_data); - if (p_handle == INVALID_HANDLE_VALUE) + if (p_handle == INVALID_HANDLE_VALUE) { return false; - while (!strcmp(p_data.cFileName, ".") || - !strcmp(p_data.cFileName, "..")) { + } + while ( + !strcmp(p_data.cFileName, ".") || !strcmp(p_data.cFileName, "..") + ) { if (!FindNextFile(p_handle, &p_data)) { FindClose(p_handle); p_handle = INVALID_HANDLE_VALUE; @@ -396,47 +421,55 @@ struct DirectoryStream { bool is_open() const { return p_handle != INVALID_HANDLE_VALUE; } void close() { - if (p_handle != INVALID_HANDLE_VALUE) + if (p_handle != INVALID_HANDLE_VALUE) { FindClose(p_handle); + } p_handle = INVALID_HANDLE_VALUE; p_data.cFileName[0] = '\0'; } long size() const { - if (p_handle == INVALID_HANDLE_VALUE) + if (p_handle == INVALID_HANDLE_VALUE) { return -1; + } WIN32_FIND_DATA wfd; HANDLE td = FindFirstFile(p_path.data(), &wfd); - if (td == INVALID_HANDLE_VALUE) + if (td == INVALID_HANDLE_VALUE) { return -1; - while (!strcmp(wfd.cFileName, ".") && !strcmp(wfd.cFileName, "..")) + } + while (!strcmp(wfd.cFileName, ".") && !strcmp(wfd.cFileName, "..")) { if (!FindNextFile(td, &wfd)) { FindClose(td); return 0; } + } long ret = 1; - while (FindNextFile(td, &wfd)) + while (FindNextFile(td, &wfd)) { ++ret; + } FindClose(td); return ret; } bool rewind() { - if (p_handle != INVALID_HANDLE_VALUE) + if (p_handle != INVALID_HANDLE_VALUE) { FindClose(p_handle); + } p_handle = FindFirstFile(p_path.data(), &p_data); if (p_handle == INVALID_HANDLE_VALUE) { p_data.cFileName[0] = '\0'; return false; } - while (!strcmp(p_data.cFileName, ".") || - !strcmp(p_data.cFileName, "..")) + while ( + !strcmp(p_data.cFileName, ".") || !strcmp(p_data.cFileName, "..") + ) { if (!FindNextFile(p_handle, &p_data)) { FindClose(p_handle); p_handle = INVALID_HANDLE_VALUE; p_data.cFileName[0] = '\0'; return false; } + } return true; } @@ -445,8 +478,9 @@ struct DirectoryStream { } FileInfo read() { - if (!pop_front()) + if (!pop_front()) { return FileInfo(); + } return front(); } @@ -460,8 +494,9 @@ struct DirectoryStream { private: bool pop_front() { - if (!is_open()) + if (!is_open()) { return false; + } if (!FindNextFile(p_handle, &p_data)) { p_data.cFileName[0] = '\0'; return false; @@ -470,8 +505,9 @@ private: } FileInfo front() const { - if (empty()) + if (empty()) { return FileInfo(); + } String ap = p_path; ap += PathSeparator; ap += static_cast(p_data.cFileName); @@ -521,7 +557,8 @@ inline DirectoryRange DirectoryStream::iter() { } namespace detail { - template struct PathJoin { + template + struct PathJoin { template static void join(String &s, T const &a, A const &...b) { s += a; @@ -530,7 +567,8 @@ namespace detail { } }; - template<> struct PathJoin<1> { + template<> + struct PathJoin<1> { template static void join(String &s, T const &a) { s += a; @@ -548,8 +586,9 @@ inline FileInfo path_join(A const &...args) { inline bool directory_change(ConstCharRange path) { char buf[1024]; - if (path.size() >= 1024) + if (path.size() >= 1024) { return false; + } memcpy(buf, path.data(), path.size()); buf[path.size()] = '\0'; #ifndef OSTD_PLATFORM_WIN32 diff --git a/ostd/format.hh b/ostd/format.hh index d86ceee..87076a2 100644 --- a/ostd/format.hh +++ b/ostd/format.hh @@ -110,17 +110,17 @@ namespace detail { /* retrieve width/precision */ template - bool convert_arg_param(T const &val, int ¶m, EnableIf< - IsIntegral, bool - > = true) { + bool convert_arg_param( + T const &val, int ¶m, EnableIf, bool> = true + ) { param = int(val); return true; } template - bool convert_arg_param(T const &, int &, EnableIf< - !IsIntegral, bool - > = true) { + bool convert_arg_param( + T const &, int &, EnableIf, bool> = true + ) { assert(false && "invalid argument for width/precision"); return false; } @@ -135,7 +135,9 @@ namespace detail { } template bool get_arg_param(Size idx, int ¶m, T const &val, A const &...args) { - if (idx) return get_arg_param(idx - 1, param, args...); + if (idx) { + return get_arg_param(idx - 1, param, args...); + } return convert_arg_param(val, param); } } @@ -143,19 +145,28 @@ namespace detail { struct FormatSpec { FormatSpec(): p_nested_escape(false), p_fmt() {} FormatSpec(ConstCharRange fmt, bool escape = false): - p_nested_escape(escape), p_fmt(fmt) {} + p_nested_escape(escape), p_fmt(fmt) + {} template bool read_until_spec(R &writer, Size *wret) { Size written = 0; - if (wret) *wret = 0; - if (p_fmt.empty()) return false; + if (wret) { + *wret = 0; + } + if (p_fmt.empty()) { + return false; + } while (!p_fmt.empty()) { if (p_fmt.front() == '%') { p_fmt.pop_front(); - if (p_fmt.front() == '%') goto plain; + if (p_fmt.front() == '%') { + goto plain; + } bool r = read_spec(); - if (wret) *wret = written; + if (wret) { + *wret = written; + } return r; } plain: @@ -163,16 +174,22 @@ struct FormatSpec { writer.put(p_fmt.front()); p_fmt.pop_front(); } - if (wret) *wret = written; + if (wret) { + *wret = written; + } return false; } template Size write_spaces(R &writer, Size n, bool left, char c = ' ') const { - if (left == bool(p_flags & FMT_FLAG_DASH)) return 0; + if (left == bool(p_flags & FMT_FLAG_DASH)) { + return 0; + } int r = p_width - int(n); for (int w = p_width - int(n); --w >= 0; writer.put(c)); - if (r < 0) return 0; + if (r < 0) { + return 0; + } return r; } @@ -183,11 +200,21 @@ struct FormatSpec { template Size build_spec(R &&out, ConstCharRange spec) { Size ret = out.put('%'); - if (p_flags & FMT_FLAG_DASH ) ret += out.put('-'); - if (p_flags & FMT_FLAG_ZERO ) ret += out.put('0'); - if (p_flags & FMT_FLAG_SPACE) ret += out.put(' '); - if (p_flags & FMT_FLAG_PLUS ) ret += out.put('+'); - if (p_flags & FMT_FLAG_HASH ) ret += out.put('#'); + if (p_flags & FMT_FLAG_DASH ) { + ret += out.put('-'); + } + if (p_flags & FMT_FLAG_ZERO ) { + ret += out.put('0'); + } + if (p_flags & FMT_FLAG_SPACE) { + ret += out.put(' '); + } + if (p_flags & FMT_FLAG_PLUS ) { + ret += out.put('+'); + } + if (p_flags & FMT_FLAG_HASH ) { + ret += out.put('#'); + } ret += out.put_n("*.*", 3); ret += out.put_n(&spec[0], spec.size()); return ret; @@ -250,7 +277,9 @@ protected: while (!p_fmt.empty()) { if (p_fmt.front() == '%') { p_fmt.pop_front(); - if (p_fmt.front() == '%') goto plain; + if (p_fmt.front() == '%') { + goto plain; + } return read_spec(); } plain: @@ -339,12 +368,17 @@ protected: p_flags = detail::parse_fmt_flags(p_fmt, 0); } else { for (Size i = 0; i < ndig; ++i) { - if (p_buf[i] != '0') break; + if (p_buf[i] != '0') { + break; + } ++skipd; } - if (skipd) p_flags = FMT_FLAG_ZERO; - if (skipd == ndig) + if (skipd) { + p_flags = FMT_FLAG_ZERO; + } + if (skipd == ndig) { p_flags = detail::parse_fmt_flags(p_fmt, p_flags); + } } /* range/array formatting */ @@ -371,7 +405,9 @@ protected: p_precision = 0; p_has_precision = false; p_arg_precision = false; - if (p_fmt.front() != '.') goto fmtchar; + if (p_fmt.front() != '.') { + goto fmtchar; + } p_fmt.pop_front(); if (detail::read_digits(p_fmt, p_buf)) { @@ -380,7 +416,9 @@ protected: } else if (p_fmt.front() == '*') { p_arg_precision = p_has_precision = true; p_fmt.pop_front(); - } else return false; + } else { + return false; + } fmtchar: p_spec = p_fmt.front(); @@ -397,11 +435,14 @@ protected: /* for custom container formatting */ -template() - .to_format(declval(), declval())), bool +template< + typename T, typename R, typename = EnableIf< + IsSame() + .to_format(declval(), declval())), bool + > > ->> inline bool to_format(T const &v, R &writer, FormatSpec const &fs) { +> +inline bool to_format(T const &v, R &writer, FormatSpec const &fs) { return v.to_format(writer, fs); } @@ -421,9 +462,12 @@ namespace detail { } int base = detail::fmt_bases[specn]; - if (!val) buf[n++] = '0'; - for (; val; val /= base) + if (!val) { + buf[n++] = '0'; + } + for (; val; val /= base) { buf[n++] = detail::fmt_digits[spec >= 'a'][val % base]; + } r = n; int flags = fl->flags(); @@ -441,12 +485,16 @@ namespace detail { r += pfxlen; } - if (!zero) + if (!zero) { r += fl->write_spaces(writer, n + pfxlen + sign, true, ' '); - if (sign) writer.put(neg ? '-' : *((" \0+") + lsgn * 2)); + } + if (sign) { + writer.put(neg ? '-' : *((" \0+") + lsgn * 2)); + } writer.put_n(pfx, pfxlen); - if (zero) + if (zero) { r += fl->write_spaces(writer, n + pfxlen + sign, true, '0'); + } for (int i = int(n - 1); i >= 0; --i) { writer.put(buf[i]); @@ -456,8 +504,10 @@ namespace detail { } template - static Ptrdiff format_impl(R &writer, Size &fmtn, bool escape, - ConstCharRange fmt, A const &...args); + static Ptrdiff format_impl( + R &writer, Size &fmtn, bool escape, + ConstCharRange fmt, A const &...args + ); template> static True test_fmt_range(int); @@ -470,88 +520,99 @@ namespace detail { template struct FmtTupleUnpacker { template - static inline Ptrdiff unpack(R &writer, Size &fmtn, bool esc, - ConstCharRange fmt, T const &item, - A const &...args) { - return FmtTupleUnpacker::unpack(writer, fmtn, esc, fmt, - item, get(item), args...); + static inline Ptrdiff unpack( + R &writer, Size &fmtn, bool esc, ConstCharRange fmt, + T const &item, A const &...args + ) { + return FmtTupleUnpacker::unpack( + writer, fmtn, esc, fmt, item, get(item), args... + ); } }; template<> struct FmtTupleUnpacker<0> { template - static inline Ptrdiff unpack(R &writer, Size &fmtn, bool esc, - ConstCharRange fmt, T const &, - A const &...args) { + static inline Ptrdiff unpack( + R &writer, Size &fmtn, bool esc, ConstCharRange fmt, + T const &, A const &...args + ) { return format_impl(writer, fmtn, esc, fmt, args...); } }; template - inline Ptrdiff format_ritem(R &writer, Size &fmtn, bool esc, bool, - ConstCharRange fmt, T const &item, - EnableIf, bool> - = true) { + inline Ptrdiff format_ritem( + R &writer, Size &fmtn, bool esc, bool, ConstCharRange fmt, + T const &item, EnableIf, bool> = true + ) { return format_impl(writer, fmtn, esc, fmt, item); } template - inline Ptrdiff format_ritem(R &writer, Size &fmtn, bool esc, - bool expandval, ConstCharRange fmt, - T const &item, - EnableIf, bool> - = true) { + inline Ptrdiff format_ritem( + R &writer, Size &fmtn, bool esc, bool expandval, ConstCharRange fmt, + T const &item, EnableIf, bool> = true + ) { if (expandval) { - return FmtTupleUnpacker>::unpack(writer, - fmtn, esc, fmt, item); + return FmtTupleUnpacker>::unpack( + writer, fmtn, esc, fmt, item + ); } return format_impl(writer, fmtn, esc, fmt, item); } template - inline Ptrdiff write_range(R &writer, FormatSpec const *fl, - bool escape, bool expandval, - ConstCharRange sep, - T const &val, - EnableIf, bool> - = true) { + inline Ptrdiff write_range( + R &writer, FormatSpec const *fl, bool escape, bool expandval, + ConstCharRange sep, T const &val, EnableIf, bool> = true + ) { auto range = ostd::iter(val); - if (range.empty()) return 0; + if (range.empty()) { + return 0; + } Ptrdiff ret = 0; Size fmtn = 0; /* test first item */ - Ptrdiff fret = format_ritem(writer, fmtn, escape, expandval, - fl->rest(), range.front()); - if (fret < 0) return fret; + Ptrdiff fret = format_ritem( + writer, fmtn, escape, expandval, fl->rest(), range.front() + ); + if (fret < 0) { + return fret; + } ret += fret; range.pop_front(); /* write the rest (if any) */ for (; !range.empty(); range.pop_front()) { auto v = writer.put_n(&sep[0], sep.size()); - if (v != sep.size()) + if (v != sep.size()) { return -1; + } ret += sep.size(); - fret = format_ritem(writer, fmtn, escape, expandval, - fl->rest(), range.front()); - if (fret < 0) return fret; + fret = format_ritem( + writer, fmtn, escape, expandval, fl->rest(), range.front() + ); + if (fret < 0) { + return fret; + } ret += fret; } return ret; } template - inline Ptrdiff write_range(R &, FormatSpec const *, bool, bool, - ConstCharRange, T const &, - EnableIf, bool> - = true) { + inline Ptrdiff write_range( + R &, FormatSpec const *, bool, bool, ConstCharRange, + T const &, EnableIf, bool> = true + ) { assert(false && "invalid value for ranged format"); return -1; } template static True test_fmt_tostr(decltype(ostd::to_string(declval())) *); - template static False test_fmt_tostr(...); + template + static False test_fmt_tostr(...); template constexpr bool FmtTostrTest = decltype(test_fmt_tostr(0))::value; @@ -583,10 +644,11 @@ namespace detail { ret.push('"'); while (!val.empty()) { char const *esc = escape_fmt_char(val.front(), '"'); - if (esc) + if (esc) { ret.append(esc); - else + } else { ret.push(val.front()); + } val.pop_front(); } ret.push('"'); @@ -594,9 +656,9 @@ namespace detail { } template - static True test_tofmt(decltype(to_format(declval(), - declval(), - declval())) *); + static True test_tofmt(decltype(to_format( + declval(), declval(), declval() + )) *); template static False test_tofmt(...); @@ -615,7 +677,9 @@ namespace detail { return write_str(writer, false, escape_fmt_str(val)); } Size n = val.size(); - if (this->precision()) n = this->precision(); + if (this->precision()) { + n = this->precision(); + } Ptrdiff r = n; r += this->write_spaces(writer, n, true); writer.put_n(&val[0], n); @@ -625,9 +689,11 @@ namespace detail { /* any string value */ template - Ptrdiff write(R &writer, bool escape, T const &val, EnableIf< - IsConstructible, bool - > = true) { + Ptrdiff write( + R &writer, bool escape, T const &val, EnableIf< + IsConstructible, bool + > = true + ) { if (this->spec() != 's') { assert(false && "cannot print strings with the given spec"); return -1; @@ -661,7 +727,9 @@ namespace detail { writer.put('\''); writer.put(val); writer.put('\''); - } else writer.put(val); + } else { + writer.put(val); + } r += this->write_spaces(writer, 1 + escape * 2, false); return r; } @@ -669,33 +737,41 @@ namespace detail { /* bool */ template Ptrdiff write(R &writer, bool, bool val) { - if (this->spec() == 's') + if (this->spec() == 's') { return write(writer, ("false\0true") + (6 * val)); - else + } else { return write(writer, int(val)); + } } /* signed integers */ template - Ptrdiff write(R &writer, bool, T val, EnableIf< - IsIntegral && IsSigned, bool - > = true) { + Ptrdiff write( + R &writer, bool, T val, EnableIf< + IsIntegral && IsSigned, bool + > = true + ) { using UT = MakeUnsigned; - return detail::write_u(writer, this, val < 0, - (val < 0) ? static_cast(-val) : static_cast(val)); + return detail::write_u( + writer, this, val < 0, + (val < 0) ? static_cast(-val) : static_cast(val) + ); } /* unsigned integers */ template - Ptrdiff write(R &writer, bool, T val, EnableIf< - IsIntegral && IsUnsigned, bool - > = true) { + Ptrdiff write( + R &writer, bool, T val, EnableIf< + IsIntegral && IsUnsigned, bool + > = true + ) { return detail::write_u(writer, this, false, val); } template> - Ptrdiff write(R &writer, bool, T val, EnableIf, bool> - = true) { + Ptrdiff write( + R &writer, bool, T val, EnableIf, bool> = true + ) { char buf[16], rbuf[128]; char fmtspec[Long + 1]; @@ -705,31 +781,42 @@ namespace detail { assert(false && "cannot format floats with the given spec"); return -1; } - if (specn == 7) fmtspec[Long] = 'g'; - if (Long) fmtspec[0] = 'L'; + if (specn == 7) { + fmtspec[Long] = 'g'; + } + if (Long) { + fmtspec[0] = 'L'; + } buf[this->build_spec(iter(buf), fmtspec)] = '\0'; - Ptrdiff ret = snprintf(rbuf, sizeof(rbuf), buf, - this->width(), - this->has_precision() ? this->precision() : 6, val); + Ptrdiff ret = snprintf( + rbuf, sizeof(rbuf), buf, this->width(), + this->has_precision() ? this->precision() : 6, val + ); char *dbuf = nullptr; if (Size(ret) >= sizeof(rbuf)) { /* this should typically never happen */ dbuf = new char[ret + 1]; - ret = snprintf(dbuf, ret + 1, buf, this->width(), - this->has_precision() ? this->precision() : 6, val); + ret = snprintf( + dbuf, ret + 1, buf, this->width(), + this->has_precision() ? this->precision() : 6, val + ); writer.put_n(dbuf, ret); delete[] dbuf; - } else writer.put_n(rbuf, ret); + } else { + writer.put_n(rbuf, ret); + } return ret; } /* pointer value */ template - Ptrdiff write(R &writer, bool, T *val, EnableIf< - !IsConstructible, bool - > = true) { + Ptrdiff write( + R &writer, bool, T *val, EnableIf< + !IsConstructible, bool + > = true + ) { if (this->p_spec == 's') { this->p_spec = 'x'; this->p_flags |= FMT_FLAG_HASH; @@ -739,11 +826,13 @@ namespace detail { /* generic value */ template - Ptrdiff write(R &writer, bool, T const &val, EnableIf< - !IsArithmetic && - !IsConstructible && - FmtTostrTest && !FmtTofmtTest>, bool - > = true) { + Ptrdiff write( + R &writer, bool, T const &val, EnableIf< + !IsArithmetic && + !IsConstructible && + FmtTostrTest && !FmtTofmtTest>, bool + > = true + ) { if (this->spec() != 's') { assert(false && "custom objects need '%s' format"); return -1; @@ -753,21 +842,26 @@ namespace detail { /* custom format case */ template - Ptrdiff write(R &writer, bool, T const &val, - EnableIf>, bool - > = true) { + Ptrdiff write( + R &writer, bool, T const &val, + EnableIf>, bool> = true + ) { TostrRange sink(writer); - if (!to_format(val, sink, *this)) return -1; + if (!to_format(val, sink, *this)) { + return -1; + } return sink.get_written(); } /* generic failure case */ template - Ptrdiff write(R &, bool, T const &, EnableIf< - !IsArithmetic && - !IsConstructible && - !FmtTostrTest && !FmtTofmtTest>, bool - > = true) { + Ptrdiff write( + R &, bool, T const &, EnableIf< + !IsArithmetic && + !IsConstructible && + !FmtTostrTest && !FmtTofmtTest>, bool + > = true + ) { assert(false && "value cannot be formatted"); return -1; } @@ -783,39 +877,48 @@ namespace detail { } template - Ptrdiff write_arg(R &writer, Size idx, T const &val, - A const &...args) { - if (idx) return write_arg(writer, idx - 1, args...); + Ptrdiff write_arg( + R &writer, Size idx, T const &val, A const &...args + ) { + if (idx) { + return write_arg(writer, idx - 1, args...); + } return write(writer, this->p_nested_escape, val); } /* range writer */ template - Ptrdiff write_range(R &writer, Size idx, bool expandval, - ConstCharRange sep, T const &val) { + Ptrdiff write_range( + R &writer, Size idx, bool expandval, + ConstCharRange sep, T const &val + ) { if (idx) { assert(false && "not enough format args"); return -1; } - return detail::write_range(writer, this, this->p_nested_escape, - expandval, sep, val); + return detail::write_range( + writer, this, this->p_nested_escape, expandval, sep, val + ); } template - Ptrdiff write_range(R &writer, Size idx, bool expandval, - ConstCharRange sep, T const &val, - A const &...args) { + Ptrdiff write_range( + R &writer, Size idx, bool expandval, ConstCharRange sep, + T const &val, A const &...args + ) { if (idx) { return write_range(writer, idx - 1, expandval, sep, args...); } - return detail::write_range(writer, this, - this->p_nested_escape, expandval, sep, val); + return detail::write_range( + writer, this, this->p_nested_escape, expandval, sep, val + ); } }; template - inline Ptrdiff format_impl(R &writer, Size &fmtn, bool escape, - ConstCharRange fmt, A const &...args) { + inline Ptrdiff format_impl( + R &writer, Size &fmtn, bool escape, ConstCharRange fmt, A const &...args + ) { Size argidx = 1, retn = 0, twr = 0; Ptrdiff written = 0; detail::WriteSpec spec(fmt, escape); @@ -823,26 +926,33 @@ namespace detail { written += twr; Size argpos = spec.index(); if (spec.is_nested()) { - if (!argpos) argpos = argidx++; + if (!argpos) { + argpos = argidx++; + } /* FIXME: figure out a better way */ detail::WriteSpec nspec(spec.nested(), spec.nested_escape()); - Ptrdiff sw = nspec.write_range(writer, argpos - 1, - (spec.flags() & FMT_FLAG_HASH), - spec.nested_sep(), args...); - if (sw < 0) return sw; + Ptrdiff sw = nspec.write_range( + writer, argpos - 1, (spec.flags() & FMT_FLAG_HASH), + spec.nested_sep(), args... + ); + if (sw < 0) { + return sw; + } written += sw; continue; } if (!argpos) { argpos = argidx++; if (spec.arg_width()) { - if (!spec.set_width(argpos - 1, args...)) + if (!spec.set_width(argpos - 1, args...)) { return -1; + } argpos = argidx++; } if (spec.arg_precision()) { - if (!spec.set_precision(argpos - 1, args...)) + if (!spec.set_precision(argpos - 1, args...)) { return -1; + } argpos = argidx++; } } else { @@ -852,20 +962,24 @@ namespace detail { assert(false && "argument precision not given"); return -1; } - if (!spec.set_precision(argpos - 2, args...)) + if (!spec.set_precision(argpos - 2, args...)) { return -1; + } } if (spec.arg_width()) { if (argpos <= (Size(argprec) + 1)) { assert(false && "argument width not given"); return -1; } - if (!spec.set_width(argpos - 2 - argprec, args...)) + if (!spec.set_width(argpos - 2 - argprec, args...)) { return -1; + } } } Ptrdiff sw = spec.write_arg(writer, argpos - 1, args...); - if (sw < 0) return sw; + if (sw < 0) { + return sw; + } written += sw; } written += twr; @@ -874,19 +988,23 @@ namespace detail { } template - inline Ptrdiff format_impl(R &writer, Size &fmtn, bool, - ConstCharRange fmt) { + inline Ptrdiff format_impl( + R &writer, Size &fmtn, bool, ConstCharRange fmt + ) { Size written = 0; detail::WriteSpec spec(fmt, false); - if (spec.read_until_spec(writer, &written)) return -1; + if (spec.read_until_spec(writer, &written)) { + return -1; + } fmtn = 0; return written; } } /* namespace detail */ template -inline Ptrdiff format(R &&writer, Size &fmtn, ConstCharRange fmt, - A const &...args) { +inline Ptrdiff format( + R &&writer, Size &fmtn, ConstCharRange fmt, A const &...args +) { return detail::format_impl(writer, fmtn, false, fmt, args...); } diff --git a/ostd/functional.hh b/ostd/functional.hh index 3940fb0..4594267 100644 --- a/ostd/functional.hh +++ b/ostd/functional.hh @@ -19,7 +19,8 @@ namespace ostd { /* basic function objects */ #define OSTD_DEFINE_BINARY_OP(name, op, RT) \ -template struct name { \ +template \ +struct name { \ RT operator()(T const &x, T const &y) const { \ return x op y; \ } \ @@ -58,7 +59,8 @@ namespace detail { } }; - template struct CharEqual { + template + struct CharEqual { using FirstArgument = T *; using SecondArgument = T *; using Result = bool; @@ -68,7 +70,8 @@ namespace detail { }; } -template struct EqualWithCstr { +template +struct EqualWithCstr { using FirstArgument = T; using SecondArgument = T; bool operator()(T const &x, T const &y) const { @@ -76,36 +79,40 @@ template struct EqualWithCstr { } }; -template struct EqualWithCstr: detail::CharEqual {}; +template +struct EqualWithCstr: detail::CharEqual {}; -template struct LogicalNot { +template +struct LogicalNot { bool operator()(T const &x) const { return !x; } using Argument = T; using Result = bool; }; -template struct Negate { +template +struct Negate { bool operator()(T const &x) const { return -x; } using Argument = T; using Result = T; }; -template struct BinaryNegate { +template +struct BinaryNegate { using FirstArgument = typename T::FirstArgument; using SecondArgument = typename T::SecondArgument; using Result = bool; explicit BinaryNegate(T const &f): p_fn(f) {} - bool operator()(FirstArgument const &x, - SecondArgument const &y) { + bool operator()(FirstArgument const &x, SecondArgument const &y) { return !p_fn(x, y); } private: T p_fn; }; -template struct UnaryNegate { +template +struct UnaryNegate { using Argument = typename T::Argument; using Result = bool; @@ -117,11 +124,13 @@ private: T p_fn; }; -template UnaryNegate not1(T const &fn) { +template +UnaryNegate not1(T const &fn) { return UnaryNegate(fn); } -template BinaryNegate not2(T const &fn) { +template +BinaryNegate not2(T const &fn) { return BinaryNegate(fn); } @@ -194,19 +203,26 @@ namespace detail { } #if OSTD_BYTE_ORDER == OSTD_ENDIAN_LIL -template struct FromLilEndian: detail::EndianSame {}; -template struct FromBigEndian: EndianSwap {}; +template +struct FromLilEndian: detail::EndianSame {}; +template +struct FromBigEndian: EndianSwap {}; #else -template struct FromLilEndian: EndianSwap {}; -template struct FromBigEndian: detail::EndianSame {}; +template +struct FromLilEndian: EndianSwap {}; +template +struct FromBigEndian: detail::EndianSame {}; #endif -template T from_lil_endian(T x) { return FromLilEndian()(x); } -template T from_big_endian(T x) { return FromBigEndian()(x); } +template +T from_lil_endian(T x) { return FromLilEndian()(x); } +template +T from_big_endian(T x) { return FromBigEndian()(x); } /* hash */ -template struct ToHash { +template +struct ToHash { using Argument = T; using Result = Size; @@ -216,7 +232,8 @@ template struct ToHash { }; namespace detail { - template struct ToHashBase { + template + struct ToHashBase { using Argument = T; using Result = Size; @@ -226,7 +243,9 @@ namespace detail { }; } -#define OSTD_HASH_BASIC(T) template<> struct ToHash: detail::ToHashBase {}; +#define OSTD_HASH_BASIC(T) \ +template<> \ +struct ToHash: detail::ToHashBase {}; OSTD_HASH_BASIC(bool) OSTD_HASH_BASIC(char) @@ -249,13 +268,15 @@ OSTD_HASH_BASIC(Wchar) #undef OSTD_HASH_BASIC namespace detail { - template struct FnvConstants { + template + struct FnvConstants { static constexpr Size prime = 16777619u; static constexpr Size offset = 2166136261u; }; - template<> struct FnvConstants<8> { + template<> + struct FnvConstants<8> { /* conversion is necessary here because when compiling on * 32bit, compilers will complain, despite this template * not being instantiated... @@ -278,7 +299,8 @@ namespace detail { template struct ScalarHash; - template struct ScalarHash { + template + struct ScalarHash { using Argument = T; using Result = Size; @@ -290,7 +312,8 @@ namespace detail { } }; - template struct ScalarHash { + template + struct ScalarHash { using Argument = T; using Result = Size; @@ -301,7 +324,8 @@ namespace detail { } }; - template struct ScalarHash { + template + struct ScalarHash { using Argument = T; using Result = Size; @@ -312,7 +336,8 @@ namespace detail { } }; - template struct ScalarHash { + template + struct ScalarHash { using Argument = T; using Result = Size; @@ -323,7 +348,8 @@ namespace detail { } }; - template struct ScalarHash { + template + struct ScalarHash { using Argument = T; using Result = Size; @@ -335,26 +361,33 @@ namespace detail { }; } /* namespace detail */ -template<> struct ToHash: detail::ScalarHash {}; -template<> struct ToHash: detail::ScalarHash {}; +template<> +struct ToHash: detail::ScalarHash {}; +template<> +struct ToHash: detail::ScalarHash {}; -template<> struct ToHash: detail::ScalarHash { +template<> +struct ToHash: detail::ScalarHash { Size operator()(float v) const { if (v == 0) return 0; return detail::ScalarHash::operator()(v); } }; -template<> struct ToHash: detail::ScalarHash { +template<> +struct ToHash: detail::ScalarHash { Size operator()(double v) const { if (v == 0) return 0; return detail::ScalarHash::operator()(v); } }; -template<> struct ToHash: detail::ScalarHash { +template<> +struct ToHash: detail::ScalarHash { Size operator()(ldouble v) const { - if (v == 0) return 0; + if (v == 0) { + return 0; + } #ifdef __i386__ union { ldouble v; struct { Size h1, h2, h3, h4; }; } u; u.h1 = u.h2 = u.h3 = u.h4 = 0; @@ -385,7 +418,8 @@ namespace detail { } }; - template struct ToHashPtr { + template + struct ToHashPtr { using Argument = T *; using Result = Size; Size operator()(T *v) const { @@ -394,7 +428,8 @@ namespace detail { }; } -template struct ToHash: detail::ToHashPtr {}; +template +struct ToHash: detail::ToHashPtr {}; template typename ToHash::Result to_hash(T const &v) { @@ -428,7 +463,8 @@ template ReferenceWrapper ref(ReferenceWrapper v) { return ReferenceWrapper(v); } -template void ref(T const &&) = delete; +template +void ref(T const &&) = delete; template ReferenceWrapper cref(T const &v) { @@ -438,12 +474,14 @@ template ReferenceWrapper cref(ReferenceWrapper v) { return ReferenceWrapper(v); } -template void cref(T const &&) = delete; +template +void cref(T const &&) = delete; /* mem_fn */ namespace detail { - template struct MemTypes; + template + struct MemTypes; template struct MemTypes { using Result = R; @@ -474,22 +512,26 @@ namespace detail { MemFn(R T::*ptr): p_ptr(ptr) {} template auto operator()(T &obj, A &&...args) -> - decltype(((obj).*(p_ptr))(forward(args)...)) { + decltype(((obj).*(p_ptr))(forward(args)...)) + { return ((obj).*(p_ptr))(forward(args)...); } template auto operator()(T const &obj, A &&...args) -> - decltype(((obj).*(p_ptr))(forward(args)...)) const { + decltype(((obj).*(p_ptr))(forward(args)...)) + const { return ((obj).*(p_ptr))(forward(args)...); } template auto operator()(T *obj, A &&...args) -> - decltype(((obj)->*(p_ptr))(forward(args)...)) { + decltype(((obj)->*(p_ptr))(forward(args)...)) + { return ((obj)->*(p_ptr))(forward(args)...); } template auto operator()(T const *obj, A &&...args) -> - decltype(((obj)->*(p_ptr))(forward(args)...)) const { + decltype(((obj)->*(p_ptr))(forward(args)...)) + const { return ((obj)->*(p_ptr))(forward(args)...); } }; @@ -504,7 +546,8 @@ detail::MemFn mem_fn(R T:: *ptr) { * reference: http://probablydance.com/2013/01/13/a-faster-implementation-of-stdfunction */ -template struct Function; +template +struct Function; namespace detail { struct FunctorData { @@ -512,9 +555,9 @@ namespace detail { }; template - constexpr bool FunctorInPlace = sizeof(T) <= sizeof(FunctorData) && - (alignof(FunctorData) % alignof(T)) == 0 && - IsMoveConstructible; + constexpr bool FunctorInPlace = + sizeof(T) <= sizeof(FunctorData) && + (alignof(FunctorData) % alignof(T)) == 0 && IsMoveConstructible; struct FunctionManager; @@ -547,7 +590,8 @@ namespace detail { template static R call(FunctorData const &s, Args ...args) { return (*reinterpret_cast(&const_cast(s)))( - forward(args)...); + forward(args)... + ); } static void store_f(FmStorage &s, T v) { @@ -577,7 +621,8 @@ namespace detail { template static R call(FunctorData const &s, Args ...args) { return (*reinterpret_cast &>( - const_cast(s)))(forward(args)...); + const_cast(s)) + )(forward(args)...); } static void store_f(FmStorage &s, T v) { @@ -594,7 +639,9 @@ namespace detail { static void destroy_f(A &a, FmStorage &s) { AllocatorPointer &ptr = get_ptr_ref(s); - if (!ptr) return; + if (!ptr) { + return; + } allocator_destroy(a, ptr); allocator_deallocate(a, ptr, 1); ptr = nullptr; @@ -610,7 +657,8 @@ namespace detail { static AllocatorPointer &get_ptr_ref(FmStorage const &s) { return reinterpret_cast &>( - const_cast(s.data)); + const_cast(s.data) + ); } }; @@ -634,17 +682,19 @@ namespace detail { }; } - void (* const call_move_and_destroyf)(FmStorage &lhs, - FmStorage &&rhs); - void (* const call_copyf)(FmStorage &lhs, - FmStorage const &rhs); - void (* const call_copyf_fo)(FmStorage &lhs, - FmStorage const &rhs); + void (* const call_move_and_destroyf)( + FmStorage &lhs, FmStorage &&rhs + ); + void (* const call_copyf)( + FmStorage &lhs, FmStorage const &rhs + ); + void (* const call_copyf_fo)( + FmStorage &lhs, FmStorage const &rhs + ); void (* const call_destroyf)(FmStorage &s); template - static void call_move_and_destroy(FmStorage &lhs, - FmStorage &&rhs) { + static void call_move_and_destroy(FmStorage &lhs, FmStorage &&rhs) { using Spec = FunctorDataManager; Spec::move_f(lhs, move(rhs)); Spec::destroy_f(rhs.get_alloc(), rhs); @@ -653,16 +703,14 @@ namespace detail { } template - static void call_copy(FmStorage &lhs, - FmStorage const &rhs) { + static void call_copy(FmStorage &lhs, FmStorage const &rhs) { using Spec = FunctorDataManager; create_fm(lhs, A(rhs.get_alloc())); Spec::store_f(lhs, Spec::get_ref(rhs)); } template - static void call_copy_fo(FmStorage &lhs, - FmStorage const &rhs) { + static void call_copy_fo(FmStorage &lhs, FmStorage const &rhs) { using Spec = FunctorDataManager; Spec::store_f(lhs, Spec::get_ref(rhs)); } @@ -677,8 +725,8 @@ namespace detail { template inline static FunctionManager const &get_default_fm() { - static FunctionManager const def_manager - = FunctionManager::create_default_manager(); + static FunctionManager const def_manager = + FunctionManager::create_default_manager(); return def_manager; } @@ -726,14 +774,15 @@ namespace detail { struct ValidFunctorNat {}; template - static decltype(func_to_functor(declval()) (declval()...)) - valid_functor_test(U *); + static decltype( + func_to_functor(declval()) (declval()...) + ) valid_functor_test(U *); template static ValidFunctorNat valid_functor_test(...); template - constexpr bool IsValidFunctor - = IsConvertible(nullptr)), R>; + constexpr bool IsValidFunctor = + IsConvertible(nullptr)), R>; template using FunctorType = decltype(func_to_functor(declval())); @@ -755,13 +804,15 @@ struct Function: detail::FunctionBase { template - >> Function(T f) { + >> + Function(T f) { if (func_is_null(f)) { init_empty(); return; } - initialize(detail::func_to_functor(forward(f)), - Allocator>()); + initialize(detail::func_to_functor( + forward(f)), Allocator>() + ); } template @@ -778,9 +829,10 @@ struct Function: detail::FunctionBase { template Function(AllocatorArg, A const &a, Function const &f): - p_call(f.p_call) { - detail::FunctionManager const *mfa - = &detail::get_default_fm, A>(); + p_call(f.p_call) + { + detail::FunctionManager const *mfa = + &detail::get_default_fm, A>(); if (f.p_stor.manager == mfa) { detail::create_fm, A>(p_stor, A(a)); mfa->call_copyf_fo(p_stor, f.p_stor); @@ -788,8 +840,8 @@ struct Function: detail::FunctionBase { } using AA = AllocatorRebind; - detail::FunctionManager const *mff - = &detail::get_default_fm(); + detail::FunctionManager const *mff = + &detail::get_default_fm(); if (f.p_stor.manager == mff) { detail::create_fm(p_stor, AA(a)); mff->call_copyf_fo(p_stor, f.P_stor); @@ -801,7 +853,8 @@ struct Function: detail::FunctionBase { template - >> Function(AllocatorArg, A const &a, T f) { + >> + Function(AllocatorArg, A const &a, T f) { if (func_is_null(f)) { init_empty(); return; @@ -860,8 +913,7 @@ private: using emptya = Allocator; p_call = nullptr; detail::create_fm(p_stor, emptya()); - detail::FunctorDataManager::store_f(p_stor, - nullptr); + detail::FunctorDataManager::store_f(p_stor, nullptr); } template @@ -922,9 +974,10 @@ namespace detail { using Type = typename DcLambdaTypes::Ptr; }; - template && - IsMoveConstructible - > struct DcFuncTypeObj { + template && IsMoveConstructible + > + struct DcFuncTypeObj { using Type = typename DcFuncTypeObjBase::Type; }; @@ -944,8 +997,8 @@ namespace detail { }; } -template using FunctionMakeDefaultConstructible - = typename detail::DcFuncType::Type; +template +using FunctionMakeDefaultConstructible = typename detail::DcFuncType::Type; } /* namespace ostd */ diff --git a/ostd/initializer_list.hh b/ostd/initializer_list.hh index b6ec393..14e0fb2 100644 --- a/ostd/initializer_list.hh +++ b/ostd/initializer_list.hh @@ -36,7 +36,8 @@ public: namespace ostd { -template using InitializerList = std::initializer_list; +template +using InitializerList = std::initializer_list; template PointerRange iter(std::initializer_list init) { diff --git a/ostd/internal/hashtable.hh b/ostd/internal/hashtable.hh index a60acc3..4f9d21c 100644 --- a/ostd/internal/hashtable.hh +++ b/ostd/internal/hashtable.hh @@ -26,15 +26,15 @@ namespace detail { }; template - static inline Size estimate_hrsize(const R &range, - EnableIf, bool> = true + static inline Size estimate_hrsize( + const R &range, EnableIf, bool> = true ) { return range.size(); } template - static inline Size estimate_hrsize(const R &, - EnableIf, bool> = true + static inline Size estimate_hrsize( + const R &, EnableIf, bool> = true ) { /* we have no idea how big the range actually is */ return 16; @@ -55,9 +55,13 @@ public: HashRange(Chain *node): p_node(node) {} template - HashRange(const HashRange &v, EnableIf< - IsSame, RemoveCv> && IsConvertible, bool - > = true): p_node(const_cast(v.p_node)) {} + HashRange( + const HashRange &v, EnableIf< + IsSame, RemoveCv> && IsConvertible, bool + > = true + ): + p_node(const_cast(v.p_node)) + {} HashRange &operator=(const HashRange &v) { p_node = v.p_node; @@ -67,7 +71,9 @@ public: bool empty() const { return !p_node; } bool pop_front() { - if (!p_node) return false; + if (!p_node) { + return false; + } p_node = p_node->next; return true; } @@ -93,10 +99,14 @@ public: BucketRange(const BucketRange &v): p_node(v.p_node), p_end(v.p_end) {} template - BucketRange(const BucketRange &v, EnableIf< - IsSame, RemoveCv> && IsConvertible, bool - > = true): p_node(const_cast(v.p_node)), - p_end(const_cast(v.p_end)) {} + BucketRange( + const BucketRange &v, EnableIf< + IsSame, RemoveCv> && IsConvertible, bool + > = true + ): + p_node(const_cast(v.p_node)), + p_end(const_cast(v.p_end)) + {} BucketRange &operator=(const BucketRange &v) { p_node = v.p_node; @@ -107,7 +117,9 @@ public: bool empty() const { return p_node == p_end; } bool pop_front() { - if (p_node == p_end) return false; + if (p_node == p_end) { + return false; + } p_node = p_node->next; return true; } @@ -131,8 +143,8 @@ namespace detail { static constexpr Size ChunkLowerBound = 32; static constexpr Size ChunkUpperBound = 128; - template constexpr Size HashChainAlign - = (((sizeof(HashChain[N]) + sizeof(void *)) % CacheLineSize) == 0) + template constexpr Size HashChainAlign = + (((sizeof(HashChain[N]) + sizeof(void *)) % CacheLineSize) == 0) ? N : HashChainAlign; template @@ -152,9 +164,11 @@ namespace detail { template struct HashPad: HashChainPad {}; - template, - bool P = (V == ChunkUpperBound) - > struct HashChunk; + template< + typename E, Size V = HashChainAlign, + bool P = (V == ChunkUpperBound) + > + struct HashChunk; template struct HashChunk { @@ -181,7 +195,8 @@ namespace detail { typename C, /* equality check */ typename A, /* allocator */ bool Multihash - > struct Hashtable { + > + struct Hashtable { private: using Chain = HashChain; using Chunk = HashChunk; @@ -220,12 +235,16 @@ private: } Chain *find(const K &key, Size &h) const { - if (!p_size) return nullptr; + if (!p_size) { + return nullptr; + } h = bucket(key); Chain **cp = p_data.first(); - for (Chain *c = cp[h], *e = cp[h + 1]; c != e; c = c->next) - if (get_eq()(key, B::get_key(c->value))) + for (Chain *c = cp[h], *e = cp[h + 1]; c != e; c = c->next) { + if (get_eq()(key, B::get_key(c->value))) { return c; + } + } return nullptr; } @@ -236,18 +255,28 @@ private: if (it) { c->prev = it->prev; it->prev = c; - if (c->prev) c->prev->next = c; + if (c->prev) { + c->prev->next = c; + } } else { size_t nb = h; - while (nb && !cp[nb]) --nb; + while (nb && !cp[nb]) { + --nb; + } Chain *prev = cp[nb]; - while (prev && prev->next) prev = prev->next; + while (prev && prev->next) { + prev = prev->next; + } c->prev = prev; - if (prev) prev->next = c; + if (prev) { + prev->next = c; + } } for (; it == cp[h]; --h) { cp[h] = c; - if (!h) break; + if (!h) { + break; + } } return c; } @@ -258,8 +287,9 @@ private: allocator_construct(get_challoc(), chunk); chunk->next = p_chunks; p_chunks = chunk; - for (Size i = 0; i < (Chunk::num - 1); ++i) + for (Size i = 0; i < (Chunk::num - 1); ++i) { chunk->chains[i].next = &chunk->chains[i + 1]; + } chunk->chains[Chunk::num - 1].next = p_unused; p_unused = chunk->chains; } @@ -282,10 +312,11 @@ private: } void rehash_ahead(Size n) { - if (!bucket_count()) + if (!bucket_count()) { reserve(n); - else if ((float(size() + n) / bucket_count()) > max_load_factor()) + } else if ((float(size() + n) / bucket_count()) > max_load_factor()) { rehash(Size((size() + 1) / max_load_factor()) * 2); + } } protected: @@ -299,7 +330,9 @@ protected: T &access_or_insert(const K &key) { Size h = 0; Chain *c = find(key, h); - if (c) return B::get_data(c->value); + if (c) { + return B::get_data(c->value); + } rehash_ahead(1); return insert(bucket(key), key); } @@ -307,7 +340,9 @@ protected: T &access_or_insert(K &&key) { Size h = 0; Chain *c = find(key, h); - if (c) return B::get_data(c->value); + if (c) { + return B::get_data(c->value); + } rehash_ahead(1); return insert(bucket(key), move(key)); } @@ -315,7 +350,9 @@ protected: T *access(const K &key) const { Size h; Chain *c = find(key, h); - if (c) return &B::get_data(c->value); + if (c) { + return &B::get_data(c->value); + } return nullptr; } @@ -323,8 +360,9 @@ protected: void assign_range(R range) { clear(); reserve_at_least(detail::estimate_hrsize(range)); - for (; !range.empty(); range.pop_front()) + for (; !range.empty(); range.pop_front()) { emplace(range.front()); + } rehash_up(); } @@ -332,8 +370,9 @@ protected: const E *beg = il.begin(), *end = il.end(); clear(); reserve_at_least(end - beg); - while (beg != end) + while (beg != end) { emplace(*beg++); + } } const H &get_hash() const { return p_data.second().second().first(); } @@ -357,7 +396,9 @@ protected: p_data(nullptr, FAPair(AllocPair(alloc, CoreAllocPair(alloc, alloc)), FuncPair(hf, eqf))), p_maxlf(1.0f) { - if (!size) return; + if (!size) { + return; + } init_buckets(); } @@ -366,7 +407,9 @@ protected: p_data(nullptr, FAPair(AllocPair(alloc, CoreAllocPair(alloc, alloc)), FuncPair(ht.get_hash(), ht.get_eq()))), p_maxlf(ht.p_maxlf) { - if (!p_size) return; + if (!p_size) { + return; + } init_buckets(); Chain **och = ht.p_data.first(); for (Chain *oc = *och; oc; oc = oc->next) { @@ -418,16 +461,18 @@ protected: clear(); if (AllocatorPropagateOnContainerCopyAssignment) { if ((get_cpalloc() != ht.get_cpalloc()) && p_size) { - allocator_deallocate(get_cpalloc(), - p_data.first(), p_size + 1); + allocator_deallocate( + get_cpalloc(), p_data.first(), p_size + 1 + ); init_buckets(); } get_alloc() = ht.get_alloc(); get_cpalloc() = ht.get_cpalloc(); get_challoc() = ht.get_challoc(); } - for (ConstRange range = ht.iter(); !range.empty(); range.pop_front()) + for (ConstRange range = ht.iter(); !range.empty(); range.pop_front()) { emplace(range.front()); + } return *this; } @@ -439,19 +484,24 @@ protected: swap_adl(p_unused, ht.p_unused); swap_adl(p_data.first(), ht.p_data.first()); swap_adl(p_data.second().second(), ht.p_data.second().second()); - if (AllocatorPropagateOnContainerMoveAssignment) + if (AllocatorPropagateOnContainerMoveAssignment) { swap_adl(p_data.second().first(), ht.p_data.second().first()); + } return *this; } void rehash_up() { - if (load_factor() <= max_load_factor()) return; + if (load_factor() <= max_load_factor()) { + return; + } rehash(Size(size() / max_load_factor()) * 2); } void reserve_at_least(Size count) { Size nc = Size(ceil(count / max_load_factor())); - if (p_size > nc) return; + if (p_size > nc) { + return; + } rehash(nc); } @@ -462,14 +512,16 @@ protected: swap_adl(p_unused, ht.p_unused); swap_adl(p_data.first(), ht.p_data.first()); swap_adl(p_data.second().second(), ht.p_data.second().second()); - if (AllocatorPropagateOnContainerSwap) + if (AllocatorPropagateOnContainerSwap) { swap_adl(p_data.second().first(), ht.p_data.second().first()); + } } public: ~Hashtable() { - if (p_size) allocator_deallocate(get_cpalloc(), - p_data.first(), p_size + 1); + if (p_size) { + allocator_deallocate(get_cpalloc(), p_data.first(), p_size + 1); + } delete_chunks(p_chunks); } @@ -478,7 +530,9 @@ public: } void clear() { - if (!p_len) return; + if (!p_len) { + return; + } clear_buckets(); p_len = 0; p_unused = nullptr; @@ -498,10 +552,13 @@ public: Size bucket_size(Size n) const { Size ret = 0; - if (n >= p_size) return ret; + if (n >= p_size) { + return ret; + } Chain **cp = p_data.first(); - for (Chain *c = cp[n], *e = cp[n + 1]; c != e; c = c->next) + for (Chain *c = cp[n], *e = cp[n + 1]; c != e; c = c->next) { ++ret; + } return ret; } @@ -540,26 +597,38 @@ public: Size erase(const K &key) { Size h = 0; Chain *c = find(key, h); - if (!c) return 0; + if (!c) { + return 0; + } Chain **cp = p_data.first(); Size olen = p_len; for (Chain *e = cp[h + 1]; c != e; c = c->next) { - if (!get_eq()(key, B::get_key(c->value))) break; + if (!get_eq()(key, B::get_key(c->value))) { + break; + } --p_len; Size hh = h; Chain *next = c->next; for (; cp[hh] == c; --hh) { cp[hh] = next; - if (!hh) break; + if (!hh) { + break; + } + } + if (c->prev) { + c->prev->next = next; + } + if (next) { + next->prev = c->prev; } - if (c->prev) c->prev->next = next; - if (next) next->prev = c->prev; c->next = p_unused; c->prev = nullptr; p_unused = c; allocator_destroy(get_alloc(), &c->value); allocator_construct(get_alloc(), &c->value); - if (!Multihash) return 1; + if (!Multihash) { + return 1; + } } return olen - p_len; } @@ -567,11 +636,18 @@ public: Size count(const K &key) { Size h = 0; Chain *c = find(key, h); - if (!c) return 0; + if (!c) { + return 0; + } Size ret = 1; - if (!Multihash) return ret; - for (c = c->next; c; c = c->next) - if (get_eq()(key, B::get_key(c->value))) ++ret; + if (!Multihash) { + return ret; + } + for (c = c->next; c; c = c->next) { + if (get_eq()(key, B::get_key(c->value))) { + ++ret; + } + } return ret; } @@ -582,7 +658,9 @@ public: ConstRange find(const K &key) const { Size h = 0; - return ConstRange(reinterpret_cast *>(find(key, h))); + return ConstRange(reinterpret_cast *>( + find(key, h) + )); } float load_factor() const { return float(p_len) / p_size; } @@ -591,7 +669,9 @@ public: void rehash(Size count) { Size fbcount = Size(p_len / max_load_factor()); - if (fbcount > count) count = fbcount; + if (fbcount > count) { + count = fbcount; + } Chain **och = p_data.first(); Size osize = p_size; @@ -608,8 +688,9 @@ public: p = pp; } - if (och && osize) allocator_deallocate(get_cpalloc(), - och, osize + 1); + if (och && osize) { + allocator_deallocate(get_cpalloc(), och, osize + 1); + } } void reserve(Size count) { @@ -617,35 +698,51 @@ public: } Range iter() { - if (!p_len) return Range(); + if (!p_len) { + return Range(); + } return Range(*p_data.first()); } ConstRange iter() const { using Chain = detail::HashChain; - if (!p_len) return ConstRange(); + if (!p_len) { + return ConstRange(); + } return ConstRange(reinterpret_cast(*p_data.first())); } ConstRange citer() const { using Chain = detail::HashChain; - if (!p_len) return ConstRange(); + if (!p_len) { + return ConstRange(); + } return ConstRange(reinterpret_cast(*p_data.first())); } LocalRange iter(Size n) { - if (n >= p_size) return LocalRange(); + if (n >= p_size) { + return LocalRange(); + } return LocalRange(p_data.first()[n], p_data.first()[n + 1]); } ConstLocalRange iter(Size n) const { using Chain = detail::HashChain; - if (n >= p_size) return ConstLocalRange(); - return ConstLocalRange(reinterpret_cast(p_data.first()[n]), - reinterpret_cast(p_data.first()[n + 1])); + if (n >= p_size) { + return ConstLocalRange(); + } + return ConstLocalRange( + reinterpret_cast(p_data.first()[n]), + reinterpret_cast(p_data.first()[n + 1]) + ); } ConstLocalRange citer(Size n) const { using Chain = detail::HashChain; - if (n >= p_size) return ConstLocalRange(); - return ConstLocalRange(reinterpret_cast(p_data.first()[n]), - reinterpret_cast(p_data.first()[n + 1])); + if (n >= p_size) { + return ConstLocalRange(); + } + return ConstLocalRange( + reinterpret_cast(p_data.first()[n]), + reinterpret_cast(p_data.first()[n + 1]) + ); } }; } /* namespace detail */ diff --git a/ostd/internal/mutex.hh b/ostd/internal/mutex.hh index 0145c88..2dab1a4 100644 --- a/ostd/internal/mutex.hh +++ b/ostd/internal/mutex.hh @@ -92,7 +92,9 @@ struct UniqueLock { UniqueLock(MutexType &m, AdoptLock): p_mtx(&m), p_owns(true) {} ~UniqueLock() { - if (p_owns) p_mtx->unlock(); + if (p_owns) { + p_mtx->unlock(); + } } UniqueLock(const UniqueLock &) = delete; @@ -104,7 +106,9 @@ struct UniqueLock { } UniqueLock &operator=(UniqueLock &&u) { - if (p_owns) p_mtx->unlock(); + if (p_owns) { + p_mtx->unlock(); + } p_mtx = u.p_mtx; p_owns = u.p_owns; u.p_mtx = nullptr; @@ -113,24 +117,27 @@ struct UniqueLock { } bool lock() { - if (!p_mtx || p_owns) return false; - bool ret = p_mtx->lock(); - if (ret) p_owns = true; - return ret; + if (!p_mtx || p_owns) { + return false; + } + return (p_owns = p_mtx->lock()); } int try_lock() { - if (!p_mtx || p_owns) return 1; + if (!p_mtx || p_owns) { + return 1; + } int ret = p_mtx->try_lock(); - if (ret) return ret; p_owns = (ret == 0); return ret; } bool unlock() { - if (!p_mtx || p_owns) return false; + if (!p_mtx || !p_owns) { + return false; + } bool ret = p_mtx->unlock(); - if (ret) p_owns = false; + p_owns = !ret; return ret; } @@ -176,8 +183,9 @@ struct Condition { } bool wait(UniqueLock &l) { - if (!l.owns_lock()) + if (!l.owns_lock()) { return false; + } return !pthread_cond_wait(&p_cnd, l.mutex()->native_handle()); } diff --git a/ostd/internal/tuple.hh b/ostd/internal/tuple.hh index fb30f95..c585fd1 100644 --- a/ostd/internal/tuple.hh +++ b/ostd/internal/tuple.hh @@ -12,21 +12,29 @@ namespace ostd { -template class Tuple; -template struct Pair; -template struct Array; +template +class Tuple; +template +struct Pair; +template +struct Array; /* tuple size */ -template constexpr Size TupleSize = detail::Undefined(); +template +constexpr Size TupleSize = detail::Undefined(); -template constexpr Size TupleSize = TupleSize; -template constexpr Size TupleSize = TupleSize; -template constexpr Size TupleSize = TupleSize; +template +constexpr Size TupleSize = TupleSize; +template +constexpr Size TupleSize = TupleSize; +template +constexpr Size TupleSize = TupleSize; /* tuple element */ -template struct TupleElementBase; +template +struct TupleElementBase; template struct TupleElementBase { using Type = AddConst::Type>; @@ -45,15 +53,20 @@ using TupleElement = typename TupleElementBase::Type; /* is tuple-like */ -template constexpr bool IsTupleLike = false; +template +constexpr bool IsTupleLike = false; -template constexpr bool IsTupleLike = IsTupleLike; -template constexpr bool IsTupleLike = IsTupleLike; -template constexpr bool IsTupleLike = IsTupleLike; +template +constexpr bool IsTupleLike = IsTupleLike; +template +constexpr bool IsTupleLike = IsTupleLike; +template +constexpr bool IsTupleLike = IsTupleLike; /* tuple specializations */ -template constexpr bool IsTupleLike> = true; +template +constexpr bool IsTupleLike> = true; template inline TupleElement> &get(Tuple &); @@ -69,7 +82,8 @@ inline const TupleElement> &&get(const Tuple &&); /* pair specializations */ -template constexpr bool IsTupleLike> = true; +template +constexpr bool IsTupleLike> = true; template inline TupleElement> &get(Pair &); @@ -85,7 +99,8 @@ inline const TupleElement> &&get(const Pair &&); /* array specializations */ -template constexpr bool IsTupleLike> = true; +template +constexpr bool IsTupleLike> = true; template inline T &get(Array &); @@ -102,14 +117,16 @@ inline const T &&get(const Array &&); /* make tuple indices */ namespace detail { - template struct TupleIndices {}; + template + struct TupleIndices {}; - template struct MakeTupleIndicesBase; + template + struct MakeTupleIndicesBase; template struct MakeTupleIndicesBase, E> { - using Type = typename MakeTupleIndicesBase, E>::Type; + using Type = + typename MakeTupleIndicesBase, E>::Type; }; template @@ -130,10 +147,12 @@ namespace detail { /* tuple types */ namespace detail { - template struct TupleTypes {}; + template + struct TupleTypes {}; } -template struct TupleElementBase> { +template +struct TupleElementBase> { public: static_assert(I == 0, "TupleElement index out of range"); static_assert(I != 0, "TupleElement index out of range"); @@ -148,14 +167,15 @@ public: template struct TupleElementBase> { public: - using Type = typename TupleElementBase>::Type; + using Type = + typename TupleElementBase>::Type; }; -template constexpr Size TupleSize> - = sizeof...(T); +template +constexpr Size TupleSize> = sizeof...(T); -template constexpr bool IsTupleLike> = true; +template +constexpr bool IsTupleLike> = true; /* make tuple types */ @@ -166,10 +186,17 @@ namespace detail { template struct MakeTupleTypesBase, T, S, E> { using TR = RemoveReference; - using Type = typename MakeTupleTypesBase, - TupleElement &, - TupleElement>>, T, S + 1, E>::Type; + using Type = typename MakeTupleTypesBase< + TupleTypes< + TS..., + Conditional< + IsLvalueReference, + TupleElement &, + TupleElement + > + >, + T, S + 1, E + >::Type; }; template @@ -194,9 +221,11 @@ namespace detail { constexpr bool TupleConvertibleBase = false; template - constexpr bool TupleConvertibleBase, TupleTypes> - = IsConvertible && TupleConvertibleBase, - TupleTypes>; + constexpr bool TupleConvertibleBase< + TupleTypes, TupleTypes + > = + IsConvertible && + TupleConvertibleBase, TupleTypes>; template<> constexpr bool TupleConvertibleBase, TupleTypes<>> = true; @@ -205,17 +234,20 @@ namespace detail { constexpr bool TupleConvertibleApply = false; template - constexpr bool TupleConvertibleApply - = TupleConvertibleBase, MakeTupleTypes>; + constexpr bool TupleConvertibleApply = + TupleConvertibleBase, MakeTupleTypes>; - template>, - bool = IsTupleLike> + template< + typename T, typename U, bool = IsTupleLike>, + bool = IsTupleLike + > constexpr bool TupleConvertible = false; template - constexpr bool TupleConvertible = TupleConvertibleApply< - TupleSize> == TupleSize, T, U - >; + constexpr bool TupleConvertible = + TupleConvertibleApply< + TupleSize> == TupleSize, T, U + >; } /* tuple constructible */ @@ -225,9 +257,11 @@ namespace detail { constexpr bool TupleConstructibleBase = false; template - constexpr bool TupleConstructibleBase, TupleTypes> - = IsConstructible && TupleConstructibleBase, - TupleTypes>; + constexpr bool TupleConstructibleBase< + TupleTypes, TupleTypes + > = + IsConstructible && + TupleConstructibleBase, TupleTypes>; template<> constexpr bool TupleConstructibleBase, TupleTypes<>> = true; @@ -236,17 +270,20 @@ namespace detail { constexpr bool TupleConstructibleApply = false; template - constexpr bool TupleConstructibleApply - = TupleConstructibleBase, MakeTupleTypes>; + constexpr bool TupleConstructibleApply = + TupleConstructibleBase, MakeTupleTypes>; - template>, - bool = IsTupleLike> + template< + typename T, typename U, bool = IsTupleLike>, + bool = IsTupleLike + > constexpr bool TupleConstructible = false; template - constexpr bool TupleConstructible = TupleConstructibleApply< - TupleSize> == TupleSize, T, U - >; + constexpr bool TupleConstructible = + TupleConstructibleApply< + TupleSize> == TupleSize, T, U + >; } /* tuple assignable */ @@ -256,9 +293,11 @@ namespace detail { constexpr bool TupleAssignableBase = false; template - constexpr bool TupleAssignableBase, TupleTypes> - = IsAssignable && TupleAssignableBase, - TupleTypes>; + constexpr bool TupleAssignableBase< + TupleTypes, TupleTypes + > = + IsAssignable && + TupleAssignableBase, TupleTypes>; template<> constexpr bool TupleAssignableBase, TupleTypes<>> = true; @@ -267,17 +306,20 @@ namespace detail { constexpr bool TupleAssignableApply = false; template - constexpr bool TupleAssignableApply - = TupleAssignableBase, MakeTupleTypes>; + constexpr bool TupleAssignableApply = + TupleAssignableBase, MakeTupleTypes>; - template>, - bool = IsTupleLike> + template< + typename T, typename U, bool = IsTupleLike>, + bool = IsTupleLike + > constexpr bool TupleAssignable = false; template - constexpr bool TupleAssignable = TupleAssignableApply< - TupleSize> == TupleSize, T, U - >; + constexpr bool TupleAssignable = + TupleAssignableApply< + TupleSize> == TupleSize, T, U + >; } } /* namespace ostd */ diff --git a/ostd/io.hh b/ostd/io.hh index 8e601a4..4a7ac11 100644 --- a/ostd/io.hh +++ b/ostd/io.hh @@ -49,7 +49,9 @@ struct FileStream: Stream { } bool open(ConstCharRange path, StreamMode mode = StreamMode::read) { - if (p_f || (path.size() > FILENAME_MAX)) return false; + if (p_f || (path.size() > FILENAME_MAX)) { + return false; + } char buf[FILENAME_MAX + 1]; memcpy(buf, &path[0], path.size()); buf[path.size()] = '\0'; @@ -57,15 +59,18 @@ struct FileStream: Stream { #ifndef OSTD_PLATFORM_WIN32 p_f = fopen(buf, detail::filemodes[Size(mode)]); #else - if (fopen_s(&p_f, buf, detail::filemodes[Size(mode)]) != 0) + if (fopen_s(&p_f, buf, detail::filemodes[Size(mode)]) != 0) { return false; + } #endif p_owned = !!p_f; return is_open(); } bool open(FILE *f) { - if (p_f) return false; + if (p_f) { + return false; + } p_f = f; p_owned = false; return is_open(); @@ -75,7 +80,9 @@ struct FileStream: Stream { bool is_owned() const { return p_owned; } void close() { - if (p_f && p_owned) fclose(p_f); + if (p_f && p_owned) { + fclose(p_f); + } p_f = nullptr; p_owned = false; } @@ -144,9 +151,11 @@ namespace detail { } template - inline void write_impl(T const &v, EnableIf< - !IsConstructible, IoNat - > = IoNat()) { + inline void write_impl( + T const &v, EnableIf< + !IsConstructible, IoNat + > = IoNat() + ) { write(ostd::to_string(v)); } } @@ -178,10 +187,12 @@ inline void writeln(T const &v, A const &...args) { template inline void writef(ConstCharRange fmt, A const &...args) { char buf[512]; - Ptrdiff need = format(detail::FormatOutRange(buf), - fmt, args...); - if (need < 0) return; - else if (Size(need) < sizeof(buf)) { + Ptrdiff need = format( + detail::FormatOutRange(buf), fmt, args... + ); + if (need < 0) { + return; + } else if (Size(need) < sizeof(buf)) { fwrite(buf, 1, need, stdout); return; } diff --git a/ostd/keyset.hh b/ostd/keyset.hh index f7e5051..f1dcdce 100644 --- a/ostd/keyset.hh +++ b/ostd/keyset.hh @@ -40,7 +40,8 @@ namespace detail { template< typename T, typename H, typename C, typename A, bool IsMultihash - > struct KeysetImpl: detail::Hashtable, + > + struct KeysetImpl: detail::Hashtable, T, KeysetKey, T, H, C, A, IsMultihash > { private: @@ -65,20 +66,24 @@ namespace detail { using ConstLocalRange = BucketRange; using Allocator = A; - explicit KeysetImpl(Size size, H const &hf = H(), - C const &eqf = C(), A const &alloc = A() + explicit KeysetImpl( + Size size, H const &hf = H(), C const &eqf = C(), + A const &alloc = A() ): Base(size, hf, eqf, alloc) {} KeysetImpl(): KeysetImpl(0) {} explicit KeysetImpl(A const &alloc): KeysetImpl(0, H(), C(), alloc) {} KeysetImpl(Size size, A const &alloc): - KeysetImpl(size, H(), C(), alloc) {} + KeysetImpl(size, H(), C(), alloc) + {} KeysetImpl(Size size, H const &hf, A const &alloc): - KeysetImpl(size, hf, C(), alloc) {} + KeysetImpl(size, hf, C(), alloc) + {} - KeysetImpl(KeysetImpl const &m): Base(m, - allocator_container_copy(m.get_alloc())) {} + KeysetImpl(KeysetImpl const &m): + Base(m, allocator_container_copy(m.get_alloc()) + {} KeysetImpl(KeysetImpl const &m, A const &alloc): Base(m, alloc) {} @@ -87,33 +92,45 @@ namespace detail { template && IsConvertible, Value> - >> KeysetImpl(R range, Size size = 0, H const &hf = H(), + >> + KeysetImpl( + R range, Size size = 0, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): Base(size ? size : detail::estimate_hrsize(range), - hf, eqf, alloc) { - for (; !range.empty(); range.pop_front()) + ): + Base(size ? size : detail::estimate_hrsize(range), hf, eqf, alloc) + { + for (; !range.empty(); range.pop_front()) { Base::emplace(range.front()); + } Base::rehash_up(); } template - KeysetImpl(R range, Size size, A const &alloc) - : KeysetImpl(range, size, H(), C(), alloc) {} + KeysetImpl(R range, Size size, A const &alloc): + KeysetImpl(range, size, H(), C(), alloc) + {} template - KeysetImpl(R range, Size size, H const &hf, A const &alloc) - : KeysetImpl(range, size, hf, C(), alloc) {} + KeysetImpl(R range, Size size, H const &hf, A const &alloc): + KeysetImpl(range, size, hf, C(), alloc) + {} - KeysetImpl(InitializerList init, Size size = 0, + KeysetImpl( + InitializerList init, Size size = 0, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): KeysetImpl(iter(init), size, hf, eqf, alloc) {} + ): + KeysetImpl(iter(init), size, hf, eqf, alloc) + {} - KeysetImpl(InitializerList init, Size size, A const &alloc) - : KeysetImpl(iter(init), size, H(), C(), alloc) {} + KeysetImpl(InitializerList init, Size size, A const &alloc): + KeysetImpl(iter(init), size, H(), C(), alloc) + {} - KeysetImpl(InitializerList init, Size size, H const &hf, - A const &alloc - ): KeysetImpl(iter(init), size, hf, C(), alloc) {} + KeysetImpl( + InitializerList init, Size size, H const &hf, A const &alloc + ): + KeysetImpl(iter(init), size, hf, C(), alloc) + {} KeysetImpl &operator=(KeysetImpl const &m) { Base::operator=(m); @@ -127,7 +144,8 @@ namespace detail { template && IsConvertible, Value> - >> KeysetImpl &operator=(R range) { + >> + KeysetImpl &operator=(R range) { Base::assign_range(range); return *this; } @@ -166,14 +184,16 @@ template< typename H = ToHash>, typename C = EqualWithCstr>, typename A = Allocator -> using Keyset = detail::KeysetImpl; +> +using Keyset = detail::KeysetImpl; template< typename T, typename H = ToHash>, typename C = EqualWithCstr>, typename A = Allocator -> using Multikeyset = detail::KeysetImpl; +> +using Multikeyset = detail::KeysetImpl; } /* namespace ostd */ diff --git a/ostd/map.hh b/ostd/map.hh index 6f61054..131c353 100644 --- a/ostd/map.hh +++ b/ostd/map.hh @@ -40,7 +40,8 @@ namespace detail { template< typename K, typename T, typename H, typename C, typename A, bool IsMultihash - > struct MapImpl: detail::Hashtable, + > + struct MapImpl: detail::Hashtable, Pair, K, T, H, C, A, IsMultihash > { private: @@ -65,20 +66,26 @@ namespace detail { using ConstLocalRange = BucketRange const>; using Allocator = A; - explicit MapImpl(Size size, H const &hf = H(), + explicit MapImpl( + Size size, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): Base(size, hf, eqf, alloc) {} + ): + Base(size, hf, eqf, alloc) + {} MapImpl(): MapImpl(0) {} explicit MapImpl(A const &alloc): MapImpl(0, H(), C(), alloc) {} MapImpl(Size size, A const &alloc): - MapImpl(size, H(), C(), alloc) {} + MapImpl(size, H(), C(), alloc) + {} MapImpl(Size size, H const &hf, A const &alloc): - MapImpl(size, hf, C(), alloc) {} + MapImpl(size, hf, C(), alloc) + {} - MapImpl(MapImpl const &m): Base(m, - allocator_container_copy(m.get_alloc())) {} + MapImpl(MapImpl const &m): + Base(m, allocator_container_copy(m.get_alloc())) + {} MapImpl(MapImpl const &m, A const &alloc): Base(m, alloc) {} @@ -87,33 +94,45 @@ namespace detail { template && IsConvertible, Value> - >> MapImpl(R range, Size size = 0, H const &hf = H(), + >> + MapImpl( + R range, Size size = 0, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): Base(size ? size : detail::estimate_hrsize(range), - hf, eqf, alloc) { - for (; !range.empty(); range.pop_front()) + ): + Base(size ? size : detail::estimate_hrsize(range), hf, eqf, alloc) + { + for (; !range.empty(); range.pop_front()) { Base::emplace(range.front()); + } Base::rehash_up(); } template - MapImpl(R range, Size size, A const &alloc) - : MapImpl(range, size, H(), C(), alloc) {} + MapImpl(R range, Size size, A const &alloc): + MapImpl(range, size, H(), C(), alloc) + {} template - MapImpl(R range, Size size, H const &hf, A const &alloc) - : MapImpl(range, size, hf, C(), alloc) {} + MapImpl(R range, Size size, H const &hf, A const &alloc): + MapImpl(range, size, hf, C(), alloc) + {} - MapImpl(InitializerList init, Size size = 0, + MapImpl( + InitializerList init, Size size = 0, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): MapImpl(iter(init), size, hf, eqf, alloc) {} + ): + MapImpl(iter(init), size, hf, eqf, alloc) + {} - MapImpl(InitializerList init, Size size, A const &alloc) - : MapImpl(iter(init), size, H(), C(), alloc) {} + MapImpl(InitializerList init, Size size, A const &alloc): + MapImpl(iter(init), size, H(), C(), alloc) + {} - MapImpl(InitializerList init, Size size, H const &hf, - A const &alloc - ): MapImpl(iter(init), size, hf, C(), alloc) {} + MapImpl( + InitializerList init, Size size, H const &hf, A const &alloc + ): + MapImpl(iter(init), size, hf, C(), alloc) + {} MapImpl &operator=(MapImpl const &m) { Base::operator=(m); @@ -127,7 +146,8 @@ namespace detail { template && IsConvertible, Value> - >> MapImpl &operator=(R range) { + >> + MapImpl &operator=(R range) { Base::assign_range(range); return *this; } @@ -166,14 +186,16 @@ template< typename H = ToHash, typename C = EqualWithCstr, typename A = Allocator> -> using Map = detail::MapImpl; +> +using Map = detail::MapImpl; template< typename K, typename T, typename H = ToHash, typename C = EqualWithCstr, typename A = Allocator> -> using Multimap = detail::MapImpl; +> +using Multimap = detail::MapImpl; } /* namespace ostd */ diff --git a/ostd/maybe.hh b/ostd/maybe.hh index ae137f3..ad8f464 100644 --- a/ostd/maybe.hh +++ b/ostd/maybe.hh @@ -37,22 +37,28 @@ namespace detail { constexpr MaybeStorage(): p_null_state('\0') {} MaybeStorage(MaybeStorage const &v): p_engaged(v.p_engaged) { - if (p_engaged) ::new(address_of(p_value)) Value(v.p_value); + if (p_engaged) { + ::new(address_of(p_value)) Value(v.p_value); + } } MaybeStorage(MaybeStorage &&v): p_engaged(v.p_engaged) { - if (p_engaged) + if (p_engaged) { ::new(address_of(p_value)) Value(move(v.p_value)); + } } constexpr MaybeStorage(Value const &v): p_value(v), p_engaged(true) {} constexpr MaybeStorage(Value &&v): p_value(move(v)), p_engaged(true) {} template constexpr MaybeStorage(InPlace, A &&...args): - p_value(forward(args)...), p_engaged(true) {} + p_value(forward(args)...), p_engaged(true) + {} ~MaybeStorage() { - if (p_engaged) p_value.~Value(); + if (p_engaged) { + p_value.~Value(); + } } }; @@ -69,21 +75,26 @@ namespace detail { constexpr MaybeStorage(): p_null_state('\0') {} MaybeStorage(MaybeStorage const &v): p_engaged(v.p_engaged) { - if (p_engaged) ::new(address_of(p_value)) Value(v.p_value); + if (p_engaged) { + ::new(address_of(p_value)) Value(v.p_value); + } } MaybeStorage(MaybeStorage &&v): p_engaged(v.p_engaged) { - if (p_engaged) + if (p_engaged) { ::new(address_of(p_value)) Value(move(v.p_value)); + } } constexpr MaybeStorage(Value const &v): p_value(v), p_engaged(true) {} constexpr MaybeStorage(Value &&v): - p_value(move(v)), p_engaged(true) {} + p_value(move(v)), p_engaged(true) + {} template constexpr MaybeStorage(InPlace, A &&...args): - p_value(forward(args)...), p_engaged(true) {} + p_value(forward(args)...), p_engaged(true) + {} }; } @@ -93,16 +104,26 @@ class Maybe: private detail::MaybeStorage { public: using Value = T; - static_assert(!IsReference, - "Initialization of Maybe with a reference type is not allowed."); - static_assert(!IsSame, InPlace>, - "Initialization of Maybe with InPlace is not allowed."); - static_assert(!IsSame, Nothing>, - "Initialization of Maybe with Nothing is not allowed."); - static_assert(IsObject, - "Initialization of Maybe with non-object type is not allowed."); - static_assert(IsDestructible, - "Initialization of Maybe with a non-destructible object is not allowed."); + static_assert( + !IsReference, + "Initialization of Maybe with a reference type is not allowed." + ); + static_assert( + !IsSame, InPlace>, + "Initialization of Maybe with InPlace is not allowed." + ); + static_assert( + !IsSame, Nothing>, + "Initialization of Maybe with Nothing is not allowed." + ); + static_assert( + IsObject, + "Initialization of Maybe with non-object type is not allowed." + ); + static_assert( + IsDestructible, + "Initialization of Maybe with a non-destructible object is not allowed." + ); constexpr Maybe() {} Maybe(Maybe const &) = default; @@ -112,14 +133,16 @@ public: constexpr Maybe(Value &&v): Base(move(v)) {} template>> - constexpr explicit Maybe(InPlace, A &&...args): Base(in_place, - forward(args)...) {} + constexpr explicit Maybe(InPlace, A &&...args): + Base(in_place, forward(args)...) + {} template &, A...>>> - constexpr explicit - Maybe(InPlace, std::initializer_list il, A &&...args): - Base(in_place, il, forward(args)...) {} + IsConstructible &, A...>> + > + constexpr explicit Maybe(InPlace, std::initializer_list il, A &&...args): + Base(in_place, il, forward(args)...) + {} ~Maybe() = default; @@ -133,12 +156,15 @@ public: Maybe &operator=(Maybe const &v) { if (this->p_engaged == v.p_engaged) { - if (this->p_engaged) this->p_value = v.p_value; + if (this->p_engaged) { + this->p_value = v.p_value; + } } else { - if (this->p_engaged) + if (this->p_engaged) { this->p_value.~Value(); - else + } else { ::new(address_of(this->p_value)) Value(v.p_value); + } this->p_engaged = v.p_engaged; } return *this; @@ -146,11 +172,13 @@ public: Maybe &operator=(Maybe &&v) { if (this->p_engaged == v.p_engaged) { - if (this->p_engaged) this->p_value = move(v.p_value); + if (this->p_engaged) { + this->p_value = move(v.p_value); + } } else { - if (this->p_engaged) + if (this->p_engaged) { this->p_value.~Value(); - else { + } else { ::new(address_of(this->p_value)) Value(move(v.p_value)); } this->p_engaged = v.p_engaged; @@ -217,26 +245,35 @@ public: template constexpr Value value_or(U &&v) const & { - static_assert(IsCopyConstructible, - "Maybe::value_or: T must be copy constructible"); - static_assert(IsConvertible, - "Maybe::value_or: U must be convertible to T"); + static_assert( + IsCopyConstructible, + "Maybe::value_or: T must be copy constructible" + ); + static_assert( + IsConvertible, + "Maybe::value_or: U must be convertible to T" + ); return this->p_engaged ? this->p_value : Value(forward(v)); } template Value value_or(U &&v) && { - static_assert(IsMoveConstructible, - "Maybe::value_or: T must be copy constructible"); - static_assert(IsConvertible, - "Maybe::value_or: U must be convertible to T"); - return this->p_engaged ? move(this->p_value) - : Value(forward(v)); + static_assert( + IsMoveConstructible, + "Maybe::value_or: T must be copy constructible" + ); + static_assert( + IsConvertible, + "Maybe::value_or: U must be convertible to T" + ); + return this->p_engaged ? move(this->p_value) : Value(forward(v)); } void swap(Maybe &v) { if (this->p_engaged == v.p_engaged) { - if (this->p_engaged) detail::swap_adl(this->p_value, v.p_value); + if (this->p_engaged) { + detail::swap_adl(this->p_value, v.p_value); + } } else { if (this->p_engaged) { ::new(address_of(v.p_value)) Value(move(this->p_value)); diff --git a/ostd/memory.hh b/ostd/memory.hh index 71a5abf..2c2e987 100644 --- a/ostd/memory.hh +++ b/ostd/memory.hh @@ -16,8 +16,9 @@ namespace ostd { /* address of */ template constexpr T *address_of(T &v) { - return reinterpret_cast(&const_cast - (reinterpret_cast(v))); + return reinterpret_cast( + &const_cast(reinterpret_cast(v)) + ); } /* pointer traits */ @@ -25,8 +26,10 @@ template constexpr T *address_of(T &v) { namespace detail { template struct HasElement { - template static int test(...); - template static char test(typename U::Element * = 0); + template + static int test(...); + template + static char test(typename U::Element * = 0); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -34,7 +37,8 @@ namespace detail { template::value> struct PointerElementBase; - template struct PointerElementBase { + template + struct PointerElementBase { using Type = typename T::Element; }; @@ -60,8 +64,10 @@ namespace detail { template struct HasDifference { - template static int test(...); - template static char test(typename U::Difference * = 0); + template + static int test(...); + template + static char test(typename U::Difference * = 0); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -71,7 +77,8 @@ namespace detail { using Type = Ptrdiff; }; - template struct PointerDifferenceBase { + template + struct PointerDifferenceBase { using Type = typename T::Difference; }; @@ -87,9 +94,10 @@ namespace detail { template struct HasRebind { - template static int test(...); - template static char test( - typename V::template Rebind * = 0); + template + static int test(...); + template + static char test(typename V::template Rebind * = 0); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -99,14 +107,16 @@ namespace detail { using Type = typename T::template Rebind; }; - template class T, typename U, + template< + template class T, typename U, typename ...A, typename V > struct PointerRebindBase, V, true> { using Type = typename T::template Rebind; }; - template class T, typename U, + template< + template class T, typename U, typename ...A, typename V > struct PointerRebindBase, V, false> { @@ -153,9 +163,11 @@ namespace detail { template struct PointerTo { - static T pointer_to(Conditional>, - PointerToNat, PointerElement - > &r) { + static T pointer_to( + Conditional< + IsVoid>, PointerToNat, PointerElement + > &r + ) { return T::pointer_to(r); } }; @@ -169,9 +181,11 @@ namespace detail { } template -static T pointer_to(Conditional>, - detail::PointerToNat, PointerElement -> &r) { +static T pointer_to( + Conditional< + IsVoid>, detail::PointerToNat, PointerElement + > &r +) { return detail::PointerTo::pointer_to(r); } @@ -181,7 +195,8 @@ template struct DefaultDelete { constexpr DefaultDelete() = default; - template DefaultDelete(DefaultDelete const &) {}; + template + DefaultDelete(DefaultDelete const &) {}; void operator()(T *p) const { delete p; @@ -192,12 +207,14 @@ template struct DefaultDelete { constexpr DefaultDelete() = default; - template DefaultDelete(DefaultDelete const &) {}; + template + DefaultDelete(DefaultDelete const &) {}; void operator()(T *p) const { delete[] p; } - template void operator()(U *) const = delete; + template + void operator()(U *) const = delete; }; /* box */ @@ -208,18 +225,21 @@ namespace detail { template static char ptr_test(typename T::Pointer * = 0); - template constexpr bool HasPtr = sizeof(ptr_test(0)) == 1; + template + constexpr bool HasPtr = sizeof(ptr_test(0)) == 1; template> struct PointerBase { using Type = typename D::Pointer; }; - template struct PointerBase { + template + struct PointerBase { using Type = T *; }; - template struct PointerType { + template + struct PointerType { using Type = typename PointerBase>::Type; }; } /* namespace detail */ @@ -249,20 +269,26 @@ public: } Box(Pointer p, Conditional, D, AddLvalueReference> d): - p_stor(p, d) {} + p_stor(p, d) + {} Box(Pointer p, RemoveReference &&d): - p_stor(p, move(d)) { + p_stor(p, move(d)) + { static_assert(!IsReference, "rvalue deleter cannot be a ref"); } Box(Box &&u): p_stor(u.release(), forward(u.get_deleter())) {} template - Box(Box &&u, EnableIf - && IsConvertible::Pointer, Pointer> - && IsConvertible && (!IsReference || IsSame) - > = Nat()): p_stor(u.release(), forward

(u.get_deleter())) {} + Box( + Box &&u, EnableIf< + !IsArray && + IsConvertible::Pointer, Pointer> && + IsConvertible && (!IsReference || IsSame), + Nat + > = Nat() + ): p_stor(u.release(), forward
(u.get_deleter())) {} Box &operator=(Box &&u) { reset(u.release()); @@ -271,9 +297,10 @@ public: } template - EnableIf - && IsConvertible::Pointer, Pointer> - && IsAssignable, + EnableIf< + !IsArray && + IsConvertible::Pointer, Pointer> && + IsAssignable, Box & > operator=(Box &&u) { reset(u.release()); @@ -309,7 +336,9 @@ public: void reset(Pointer p = nullptr) { Pointer tmp = p_stor.first(); p_stor.first() = p; - if (tmp) p_stor.second()(tmp); + if (tmp) { + p_stor.second()(tmp); + } } void swap(Box &u) { @@ -324,14 +353,16 @@ namespace detail { template>, RemoveCv> - >> constexpr bool SameOrLessCvQualifiedBase = IsConvertible; + >> + constexpr bool SameOrLessCvQualifiedBase = IsConvertible; template constexpr bool SameOrLessCvQualifiedBase = false; - template - || IsSame || detail::HasElement::value - > constexpr bool SameOrLessCvQualified = SameOrLessCvQualifiedBase; + template || IsSame || detail::HasElement::value + > + constexpr bool SameOrLessCvQualified = SameOrLessCvQualifiedBase; template constexpr bool SameOrLessCvQualified = false; @@ -366,30 +397,39 @@ public: template Box(U p, Conditional< IsReference, D, AddLvalueReference > d, EnableIf, Nat> = Nat()): - p_stor(p, d) {} + p_stor(p, d) + {} Box(Nullptr, Conditional, D, AddLvalueReference> d): - p_stor(nullptr, d) {} + p_stor(nullptr, d) + {} template Box(U p, RemoveReference &&d, EnableIf, Nat> = Nat()): - p_stor(p, move(d)) { + p_stor(p, move(d)) + { static_assert(!IsReference, "rvalue deleter cannot be a ref"); } Box(Nullptr, RemoveReference &&d): - p_stor(nullptr, move(d)) { + p_stor(nullptr, move(d)) + { static_assert(!IsReference, "rvalue deleter cannot be a ref"); } Box(Box &&u): p_stor(u.release(), forward(u.get_deleter())) {} template - Box(Box &&u, EnableIf - && detail::SameOrLessCvQualified::Pointer, - Pointer> - && IsConvertible && (!IsReference || IsSame)> = Nat() - ): p_stor(u.release(), forward
(u.get_deleter())) {} + Box( + Box &&u, EnableIf< + IsArray && + detail::SameOrLessCvQualified::Pointer,Pointer> && + IsConvertible && (!IsReference || IsSame), + Nat + > = Nat() + ): + p_stor(u.release(), forward
(u.get_deleter())) + {} Box &operator=(Box &&u) { reset(u.release()); @@ -398,10 +438,10 @@ public: } template - EnableIf - && detail::SameOrLessCvQualified::Pointer, - Pointer> - && IsAssignable, + EnableIf< + IsArray && + detail::SameOrLessCvQualified::Pointer, Pointer> && + IsAssignable, Box & > operator=(Box &&u) { reset(u.release()); @@ -435,18 +475,23 @@ public: return p; } - template EnableIf< + template + EnableIf< detail::SameOrLessCvQualified, void > reset(U p) { Pointer tmp = p_stor.first(); p_stor.first() = p; - if (tmp) p_stor.second()(tmp); + if (tmp) { + p_stor.second()(tmp); + } } void reset(Nullptr) { Pointer tmp = p_stor.first(); p_stor.first() = nullptr; - if (tmp) p_stor.second()(tmp); + if (tmp) { + p_stor.second()(tmp); + } } void reset() { @@ -462,15 +507,18 @@ private: }; namespace detail { - template struct BoxIf { + template + struct BoxIf { using BoxType = Box; }; - template struct BoxIf { + template + struct BoxIf { using BoxUnknownSize = Box; }; - template struct BoxIf { + template + struct BoxIf { using BoxKnownSize = void; }; } @@ -490,25 +538,31 @@ typename detail::BoxIf::BoxKnownSize make_box(A &&...args) = delete; /* allocator */ -template struct Allocator; +template +struct Allocator; -template<> struct Allocator { +template<> +struct Allocator { using Value = void; using Pointer = void *; using ConstPointer = void const *; - template using Rebind = Allocator; + template + using Rebind = Allocator; }; -template<> struct Allocator { +template<> +struct Allocator { using Value = void const; using Pointer = void const *; using ConstPointer = void const *; - template using Rebind = Allocator; + template + using Rebind = Allocator; }; -template struct Allocator { +template +struct Allocator { using Size = ostd::Size; using Difference = Ptrdiff; using Value = T; @@ -517,10 +571,12 @@ template struct Allocator { using Pointer = T *; using ConstPointer = T const *; - template using Rebind = Allocator; + template + using Rebind = Allocator; Allocator() {} - template Allocator(Allocator const &) {} + template + Allocator(Allocator const &) {} Pointer address(Reference v) const { return address_of(v); @@ -545,7 +601,8 @@ template struct Allocator { void destroy(Pointer p) { p->~T(); } }; -template struct Allocator { +template +struct Allocator { using Size = ostd::Size; using Difference = Ptrdiff; using Value = T const; @@ -554,10 +611,12 @@ template struct Allocator { using Pointer = T const *; using ConstPointer = T const *; - template using Rebind = Allocator; + template + using Rebind = Allocator; Allocator() {} - template Allocator(Allocator const &) {} + template + Allocator(Allocator const &) {} ConstPointer address(ConstReference v) const { return address_of(v); @@ -594,14 +653,14 @@ bool operator!=(Allocator const &, Allocator const &) { namespace detail { template struct ConstPtrTest { - template static char test( - typename U::ConstPointer * = 0); - template static int test(...); + template + static char test(typename U::ConstPointer * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; - template::value> + template::value> struct ConstPointer { using Type = typename A::ConstPointer; }; @@ -613,9 +672,10 @@ namespace detail { template struct VoidPtrTest { - template static char test( - typename U::VoidPointer * = 0); - template static int test(...); + template + static char test(typename U::VoidPointer * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -649,8 +709,10 @@ namespace detail { template struct SizeTest { - template static char test(typename U::Size * = 0); - template static int test(...); + template + static char test(typename U::Size * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -698,8 +760,10 @@ using AllocatorConstVoidPointer = typename detail::ConstVoidPointer< namespace detail { template struct DiffTest { - template static char test(typename U::Difference * = 0); - template static int test(...); + template + static char test(typename U::Difference * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -734,14 +798,16 @@ namespace detail { using Type = typename T::template Rebind; }; - template class A, typename T, + template< + template class A, typename T, typename ...Args, typename U > struct AllocTraitsRebindType, U, true> { using Type = typename A::template Rebind; }; - template class A, typename T, + template< + template class A, typename T, typename ...Args, typename U > struct AllocTraitsRebindType, U, false> { @@ -759,57 +825,62 @@ using AllocatorRebind = typename detail::AllocTraitsRebindType< namespace detail { template struct PropagateOnContainerCopyAssignmentTest { - template static char test( - decltype(U::PropagateOnContainerCopyAssignment) * = 0); - template static int test(...); + template + static char test(decltype(U::PropagateOnContainerCopyAssignment) * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; - template::value> constexpr bool PropagateOnContainerCopyAssignmentBase = false; + template::value + > + constexpr bool PropagateOnContainerCopyAssignmentBase = false; template - constexpr bool PropagateOnContainerCopyAssignmentBase - = A::PropagateOnContainerCopyAssignment; + constexpr bool PropagateOnContainerCopyAssignmentBase = + A::PropagateOnContainerCopyAssignment; } /* namespace detail */ template -constexpr bool AllocatorPropagateOnContainerCopyAssignment - = detail::PropagateOnContainerCopyAssignmentBase; +constexpr bool AllocatorPropagateOnContainerCopyAssignment = + detail::PropagateOnContainerCopyAssignmentBase; /* allocator propagate on container move assignment */ namespace detail { template struct PropagateOnContainerMoveAssignmentTest { - template static char test( - decltype(U::PropagateOnContainerMoveAssignment) * = 0); - template static int test(...); + template + static char test(decltype(U::PropagateOnContainerMoveAssignment) * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; - template::value> constexpr bool PropagateOnContainerMoveAssignmentBase = false; + template::value + > + constexpr bool PropagateOnContainerMoveAssignmentBase = false; template - constexpr bool PropagateOnContainerMoveAssignmentBase - = A::PropagateOnContainerMoveAssignment; + constexpr bool PropagateOnContainerMoveAssignmentBase = + A::PropagateOnContainerMoveAssignment; } /* namespace detail */ template -constexpr bool AllocatorPropagateOnContainerMoveAssignment - = detail::PropagateOnContainerMoveAssignmentBase; +constexpr bool AllocatorPropagateOnContainerMoveAssignment = + detail::PropagateOnContainerMoveAssignmentBase; /* allocator propagate on container swap */ namespace detail { template struct PropagateOnContainerSwapTest { - template static char test( - decltype(U::PropagateOnContainerSwap) * = 0); - template static int test(...); + template + static char test(decltype(U::PropagateOnContainerSwap) * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -817,21 +888,23 @@ namespace detail { constexpr bool PropagateOnContainerSwapBase = false; template - constexpr bool PropagateOnContainerSwapBase - = A::PropagateOnContainerSwap; + constexpr bool PropagateOnContainerSwapBase = + A::PropagateOnContainerSwap; } /* namespace detail */ template -constexpr bool AllocatorPropagateOnContainerSwap - = detail::PropagateOnContainerSwapBase; +constexpr bool AllocatorPropagateOnContainerSwap = + detail::PropagateOnContainerSwapBase; /* allocator is always equal */ namespace detail { template struct IsAlwaysEqualTest { - template static char test(decltype(U::IsAlwaysEqual) * = 0); - template static int test(...); + template + static char test(decltype(U::IsAlwaysEqual) * = 0); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -848,56 +921,58 @@ constexpr bool AllocatorIsAlwaysEqual = detail::IsAlwaysEqualBase; /* allocator allocate */ template -inline AllocatorPointer -allocator_allocate(A &a, AllocatorSize n) { +inline AllocatorPointer allocator_allocate(A &a, AllocatorSize n) { return a.allocate(n); } namespace detail { template - auto allocate_hint_test(A &&a, S &&sz, CVP &&p) - -> decltype(a.allocate(sz, p), True()); + auto allocate_hint_test(A &&a, S &&sz, CVP &&p) -> + decltype(a.allocate(sz, p), True()); template - auto allocate_hint_test(A const &, S &&, CVP &&) - -> False; + auto allocate_hint_test(A const &, S &&, CVP &&) -> False; template - constexpr bool AllocateHintTest - = IsSame(), - declval(), - declval())), True + constexpr bool AllocateHintTest = + IsSame< + decltype(allocate_hint_test( + declval(), declval(), declval() + )), True >; template - inline AllocatorPointer allocate(A &a, AllocatorSize n, - AllocatorConstVoidPointer h, - True) { + inline AllocatorPointer allocate( + A &a, AllocatorSize n, AllocatorConstVoidPointer h, True + ) { return a.allocate(n, h); } template - inline AllocatorPointer allocate(A &a, AllocatorSize n, - AllocatorConstVoidPointer, - False) { + inline AllocatorPointer allocate( + A &a, AllocatorSize n, AllocatorConstVoidPointer, False + ) { return a.allocate(n); } } /* namespace detail */ template -inline AllocatorPointer -allocator_allocate(A &a, AllocatorSize n, - AllocatorConstVoidPointer h) { - return detail::allocate(a, n, h, BoolConstant allocator_allocate( + A &a, AllocatorSize n, AllocatorConstVoidPointer h +) { + return detail::allocate( + a, n, h, BoolConstant, AllocatorConstVoidPointer - >>()); + >>() + ); } /* allocator deallocate */ template -inline void allocator_deallocate(A &a, AllocatorPointer p, - AllocatorSize n) { +inline void allocator_deallocate( + A &a, AllocatorPointer p, AllocatorSize n +) { a.deallocate(p, n); } @@ -905,19 +980,18 @@ inline void allocator_deallocate(A &a, AllocatorPointer p, namespace detail { template - auto construct_test(A &&a, T *p, Args &&...args) - -> decltype(a.construct(p, forward(args)...), - True()); + auto construct_test(A &&a, T *p, Args &&...args) -> + decltype(a.construct(p, forward(args)...), True()); template - auto construct_test(A const &, T *, Args &&...) - -> False; + auto construct_test(A const &, T *, Args &&...) -> False; template - constexpr bool ConstructTest - = IsSame(), - declval(), - declval()...)), True + constexpr bool ConstructTest = + IsSame< + decltype(construct_test( + declval(), declval(), declval()... + )), True >; template @@ -933,8 +1007,10 @@ namespace detail { template inline void allocator_construct(A &a, T *p, Args &&...args) { - detail::construct(BoolConstant>(), - a, p, forward(args)...); + detail::construct( + BoolConstant>(), + a, p, forward(args)... + ); } /* allocator destroy */ @@ -947,8 +1023,8 @@ namespace detail { auto destroy_test(A const &, P &&) -> False; template - constexpr bool DestroyTest - = IsSame(), declval

())), True>; + constexpr bool DestroyTest = + IsSame(), declval

())), True>; template inline void destroy(True, A &a, T *p) { @@ -976,8 +1052,8 @@ namespace detail { auto alloc_max_size_test(A const &) -> False; template - constexpr bool AllocMaxSizeTest - = IsSame())), True>; + constexpr bool AllocMaxSizeTest = + IsSame())), True>; template inline AllocatorSize alloc_max_size(True, A const &a) { @@ -992,9 +1068,9 @@ namespace detail { template inline AllocatorSize allocator_max_size(A const &a) { - return detail::alloc_max_size(BoolConstant< - detail::AllocMaxSizeTest - >(), a); + return detail::alloc_max_size( + BoolConstant>(), a + ); } /* allocator container copy */ @@ -1007,8 +1083,8 @@ namespace detail { auto alloc_copy_test(A const &) -> False; template - constexpr bool AllocCopyTest - = IsSame())), True>; + constexpr bool AllocCopyTest = + IsSame())), True>; template inline AllocatorType alloc_container_copy(True, A const &a) { @@ -1023,9 +1099,9 @@ namespace detail { template inline AllocatorType allocator_container_copy(A const &a) { - return detail::alloc_container_copy(BoolConstant< - detail::AllocCopyTest - >(), a); + return detail::alloc_container_copy( + BoolConstant>(), a + ); } /* allocator arg */ @@ -1037,9 +1113,12 @@ constexpr AllocatorArg allocator_arg = AllocatorArg(); /* uses allocator */ namespace detail { - template struct HasAllocatorType { - template static char test(typename U::Allocator *); - template static int test(...); + template + struct HasAllocatorType { + template + static char test(typename U::Allocator *); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == 1); }; @@ -1067,8 +1146,8 @@ namespace detail { } template -constexpr int UsesAllocatorConstructor - = detail::UsesAllocCtor::value; +constexpr int UsesAllocatorConstructor = + detail::UsesAllocCtor::value; } /* namespace ostd */ diff --git a/ostd/platform.hh b/ostd/platform.hh index d8b9616..7870d8a 100644 --- a/ostd/platform.hh +++ b/ostd/platform.hh @@ -136,7 +136,9 @@ inline uint32_t endian_swap32(uint32_t x) { return (x << 24) | (x >> 24) | ((x >> 8) & 0xFF00) | ((x << 8) & 0xFF0000); } inline uint64_t endian_swap64(uint64_t x) { - return endian_swap32(uint32_t(x >> 32)) | (uint64_t(endian_swap32(uint32_t(x))) << 32); + return endian_swap32( + uint32_t(x >> 32)) | (uint64_t(endian_swap32(uint32_t(x))) << 32 + ); } #endif diff --git a/ostd/range.hh b/ostd/range.hh index fb69f47..fb6cc79 100644 --- a/ostd/range.hh +++ b/ostd/range.hh @@ -25,14 +25,17 @@ struct RandomAccessRangeTag: BidirectionalRangeTag {}; struct FiniteRandomAccessRangeTag: RandomAccessRangeTag {}; struct ContiguousRangeTag: FiniteRandomAccessRangeTag {}; -template struct RangeHalf; +template +struct RangeHalf; #define OSTD_RANGE_TRAIT(Name) \ namespace detail { \ template \ struct Range##Name##Test { \ - template static char test(RemoveReference *); \ - template static int test(...); \ + template \ + static char test(RemoveReference *); \ + template \ + static int test(...); \ static constexpr bool value = (sizeof(test(0)) == sizeof(char)); \ }; \ template::value> \ @@ -54,24 +57,25 @@ OSTD_RANGE_TRAIT(Difference) #undef OSTD_RANGE_TRAIT namespace detail { - template static char is_range_test(typename U::Category *, - typename U::Size *, - typename U::Difference *, - typename U::Value *, - RemoveReference< - typename U::Reference - > *); - template static int is_range_test(...); + template + static char is_range_test( + typename U::Category *, typename U::Size *, + typename U::Difference *, typename U::Value *, + RemoveReference * + ); + template + static int is_range_test(...); - template constexpr bool IsRangeTest - = (sizeof(is_range_test(0, 0, 0, 0, 0)) == sizeof(char)); + template constexpr bool IsRangeTest = + (sizeof(is_range_test(0, 0, 0, 0, 0)) == sizeof(char)); } // is input range namespace detail { - template constexpr bool IsInputRangeCore - = IsConvertible, InputRangeTag>; + template + constexpr bool IsInputRangeCore = + IsConvertible, InputRangeTag>; template> constexpr bool IsInputRangeBase = false; @@ -86,8 +90,9 @@ constexpr bool IsInputRange = detail::IsInputRangeBase; // is forward range namespace detail { - template constexpr bool IsForwardRangeCore - = IsConvertible, ForwardRangeTag>; + template + constexpr bool IsForwardRangeCore = + IsConvertible, ForwardRangeTag>; template> constexpr bool IsForwardRangeBase = false; @@ -102,8 +107,9 @@ constexpr bool IsForwardRange = detail::IsForwardRangeBase; // is bidirectional range namespace detail { - template constexpr bool IsBidirectionalRangeCore - = IsConvertible, BidirectionalRangeTag>; + template + constexpr bool IsBidirectionalRangeCore = + IsConvertible, BidirectionalRangeTag>; template> constexpr bool IsBidirectionalRangeBase = false; @@ -113,14 +119,15 @@ namespace detail { detail::IsBidirectionalRangeCore; } -template constexpr bool IsBidirectionalRange - = detail::IsBidirectionalRangeBase; +template constexpr bool IsBidirectionalRange = + detail::IsBidirectionalRangeBase; // is random access range namespace detail { - template constexpr bool IsRandomAccessRangeCore - = IsConvertible, RandomAccessRangeTag>; + template + constexpr bool IsRandomAccessRangeCore = + IsConvertible, RandomAccessRangeTag>; template> constexpr bool IsRandomAccessRangeBase = false; @@ -130,14 +137,15 @@ namespace detail { detail::IsRandomAccessRangeCore; } -template constexpr bool IsRandomAccessRange - = detail::IsRandomAccessRangeBase; +template constexpr bool IsRandomAccessRange = + detail::IsRandomAccessRangeBase; // is finite random access range namespace detail { - template constexpr bool IsFiniteRandomAccessRangeCore - = IsConvertible, FiniteRandomAccessRangeTag>; + template + constexpr bool IsFiniteRandomAccessRangeCore = + IsConvertible, FiniteRandomAccessRangeTag>; template> constexpr bool IsFiniteRandomAccessRangeBase = false; @@ -147,19 +155,20 @@ namespace detail { detail::IsFiniteRandomAccessRangeCore; } -template constexpr bool IsFiniteRandomAccessRange - = detail::IsFiniteRandomAccessRangeBase; +template constexpr bool IsFiniteRandomAccessRange = + detail::IsFiniteRandomAccessRangeBase; // is infinite random access range -template constexpr bool IsInfiniteRandomAccessRange - = IsRandomAccessRange && !IsFiniteRandomAccessRange; +template constexpr bool IsInfiniteRandomAccessRange = + IsRandomAccessRange && !IsFiniteRandomAccessRange; // is contiguous range namespace detail { - template constexpr bool IsContiguousRangeCore - = IsConvertible, ContiguousRangeTag>; + template + constexpr bool IsContiguousRangeCore = + IsConvertible, ContiguousRangeTag>; template> constexpr bool IsContiguousRangeBase = false; @@ -169,26 +178,32 @@ namespace detail { detail::IsContiguousRangeCore; } -template constexpr bool IsContiguousRange - = detail::IsContiguousRangeBase; +template constexpr bool IsContiguousRange = + detail::IsContiguousRangeBase; // is output range namespace detail { template struct OutputRangeTest { - template struct Test {}; - template static char test(Test *); - template static int test(...); + template + struct Test {}; + template + static char test(Test *); + template + static int test(...); static constexpr bool value = (sizeof(test(0)) == sizeof(char)); }; - template constexpr bool IsOutputRangeCore - = IsConvertible, OutputRangeTag> || - (IsInputRange && - (detail::OutputRangeTest const &>::value || - detail::OutputRangeTest &&>::value || - detail::OutputRangeTest >::value)); + template + constexpr bool IsOutputRangeCore = + IsConvertible, OutputRangeTag> || ( + IsInputRange && ( + detail::OutputRangeTest const &>::value || + detail::OutputRangeTest &&>::value || + detail::OutputRangeTest >::value + ) + ); template> constexpr bool IsOutputRangeBase = false; @@ -204,13 +219,33 @@ namespace detail { template struct RangeIterator { - RangeIterator(): p_range() {} - explicit RangeIterator(T const &range) { + RangeIterator(): p_range(), p_init(false) {} + explicit RangeIterator(T const &range): p_range(), p_init(true) { ::new(&get_ref()) T(range); } - explicit RangeIterator(T &&range) { + explicit RangeIterator(T &&range): p_range(), p_init(true) { ::new(&get_ref()) T(move(range)); } + RangeIterator(const RangeIterator &v): p_range(), p_init(true) { + ::new(&get_ref()) T(v.get_ref()); + } + RangeIterator(RangeIterator &&v): p_range(), p_init(true) { + ::new(&get_ref()) T(move(v.get_ref())); + } + RangeIterator &operator=(const RangeIterator &v) { + destroy(); + ::new(&get_ref()) T(v.get_ref()); + p_init = true; + return *this; + } + RangeIterator &operator=(RangeIterator &&v) { + destroy(); + swap(v); + return *this; + } + ~RangeIterator() { + destroy(); + } RangeIterator &operator++() { get_ref().pop_front(); return *this; @@ -219,16 +254,28 @@ namespace detail { return get_ref().front(); } bool operator!=(RangeIterator) const { return !get_ref().empty(); } + void swap(RangeIterator &v) { + detail::swap_adl(get_ref(). v.get_ref()); + detail::swap_adl(p_init, v.p_init); + } private: T &get_ref() { return *reinterpret_cast(&p_range); } T const &get_ref() const { return *reinterpret_cast(&p_range); } + void destroy() { + if (p_init) { + get_ref().~T(); + p_init = false; + } + } AlignedStorage p_range; + bool p_init; }; } // range half -template struct HalfRange; +template +struct HalfRange; namespace detail { template> @@ -239,11 +286,15 @@ namespace detail { using Diff = RangeDifference; static Diff add_n(R &half, Diff n) { - if (n < 0) return -half.prev_n(n); + if (n < 0) { + return -half.prev_n(n); + } return half.next_n(n); } static Diff sub_n(R &half, Diff n) { - if (n < 0) return -half.next_n(n); + if (n < 0) { + return -half.next_n(n); + } return half.prev_n(n); } }; @@ -253,11 +304,15 @@ namespace detail { using Diff = RangeDifference; static Diff add_n(R &half, Diff n) { - if (n < 0) return 0; + if (n < 0) { + return 0; + } return half.next_n(n); } static Diff sub_n(R &half, Diff n) { - if (n < 0) return 0; + if (n < 0) { + return 0; + } return half.prev_n(n); } }; @@ -393,44 +448,65 @@ inline RangeDifference operator-(R const &lhs, R const &rhs) { namespace detail { template RangeSize pop_front_n(R &range, RangeSize n) { - for (RangeSize i = 0; i < n; ++i) - if (!range.pop_front()) return i; + for (RangeSize i = 0; i < n; ++i) { + if (!range.pop_front()) { + return i; + } + } return n; } template RangeSize pop_back_n(R &range, RangeSize n) { - for (RangeSize i = 0; i < n; ++i) - if (!range.pop_back()) return i; + for (RangeSize i = 0; i < n; ++i) { + if (!range.pop_back()) { + return i; + } + } return n; } template RangeSize push_front_n(R &range, RangeSize n) { - for (RangeSize i = 0; i < n; ++i) - if (!range.push_front()) return i; + for (RangeSize i = 0; i < n; ++i) { + if (!range.push_front()) { + return i; + } + } return n; } template RangeSize push_back_n(R &range, RangeSize n) { - for (RangeSize i = 0; i < n; ++i) - if (!range.push_back()) return i; + for (RangeSize i = 0; i < n; ++i) { + if (!range.push_back()) { + return i; + } + } return n; } } -template struct ReverseRange; -template struct MoveRange; -template struct EnumeratedRange; -template struct TakeRange; -template struct ChunksRange; -template struct JoinRange; -template struct ZipRange; +template +struct ReverseRange; +template +struct MoveRange; +template +struct EnumeratedRange; +template +struct TakeRange; +template +struct ChunksRange; +template +struct JoinRange; +template +struct ZipRange; -template struct InputRange { +template< + typename B, typename C, typename V, typename R = V &, + typename S = Size, typename D = Ptrdiff +> +struct InputRange { using Category = C; using Size = S; using Difference = D; @@ -510,8 +586,9 @@ template(this)); Size on = n; for (; n && !r.empty(); --n) { - if (!orange.put(r.front())) + if (!orange.put(r.front())) { break; + } r.pop_front(); } return (on - n); @@ -629,11 +706,14 @@ inline auto join(R &&range) { template inline auto join(R1 &&r1, R &&...rr) { - return [ranges = forward_as_tuple(forward(r1), forward(rr)...)] - (auto &&obj) mutable { + return [ + ranges = forward_as_tuple(forward(r1), forward(rr)...) + ] (auto &&obj) mutable { using Index = detail::MakeTupleIndices; - return detail::join_proxy(forward(obj), - forward(ranges), Index()); + return detail::join_proxy( + forward(obj), + forward(ranges), Index() + ); }; } @@ -646,11 +726,14 @@ inline auto zip(R &&range) { template inline auto zip(R1 &&r1, R &&...rr) { - return [ranges = forward_as_tuple(forward(r1), forward(rr)...)] - (auto &&obj) mutable { + return [ + ranges = forward_as_tuple(forward(r1), forward(rr)...) + ] (auto &&obj) mutable { using Index = detail::MakeTupleIndices; - return detail::zip_proxy(forward(obj), - forward(ranges), Index()); + return detail::zip_proxy( + forward(obj), + forward(ranges), Index() + ); }; } @@ -669,9 +752,11 @@ inline auto citer(T const &r) -> decltype(r.iter()) { return r.iter(); } -template struct OutputRange { +template< + typename B, typename V, typename R = V &, + typename S = Size, typename D = Ptrdiff +> +struct OutputRange { using Category = OutputRangeTag; using Size = S; using Difference = D; @@ -700,14 +785,18 @@ private: T p_end; public: HalfRange() = delete; - HalfRange(HalfRange const &range): p_beg(range.p_beg), - p_end(range.p_end) {} - HalfRange(HalfRange &&range): p_beg(move(range.p_beg)), - p_end(move(range.p_end)) {} - HalfRange(T const &beg, T const &end): p_beg(beg), - p_end(end) {} - HalfRange(T &&beg, T &&end): p_beg(move(beg)), - p_end(move(end)) {} + HalfRange(HalfRange const &range): + p_beg(range.p_beg), p_end(range.p_end) + {} + HalfRange(HalfRange &&range): + p_beg(move(range.p_beg)), p_end(move(range.p_end)) + {} + HalfRange(T const &beg, T const &end): + p_beg(beg),p_end(end) + {} + HalfRange(T &&beg, T &&end): + p_beg(move(beg)), p_end(move(end)) + {} HalfRange &operator=(HalfRange const &range) { p_beg = range.p_beg; @@ -724,14 +813,18 @@ public: bool empty() const { return p_beg == p_end; } bool pop_front() { - if (empty()) return false; + if (empty()) { + return false; + } return p_beg.next(); } bool push_front() { return p_beg.prev(); } bool pop_back() { - if (empty()) return false; + if (empty()) { + return false; + } return p_end.prev(); } bool push_back() { @@ -757,8 +850,7 @@ public: RangeSize size() const { return p_end - p_beg; } - HalfRange - slice(RangeSize start, RangeSize end) const { + HalfRange slice(RangeSize start, RangeSize end) const { return HalfRange(p_beg + start, p_beg + end); } @@ -815,7 +907,7 @@ public: Rsize size() const { return p_range.size(); } bool equals_front(ReverseRange const &r) const { - return p_range.equals_back(r.p_range); + return p_range.equals_back(r.p_range); } bool equals_back(ReverseRange const &r) const { return p_range.equals_front(r.p_range); @@ -931,10 +1023,12 @@ public: template struct NumberRange: InputRange, ForwardRangeTag, T, T> { NumberRange() = delete; - NumberRange(NumberRange const &it): p_a(it.p_a), p_b(it.p_b), - p_step(it.p_step) {} - NumberRange(T a, T b, T step = T(1)): p_a(a), p_b(b), - p_step(step) {} + NumberRange(NumberRange const &it): + p_a(it.p_a), p_b(it.p_b), p_step(it.p_step) + {} + NumberRange(T a, T b, T step = T(1)): + p_a(a), p_b(b), p_step(step) + {} NumberRange(T v): p_a(0), p_b(v), p_step(1) {} bool empty() const { return p_a * p_step >= p_b * p_step; } @@ -988,7 +1082,9 @@ public: bool empty() const { return p_beg == p_end; } bool pop_front() { - if (p_beg == p_end) return false; + if (p_beg == p_end) { + return false; + } ++p_beg; return true; } @@ -1022,7 +1118,9 @@ public: /* satisfy BidirectionalRange */ bool pop_back() { - if (p_end == p_beg) return false; + if (p_end == p_beg) { + return false; + } --p_end; return true; } @@ -1065,39 +1163,50 @@ public: /* satisfy OutputRange */ bool put(T const &v) { - if (empty()) return false; + if (empty()) { + return false; + } *(p_beg++) = v; return true; } bool put(T &&v) { - if (empty()) return false; + if (empty()) { + return false; + } *(p_beg++) = move(v); return true; } Size put_n(T const *p, Size n) { Size ret = size(); - if (n < ret) ret = n; + if (n < ret) { + ret = n; + } if (IsPod) { memcpy(p_beg, p, ret * sizeof(T)); p_beg += ret; return ret; } - for (Size i = ret; i; --i) + for (Size i = ret; i; --i) { *p_beg++ = *p++; + } return ret; } template EnableIf, Size> copy(R &&orange, Size n = -1) { Size c = size(); - if (n < c) c = n; + if (n < c) { + c = n; + } return orange.put_n(p_beg, c); } Size copy(RemoveCv *p, Size n = -1) { Size c = size(); - if (n < c) c = n; + if (n < c) { + c = n; + } if (IsPod) { memcpy(p_beg, data(), c * sizeof(T)); return c; @@ -1163,10 +1272,12 @@ public: EnumeratedRange(T const &range): p_range(range), p_index(0) {} EnumeratedRange(EnumeratedRange const &it): - p_range(it.p_range), p_index(it.p_index) {} + p_range(it.p_range), p_index(it.p_index) + {} EnumeratedRange(EnumeratedRange &&it): - p_range(move(it.p_range)), p_index(it.p_index) {} + p_range(move(it.p_range)), p_index(it.p_index) + {} EnumeratedRange &operator=(EnumeratedRange const &v) { p_range = v.p_range; @@ -1224,12 +1335,15 @@ private: RangeSize p_remaining; public: TakeRange() = delete; - TakeRange(T const &range, RangeSize rem): p_range(range), - p_remaining(rem) {} - TakeRange(TakeRange const &it): p_range(it.p_range), - p_remaining(it.p_remaining) {} - TakeRange(TakeRange &&it): p_range(move(it.p_range)), - p_remaining(it.p_remaining) {} + TakeRange(T const &range, RangeSize rem): + p_range(range), p_remaining(rem) + {} + TakeRange(TakeRange const &it): + p_range(it.p_range), p_remaining(it.p_remaining) + {} + TakeRange(TakeRange &&it): + p_range(move(it.p_range)), p_remaining(it.p_remaining) + {} TakeRange &operator=(TakeRange const &v) { p_range = v.p_range; p_remaining = v.p_remaining; return *this; @@ -1273,12 +1387,15 @@ private: RangeSize p_chunksize; public: ChunksRange() = delete; - ChunksRange(T const &range, RangeSize chs): p_range(range), - p_chunksize(chs) {} - ChunksRange(ChunksRange const &it): p_range(it.p_range), - p_chunksize(it.p_chunksize) {} - ChunksRange(ChunksRange &&it): p_range(move(it.p_range)), - p_chunksize(it.p_chunksize) {} + ChunksRange(T const &range, RangeSize chs): + p_range(range), p_chunksize(chs) + {} + ChunksRange(ChunksRange const &it): + p_range(it.p_range), p_chunksize(it.p_chunksize) + {} + ChunksRange(ChunksRange &&it): + p_range(move(it.p_range)), p_chunksize(it.p_chunksize) + {} ChunksRange &operator=(ChunksRange const &v) { p_range = v.p_range; p_chunksize = v.p_chunksize; return *this; @@ -1308,8 +1425,9 @@ namespace detail { struct JoinRangeEmpty { template static bool empty(T const &tup) { - if (!ostd::get(tup).empty()) + if (!ostd::get(tup).empty()) { return false; + } return JoinRangeEmpty::empty(tup); } }; @@ -1326,8 +1444,9 @@ namespace detail { struct TupleRangeEqual { template static bool equal(T const &tup1, T const &tup2) { - if (!ostd::get(tup1).equals_front(ostd::get(tup2))) + if (!ostd::get(tup1).equals_front(ostd::get(tup2))) { return false; + } return TupleRangeEqual::equal(tup1, tup2); } }; @@ -1408,8 +1527,9 @@ public: } bool equals_front(JoinRange const &r) const { - return detail::TupleRangeEqual<0, sizeof...(R)>::equal(p_ranges, - r.p_ranges); + return detail::TupleRangeEqual<0, sizeof...(R)>::equal( + p_ranges, r.p_ranges + ); } bool pop_front() { @@ -1417,8 +1537,9 @@ public: } CommonType...> front() const { - return detail::JoinRangeFront<0, sizeof...(R), - CommonType...>>::front(p_ranges); + return detail::JoinRangeFront< + 0, sizeof...(R), CommonType...> + >::front(p_ranges); } }; @@ -1440,8 +1561,9 @@ namespace detail { struct ZipRangeEmpty { template static bool empty(T const &tup) { - if (ostd::get(tup).empty()) + if (ostd::get(tup).empty()) { return true; + } return ZipRangeEmpty::empty(tup); } }; @@ -1458,8 +1580,9 @@ namespace detail { struct ZipRangePop { template static bool pop(T &tup) { - return ostd::get(tup).pop_front() && - ZipRangePop::pop(tup); + return ( + ostd::get(tup).pop_front() && ZipRangePop::pop(tup) + ); } }; @@ -1516,8 +1639,9 @@ public: } bool equals_front(ZipRange const &r) const { - return detail::TupleRangeEqual<0, sizeof...(R)>::equal(p_ranges, - r.p_ranges); + return detail::TupleRangeEqual<0, sizeof...(R)>::equal( + p_ranges, r.p_ranges + ); } bool pop_front() { diff --git a/ostd/set.hh b/ostd/set.hh index 55f74f1..b91b074 100644 --- a/ostd/set.hh +++ b/ostd/set.hh @@ -17,7 +17,8 @@ namespace ostd { namespace detail { - template struct SetBase { + template + struct SetBase { static inline T const &get_key(T const &e) { return e; } @@ -54,20 +55,26 @@ namespace detail { using ConstLocalRange = BucketRange; using Allocator = A; - explicit SetImpl(Size size, H const &hf = H(), + explicit SetImpl( + Size size, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): Base(size, hf, eqf, alloc) {} + ): + Base(size, hf, eqf, alloc) + {} SetImpl(): SetImpl(0) {} explicit SetImpl(A const &alloc): SetImpl(0, H(), C(), alloc) {} SetImpl(Size size, A const &alloc): - SetImpl(size, H(), C(), alloc) {} + SetImpl(size, H(), C(), alloc) + {} SetImpl(Size size, H const &hf, A const &alloc): - SetImpl(size, hf, C(), alloc) {} + SetImpl(size, hf, C(), alloc) + {} - SetImpl(SetImpl const &m): Base(m, - allocator_container_copy(m.get_alloc())) {} + SetImpl(SetImpl const &m): + Base(m, allocator_container_copy(m.get_alloc())) + {} SetImpl(SetImpl const &m, A const &alloc): Base(m, alloc) {} @@ -76,33 +83,45 @@ namespace detail { template && IsConvertible, Value> - >> SetImpl(R range, Size size = 0, H const &hf = H(), + >> + SetImpl( + R range, Size size = 0, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): Base(size ? size : detail::estimate_hrsize(range), - hf, eqf, alloc) { - for (; !range.empty(); range.pop_front()) + ): + Base(size ? size : detail::estimate_hrsize(range), hf, eqf, alloc) + { + for (; !range.empty(); range.pop_front()) { Base::emplace(range.front()); + } Base::rehash_up(); } template - SetImpl(R range, Size size, A const &alloc) - : SetImpl(range, size, H(), C(), alloc) {} + SetImpl(R range, Size size, A const &alloc): + SetImpl(range, size, H(), C(), alloc) + {} template - SetImpl(R range, Size size, H const &hf, A const &alloc) - : SetImpl(range, size, hf, C(), alloc) {} + SetImpl(R range, Size size, H const &hf, A const &alloc): + SetImpl(range, size, hf, C(), alloc) + {} - SetImpl(InitializerList init, Size size = 0, + SetImpl( + InitializerList init, Size size = 0, H const &hf = H(), C const &eqf = C(), A const &alloc = A() - ): SetImpl(iter(init), size, hf, eqf, alloc) {} + ): + SetImpl(iter(init), size, hf, eqf, alloc) + {} - SetImpl(InitializerList init, Size size, A const &alloc) - : SetImpl(iter(init), size, H(), C(), alloc) {} + SetImpl(InitializerList init, Size size, A const &alloc): + SetImpl(iter(init), size, H(), C(), alloc) + {} - SetImpl(InitializerList init, Size size, H const &hf, - A const &alloc - ): SetImpl(iter(init), size, hf, C(), alloc) {} + SetImpl( + InitializerList init, Size size, H const &hf, A const &alloc + ): + SetImpl(iter(init), size, hf, C(), alloc) + {} SetImpl &operator=(SetImpl const &m) { Base::operator=(m); @@ -116,7 +135,8 @@ namespace detail { template && IsConvertible, Value> - >> SetImpl &operator=(R range) { + >> + SetImpl &operator=(R range) { Base::assign_range(range); return *this; } @@ -137,14 +157,16 @@ template< typename H = ToHash, typename C = EqualWithCstr, typename A = Allocator -> using Set = detail::SetImpl; +> +using Set = detail::SetImpl; template< typename T, typename H = ToHash, typename C = EqualWithCstr, typename A = Allocator -> using Multiset = detail::SetImpl; +> +using Multiset = detail::SetImpl; } /* namespace ostd */ diff --git a/ostd/stream.hh b/ostd/stream.hh index 5f73f7e..556313c 100644 --- a/ostd/stream.hh +++ b/ostd/stream.hh @@ -68,9 +68,11 @@ private: } template - inline bool write_impl(T const &v, EnableIf< - !IsConstructible, StNat - > = StNat()) { + inline bool write_impl( + T const &v, EnableIf< + !IsConstructible, StNat + > = StNat() + ) { return write(ostd::to_string(v)); } @@ -85,7 +87,9 @@ public: virtual Offset size() { Offset p = tell(); - if ((p < 0) || !seek(0, StreamSeek::end)) return -1; + if ((p < 0) || !seek(0, StreamSeek::end)) { + return -1; + } Offset e = tell(); return ((p == e) || seek(p, StreamSeek::set)) ? e : -1; } @@ -134,12 +138,14 @@ public: template bool writef(ConstCharRange fmt, A const &...args) { char buf[512]; - Ptrdiff need = format(detail::FormatOutRange(buf), - fmt, args...); - if (need < 0) + Ptrdiff need = format( + detail::FormatOutRange(buf), fmt, args... + ); + if (need < 0) { return false; - else if (Size(need) < sizeof(buf)) + } else if (Size(need) < sizeof(buf)) { return write_bytes(buf, need) == Size(need); + } Vector s; s.reserve(need); format(detail::UnsafeWritefRange(s.data()), fmt, args...); @@ -154,23 +160,28 @@ public: template StreamRange iter(); - template Size put(T const *v, Size count) { + template + Size put(T const *v, Size count) { return write_bytes(v, count * sizeof(T)) / sizeof(T); } - template bool put(T v) { + template + bool put(T v) { return write_bytes(&v, sizeof(T)) == sizeof(T); } - template Size get(T *v, Size count) { + template + Size get(T *v, Size count) { return read_bytes(v, count * sizeof(T)) / sizeof(T); } - template bool get(T &v) { + template + bool get(T &v) { return read_bytes(&v, sizeof(T)) == sizeof(T); } - template T get() { + template + T get() { T r; return get(r) ? r : T(); } @@ -189,7 +200,9 @@ struct StreamRange: InputRange< } bool pop_front() { - if (empty()) return false; + if (empty()) { + return false; + } T val; return !!p_stream->read_bytes(&val, sizeof(T)); } diff --git a/ostd/string.hh b/ostd/string.hh index 993873e..0397fc7 100644 --- a/ostd/string.hh +++ b/ostd/string.hh @@ -18,7 +18,8 @@ namespace ostd { static constexpr Size npos = -1; -template> class StringBase; +template> +class StringBase; template struct CharRangeBase: InputRange< @@ -39,25 +40,28 @@ public: /* TODO: traits for utf-16/utf-32 string lengths, for now assume char */ template - CharRangeBase(U beg, EnableIf && !IsArray, Nat> - = Nat()): p_beg(beg), p_end(static_cast(beg) - + (beg ? strlen(beg) : 0)) {} + CharRangeBase( + U beg, EnableIf && !IsArray, Nat> = Nat() + ): p_beg(beg), p_end(static_cast(beg) + (beg ? strlen(beg) : 0)) {} CharRangeBase(Nullptr): p_beg(nullptr), p_end(nullptr) {} template CharRangeBase(U (&beg)[N], EnableIf, Nat> = Nat()): - p_beg(beg), p_end(beg + N - (beg[N - 1] == '\0')) {} + p_beg(beg), p_end(beg + N - (beg[N - 1] == '\0')) + {} template CharRangeBase(StringBase const &s, EnableIf< IsConvertible, Nat - > = Nat()): p_beg(s.data()), - p_end(s.data() + s.size()) {} + > = Nat()): + p_beg(s.data()), p_end(s.data() + s.size()) + {} template>> CharRangeBase(CharRangeBase const &v): - p_beg(&v[0]), p_end(&v[v.size()]) {} + p_beg(&v[0]), p_end(&v[v.size()]) + {} CharRangeBase &operator=(CharRangeBase const &v) { p_beg = v.p_beg; p_end = v.p_end; return *this; @@ -75,7 +79,9 @@ public: bool empty() const { return p_beg == p_end; } bool pop_front() { - if (p_beg == p_end) return false; + if (p_beg == p_end) { + return false; + } ++p_beg; return true; } @@ -104,7 +110,9 @@ public: } bool pop_back() { - if (p_end == p_beg) return false; + if (p_end == p_beg) { + return false; + } --p_end; return true; } @@ -141,7 +149,9 @@ public: T &operator[](Size i) const { return p_beg[i]; } bool put(T v) { - if (empty()) return false; + if (empty()) { + return false; + } *(p_beg++) = v; return true; } @@ -209,8 +219,9 @@ inline bool operator>=(ConstCharRange lhs, ConstCharRange rhs) { } inline bool starts_with(ConstCharRange a, ConstCharRange b) { - if (a.size() < b.size()) + if (a.size() < b.size()) { return false; + } return a.slice(0, b.size()) == b; } @@ -225,7 +236,9 @@ class StringBase { void ctor_from_range(R &range, EnableIf< IsFiniteRandomAccessRange && IsSame>>, bool > = true) { - if (range.empty()) return; + if (range.empty()) { + return; + } RangeSize l = range.size(); reserve(l); p_len = l; @@ -238,12 +251,16 @@ class StringBase { !IsFiniteRandomAccessRange || !IsSame>>, bool > = true) { - if (range.empty()) return; + if (range.empty()) { + return; + } Size i = 0; for (; !range.empty(); range.pop_front()) { reserve(i + 1); - allocator_construct(p_buf.second(), &p_buf.first()[i], - range.front()); + allocator_construct( + p_buf.second(), &p_buf.first()[i], + range.front() + ); ++i; p_len = i; } @@ -262,42 +279,60 @@ public: using ConstRange = CharRangeBase; using Allocator = A; - StringBase(A const &a = A()): p_len(0), p_cap(0), - p_buf(reinterpret_cast(&p_len), a) {} + StringBase(A const &a = A()): + p_len(0), p_cap(0), + p_buf(reinterpret_cast(&p_len), a) + {} explicit StringBase(Size n, T val = T(), A const &al = A()): - StringBase(al) { - if (!n) return; + StringBase(al) + { + if (!n) { + return; + } p_buf.first() = allocator_allocate(p_buf.second(), n + 1); p_len = p_cap = n; Pointer cur = p_buf.first(), last = p_buf.first() + n; - while (cur != last) *cur++ = val; + while (cur != last) { + *cur++ = val; + } *cur = '\0'; } - StringBase(StringBase const &s): p_len(0), p_cap(0), - p_buf(reinterpret_cast(&p_len), - allocator_container_copy(s.p_buf.second())) { - if (!s.p_len) return; + StringBase(StringBase const &s): + p_len(0), p_cap(0), p_buf(reinterpret_cast(&p_len), + allocator_container_copy(s.p_buf.second())) + { + if (!s.p_len) { + return; + } reserve(s.p_len); p_len = s.p_len; memcpy(p_buf.first(), s.p_buf.first(), (p_len + 1) * sizeof(T)); } - StringBase(StringBase const &s, A const &a): p_len(0), p_cap(0), - p_buf(reinterpret_cast(&p_len), a) { - if (!s.p_len) return; + StringBase(StringBase const &s, A const &a): + p_len(0), p_cap(0), p_buf(reinterpret_cast(&p_len), a) + { + if (!s.p_len) { + return; + } reserve(s.p_len); p_len = s.p_len; memcpy(p_buf.first(), s.p_buf.first(), (p_len + 1) * sizeof(T)); } - StringBase(StringBase &&s): p_len(s.p_len), p_cap(s.p_cap), - p_buf(s.p_buf.first(), move(s.p_buf.second())) { + StringBase(StringBase &&s): + p_len(s.p_len), p_cap(s.p_cap), + p_buf(s.p_buf.first(), move(s.p_buf.second())) + { s.p_len = s.p_cap = 0; s.p_buf.first() = reinterpret_cast(&s.p_len); } - StringBase(StringBase &&s, A const &a): p_len(0), p_cap(0), - p_buf(reinterpret_cast(&p_len), a) { - if (!s.p_len) return; + StringBase(StringBase &&s, A const &a): + p_len(0), p_cap(0), p_buf(reinterpret_cast(&p_len), a) + { + if (!s.p_len) { + return; + } if (a != s.p_buf.second()) { reserve(s.p_cap); p_len = s.p_len; @@ -311,8 +346,9 @@ public: s.p_buf.first() = &s.p_cap; } - StringBase(StringBase const &s, Size pos, Size len = npos, - A const &a = A()): StringBase(a) { + StringBase( + StringBase const &s, Size pos, Size len = npos, A const &a = A() + ): StringBase(a) { Size end = (len == npos) ? s.size() : (pos + len); Size nch = (end - pos); reserve(nch); @@ -323,7 +359,9 @@ public: /* TODO: traits for utf-16/utf-32 string lengths, for now assume char */ StringBase(ConstRange v, A const &a = A()): StringBase(a) { - if (!v.size()) return; + if (!v.size()) { + return; + } reserve(v.size()); memcpy(p_buf.first(), &v[0], v.size()); p_buf.first()[v.size()] = '\0'; @@ -342,23 +380,30 @@ public: template && IsConvertible, Value> - >> StringBase(R range, A const &a = A()): StringBase(a) { + >> + StringBase(R range, A const &a = A()): StringBase(a) { ctor_from_range(range); } ~StringBase() { - if (!p_cap) return; + if (!p_cap) { + return; + } allocator_deallocate(p_buf.second(), p_buf.first(), p_cap + 1); } void clear() { - if (!p_len) return; + if (!p_len) { + return; + } p_len = 0; *p_buf.first() = '\0'; } StringBase &operator=(StringBase const &v) { - if (this == &v) return *this; + if (this == &v) { + return *this; + } clear(); if (AllocatorPropagateOnContainerCopyAssignment) { if ((p_buf.second() != v.p_buf.second()) && p_cap) { @@ -373,40 +418,51 @@ public: if (p_len) { memcpy(p_buf.first(), v.p_buf.first(), p_len); p_buf.first()[p_len] = '\0'; - } else p_buf.first() = reinterpret_cast(&p_len); + } else { + p_buf.first() = reinterpret_cast(&p_len); + } return *this; } StringBase &operator=(StringBase &&v) { clear(); - if (p_cap) allocator_deallocate(p_buf.second(), p_buf.first(), p_cap); - if (AllocatorPropagateOnContainerMoveAssignment) + if (p_cap) { + allocator_deallocate(p_buf.second(), p_buf.first(), p_cap); + } + if (AllocatorPropagateOnContainerMoveAssignment) { p_buf.second() = v.p_buf.second(); + } p_len = v.p_len; p_cap = v.p_cap; p_buf.~StrPair(); new (&p_buf) StrPair(v.disown(), move(v.p_buf.second())); - if (!p_cap) p_buf.first() = reinterpret_cast(&p_len); + if (!p_cap) { + p_buf.first() = reinterpret_cast(&p_len); + } return *this; } StringBase &operator=(ConstRange v) { reserve(v.size()); - if (v.size()) memcpy(p_buf.first(), &v[0], v.size()); + if (v.size()) { + memcpy(p_buf.first(), &v[0], v.size()); + } p_buf.first()[v.size()] = '\0'; p_len = v.size(); return *this; } template - EnableIf && !IsArray, StringBase &> - operator=(U v) { + EnableIf< + IsConvertible && !IsArray, StringBase & + > operator=(U v) { return operator=(ConstRange(v)); } template - EnableIf, StringBase &> - operator=(U (&v)[N]) { + EnableIf< + IsConvertible, StringBase & + > operator=(U (&v)[N]) { return operator=(ConstRange(v)); } @@ -433,7 +489,9 @@ public: } void reserve(Size n) { - if (n <= p_cap) return; + if (n <= p_cap) { + return; + } Size oc = p_cap; if (!oc) { p_cap = max(n, Size(8)); @@ -495,7 +553,9 @@ public: } StringBase &append(ConstRange r) { - if (!r.size()) return *this; + if (!r.size()) { + return *this; + } reserve(p_len + r.size()); memcpy(p_buf.first() + p_len, &r[0], r.size()); p_len += r.size(); @@ -504,9 +564,13 @@ public: } StringBase &append(Size n, T c) { - if (!n) return *this; + if (!n) { + return *this; + } reserve(p_len + n); - for (Size i = 0; i < n; ++i) p_buf.first()[p_len + i] = c; + for (Size i = 0; i < n; ++i) { + p_buf.first()[p_len + i] = c; + } p_len += n; p_buf.first()[p_len] = '\0'; return *this; @@ -559,8 +623,9 @@ public: detail::swap_adl(p_len, v.p_len); detail::swap_adl(p_cap, v.p_cap); detail::swap_adl(p_buf.first(), v.p_buf.first()); - if (AllocatorPropagateOnContainerSwap) + if (AllocatorPropagateOnContainerSwap) { detail::swap_adl(p_buf.second(), v.p_buf.second()); + } } Size to_hash() const { @@ -576,7 +641,8 @@ using String = StringBase; /* string literals */ -inline namespace literals { inline namespace string_literals { +inline namespace literals { +inline namespace string_literals { inline String operator "" _s(char const *str, Size len) { return String(ConstCharRange(str, len)); } @@ -584,11 +650,14 @@ inline namespace literals { inline namespace string_literals { inline ConstCharRange operator "" _S(char const *str, Size len) { return ConstCharRange(str, len); } -} } +} +} namespace detail { - template, - bool = IsConvertible> + template< + typename T, bool = IsConvertible, + bool = IsConvertible + > struct ConcatPut; template @@ -611,14 +680,19 @@ namespace detail { template bool concat(R &&sink, T const &v, ConstCharRange sep, F func) { auto range = ostd::iter(v); - if (range.empty()) return true; + if (range.empty()) { + return true; + } for (;;) { if (!detail::ConcatPut< decltype(func(range.front())) - >::put(sink, func(range.front()))) + >::put(sink, func(range.front()))) { return false; + } range.pop_front(); - if (range.empty()) break; + if (range.empty()) { + break; + } sink.put_n(&sep[0], sep.size()); } return true; @@ -627,13 +701,18 @@ bool concat(R &&sink, T const &v, ConstCharRange sep, F func) { template bool concat(R &&sink, T const &v, ConstCharRange sep = " ") { auto range = ostd::iter(v); - if (range.empty()) return true; + if (range.empty()) { + return true; + } for (;;) { ConstCharRange ret = range.front(); - if (!ret.size() || (sink.put_n(&ret[0], ret.size()) != ret.size())) + if (!ret.size() || (sink.put_n(&ret[0], ret.size()) != ret.size())) { return false; + } range.pop_front(); - if (range.empty()) break; + if (range.empty()) { + break; + } sink.put_n(&sep[0], sep.size()); } return true; @@ -674,7 +753,7 @@ namespace detail { }; template - auto test_stringify(int) -> + static auto test_stringify(int) -> BoolConstant().stringify()), String>>; template @@ -682,14 +761,15 @@ namespace detail { (declval())) *); template - False test_stringify(...); + static False test_stringify(...); template constexpr bool StringifyTest = decltype(test_stringify(0))::value; template - True test_iterable(decltype(ostd::iter(declval())) *); - template static False test_iterable(...); + static True test_iterable(decltype(ostd::iter(declval())) *); + template + static False test_iterable(...); template constexpr bool IterableTest = decltype(test_iterable(0))::value; @@ -710,7 +790,9 @@ struct ToString>> { RemoveConst >> - >())) ret += x.get(); + >())) { + ret += x.get(); + } ret += "}"; return ret; } @@ -726,7 +808,9 @@ struct ToString(); detail::TostrRange> sink(app); - if (!v.to_string(sink)) return String(); + if (!v.to_string(sink)) { + return String(); + } return move(app.get()); } }; @@ -738,18 +822,19 @@ namespace detail { int n = snprintf(buf, sizeof(buf), fmt, v); s.clear(); s.reserve(n); - if (n >= int(sizeof(buf))) + if (n >= int(sizeof(buf))) { snprintf(s.data(), n + 1, fmt, v); - else if (n > 0) + } else if (n > 0) { memcpy(s.data(), buf, n + 1); - else { + } else { s.clear(); } *reinterpret_cast(&s) = n; } } -template<> struct ToString { +template<> +struct ToString { using Argument = bool; using Result = String; String operator()(bool b) { @@ -757,7 +842,8 @@ template<> struct ToString { } }; -template<> struct ToString { +template<> +struct ToString { using Argument = char; using Result = String; String operator()(char c) { @@ -768,7 +854,8 @@ template<> struct ToString { }; #define OSTD_TOSTR_NUM(T, fmt) \ -template<> struct ToString { \ +template<> \ +struct ToString { \ using Argument = T; \ using Result = String; \ String operator()(T v) { \ @@ -794,7 +881,8 @@ OSTD_TOSTR_NUM(ldouble, "%Lf") #undef OSTD_TOSTR_NUM -template struct ToString { +template +struct ToString { using Argument = T *; using Result = String; String operator()(Argument v) { @@ -804,7 +892,8 @@ template struct ToString { } }; -template<> struct ToString { +template<> +struct ToString { using Argument = char const *; using Result = String; String operator()(char const *s) { @@ -812,7 +901,8 @@ template<> struct ToString { } }; -template<> struct ToString { +template<> +struct ToString { using Argument = char *; using Result = String; String operator()(char *s) { @@ -820,7 +910,8 @@ template<> struct ToString { } }; -template<> struct ToString { +template<> +struct ToString { using Argument = String; using Result = String; String operator()(Argument const &s) { @@ -828,7 +919,8 @@ template<> struct ToString { } }; -template<> struct ToString { +template<> +struct ToString { using Argument = CharRange; using Result = String; String operator()(Argument const &s) { @@ -836,7 +928,8 @@ template<> struct ToString { } }; -template<> struct ToString { +template<> +struct ToString { using Argument = ConstCharRange; using Result = String; String operator()(Argument const &s) { @@ -844,7 +937,8 @@ template<> struct ToString { } }; -template struct ToString> { +template +struct ToString> { using Argument = Pair; using Result = String; String operator()(Argument const &v) { @@ -864,7 +958,8 @@ namespace detail { static void append(String &ret, T const &tup) { ret += ", "; ret += ToString(tup))>>>()(ostd::get(tup)); + decltype(ostd::get(tup)) + >>>()(ostd::get(tup)); TupleToString::append(ret, tup); } }; @@ -880,13 +975,15 @@ namespace detail { template static void append(String &ret, T const &tup) { ret += ToString(tup))>>>()(ostd::get<0>(tup)); + decltype(ostd::get<0>(tup)) + >>>()(ostd::get<0>(tup)); TupleToString<1, N>::append(ret, tup); } }; } -template struct ToString> { +template +struct ToString> { using Argument = Tuple; using Result = String; String operator()(Argument const &v) { @@ -948,15 +1045,21 @@ public: } TempCString(R input, RemoveCv> *sbuf, Size bufsize) : p_buf(nullptr), p_allocated(false) { - if (input.empty()) return; + if (input.empty()) { + return; + } if (input.size() >= bufsize) { p_buf = new RemoveCv>[input.size() + 1]; p_allocated = true; - } else p_buf = sbuf; + } else { + p_buf = sbuf; + } p_buf[input.copy(p_buf)] = '\0'; } ~TempCString() { - if (p_allocated) delete[] p_buf; + if (p_allocated) { + delete[] p_buf; + } } TempCString &operator=(TempCString const &) = delete; @@ -975,8 +1078,9 @@ public: }; template -inline TempCString to_temp_cstr(R input, RemoveCv> *buf, - Size bufsize) { +inline TempCString to_temp_cstr( + R input, RemoveCv> *buf, Size bufsize +) { return TempCString(input, buf, bufsize); } diff --git a/ostd/thread.hh b/ostd/thread.hh index 449aaea..6d1f81c 100644 --- a/ostd/thread.hh +++ b/ostd/thread.hh @@ -109,30 +109,38 @@ struct Thread { Thread(): p_thread(0) {} Thread(Thread &&o): p_thread(o.p_thread) { o.p_thread = 0; } - template, Thread>>> + template< + typename F, typename ...A, typename = EnableIf, Thread>> + > Thread(F &&func, A &&...args) { using FuncT = Tuple, Decay...>; - Box p(new FuncT(detail::decay_copy(forward(func)), - detail::decay_copy(forward(args))...)); - int res = pthread_create(&p_thread, 0, &detail::thread_proxy, p.get()); - if (!res) + Box p(new FuncT( + detail::decay_copy(forward(func)), + detail::decay_copy(forward(args))... + )); + int res = pthread_create( + &p_thread, 0, &detail::thread_proxy, p.get() + ); + if (!res) { p.release(); - else + } else { p_thread = 0; + } } Thread &operator=(Thread &&other) { - if (joinable()) + if (joinable()) { abort(); + } p_thread = other.p_thread; other.p_thread = 0; return *this; } ~Thread() { - if (joinable()) + if (joinable()) { abort(); + } } explicit operator bool() const { return joinable(); } @@ -152,8 +160,9 @@ struct Thread { bool detach() { bool ret = false; - if (p_thread) + if (p_thread) { ret = !pthread_detach(p_thread); + } p_thread = 0; return ret; } @@ -174,8 +183,9 @@ struct Thread { #elif defined(_SC_NPROCESSORS_ONLN) count = ostd::uint(sysconf(_SC_NPROCESSORS_ONLN)); #endif - if (count <= 0) + if (count <= 0) { count = 1; + } } return count; } diff --git a/ostd/tuple.hh b/ostd/tuple.hh index 9f2f9f7..31477ff 100644 --- a/ostd/tuple.hh +++ b/ostd/tuple.hh @@ -17,7 +17,8 @@ namespace ostd { /* tuple size */ -template constexpr Size TupleSize> = sizeof...(T); +template +constexpr Size TupleSize> = sizeof...(T); /* tuple element */ @@ -32,71 +33,100 @@ namespace detail { template> struct TupleLeaf { constexpr TupleLeaf(): p_value() { - static_assert(!IsReference, - "attempt to default construct a reference element in a tuple"); + static_assert( + !IsReference, + "attempt to default construct a reference element in a tuple" + ); } template TupleLeaf(Constant, A const &): p_value() { - static_assert(!IsReference, - "attempt to default construct a reference element in a tuple"); + static_assert( + !IsReference, + "attempt to default construct a reference element in a tuple" + ); } template TupleLeaf(Constant, A const &a): p_value(allocator_arg, a) { - static_assert(!IsReference, - "attempt to default construct a reference element in a tuple"); + static_assert( + !IsReference, + "attempt to default construct a reference element in a tuple" + ); } template TupleLeaf(Constant, A const &a): p_value(a) { - static_assert(!IsReference, - "attempt to default construct a reference element in a tuple"); + static_assert( + !IsReference, + "attempt to default construct a reference element in a tuple" + ); } template, TupleLeaf> && IsConstructible >> explicit TupleLeaf(T &&t): p_value(forward(t)) { - static_assert(!IsReference || - (IsLvalueReference && - (IsLvalueReference || - IsSame, - ReferenceWrapper>>)) || - (IsRvalueReference && - !IsLvalueReference), - "attempt to construct a reference element in a tuple with an rvalue"); + static_assert( + !IsReference || ( + IsLvalueReference && ( + IsLvalueReference || IsSame< + RemoveReference, + ReferenceWrapper> + > + ) + ) || (IsRvalueReference && !IsLvalueReference), + "attempt to construct a reference element in a tuple with an rvalue" + ); } template explicit TupleLeaf(Constant, A const &, T &&t): - p_value(forward(t)) { - static_assert(!IsLvalueReference || - (IsLvalueReference && - (IsLvalueReference || - IsSame, - ReferenceWrapper>>)), - "attempt to construct a reference element in a tuple with an rvalue"); + p_value(forward(t)) + { + static_assert( + !IsLvalueReference || ( + IsLvalueReference && ( + IsLvalueReference || IsSame< + RemoveReference, + ReferenceWrapper> + > + ) + ), + "attempt to construct a reference element in a tuple with an rvalue" + ); } template explicit TupleLeaf(Constant, A const &a, T &&t): - p_value(allocator_arg, a, forward(t)) { - static_assert(!IsLvalueReference || - (IsLvalueReference && - (IsLvalueReference || - IsSame, - ReferenceWrapper>>)), - "attempt to construct a reference element in a tuple with an rvalue"); + p_value(allocator_arg, a, forward(t)) + { + static_assert( + !IsLvalueReference || ( + IsLvalueReference && ( + IsLvalueReference || IsSame< + RemoveReference, + ReferenceWrapper> + > + ) + ), + "attempt to construct a reference element in a tuple with an rvalue" + ); } template explicit TupleLeaf(Constant, A const &a, T &&t): - p_value(forward(t), a) { - static_assert(!IsLvalueReference || - (IsLvalueReference && - (IsLvalueReference || - IsSame, - ReferenceWrapper>>)), - "attempt to construct a reference element in a tuple with an rvalue"); + p_value(forward(t), a) + { + static_assert( + !IsLvalueReference || ( + IsLvalueReference && ( + IsLvalueReference || IsSame< + RemoveReference, + ReferenceWrapper> + > + ) + ), + "attempt to construct a reference element in a tuple with an rvalue" + ); } TupleLeaf(TupleLeaf const &) = default; @@ -129,26 +159,31 @@ namespace detail { template TupleLeaf(Constant, A const &a): - H(allocator_arg, a) {} + H(allocator_arg, a) + {} template TupleLeaf(Constant, A const &a): H(a) {} template, TupleLeaf> && IsConstructible - >> explicit TupleLeaf(T &&t): H(forward(t)) {} + >> + explicit TupleLeaf(T &&t): H(forward(t)) {} template explicit TupleLeaf(Constant, A const &, T &&t): - H(forward(t)) {} + H(forward(t)) + {} template explicit TupleLeaf(Constant, A const &a, T &&t): - H(allocator_arg, a, forward(t)) {} + H(allocator_arg, a, forward(t)) + {} template explicit TupleLeaf(Constant, A const &a, T &&t): - H(forward(t), a) {} + H(forward(t), a) + {} TupleLeaf(TupleLeaf const &) = default; TupleLeaf(TupleLeaf &&) = default; @@ -187,58 +222,73 @@ namespace detail { constexpr bool TupleAllDefaultConstructible = detail::Undefined(); template - constexpr bool TupleAllDefaultConstructible> - = TupleAll...>; + constexpr bool TupleAllDefaultConstructible> = + TupleAll...>; } /* tuple implementation */ namespace detail { - template struct TupleBase; + template + struct TupleBase; template struct TupleBase, A...>: TupleLeaf... { constexpr TupleBase() {} - template - explicit TupleBase(TupleIndices, TupleTypes, - TupleIndices, TupleTypes, - T &&...t): + template< + Size ...Ia, typename ...Aa, Size ...Ib, + typename ...Ab, typename ...T + > + explicit TupleBase( + TupleIndices, TupleTypes, + TupleIndices, TupleTypes, T &&...t + ): TupleLeaf(forward(t))..., - TupleLeaf()... {} + TupleLeaf()... + {} - template - explicit TupleBase(AllocatorArg, Alloc const &a, - TupleIndices, TupleTypes, - TupleIndices, TupleTypes, - T &&...t): - TupleLeaf(UsesAllocatorConstructor, a, - forward(t))..., + template< + typename Alloc, Size ...Ia, typename ...Aa, + Size ...Ib, typename ...Ab, typename ...T + > + explicit TupleBase( + AllocatorArg, Alloc const &a, + TupleIndices, TupleTypes, + TupleIndices, TupleTypes, T &&...t + ): + TupleLeaf( + UsesAllocatorConstructor, a, + forward(t) + )..., TupleLeaf(UsesAllocatorConstructor, a)... {} template> - >> TupleBase(T &&t): TupleLeaf(forward< - TupleElement> - >(get(t)))... {} + >> + TupleBase(T &&t): + TupleLeaf( + forward>>(get(t)) + )... + {} template> - >> TupleBase(AllocatorArg, Alloc const &a, T &&t): - TupleLeaf(UsesAllocatorConstructor< - A, Alloc, TupleElement> - >, a, forward>>(get(t)))... + >> + TupleBase(AllocatorArg, Alloc const &a, T &&t): + TupleLeaf( + UsesAllocatorConstructor< + A, Alloc, TupleElement> + >, a, forward>>(get(t)) + )... {} template - EnableIf>, TupleBase &> - operator=(T &&t) { - tuple_swallow(TupleLeaf::operator=(forward< - TupleElement> - >(get(t)))...); + EnableIf>, TupleBase &> operator=(T &&t) { + tuple_swallow(TupleLeaf::operator=( + forward>>(get(t)) + )...); return *this; } @@ -246,19 +296,23 @@ namespace detail { TupleBase(TupleBase &&) = default; TupleBase &operator=(TupleBase const &t) { - tuple_swallow(TupleLeaf::operator=(( - static_cast const &>(t)).get())...); + tuple_swallow(TupleLeaf::operator=( + (static_cast const &>(t)).get() + )...); return *this; } TupleBase &operator=(TupleBase &&t) { - tuple_swallow(TupleLeaf::operator=(forward - ((static_cast &>(t)).get()))...); + tuple_swallow(TupleLeaf::operator=( + forward((static_cast &>(t)).get()) + )...); return *this; } void swap(TupleBase &t) { - tuple_swallow(TupleLeaf::swap(static_cast &>(t))...); + tuple_swallow( + TupleLeaf::swap(static_cast &>(t))... + ); } }; } /* namespace detail */ @@ -283,110 +337,130 @@ class Tuple { public: template)...> - >> Tuple() {} + >> + Tuple() {} explicit Tuple(A const &...t): - p_base(detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - detail::MakeTupleIndices<0>(), - detail::MakeTupleTypes(), t...) {} - - template - Tuple(AllocatorArg, Alloc const &a, A const &...t): - p_base(allocator_arg, a, + p_base( detail::MakeTupleIndices(), detail::MakeTupleTypes(), detail::MakeTupleIndices<0>(), - detail::MakeTupleTypes(), t...) {} + detail::MakeTupleTypes(), t... + ) + {} + + template + Tuple(AllocatorArg, Alloc const &a, A const &...t): + p_base( + allocator_arg, a, + detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + detail::MakeTupleIndices<0>(), + detail::MakeTupleTypes(), t... + ) + {} template, - detail::MakeTupleTypes > && detail::TupleAllDefaultConstructible< - detail::MakeTupleTypes >, bool > = true> Tuple(T &&...t): - p_base(detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - forward(t)...) {} + p_base( + detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + forward(t)... + ) + {} template, - detail::MakeTupleTypes > && !detail::TupleConvertible< Tuple, - detail::MakeTupleTypes > && detail::TupleAllDefaultConstructible< - detail::MakeTupleTypes >, bool > = true> Tuple(T &&...t): - p_base(detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - forward(t)...) {} + p_base( + detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + forward(t)... + ) + {} template, - detail::MakeTupleTypes > && detail::TupleAllDefaultConstructible< - detail::MakeTupleTypes > >> Tuple(AllocatorArg, Alloc const &a, T &&...t): - p_base(allocator_arg, a, detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - detail::MakeTupleIndices(), - detail::MakeTupleTypes(), - forward(t)...) {} + p_base( + allocator_arg, a, detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + detail::MakeTupleIndices(), + detail::MakeTupleTypes(), + forward(t)... + ) + {} template, bool - > = true> Tuple(T &&t): p_base(forward(t)) {} + > = true> + Tuple(T &&t): p_base(forward(t)) {} template && !detail::TupleConvertible, bool - > = true> Tuple(T &&t): p_base(forward(t)) {} + > = true> + Tuple(T &&t): p_base(forward(t)) {} template - >> Tuple(AllocatorArg, Alloc const &a, T &&t): - p_base(allocator_arg, a, forward(t)) {} + >> + Tuple(AllocatorArg, Alloc const &a, T &&t): + p_base(allocator_arg, a, forward(t)) + {} template>> Tuple &operator=(T &&t) { @@ -473,8 +547,7 @@ namespace detail { } template -inline Tuple::Type...> -make_tuple(T &&...t) { +inline Tuple::Type...> make_tuple(T &&...t) { return Tuple::Type...>(forward(t)...); } diff --git a/ostd/type_traits.hh b/ostd/type_traits.hh index 909e9db..029372b 100644 --- a/ostd/type_traits.hh +++ b/ostd/type_traits.hh @@ -14,14 +14,21 @@ namespace ostd { /* forward declarations */ namespace detail { - template struct RemoveCvBase; - template struct AddLr; - template struct AddRr; - template struct AddConstBase; - template struct RemoveReferenceBase; - template struct RemoveAllExtentsBase; + template + struct RemoveCvBase; + template + struct AddLr; + template + struct AddRr; + template + struct AddConstBase; + template + struct RemoveReferenceBase; + template + struct RemoveAllExtentsBase; - template struct CommonTypeBase; + template + struct CommonTypeBase; } template @@ -43,7 +50,8 @@ template using RemoveAllExtents = typename detail::RemoveAllExtentsBase::Type; namespace detail { - template AddRvalueReference declval_in(); + template + AddRvalueReference declval_in(); } /* integral constant */ @@ -65,12 +73,15 @@ using BoolConstant = Constant; using True = BoolConstant; using False = BoolConstant; -template constexpr T Constant::value; +template +constexpr T Constant::value; /* type equality */ -template constexpr bool IsSame = false; -template constexpr bool IsSame = true; +template +constexpr bool IsSame = false; +template +constexpr bool IsSame = true; /* is void */ @@ -85,27 +96,43 @@ constexpr bool IsNullPointer = IsSame, Nullptr>; /* is integer */ namespace detail { - template constexpr bool IsIntegralBase = false; + template + constexpr bool IsIntegralBase = false; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; #ifndef OSTD_TYPES_CHAR_16_32_NO_BUILTINS - template<> constexpr bool IsIntegralBase = true; - template<> constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; #endif - template<> constexpr bool IsIntegralBase = true; + template<> + constexpr bool IsIntegralBase = true; } template @@ -114,12 +141,16 @@ constexpr bool IsIntegral = detail::IsIntegralBase>; /* is floating point */ namespace detail { - template constexpr bool IsFloatingPointBase = false; + template + constexpr bool IsFloatingPointBase = false; - template<> constexpr bool IsFloatingPointBase = true; - template<> constexpr bool IsFloatingPointBase = true; + template<> + constexpr bool IsFloatingPointBase = true; + template<> + constexpr bool IsFloatingPointBase = true; - template<> constexpr bool IsFloatingPointBase = true; + template<> + constexpr bool IsFloatingPointBase = true; } template @@ -127,15 +158,20 @@ constexpr bool IsFloatingPoint = detail::IsFloatingPointBase>; /* is array */ -template constexpr bool IsArray = false; -template constexpr bool IsArray = true; -template constexpr bool IsArray = true; +template +constexpr bool IsArray = false; +template +constexpr bool IsArray = true; +template +constexpr bool IsArray = true; /* is pointer */ namespace detail { - template constexpr bool IsPointerBase = false; - template constexpr bool IsPointerBase = true; + template + constexpr bool IsPointerBase = false; + template + constexpr bool IsPointerBase = true; } template @@ -143,13 +179,17 @@ constexpr bool IsPointer = detail::IsPointerBase>; /* is lvalue reference */ -template constexpr bool IsLvalueReference = false; -template constexpr bool IsLvalueReference = true; +template +constexpr bool IsLvalueReference = false; +template +constexpr bool IsLvalueReference = true; /* is rvalue reference */ -template constexpr bool IsRvalueReference = false; -template constexpr bool IsRvalueReference = true; +template +constexpr bool IsRvalueReference = false; +template +constexpr bool IsRvalueReference = true; /* is reference */ @@ -173,22 +213,28 @@ template constexpr bool IsClass = __is_class(T); namespace detail { struct FunctionTestDummy {}; - template char function_test(T *); - template char function_test(FunctionTestDummy); - template int function_test(...); + template + char function_test(T *); + template + char function_test(FunctionTestDummy); + template + int function_test(...); - template T &function_source(int); - template FunctionTestDummy function_source(...); + template + T &function_source(int); + template + FunctionTestDummy function_source(...); - template || - IsUnion || - IsVoid || - IsReference || - IsNullPointer> - constexpr bool IsFunctionBase - = sizeof(function_test(function_source(0))) == 1; + template< + typename T, bool = + IsClass || IsUnion || IsVoid || IsReference || + IsNullPointer + > + constexpr bool IsFunctionBase = + sizeof(function_test(function_source(0))) == 1; - template constexpr bool IsFunctionBase = false; + template + constexpr bool IsFunctionBase = false; } /* namespace detail */ template @@ -212,7 +258,8 @@ constexpr bool IsCompound = !IsFundamental; /* is pointer to member */ namespace detail { - template constexpr bool IsMemberPointerBase = false; + template + constexpr bool IsMemberPointerBase = false; template constexpr bool IsMemberPointerBase = true; @@ -224,7 +271,8 @@ constexpr bool IsMemberPointer = detail::IsMemberPointerBase>; /* is pointer to member object */ namespace detail { - template constexpr bool IsMemberObjectPointerBase = false; + template + constexpr bool IsMemberObjectPointerBase = false; template constexpr bool IsMemberObjectPointerBase = !IsFunction; @@ -236,7 +284,8 @@ constexpr bool IsMemberObjectPointer = detail::IsMemberObjectPointerBase constexpr bool IsMemberFunctionPointerBase = false; + template + constexpr bool IsMemberFunctionPointerBase = false; template constexpr bool IsMemberFunctionPointerBase = IsFunction; @@ -252,13 +301,15 @@ constexpr bool IsObject = !IsFunction && !IsVoid && !IsReference; /* is scalar */ -template constexpr bool IsScalar - = IsMemberPointer || IsPointer || IsEnum || - IsNullPointer || IsArithmetic; +template +constexpr bool IsScalar = + IsMemberPointer || IsPointer || IsEnum || + IsNullPointer || IsArithmetic; /* is abstract */ -template constexpr bool IsAbstract = __is_abstract(T); +template +constexpr bool IsAbstract = __is_abstract(T); /* is const */ @@ -272,20 +323,24 @@ constexpr bool IsVolatile = IsSame; /* is empty */ -template constexpr bool IsEmpty = __is_empty(T); +template +constexpr bool IsEmpty = __is_empty(T); /* is POD */ -template constexpr bool IsPod = __is_pod(T); +template +constexpr bool IsPod = __is_pod(T); /* is polymorphic */ -template constexpr bool IsPolymorphic = __is_polymorphic(T); +template +constexpr bool IsPolymorphic = __is_polymorphic(T); /* is signed */ namespace detail { - template constexpr bool IsSignedCore = T(-1) < T(0); + template + constexpr bool IsSignedCore = T(-1) < T(0); template> constexpr bool IsSignedBase = false; @@ -300,7 +355,8 @@ constexpr bool IsSigned = detail::IsSignedBase; /* is unsigned */ namespace detail { - template constexpr bool IsUnsignedCore = T(0) < T(-1); + template + constexpr bool IsUnsignedCore = T(0) < T(-1); template> constexpr bool IsUnsignedBase = false; @@ -329,7 +385,8 @@ constexpr bool IsTriviallyCopyable = IsScalar>; /* is trivial */ -template constexpr bool IsTrivial = __is_trivial(T); +template +constexpr bool IsTrivial = __is_trivial(T); /* has virtual destructor */ @@ -341,21 +398,26 @@ constexpr bool HasVirtualDestructor = __has_virtual_destructor(T); namespace detail { #define OSTD_MOVE(v) static_cast &&>(v) - template struct Select2nd { using Type = T; }; + template + struct Select2nd { using Type = T; }; + struct Any { Any(...); }; - template typename Select2nd< + template + typename Select2nd< decltype(OSTD_MOVE(T(declval_in()...))), True >::Type is_ctible_test(T &&, A &&...); #undef OSTD_MOVE - template False is_ctible_test(Any, A &&...); + template + False is_ctible_test(Any, A &&...); template - constexpr bool CtibleCore = CommonTypeBase< - decltype(is_ctible_test(declval_in(), declval_in()...)) - >::Type::value; + constexpr bool CtibleCore = + CommonTypeBase< + decltype(is_ctible_test(declval_in(), declval_in()...)) + >::Type::value; /* function types are not constructible */ template @@ -384,27 +446,27 @@ namespace detail { /* treat scalars and refs separately */ template - constexpr bool CtibleVoidCheck = CtibleCore< - (IsScalar || IsReference), T, A... - >; + constexpr bool CtibleVoidCheck = + CtibleCore<(IsScalar || IsReference), T, A...>; /* if any of T or A is void, IsConstructible should be false */ template constexpr bool CtibleVoidCheck = false; - template constexpr bool CtibleContainsVoid = false; + template + constexpr bool CtibleContainsVoid = false; - template<> constexpr bool CtibleContainsVoid<> = false; + template<> + constexpr bool CtibleContainsVoid<> = false; template - constexpr bool CtibleContainsVoid - = IsVoid || CtibleContainsVoid; + constexpr bool CtibleContainsVoid = + IsVoid || CtibleContainsVoid; /* entry point */ template - constexpr bool Ctible = CtibleVoidCheck< - CtibleContainsVoid || IsAbstract, T, A... - >; + constexpr bool Ctible = + CtibleVoidCheck || IsAbstract, T, A...>; /* array types are default constructible if their element type is */ template @@ -430,16 +492,14 @@ constexpr bool IsDefaultConstructible = IsConstructible; /* is copy constructible */ template -constexpr bool IsCopyConstructible = IsConstructible> ->; +constexpr bool IsCopyConstructible = + IsConstructible>>; /* is move constructible */ template -constexpr bool IsMoveConstructible = IsConstructible ->; +constexpr bool IsMoveConstructible = + IsConstructible>; /* is nothrow constructible */ @@ -448,24 +508,25 @@ namespace detail { constexpr bool NothrowCtibleCore = false; template - constexpr bool NothrowCtibleCore - = noexcept(T(declval_in()...)); + constexpr bool NothrowCtibleCore = + noexcept(T(declval_in()...)); - template void implicit_conv_to(T) noexcept {} + template + void implicit_conv_to(T) noexcept {} template - constexpr bool NothrowCtibleCore - = noexcept(ostd::detail::implicit_conv_to(declval_in())); + constexpr bool NothrowCtibleCore = + noexcept(ostd::detail::implicit_conv_to(declval_in())); template constexpr bool NothrowCtibleCore = false; } /* namespace detail */ -template constexpr bool IsNothrowConstructible - = detail::NothrowCtibleCore, IsReference, T, A...>; +template constexpr bool IsNothrowConstructible = + detail::NothrowCtibleCore, IsReference, T, A...>; -template constexpr bool IsNothrowConstructible - = detail::NothrowCtibleCore, IsReference, T>; +template constexpr bool IsNothrowConstructible = + detail::NothrowCtibleCore, IsReference, T>; /* is nothrow default constructible */ @@ -475,25 +536,25 @@ constexpr bool IsNothrowDefaultConstructible = IsNothrowConstructible; /* is nothrow copy constructible */ template -constexpr bool IsNothrowCopyConstructible = IsNothrowConstructible> ->; +constexpr bool IsNothrowCopyConstructible = + IsNothrowConstructible>>; /* is nothrow move constructible */ template -constexpr bool IsNothrowMoveConstructible = IsNothrowConstructible ->; +constexpr bool IsNothrowMoveConstructible = + IsNothrowConstructible>; /* is assignable */ namespace detail { - template typename detail::Select2nd< + template + typename detail::Select2nd< decltype((declval_in() = declval_in())), True >::Type assign_test(T &&, U &&); - template False assign_test(Any, T &&); + template + False assign_test(Any, T &&); template || IsVoid> constexpr bool IsAssignableBase = CommonTypeBase< @@ -510,18 +571,14 @@ constexpr bool IsAssignable = detail::IsAssignableBase; /* is copy assignable */ template -constexpr bool IsCopyAssignable = IsAssignable< - AddLvalueReference, - AddLvalueReference> ->; +constexpr bool IsCopyAssignable = + IsAssignable, AddLvalueReference>>; /* is move assignable */ template -constexpr bool IsMoveAssignable = IsAssignable< - AddLvalueReference, - AddRvalueReference const ->; +constexpr bool IsMoveAssignable = + IsAssignable, AddRvalueReference const>; /* is nothrow assignable */ @@ -533,63 +590,69 @@ namespace detail { constexpr bool NothrowAssignableCore = false; template - constexpr bool NothrowAssignableCore - = noexcept(declval_in() = declval_in()); + constexpr bool NothrowAssignableCore = + noexcept(declval_in() = declval_in()); } -template constexpr bool IsNothrowAssignable - = detail::NothrowAssignableCore, T, A>; +template constexpr bool IsNothrowAssignable = + detail::NothrowAssignableCore, T, A>; /* is nothrow copy assignable */ template -constexpr bool IsNothrowCopyAssignable = IsNothrowAssignable< - AddLvalueReference, AddLvalueReference> ->; +constexpr bool IsNothrowCopyAssignable = + IsNothrowAssignable, AddLvalueReference>>; /* is nothrow move assignable */ template -constexpr bool IsNothrowMoveAssignable = IsNothrowAssignable< - AddLvalueReference, AddRvalueReference ->; +constexpr bool IsNothrowMoveAssignable = + IsNothrowAssignable, AddRvalueReference>; /* is destructible */ namespace detail { - template struct IsDtibleApply { using Type = int; }; + template + struct IsDtibleApply { using Type = int; }; template struct IsDestructorWellformed { - template static char test(typename IsDtibleApply< + template + static char test(typename IsDtibleApply< decltype(detail::declval_in().~TT()) >::Type); - template static int test(...); + template + static int test(...); static constexpr bool value = (sizeof(test(12)) == sizeof(char)); }; - template constexpr bool DtibleImpl = false; + template + constexpr bool DtibleImpl = false; template - constexpr bool DtibleImpl - = IsDestructorWellformed>::value; + constexpr bool DtibleImpl = + IsDestructorWellformed>::value; template constexpr bool DtibleImpl = true; - template constexpr bool DtibleFalse = false; + template + constexpr bool DtibleFalse = false; - template constexpr bool DtibleFalse - = DtibleImpl>; + template + constexpr bool DtibleFalse = DtibleImpl>; - template constexpr bool DtibleFalse = false; + template + constexpr bool DtibleFalse = false; template constexpr bool IsDestructibleBase = detail::DtibleFalse>; - template constexpr bool IsDestructibleBase = false; - template< > constexpr bool IsDestructibleBase = false; + template + constexpr bool IsDestructibleBase = false; + template<> + constexpr bool IsDestructibleBase = false; } /* namespace detail */ template @@ -598,19 +661,21 @@ constexpr bool IsDestructible = detail::IsDestructibleBase; /* is nothrow destructible */ namespace detail { - template constexpr bool NothrowDtibleCore = false; + template + constexpr bool NothrowDtibleCore = false; - template constexpr bool NothrowDtibleCore = false; + template + constexpr bool NothrowDtibleCore = false; - template constexpr bool NothrowDtibleCore - = noexcept(declval_in().~T()); + template + constexpr bool NothrowDtibleCore = noexcept(declval_in().~T()); } -template constexpr bool IsNothrowDestructible - = detail::NothrowDtibleCore, T>; +template +constexpr bool IsNothrowDestructible = detail::NothrowDtibleCore, T>; -template constexpr bool IsNothrowDestructible - = IsNothrowDestructible; +template +constexpr bool IsNothrowDestructible = IsNothrowDestructible; /* is trivially constructible */ @@ -619,40 +684,38 @@ namespace detail { constexpr bool IsTriviallyConstructibleBase = false; template - constexpr bool IsTriviallyConstructibleBase - = __has_trivial_constructor(T); + constexpr bool IsTriviallyConstructibleBase = + __has_trivial_constructor(T); template - constexpr bool IsTriviallyConstructibleBase - = __has_trivial_copy(T); + constexpr bool IsTriviallyConstructibleBase = __has_trivial_copy(T); template - constexpr bool IsTriviallyConstructibleBase - = __has_trivial_copy(T); + constexpr bool IsTriviallyConstructibleBase = + __has_trivial_copy(T); template - constexpr bool IsTriviallyConstructibleBase - = __has_trivial_copy(T); + constexpr bool IsTriviallyConstructibleBase = __has_trivial_copy(T); } /* namespace detail */ template -constexpr bool IsTriviallyConstructible - = detail::IsTriviallyConstructibleBase; +constexpr bool IsTriviallyConstructible = + detail::IsTriviallyConstructibleBase; /* is trivially default constructible */ -template constexpr bool IsTriviallyDefaultConstructible - = IsTriviallyConstructible; +template constexpr bool IsTriviallyDefaultConstructible = + IsTriviallyConstructible; /* is trivially copy constructible */ -template constexpr bool IsTriviallyCopyConstructible - = IsTriviallyConstructible>; +template constexpr bool IsTriviallyCopyConstructible = + IsTriviallyConstructible>; /* is trivially move constructible */ -template constexpr bool IsTriviallyMoveConstructible - = IsTriviallyConstructible>; +template constexpr bool IsTriviallyMoveConstructible = + IsTriviallyConstructible>; /* is trivially assignable */ @@ -661,35 +724,32 @@ namespace detail { constexpr bool IsTriviallyAssignableBase = false; template - constexpr bool IsTriviallyAssignableBase - = __has_trivial_assign(T); + constexpr bool IsTriviallyAssignableBase = __has_trivial_assign(T); template - constexpr bool IsTriviallyAssignableBase - = __has_trivial_copy(T); + constexpr bool IsTriviallyAssignableBase = __has_trivial_copy(T); template - constexpr bool IsTriviallyAssignableBase - = __has_trivial_copy(T); + constexpr bool IsTriviallyAssignableBase = __has_trivial_copy(T); template - constexpr bool IsTriviallyAssignableBase - = __has_trivial_copy(T); + constexpr bool IsTriviallyAssignableBase = __has_trivial_copy(T); } /* namespace detail */ template -constexpr bool IsTriviallyAssignable - = detail::IsTriviallyAssignableBase; +constexpr bool IsTriviallyAssignable = detail::IsTriviallyAssignableBase; /* is trivially copy assignable */ -template constexpr bool IsTriviallyCopyAssignable - = IsTriviallyAssignable>; +template +constexpr bool IsTriviallyCopyAssignable = + IsTriviallyAssignable>; /* is trivially move assignable */ -template constexpr bool IsTriviallyMoveAssignable - = IsTriviallyAssignable>; +template +constexpr bool IsTriviallyMoveAssignable = + IsTriviallyAssignable>; /* is trivially destructible */ @@ -704,33 +764,39 @@ constexpr bool IsBaseOf = __is_base_of(B, D); /* is convertible */ namespace detail { - template - || IsFunction || IsArray - > struct IsConvertibleBase { + template< + typename F, typename T, bool = + IsVoid || IsFunction || IsArray + > + struct IsConvertibleBase { static constexpr bool value = IsVoid; }; template struct IsConvertibleBase { - template static void test_f(TT); + template + static void test_f(TT); template(declval_in())) - > static True test(int); + > + static True test(int); - template static False test(...); + template + static False test(...); static constexpr bool value = decltype(test(0))::value; }; } -template constexpr bool IsConvertible - = detail::IsConvertibleBase::value; +template +constexpr bool IsConvertible = detail::IsConvertibleBase::value; /* extent */ namespace detail { - template constexpr Size ExtentBase = 0; + template + constexpr Size ExtentBase = 0; template constexpr Size ExtentBase = 0; @@ -751,7 +817,8 @@ constexpr Size Extent = detail::ExtentBase; /* rank */ namespace detail { - template constexpr Size RankBase = 0; + template + constexpr Size RankBase = 0; template constexpr Size RankBase = detail::RankBase + 1; @@ -760,18 +827,19 @@ namespace detail { constexpr Size RankBase = detail::RankBase + 1; } -template constexpr Size Rank = detail::RankBase; +template +constexpr Size Rank = detail::RankBase; /* remove const, volatile, cv */ namespace detail { template - struct RemoveConstBase { using Type = T; }; + struct RemoveConstBase { using Type = T; }; template struct RemoveConstBase { using Type = T; }; template - struct RemoveVolatileBase { using Type = T; }; + struct RemoveVolatileBase { using Type = T; }; template struct RemoveVolatileBase { using Type = T; }; } @@ -794,22 +862,26 @@ namespace detail { template || IsFunction || IsConst> struct AddConstCore { using Type = T; }; - template struct AddConstCore { + template + struct AddConstCore { using Type = T const; }; - template struct AddConstBase { + template + struct AddConstBase { using Type = typename AddConstCore::Type; }; template || IsFunction || IsVolatile> struct AddVolatileCore { using Type = T; }; - template struct AddVolatileCore { + template + struct AddVolatileCore { using Type = T volatile; }; - template struct AddVolatileBase { + template + struct AddVolatileBase { using Type = typename AddVolatileCore::Type; }; } @@ -831,9 +903,9 @@ using AddCv = typename detail::AddCvBase::Type; namespace detail { template - struct RemoveReferenceBase { using Type = T; }; + struct RemoveReferenceBase { using Type = T; }; template - struct RemoveReferenceBase { using Type = T; }; + struct RemoveReferenceBase { using Type = T; }; template struct RemoveReferenceBase { using Type = T; }; } @@ -842,13 +914,13 @@ namespace detail { namespace detail { template - struct RemovePointerBase { using Type = T; }; + struct RemovePointerBase { using Type = T; }; template - struct RemovePointerBase { using Type = T; }; + struct RemovePointerBase { using Type = T; }; template - struct RemovePointerBase { using Type = T; }; + struct RemovePointerBase { using Type = T; }; template - struct RemovePointerBase { using Type = T; }; + struct RemovePointerBase { using Type = T; }; template struct RemovePointerBase { using Type = T; }; } @@ -859,7 +931,8 @@ using RemovePointer = typename detail::RemovePointerBase::Type; /* add pointer */ namespace detail { - template struct AddPointerBase { + template + struct AddPointerBase { using Type = RemoveReference *; }; } @@ -870,18 +943,24 @@ using AddPointer = typename detail::AddPointerBase::Type; /* add lvalue reference */ namespace detail { - template struct AddLr { using Type = T &; }; - template struct AddLr { using Type = T &; }; - template<> struct AddLr { + template + struct AddLr { using Type = T &; }; + template + struct AddLr { using Type = T &; }; + template<> + struct AddLr { using Type = void; }; - template<> struct AddLr { + template<> + struct AddLr { using Type = void const; }; - template<> struct AddLr { + template<> + struct AddLr { using Type = void volatile; }; - template<> struct AddLr { + template<> + struct AddLr { using Type = void const volatile; }; } @@ -889,17 +968,22 @@ namespace detail { /* add rvalue reference */ namespace detail { - template struct AddRr { using Type = T &&; }; - template<> struct AddRr { + template + struct AddRr { using Type = T &&; }; + template<> + struct AddRr { using Type = void; }; - template<> struct AddRr { + template<> + struct AddRr { using Type = void const; }; - template<> struct AddRr { + template<> + struct AddRr { using Type = void volatile; }; - template<> struct AddRr { + template<> + struct AddRr { using Type = void const volatile; }; } @@ -908,9 +992,9 @@ namespace detail { namespace detail { template - struct RemoveExtentBase { using Type = T; }; + struct RemoveExtentBase { using Type = T; }; template - struct RemoveExtentBase { using Type = T; }; + struct RemoveExtentBase { using Type = T; }; template struct RemoveExtentBase { using Type = T; }; } @@ -921,13 +1005,16 @@ using RemoveExtent = typename detail::RemoveExtentBase::Type; /* remove all extents */ namespace detail { - template struct RemoveAllExtentsBase { using Type = T; }; + template + struct RemoveAllExtentsBase { using Type = T; }; - template struct RemoveAllExtentsBase { + template + struct RemoveAllExtentsBase { using Type = RemoveAllExtentsBase; }; - template struct RemoveAllExtentsBase { + template + struct RemoveAllExtentsBase { using Type = RemoveAllExtentsBase; }; } @@ -939,7 +1026,8 @@ namespace detail { */ namespace detail { - template struct TypeList { + template + struct TypeList { using First = T; using Rest = U; }; @@ -952,17 +1040,27 @@ namespace detail { ~TlNat() = delete; }; - using Stypes = TypeList>>>>; + using Stypes = + TypeList< + sbyte, TypeList< + short, TypeList< + int, TypeList< + long, TypeList + > + > + > + >; - using Utypes = TypeList>>>>; + using Utypes = + TypeList< + byte, TypeList< + ushort, TypeList< + uint, TypeList< + ulong, TypeList + > + > + > + >; template struct TypeFindFirst; @@ -977,7 +1075,8 @@ namespace detail { using Type = typename TypeFindFirst::Type; }; - template>, bool = IsVolatile> > struct ApplyCv { @@ -1030,39 +1129,63 @@ namespace detail { using Type = typename TypeFindFirst::Type; }; - template<> struct MakeSignedCore {}; - template<> struct MakeSignedCore { using Type = short; }; - template<> struct MakeSignedCore { using Type = int; }; - template<> struct MakeSignedCore { using Type = long; }; + template<> + struct MakeSignedCore {}; + template<> + struct MakeSignedCore { using Type = short; }; + template<> + struct MakeSignedCore { using Type = int; }; + template<> + struct MakeSignedCore { using Type = long; }; - template<> struct MakeSignedCore { using Type = sbyte; }; - template<> struct MakeSignedCore { using Type = sbyte; }; - template<> struct MakeSignedCore { using Type = short; }; - template<> struct MakeSignedCore { using Type = int; }; - template<> struct MakeSignedCore { using Type = long; }; - template<> struct MakeSignedCore { using Type = llong; }; - template<> struct MakeSignedCore { using Type = llong; }; + template<> + struct MakeSignedCore { using Type = sbyte; }; + template<> + struct MakeSignedCore { using Type = sbyte; }; + template<> + struct MakeSignedCore { using Type = short; }; + template<> + struct MakeSignedCore { using Type = int; }; + template<> + struct MakeSignedCore { using Type = long; }; + template<> + struct MakeSignedCore { using Type = llong; }; + template<> + struct MakeSignedCore { using Type = llong; }; - template<> struct MakeUnsignedCore {}; - template<> struct MakeUnsignedCore { using Type = ushort; }; - template<> struct MakeUnsignedCore { using Type = uint; }; - template<> struct MakeUnsignedCore { using Type = ulong; }; + template<> + struct MakeUnsignedCore {}; + template<> + struct MakeUnsignedCore { using Type = ushort; }; + template<> + struct MakeUnsignedCore { using Type = uint; }; + template<> + struct MakeUnsignedCore { using Type = ulong; }; - template<> struct MakeUnsignedCore { using Type = byte; }; - template<> struct MakeUnsignedCore { using Type = byte; }; - template<> struct MakeUnsignedCore { using Type = ushort; }; - template<> struct MakeUnsignedCore { using Type = uint; }; - template<> struct MakeUnsignedCore { using Type = ulong; }; - template<> struct MakeUnsignedCore { using Type = ullong; }; - template<> struct MakeUnsignedCore { using Type = ullong; }; + template<> + struct MakeUnsignedCore { using Type = byte; }; + template<> + struct MakeUnsignedCore { using Type = byte; }; + template<> + struct MakeUnsignedCore { using Type = ushort; }; + template<> + struct MakeUnsignedCore { using Type = uint; }; + template<> + struct MakeUnsignedCore { using Type = ulong; }; + template<> + struct MakeUnsignedCore { using Type = ullong; }; + template<> + struct MakeUnsignedCore { using Type = ullong; }; - template struct MakeSignedBase { + template + struct MakeSignedBase { using Type = typename ApplyCv>::Type >::Type; }; - template struct MakeUnsignedBase { + template + struct MakeUnsignedBase { using Type = typename ApplyCv>::Type >::Type; @@ -1097,28 +1220,32 @@ namespace detail { #define OSTD_FWD(T, _v) static_cast(_v) template inline auto rof_invoke(F &&f, A &&...args) -> - decltype(OSTD_FWD(F, f)(OSTD_FWD(A, args)...)) { + decltype(OSTD_FWD(F, f)(OSTD_FWD(A, args)...)) + { return OSTD_FWD(F, f)(OSTD_FWD(A, args)...); } template inline auto rof_invoke(T B::*pmd, D &&ref) -> - decltype(OSTD_FWD(D, ref).*pmd) { + decltype(OSTD_FWD(D, ref).*pmd) + { return OSTD_FWD(D, ref).*pmd; } template inline auto rof_invoke(PMD &&pmd, P &&ptr) -> - decltype((*OSTD_FWD(P, ptr)).*OSTD_FWD(PMD, pmd)) { + decltype((*OSTD_FWD(P, ptr)).*OSTD_FWD(PMD, pmd)) + { return (*OSTD_FWD(P, ptr)).*OSTD_FWD(PMD, pmd); } template inline auto rof_invoke(T B::*pmf, D &&ref, A &&...args) -> - decltype((OSTD_FWD(D, ref).*pmf)(OSTD_FWD(A, args)...)) { + decltype((OSTD_FWD(D, ref).*pmf)(OSTD_FWD(A, args)...)) + { return (OSTD_FWD(D, ref).*pmf)(OSTD_FWD(A, args)...); } template inline auto rof_invoke(PMF &&pmf, P &&ptr, A &&...args) -> - decltype(((*OSTD_FWD(P, ptr)).*OSTD_FWD(PMF, pmf)) - (OSTD_FWD(A, args)...)) { + decltype(((*OSTD_FWD(P, ptr)).*OSTD_FWD(PMF, pmf))(OSTD_FWD(A, args)...)) + { return ((*OSTD_FWD(P, ptr)).*OSTD_FWD(PMF, pmf)) (OSTD_FWD(A, args)...); } @@ -1133,7 +1260,8 @@ namespace detail { detail::declval_in()...)); }; - template struct ResultOfBase: ResultOfCore {}; + template + struct ResultOfBase: ResultOfCore {}; } /* namespace detail */ template @@ -1142,9 +1270,11 @@ using ResultOf = typename detail::ResultOfBase::Type; /* enable if */ namespace detail { - template struct EnableIfBase {}; + template + struct EnableIfBase {}; - template struct EnableIfBase { using Type = T; }; + template + struct EnableIfBase { using Type = T; }; } template @@ -1158,7 +1288,8 @@ namespace detail { private: using U = RemoveReference; public: - using Type = Conditional, + using Type = Conditional< + IsArray, RemoveExtent *, Conditional, AddPointer, RemoveCv> >; @@ -1171,15 +1302,19 @@ using Decay = typename detail::DecayBase::Type; /* common type */ namespace detail { - template struct CommonTypeBase; + template + struct CommonTypeBase; - template struct CommonTypeBase { + template + struct CommonTypeBase { using Type = Decay; }; - template struct CommonTypeBase { - using Type = Decay() - : detail::declval_in())>; + template + struct CommonTypeBase { + using Type = Decay(): detail::declval_in() + )>; }; template @@ -1196,14 +1331,16 @@ using CommonType = typename detail::CommonTypeBase::Type; /* aligned storage */ namespace detail { - template struct AlignedTest { + template + struct AlignedTest { union Type { byte data[N]; MaxAlign align; }; }; - template struct AlignedStorageBase { + template + struct AlignedStorageBase { struct Type { alignas(A) byte data[N]; }; @@ -1212,23 +1349,26 @@ namespace detail { template::Type) -> using AlignedStorage = typename detail::AlignedStorageBase::Type; +> +using AlignedStorage = typename detail::AlignedStorageBase::Type; /* aligned union */ namespace detail { - template constexpr Size AlignMax = 0; - template constexpr Size AlignMax = N; + template + constexpr Size AlignMax = 0; + template + constexpr Size AlignMax = N; - template constexpr Size AlignMax - = (N1 > N2) ? N1 : N2; + template + constexpr Size AlignMax = (N1 > N2) ? N1 : N2; template constexpr Size AlignMax = AlignMax, N...>; - template struct AlignedUnionBase { - static constexpr Size alignment_value - = AlignMax; + template + struct AlignedUnionBase { + static constexpr Size alignment_value = AlignMax; struct type { alignas(alignment_value) byte data[AlignMax]; @@ -1243,7 +1383,8 @@ using AlignedUnion = typename detail::AlignedUnionBase::Type; namespace detail { /* gotta wrap, in a struct otherwise clang ICEs... */ - template struct UnderlyingTypeBase { + template + struct UnderlyingTypeBase { using Type = __underlying_type(T); }; } diff --git a/ostd/utility.hh b/ostd/utility.hh index a46f6a9..be4ba50 100644 --- a/ostd/utility.hh +++ b/ostd/utility.hh @@ -43,7 +43,8 @@ inline T exchange(T &v, U &&nv) { /* declval */ -template AddRvalueReference declval(); +template +AddRvalueReference declval(); /* swap */ @@ -54,33 +55,38 @@ namespace detail { template False test_swap(...); - template inline void swap_fb(T &a, T &b, EnableIf< - decltype(test_swap(0))::value, bool - > = true) { + template + inline void swap_fb( + T &a, T &b, EnableIf(0))::value, bool> = true + ) { a.swap(b); } - template inline void swap_fb(T &a, T &b, EnableIf< - !decltype(test_swap(0))::value, bool - > = true) { + template + inline void swap_fb( + T &a, T &b, EnableIf(0))::value, bool> = true + ) { T c(move(a)); a = move(b); b = move(c); } } -template inline void swap(T &a, T &b) { +template +inline void swap(T &a, T &b) { detail::swap_fb(a, b); } -template inline void swap(T (&a)[N], T (&b)[N]) { +template +inline void swap(T (&a)[N], T (&b)[N]) { for (Size i = 0; i < N; ++i) { swap(a[i], b[i]); } } namespace detail { - template inline void swap_adl(T &a, T &b) { + template + inline void swap_adl(T &a, T &b) { using ostd::swap; swap(a, b); } @@ -103,14 +109,16 @@ struct Pair { template Pair(TT &&x, UU &&y): - first(forward(x)), second(forward(y)) {} + first(forward(x)), second(forward(y)) + {} template Pair(Pair const &v): first(v.first), second(v.second) {} template Pair(Pair &&v): - first(move(v.first)), second(move(v.second)) {} + first(move(v.first)), second(move(v.second)) + {} Pair &operator=(Pair const &v) { first = v.first; @@ -144,7 +152,8 @@ struct Pair { } }; -template struct ReferenceWrapper; +template +struct ReferenceWrapper; namespace detail { template @@ -164,12 +173,13 @@ namespace detail { } /* namespace detail */ template -inline Pair::Type, - typename detail::MakePairRet::Type - > make_pair(T &&a, U &&b) { - return Pair::Type, - typename detail::MakePairRet::Type - >(forward(a), forward(b));; +inline Pair< + typename detail::MakePairRet::Type, typename detail::MakePairRet::Type +> make_pair(T &&a, U &&b) { + return Pair< + typename detail::MakePairRet::Type, + typename detail::MakePairRet::Type + >(forward(a), forward(b)); } template @@ -222,9 +232,11 @@ struct TupleElementBase<1, Pair> { }; namespace detail { - template struct GetPair; + template + struct GetPair; - template<> struct GetPair<0> { + template<> + struct GetPair<0> { template static T &get(Pair &p) { return p.first; } template @@ -237,7 +249,8 @@ namespace detail { } }; - template<> struct GetPair<1> { + template<> + struct GetPair<1> { template static U &get(Pair &p) { return p.second; } template @@ -275,7 +288,8 @@ namespace detail { template, RemoveCv>, bool = IsEmpty, bool = IsEmpty - > constexpr Size CompressedPairSwitch = detail::Undefined(); + > + constexpr Size CompressedPairSwitch = detail::Undefined(); /* neither empty */ template @@ -306,8 +320,9 @@ namespace detail { U p_second; template - CompressedPairBase(TT &&a, UU &&b): p_first(forward(a)), - p_second(forward(b)) {} + CompressedPairBase(TT &&a, UU &&b): + p_first(forward(a)), p_second(forward(b)) + {} T &first() { return p_first; } T const &first() const { return p_first; } @@ -326,8 +341,9 @@ namespace detail { U p_second; template - CompressedPairBase(TT &&a, UU &&b): T(forward(a)), - p_second(forward(b)) {} + CompressedPairBase(TT &&a, UU &&b): + T(forward(a)), p_second(forward(b)) + {} T &first() { return *this; } T const &first() const { return *this; } @@ -345,8 +361,9 @@ namespace detail { T p_first; template - CompressedPairBase(TT &&a, UU &&b): U(forward(b)), - p_first(forward(a)) {} + CompressedPairBase(TT &&a, UU &&b): + U(forward(b)), p_first(forward(a)) + {} T &first() { return p_first; } T const &first() const { return p_first; } @@ -362,8 +379,9 @@ namespace detail { template struct CompressedPairBase: T, U { template - CompressedPairBase(TT &&a, UU &&b): T(forward(a)), - U(forward(b)) {} + CompressedPairBase(TT &&a, UU &&b): + T(forward(a)), U(forward(b)) + {} T &first() { return *this; } T const &first() const { return *this; } @@ -379,8 +397,9 @@ namespace detail { using Base = CompressedPairBase; template - CompressedPair(TT &&a, UU &&b): Base(forward(a), - forward(b)) {} + CompressedPair(TT &&a, UU &&b): + Base(forward(a), forward(b)) + {} T &first() { return Base::first(); } T const &first() const { return Base::first(); } diff --git a/ostd/vector.hh b/ostd/vector.hh index f873514..5fc7b53 100644 --- a/ostd/vector.hh +++ b/ostd/vector.hh @@ -26,7 +26,9 @@ class Vector { VecPair p_buf; void insert_base(Size idx, Size n) { - if (p_len + n > p_cap) reserve(p_len + n); + if (p_len + n > p_cap) { + reserve(p_len + n); + } p_len += n; for (Size i = p_len - 1; i > idx + n - 1; --i) { p_buf.first()[i] = move(p_buf.first()[i - n]); @@ -34,10 +36,12 @@ class Vector { } template - void ctor_from_range(R &range, EnableIf< - IsFiniteRandomAccessRange && IsPod && - IsSame>>, bool - > = true) { + void ctor_from_range( + R &range, EnableIf< + IsFiniteRandomAccessRange && IsPod && + IsSame>>, bool + > = true + ) { RangeSize l = range.size(); reserve(l); p_len = l; @@ -45,15 +49,18 @@ class Vector { } template - void ctor_from_range(R &range, EnableIf< - !IsFiniteRandomAccessRange || !IsPod || - !IsSame>>, bool - > = true) { + void ctor_from_range( + R &range, EnableIf< + !IsFiniteRandomAccessRange || !IsPod || + !IsSame>>, bool + > = true + ) { Size i = 0; for (; !range.empty(); range.pop_front()) { reserve(i + 1); - allocator_construct(p_buf.second(), &p_buf.first()[i], - range.front()); + allocator_construct( + p_buf.second(), &p_buf.first()[i], range.front() + ); ++i; p_len = i; } @@ -86,16 +93,22 @@ public: Vector(A const &a = A()): p_len(0), p_cap(0), p_buf(nullptr, a) {} explicit Vector(Size n, T const &val = T(), A const &al = A()): Vector(al) { - if (!n) return; + if (!n) { + return; + } p_buf.first() = allocator_allocate(p_buf.second(), n); p_len = p_cap = n; Pointer cur = p_buf.first(), last = p_buf.first() + n; - while (cur != last) + while (cur != last) { allocator_construct(p_buf.second(), cur++, val); + } } - Vector(Vector const &v): p_len(0), p_cap(0), p_buf(nullptr, - allocator_container_copy(v.p_buf.second())) { + Vector(Vector const &v): + p_len(0), p_cap(0), p_buf(nullptr, allocator_container_copy( + v.p_buf.second()) + ) + { reserve(v.p_cap); p_len = v.p_len; copy_contents(v); @@ -107,8 +120,11 @@ public: copy_contents(v); } - Vector(Vector &&v): p_len(v.p_len), p_cap(v.p_cap), p_buf(v.p_buf.first(), - move(v.p_buf.second())) { + Vector(Vector &&v): + p_len(v.p_len), p_cap(v.p_cap), p_buf( + v.p_buf.first(), move(v.p_buf.second()) + ) + { v.p_buf.first() = nullptr; v.p_len = v.p_cap = 0; } @@ -140,18 +156,21 @@ public: if (IsPod) { memcpy(p_buf.first(), &r[0], r.size() * sizeof(T)); } else { - for (Size i = 0; i < r.size(); ++i) + for (Size i = 0; i < r.size(); ++i) { allocator_construct(p_buf.second(), &p_buf.first()[i], r[i]); + } } p_len = r.size(); } Vector(InitializerList v, A const &a = A()): - Vector(ConstRange(v.begin(), v.size()), a) {} + Vector(ConstRange(v.begin(), v.size()), a) + {} template && IsConvertible, Value> - >> Vector(R range, A const &a = A()): Vector(a) { + >> + Vector(R range, A const &a = A()): Vector(a) { ctor_from_range(range); } @@ -163,14 +182,17 @@ public: void clear() { if (p_len > 0 && !IsPod) { Pointer cur = p_buf.first(), last = p_buf.first() + p_len; - while (cur != last) + while (cur != last) { allocator_destroy(p_buf.second(), cur++); + } } p_len = 0; } Vector &operator=(Vector const &v) { - if (this == &v) return *this; + if (this == &v) { + return *this; + } clear(); if (AllocatorPropagateOnContainerCopyAssignment) { if (p_buf.second() != v.p_buf.second() && p_cap) { @@ -187,10 +209,12 @@ public: Vector &operator=(Vector &&v) { clear(); - if (p_buf.first()) + if (p_buf.first()) { allocator_deallocate(p_buf.second(), p_buf.first(), p_cap); - if (AllocatorPropagateOnContainerMoveAssignment) + } + if (AllocatorPropagateOnContainerMoveAssignment) { p_buf.second() = v.p_buf.second(); + } p_len = v.p_len; p_cap = v.p_cap; p_buf.~VecPair(); @@ -218,7 +242,8 @@ public: template && IsConvertible, Value> - >> Vector &operator=(R range) { + >> + Vector &operator=(R range) { clear(); ctor_from_range(range); return *this; @@ -239,13 +264,16 @@ public: } else { Pointer first = p_buf.first() + l; Pointer last = p_buf.first() + p_len; - while (first != last) + while (first != last) { allocator_construct(p_buf.second(), first++, v); + } } } void reserve(Size n) { - if (n <= p_cap) return; + if (n <= p_cap) { + return; + } Size oc = p_cap; if (!oc) { p_cap = max(n, Size(8)); @@ -274,28 +302,38 @@ public: T const &operator[](Size i) const { return p_buf.first()[i]; } T *at(Size i) { - if (!in_range(i)) return nullptr; + if (!in_range(i)) { + return nullptr; + } return &p_buf.first()[i]; } T const *at(Size i) const { - if (!in_range(i)) return nullptr; + if (!in_range(i)) { + return nullptr; + } return &p_buf.first()[i]; } T &push(T const &v) { - if (p_len == p_cap) reserve(p_len + 1); + if (p_len == p_cap) { + reserve(p_len + 1); + } allocator_construct(p_buf.second(), &p_buf.first()[p_len], v); return p_buf.first()[p_len++]; } T &push(T &&v) { - if (p_len == p_cap) reserve(p_len + 1); + if (p_len == p_cap) { + reserve(p_len + 1); + } allocator_construct(p_buf.second(), &p_buf.first()[p_len], move(v)); return p_buf.first()[p_len++]; } T &push() { - if (p_len == p_cap) reserve(p_len + 1); + if (p_len == p_cap) { + reserve(p_len + 1); + } allocator_construct(p_buf.second(), &p_buf.first()[p_len]); return p_buf.first()[p_len++]; } @@ -305,9 +343,11 @@ public: if (IsPod) { memcpy(p_buf.first() + p_len, v, n * sizeof(T)); } else { - for (Size i = 0; i < n; ++i) - allocator_construct(p_buf.second(), - &p_buf.first()[p_len + i], v[i]); + for (Size i = 0; i < n; ++i) { + allocator_construct( + p_buf.second(), &p_buf.first()[p_len + i], v[i] + ); + } } p_len += n; return Range(&p_buf.first()[p_len - n], &p_buf.first()[p_len]); @@ -315,9 +355,12 @@ public: template T &emplace_back(U &&...args) { - if (p_len == p_cap) reserve(p_len + 1); - allocator_construct(p_buf.second(), &p_buf.first()[p_len], - forward(args)...); + if (p_len == p_cap) { + reserve(p_len + 1); + } + allocator_construct( + p_buf.second(), &p_buf.first()[p_len], forward(args)... + ); return p_buf.first()[p_len++]; } @@ -415,8 +458,9 @@ public: detail::swap_adl(p_len, v.p_len); detail::swap_adl(p_cap, v.p_cap); detail::swap_adl(p_buf.first(), v.p_buf.first()); - if (AllocatorPropagateOnContainerSwap) + if (AllocatorPropagateOnContainerSwap) { detail::swap_adl(p_buf.second(), v.p_buf.second()); + } } A get_allocator() const {