pars 0.2.1.99
Loading...
Searching...
No Matches
fib.h
Go to the documentation of this file.
1/*
2Copyright (c) 2025 Giuseppe Roberti.
3All rights reserved.
4
5Redistribution and use in source and binary forms, with or without modification,
6are permitted provided that the following conditions are met:
7
81. Redistributions of source code must retain the above copyright notice, this
9list of conditions and the following disclaimer.
10
112. Redistributions in binary form must reproduce the above copyright notice,
12this list of conditions and the following disclaimer in the documentation and/or
13other materials provided with the distribution.
14
153. Neither the name of the copyright holder nor the names of its contributors
16may be used to endorse or promote products derived from this software without
17specific prior written permission.
18
19THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
23ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29*/
30#pragma once
31
32#include <pars/concept/event.h>
33
34#include <cstdint>
35#include <optional>
36#include <stdexcept>
37#include <stop_token>
38
40{
41
42struct stop_requested : std::runtime_error
43{
45 : std::runtime_error("Stop requested!")
46 {
47 }
48};
49
50static uint64_t slow_fib(const uint16_t n, std::optional<std::stop_token> tk)
51{
52 switch (n)
53 {
54 case 0:
55 return 0;
56 case 1:
57 return 1;
58 }
59 if (tk && tk->stop_requested())
60 throw stop_requested();
61 return slow_fib(n - 2, tk) + slow_fib(n - 1, tk);
62}
63
64static uint64_t fast_fib(uint16_t n, std::optional<std::stop_token>)
65{
66 uint64_t fib[3] = {0, 1, 1};
67 for (; n > 2; --n)
68 {
69 fib[0] = fib[1];
70 fib[1] = fib[2];
71 fib[2] = fib[1] + fib[0];
72 }
73 return fib[n];
74}
75
76template<typename metadata_t>
77static uint64_t fib(const uint64_t n, const bool use_fast_fib,
78 const metadata_t& md)
79{
80 auto fib_fn = use_fast_fib ? fast_fib : slow_fib;
81
82 if constexpr (pars::ev::async_event_c<typename metadata_t::event_type,
83 metadata_t::template kind_type>)
84 return fib_fn(n, md.stop_token());
85 else
86 return fib_fn(n, {});
87}
88
89} // namespace pars_example::compute