1// -*- C++ -*-
2//===-------------------------- functional --------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP_EXPERIMENTAL_FUNCTIONAL
11#define _LIBCPP_EXPERIMENTAL_FUNCTIONAL
12
13/*
14   experimental/functional synopsis
15
16#include <algorithm>
17
18namespace std {
19namespace experimental {
20inline namespace fundamentals_v1 {
21
22    // See C++14 20.9.9, Function object binders
23    template <class T> constexpr bool is_bind_expression_v
24      = is_bind_expression<T>::value;
25    template <class T> constexpr int is_placeholder_v
26      = is_placeholder<T>::value;
27
28    // 4.2, Class template function
29    template<class> class function; // undefined
30    template<class R, class... ArgTypes> class function<R(ArgTypes...)>;
31
32    template<class R, class... ArgTypes>
33    void swap(function<R(ArgTypes...)>&, function<R(ArgTypes...)>&);
34
35    template<class R, class... ArgTypes>
36    bool operator==(const function<R(ArgTypes...)>&, nullptr_t) noexcept;
37    template<class R, class... ArgTypes>
38    bool operator==(nullptr_t, const function<R(ArgTypes...)>&) noexcept;
39    template<class R, class... ArgTypes>
40    bool operator!=(const function<R(ArgTypes...)>&, nullptr_t) noexcept;
41    template<class R, class... ArgTypes>
42    bool operator!=(nullptr_t, const function<R(ArgTypes...)>&) noexcept;
43
44    // 4.3, Searchers
45    template<class ForwardIterator, class BinaryPredicate = equal_to<>>
46      class default_searcher;
47
48    template<class RandomAccessIterator,
49             class Hash = hash<typename iterator_traits<RandomAccessIterator>::value_type>,
50             class BinaryPredicate = equal_to<>>
51      class boyer_moore_searcher;
52
53    template<class RandomAccessIterator,
54             class Hash = hash<typename iterator_traits<RandomAccessIterator>::value_type>,
55             class BinaryPredicate = equal_to<>>
56      class boyer_moore_horspool_searcher;
57
58    template<class ForwardIterator, class BinaryPredicate = equal_to<>>
59    default_searcher<ForwardIterator, BinaryPredicate>
60    make_default_searcher(ForwardIterator pat_first, ForwardIterator pat_last,
61                          BinaryPredicate pred = BinaryPredicate());
62
63    template<class RandomAccessIterator,
64             class Hash = hash<typename iterator_traits<RandomAccessIterator>::value_type>,
65             class BinaryPredicate = equal_to<>>
66    boyer_moore_searcher<RandomAccessIterator, Hash, BinaryPredicate>
67    make_boyer_moore_searcher(
68        RandomAccessIterator pat_first, RandomAccessIterator pat_last,
69        Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate());
70
71    template<class RandomAccessIterator,
72             class Hash = hash<typename iterator_traits<RandomAccessIterator>::value_type>,
73             class BinaryPredicate = equal_to<>>
74    boyer_moore_horspool_searcher<RandomAccessIterator, Hash, BinaryPredicate>
75    make_boyer_moore_horspool_searcher(
76        RandomAccessIterator pat_first, RandomAccessIterator pat_last,
77        Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate());
78
79  } // namespace fundamentals_v1
80  } // namespace experimental
81
82  template<class R, class... ArgTypes, class Alloc>
83  struct uses_allocator<experimental::function<R(ArgTypes...)>, Alloc>;
84
85} // namespace std
86
87*/
88
89#include <__memory/uses_allocator.h>
90#include <experimental/__config>
91#include <functional>
92#include <algorithm>
93#include <type_traits>
94#include <vector>
95#include <array>
96#include <unordered_map>
97
98#include <__debug>
99
100#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
101#pragma GCC system_header
102#endif
103
104_LIBCPP_PUSH_MACROS
105#include <__undef_macros>
106
107
108_LIBCPP_BEGIN_NAMESPACE_LFTS
109
110#if _LIBCPP_STD_VER > 11
111// default searcher
112template<class _ForwardIterator, class _BinaryPredicate = equal_to<>>
113class _LIBCPP_TEMPLATE_VIS default_searcher {
114public:
115    _LIBCPP_INLINE_VISIBILITY
116    default_searcher(_ForwardIterator __f, _ForwardIterator __l,
117                       _BinaryPredicate __p = _BinaryPredicate())
118        : __first_(__f), __last_(__l), __pred_(__p) {}
119
120    template <typename _ForwardIterator2>
121    _LIBCPP_INLINE_VISIBILITY
122    pair<_ForwardIterator2, _ForwardIterator2>
123    operator () (_ForwardIterator2 __f, _ForwardIterator2 __l) const
124    {
125        return _VSTD::__search(__f, __l, __first_, __last_, __pred_,
126            typename iterator_traits<_ForwardIterator>::iterator_category(),
127            typename iterator_traits<_ForwardIterator2>::iterator_category());
128    }
129
130private:
131    _ForwardIterator __first_;
132    _ForwardIterator __last_;
133    _BinaryPredicate __pred_;
134    };
135
136template<class _ForwardIterator, class _BinaryPredicate = equal_to<>>
137_LIBCPP_INLINE_VISIBILITY
138default_searcher<_ForwardIterator, _BinaryPredicate>
139make_default_searcher( _ForwardIterator __f, _ForwardIterator __l, _BinaryPredicate __p = _BinaryPredicate ())
140{
141    return default_searcher<_ForwardIterator, _BinaryPredicate>(__f, __l, __p);
142}
143
144template<class _Key, class _Value, class _Hash, class _BinaryPredicate, bool /*useArray*/> class _BMSkipTable;
145
146//  General case for BM data searching; use a map
147template<class _Key, typename _Value, class _Hash, class _BinaryPredicate>
148class _BMSkipTable<_Key, _Value, _Hash, _BinaryPredicate, false> {
149public: // TODO private:
150    typedef _Value value_type;
151    typedef _Key   key_type;
152
153    const _Value __default_value_;
154    std::unordered_map<_Key, _Value, _Hash, _BinaryPredicate> __table;
155
156public:
157    _LIBCPP_INLINE_VISIBILITY
158    _BMSkipTable(size_t __sz, _Value __default, _Hash __hf, _BinaryPredicate __pred)
159        : __default_value_(__default), __table(__sz, __hf, __pred) {}
160
161    _LIBCPP_INLINE_VISIBILITY
162    void insert(const key_type &__key, value_type __val)
163    {
164        __table [__key] = __val;    // Would skip_.insert (val) be better here?
165    }
166
167    _LIBCPP_INLINE_VISIBILITY
168    value_type operator [](const key_type & __key) const
169    {
170        auto __it = __table.find (__key);
171        return __it == __table.end() ? __default_value_ : __it->second;
172    }
173};
174
175
176//  Special case small numeric values; use an array
177template<class _Key, typename _Value, class _Hash, class _BinaryPredicate>
178class _BMSkipTable<_Key, _Value, _Hash, _BinaryPredicate, true> {
179private:
180    typedef _Value value_type;
181    typedef _Key   key_type;
182
183    typedef typename make_unsigned<key_type>::type unsigned_key_type;
184    typedef std::array<value_type, numeric_limits<unsigned_key_type>::max()> skip_map;
185    skip_map __table;
186
187public:
188    _LIBCPP_INLINE_VISIBILITY
189    _BMSkipTable(size_t /*__sz*/, _Value __default, _Hash /*__hf*/, _BinaryPredicate /*__pred*/)
190    {
191        std::fill_n(__table.begin(), __table.size(), __default);
192    }
193
194    _LIBCPP_INLINE_VISIBILITY
195    void insert(key_type __key, value_type __val)
196    {
197        __table[static_cast<unsigned_key_type>(__key)] = __val;
198    }
199
200    _LIBCPP_INLINE_VISIBILITY
201    value_type operator [](key_type __key) const
202    {
203        return __table[static_cast<unsigned_key_type>(__key)];
204    }
205};
206
207
208template <class _RandomAccessIterator1,
209          class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
210          class _BinaryPredicate = equal_to<>>
211class _LIBCPP_TEMPLATE_VIS boyer_moore_searcher {
212private:
213    typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type difference_type;
214    typedef typename std::iterator_traits<_RandomAccessIterator1>::value_type      value_type;
215    typedef _BMSkipTable<value_type, difference_type, _Hash, _BinaryPredicate,
216                    is_integral<value_type>::value && // what about enums?
217                    sizeof(value_type) == 1 &&
218                    is_same<_Hash, hash<value_type>>::value &&
219                    is_same<_BinaryPredicate, equal_to<>>::value
220            > skip_table_type;
221
222public:
223    boyer_moore_searcher(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
224                _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate())
225            : __first_(__f), __last_(__l), __pred_(__pred),
226              __pattern_length_(_VSTD::distance(__first_, __last_)),
227              __skip_{make_shared<skip_table_type>(__pattern_length_, -1, __hf, __pred_)},
228              __suffix_{make_shared<vector<difference_type>>(__pattern_length_ + 1)}
229        {
230    //  build the skip table
231        for ( difference_type __i = 0; __f != __l; ++__f, (void) ++__i )
232            __skip_->insert(*__f, __i);
233
234        this->__build_suffix_table ( __first_, __last_, __pred_ );
235        }
236
237    template <typename _RandomAccessIterator2>
238    pair<_RandomAccessIterator2, _RandomAccessIterator2>
239    operator ()(_RandomAccessIterator2 __f, _RandomAccessIterator2 __l) const
240    {
241        static_assert ( std::is_same<
242                typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator1>::value_type>::type,
243                typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator2>::value_type>::type
244                    >::value,
245                "Corpus and Pattern iterators must point to the same type" );
246
247        if (__f      == __l )    return make_pair(__l, __l); // empty corpus
248        if (__first_ == __last_) return make_pair(__f, __f); // empty pattern
249
250    //  If the pattern is larger than the corpus, we can't find it!
251        if ( __pattern_length_ > _VSTD::distance(__f, __l))
252            return make_pair(__l, __l);
253
254    //  Do the search
255        return this->__search(__f, __l);
256    }
257
258public: // TODO private:
259    _RandomAccessIterator1               __first_;
260    _RandomAccessIterator1               __last_;
261    _BinaryPredicate                     __pred_;
262    difference_type                      __pattern_length_;
263    shared_ptr<skip_table_type>          __skip_;
264    shared_ptr<vector<difference_type>>  __suffix_;
265
266    template <typename _RandomAccessIterator2>
267    pair<_RandomAccessIterator2, _RandomAccessIterator2>
268    __search(_RandomAccessIterator2 __f, _RandomAccessIterator2 __l) const
269    {
270        _RandomAccessIterator2 __cur = __f;
271        const _RandomAccessIterator2 __last = __l - __pattern_length_;
272        const skip_table_type &         __skip   = *__skip_.get();
273        const vector<difference_type> & __suffix = *__suffix_.get();
274
275        while (__cur <= __last)
276        {
277
278        //  Do we match right where we are?
279            difference_type __j = __pattern_length_;
280            while (__pred_(__first_ [__j-1], __cur [__j-1])) {
281                __j--;
282            //  We matched - we're done!
283                if ( __j == 0 )
284                    return make_pair(__cur, __cur + __pattern_length_);
285                }
286
287        //  Since we didn't match, figure out how far to skip forward
288            difference_type __k = __skip[__cur [ __j - 1 ]];
289            difference_type __m = __j - __k - 1;
290            if (__k < __j && __m > __suffix[ __j ])
291                __cur += __m;
292            else
293                __cur += __suffix[ __j ];
294        }
295
296        return make_pair(__l, __l);     // We didn't find anything
297    }
298
299
300    template<typename _Iterator, typename _Container>
301    void __compute_bm_prefix ( _Iterator __f, _Iterator __l, _BinaryPredicate __pred, _Container &__prefix )
302    {
303        const size_t __count = _VSTD::distance(__f, __l);
304
305        __prefix[0] = 0;
306        size_t __k = 0;
307        for ( size_t __i = 1; __i < __count; ++__i )
308        {
309            while ( __k > 0 && !__pred ( __f[__k], __f[__i] ))
310                __k = __prefix [ __k - 1 ];
311
312            if ( __pred ( __f[__k], __f[__i] ))
313                __k++;
314            __prefix [ __i ] = __k;
315        }
316    }
317
318    void __build_suffix_table(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
319                                                    _BinaryPredicate __pred)
320    {
321        const size_t __count = _VSTD::distance(__f, __l);
322        vector<difference_type> & __suffix = *__suffix_.get();
323        if (__count > 0)
324        {
325            vector<value_type> __scratch(__count);
326
327            __compute_bm_prefix(__f, __l, __pred, __scratch);
328            for ( size_t __i = 0; __i <= __count; __i++ )
329                __suffix[__i] = __count - __scratch[__count-1];
330
331            typedef reverse_iterator<_RandomAccessIterator1> _RevIter;
332            __compute_bm_prefix(_RevIter(__l), _RevIter(__f), __pred, __scratch);
333
334            for ( size_t __i = 0; __i < __count; __i++ )
335            {
336                const size_t     __j = __count - __scratch[__i];
337                const difference_type __k = __i     - __scratch[__i] + 1;
338
339                if (__suffix[__j] > __k)
340                    __suffix[__j] = __k;
341            }
342        }
343    }
344
345};
346
347template<class _RandomAccessIterator,
348         class _Hash = hash<typename iterator_traits<_RandomAccessIterator>::value_type>,
349         class _BinaryPredicate = equal_to<>>
350_LIBCPP_INLINE_VISIBILITY
351boyer_moore_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>
352make_boyer_moore_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
353                    _Hash __hf = _Hash(), _BinaryPredicate __p = _BinaryPredicate ())
354{
355    return boyer_moore_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>(__f, __l, __hf, __p);
356}
357
358// boyer-moore-horspool
359template <class _RandomAccessIterator1,
360          class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
361          class _BinaryPredicate = equal_to<>>
362class _LIBCPP_TEMPLATE_VIS boyer_moore_horspool_searcher {
363private:
364    typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type difference_type;
365    typedef typename std::iterator_traits<_RandomAccessIterator1>::value_type      value_type;
366    typedef _BMSkipTable<value_type, difference_type, _Hash, _BinaryPredicate,
367                    is_integral<value_type>::value && // what about enums?
368                    sizeof(value_type) == 1 &&
369                    is_same<_Hash, hash<value_type>>::value &&
370                    is_same<_BinaryPredicate, equal_to<>>::value
371            > skip_table_type;
372
373public:
374    boyer_moore_horspool_searcher(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
375                _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate())
376            : __first_(__f), __last_(__l), __pred_(__pred),
377              __pattern_length_(_VSTD::distance(__first_, __last_)),
378              __skip_{_VSTD::make_shared<skip_table_type>(__pattern_length_, __pattern_length_, __hf, __pred_)}
379        {
380    //  build the skip table
381            if ( __f != __l )
382            {
383                __l = __l - 1;
384                for ( difference_type __i = 0; __f != __l; ++__f, (void) ++__i )
385                    __skip_->insert(*__f, __pattern_length_ - 1 - __i);
386            }
387        }
388
389    template <typename _RandomAccessIterator2>
390    pair<_RandomAccessIterator2, _RandomAccessIterator2>
391    operator ()(_RandomAccessIterator2 __f, _RandomAccessIterator2 __l) const
392    {
393        static_assert ( std::is_same<
394                typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator1>::value_type>::type,
395                typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator2>::value_type>::type
396                    >::value,
397                "Corpus and Pattern iterators must point to the same type" );
398
399        if (__f      == __l )    return make_pair(__l, __l); // empty corpus
400        if (__first_ == __last_) return make_pair(__f, __f); // empty pattern
401
402    //  If the pattern is larger than the corpus, we can't find it!
403        if ( __pattern_length_ > _VSTD::distance(__f, __l))
404            return make_pair(__l, __l);
405
406    //  Do the search
407        return this->__search(__f, __l);
408    }
409
410private:
411    _RandomAccessIterator1      __first_;
412    _RandomAccessIterator1      __last_;
413    _BinaryPredicate            __pred_;
414    difference_type             __pattern_length_;
415    shared_ptr<skip_table_type> __skip_;
416
417    template <typename _RandomAccessIterator2>
418    pair<_RandomAccessIterator2, _RandomAccessIterator2>
419    __search ( _RandomAccessIterator2 __f, _RandomAccessIterator2 __l ) const {
420        _RandomAccessIterator2 __cur = __f;
421        const _RandomAccessIterator2 __last = __l - __pattern_length_;
422        const skip_table_type & __skip = *__skip_.get();
423
424        while (__cur <= __last)
425        {
426        //  Do we match right where we are?
427            difference_type __j = __pattern_length_;
428            while (__pred_(__first_[__j-1], __cur[__j-1]))
429            {
430                __j--;
431            //  We matched - we're done!
432                if ( __j == 0 )
433                    return make_pair(__cur, __cur + __pattern_length_);
434            }
435            __cur += __skip[__cur[__pattern_length_-1]];
436        }
437
438        return make_pair(__l, __l);
439    }
440};
441
442template<class _RandomAccessIterator,
443         class _Hash = hash<typename iterator_traits<_RandomAccessIterator>::value_type>,
444         class _BinaryPredicate = equal_to<>>
445_LIBCPP_INLINE_VISIBILITY
446boyer_moore_horspool_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>
447make_boyer_moore_horspool_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
448                    _Hash __hf = _Hash(), _BinaryPredicate __p = _BinaryPredicate ())
449{
450    return boyer_moore_horspool_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>(__f, __l, __hf, __p);
451}
452
453#endif // _LIBCPP_STD_VER > 11
454
455_LIBCPP_END_NAMESPACE_LFTS
456
457_LIBCPP_POP_MACROS
458
459#endif /* _LIBCPP_EXPERIMENTAL_FUNCTIONAL */
460