core.hpp 175 KB
Newer Older
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1
2
3
4
5
6
7
8
9
// Copyright (c) 2020 INRA Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef ORG_VLEPROJECT_IRRITATOR_2020
#define ORG_VLEPROJECT_IRRITATOR_2020

#include <algorithm>
#include <limits>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
10
11
12

#ifdef __has_include
#if __has_include(<numbers>)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
13
#include <numbers>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
14
15
16
17
18
19
#define irt_have_numbers 1
#else
#define irt_have_numbers 0
#endif
#endif

Gauthier Quesnel's avatar
Gauthier Quesnel committed
20
#include <string_view>
21
#include <type_traits>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
22
23
24
25

#include <cmath>
#include <cstdint>
#include <cstring>
K-H-Ismail's avatar
K-H-Ismail committed
26

27
28
29
30
31
32
/*****************************************************************************
 *
 * Helper macros
 *
 ****************************************************************************/

33
34
35
36
37
#ifndef irt_assert
#include <cassert>
#define irt_assert(_expr) assert(_expr)
#endif

38
39
40
41
42
43
namespace irt {

static inline bool is_fatal_breakpoint = true;

}

44
45
46
47
48
#ifndef NDEBUG
#if (defined(__i386__) || defined(__x86_64__)) && defined(__GNUC__) &&         \
  __GNUC__ >= 2
#define irt_breakpoint()                                                       \
    do {                                                                       \
49
50
        if (::irt::is_fatal_breakpoint)                                        \
            __asm__ __volatile__("int $03");                                   \
51
52
53
54
    } while (0)
#elif (defined(_MSC_VER) || defined(__DMC__)) && defined(_M_IX86)
#define irt_breakpoint()                                                       \
    do {                                                                       \
55
56
        if (::irt::is_fatal_breakpoint)                                        \
            __asm int 3h                                                       \
57
58
59
60
    } while (0)
#elif defined(_MSC_VER)
#define irt_breakpoint()                                                       \
    do {                                                                       \
61
62
        if (::irt::is_fatal_breakpoint)                                        \
            __debugbreak();                                                    \
63
64
65
66
67
    } while (0)
#elif defined(__alpha__) && !defined(__osf__) && defined(__GNUC__) &&          \
  __GNUC__ >= 2
#define irt_breakpoint()                                                       \
    do {                                                                       \
68
69
        if (::irt::is_fatal_breakpoint)                                        \
            __asm__ __volatile__("bpt");                                       \
70
71
72
73
    } while (0)
#elif defined(__APPLE__)
#define irt_breakpoint()                                                       \
    do {                                                                       \
74
75
        if (::irt::is_fatal_breakpoint)                                        \
            __builtin_trap();                                                  \
76
77
78
79
    } while (0)
#else /* !__i386__ && !__alpha__ */
#define irt_breakpoint()                                                       \
    do {                                                                       \
80
81
        if (::irt::is_fatal_breakpoint)                                        \
            raise(SIGTRAP);                                                    \
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    } while (0)
#endif /* __i386__ */
#else
#define irt_breakpoint()                                                       \
    do {                                                                       \
    } while (0)
#endif

#define irt_bad_return(status__)                                               \
    do {                                                                       \
        irt_breakpoint();                                                      \
        return status__;                                                       \
    } while (0)

#define irt_return_if_bad(expr__)                                              \
    do {                                                                       \
        auto status__ = (expr__);                                              \
        if (status__ != status::success) {                                     \
            irt_breakpoint();                                                  \
            return status__;                                                   \
        }                                                                      \
    } while (0)

#define irt_return_if_fail(expr__, status__)                                   \
    do {                                                                       \
        if (!(expr__)) {                                                       \
            irt_breakpoint();                                                  \
            return status__;                                                   \
        }                                                                      \
    } while (0)

113
114
115
116
117
118
119
120
#if defined(__GNUC__)
#define irt_unreachable() __builtin_unreachable();
#elif defined(_MSC_VER)
#define irt_unreachable() __assume(0)
#else
#define irt_unreachable()
#endif

Gauthier Quesnel's avatar
Gauthier Quesnel committed
121
122
123
124
125
126
127
128
129
130
131
132
namespace irt {

using i8 = int8_t;
using i16 = int16_t;
using i32 = int32_t;
using i64 = int64_t;
using u8 = uint8_t;
using u16 = uint16_t;
using u32 = uint32_t;
using u64 = uint64_t;
using sz = size_t;

133
134
135
136
137
138
139
140
template<typename Integer>
constexpr typename std::make_unsigned<Integer>::type
to_unsigned(Integer value)
{
    irt_assert(value >= 0);
    return static_cast<typename std::make_unsigned<Integer>::type>(value);
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
141
142
143
144
145
146
147
148
149
/*****************************************************************************
 *
 * Return status of many function
 *
 ****************************************************************************/

enum class status
{
    success,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
150
    unknown_dynamics,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
151
152
153
154
155
156
157
158
159
160
    block_allocator_bad_capacity,
    block_allocator_not_enough_memory,
    head_allocator_bad_capacity,
    head_allocator_not_enough_memory,
    simulation_not_enough_model,
    simulation_not_enough_memory_message_list_allocator,
    simulation_not_enough_memory_input_port_list_allocator,
    simulation_not_enough_memory_output_port_list_allocator,
    data_array_init_capacity_error,
    data_array_not_enough_memory,
161
162
    data_array_archive_init_capacity_error,
    data_array_archive_not_enough_memory,
163
164
165
    array_init_capacity_zero,
    array_init_capacity_too_big,
    array_init_not_enough_memory,
166
167
168
    vector_init_capacity_zero,
    vector_init_capacity_too_big,
    vector_init_not_enough_memory,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
169
170
171
    dynamics_unknown_id,
    dynamics_unknown_port_id,
    dynamics_not_enough_memory,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
172
173
174
    model_connect_output_port_unknown,
    model_connect_input_port_unknown,
    model_connect_already_exist,
175
    model_connect_bad_dynamics,
176
177
178
179

    model_buffer_null_ta_source,
    model_buffer_empty_ta_source,

Gauthier Quesnel's avatar
Gauthier Quesnel committed
180
181
    model_integrator_dq_error,
    model_integrator_X_error,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
182
183
184
185
    model_integrator_internal_error,
    model_integrator_output_error,
    model_integrator_running_without_x_dot,
    model_integrator_ta_with_bad_x_dot,
186
187
188
189
190
191

    model_generator_null_ta_source,
    model_generator_empty_ta_source,
    model_generator_null_value_source,
    model_generator_empty_value_source,

Gauthier Quesnel's avatar
Gauthier Quesnel committed
192
193
194
195
    model_quantifier_bad_quantum_parameter,
    model_quantifier_bad_archive_length_parameter,
    model_quantifier_shifting_value_neg,
    model_quantifier_shifting_value_less_1,
K-H-Ismail's avatar
K-H-Ismail committed
196
    model_time_func_bad_init_message,
197
198
    model_flow_bad_samplerate,
    model_flow_bad_data,
199
    gui_not_enough_memory,
200
    io_not_enough_memory,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
201
202
203
204
205
206
207
    io_file_format_error,
    io_file_format_model_error,
    io_file_format_model_number_error,
    io_file_format_model_unknown,
    io_file_format_dynamics_unknown,
    io_file_format_dynamics_limit_reach,
    io_file_format_dynamics_init_error
Gauthier Quesnel's avatar
Gauthier Quesnel committed
208
209
};

210
211
212
213
214
215
216
constexpr i8
status_last() noexcept
{
    return static_cast<i8>(status::io_file_format_dynamics_init_error);
}

constexpr sz
217
218
status_size() noexcept
{
219
    return static_cast<sz>(status_last() + static_cast<i8>(1));
220
221
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
constexpr bool
is_success(status s) noexcept
{
    return s == status::success;
}

constexpr bool
is_bad(status s) noexcept
{
    return s != status::success;
}

template<typename... Args>
constexpr bool
is_status_equal(status s, Args... args) noexcept
{
    return ((s == args) || ... || false);
}

241
242
243
244
245
246
247
248
249
inline status
check_return(status s) noexcept
{
    if (s != status::success)
        irt_breakpoint();

    return s;
}

250
251
template<typename T, typename... Args>
constexpr bool
252
match(const T& s, Args... args) noexcept
253
254
255
256
{
    return ((s == args) || ... || false);
}

257
258
259
template<class T, class... Rest>
constexpr bool
are_all_same() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
260
{
261
    return (std::is_same_v<T, Rest> && ...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
262
263
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
264
265
266
267
268
269
270
271
272
template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
almost_equal(T x, T y, int ulp)
{
    return std::fabs(x - y) <=
             std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp ||
           std::fabs(x - y) < std::numeric_limits<T>::min();
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
273
274
275
276
277
278
279
280
281
282
283
284
285
/*****************************************************************************
 *
 * Definition of a lightweight std::function
 *
 ****************************************************************************/

template<class F>
class function_ref;

template<class R, class... Args>
class function_ref<R(Args...)>
{
public:
286
    constexpr function_ref() noexcept = default;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

    /// Creates a `function_ref` which refers to the same callable as `rhs`.
    constexpr function_ref(const function_ref<R(Args...)>& rhs) noexcept =
      default;

    /// Constructs a `function_ref` referring to `f`.
    ///
    /// \synopsis template <typename F> constexpr function_ref(F &&f) noexcept
    template<
      typename F,
      std::enable_if_t<!std::is_same<std::decay_t<F>, function_ref>::value &&
                       std::is_invocable_r<R, F&&, Args...>::value>* = nullptr>
    constexpr function_ref(F&& f) noexcept
      : obj(const_cast<void*>(reinterpret_cast<const void*>(std::addressof(f))))
    {
        cb = [](void* obj, Args... args) -> R {
            return std::invoke(
              *reinterpret_cast<typename std::add_pointer<F>::type>(obj),
              std::forward<Args>(args)...);
        };
    }

    /// Makes `*this` refer to the same callable as `rhs`.
    constexpr function_ref<R(Args...)>& operator=(
      const function_ref<R(Args...)>& rhs) noexcept = default;

    /// Makes `*this` refer to `f`.
    ///
    /// \synopsis template <typename F> constexpr function_ref &operator=(F &&f)
    /// noexcept;
    template<
      typename F,
      std::enable_if_t<std::is_invocable_r<R, F&&, Args...>::value>* = nullptr>
    constexpr function_ref<R(Args...)>& operator=(F&& f) noexcept
    {
        obj = reinterpret_cast<void*>(std::addressof(f));
        cb = [](void* obj, Args... args) {
            return std::invoke(
              *reinterpret_cast<typename std::add_pointer<F>::type>(obj),
              std::forward<Args>(args)...);
        };

        return *this;
    }

    constexpr void swap(function_ref<R(Args...)>& rhs) noexcept
    {
        std::swap(obj, rhs.obj);
        std::swap(cb, rhs.cb);
    }

    R operator()(Args... args) const
    {
        return cb(obj, std::forward<Args>(args)...);
    }

343
344
345
346
347
    constexpr bool empty() const noexcept
    {
        return obj == nullptr;
    }

348
349
350
351
352
353
    constexpr void reset() noexcept
    {
        obj = nullptr;
        cb = nullptr;
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
private:
    void* obj = nullptr;
    R (*cb)(void*, Args...) = nullptr;
};

/// Swaps the referred callables of `lhs` and `rhs`.
template<typename R, typename... Args>
constexpr void
swap(function_ref<R(Args...)>& lhs, function_ref<R(Args...)>& rhs) noexcept
{
    lhs.swap(rhs);
}

template<typename R, typename... Args>
function_ref(R (*)(Args...)) -> function_ref<R(Args...)>;

template<typename R, typename... Args>
function_ref(R (*)(Args...) noexcept) -> function_ref<R(Args...) noexcept>;

373
374
375
376
377
378
379
/*****************************************************************************
 *
 * Allocator
 *
 ****************************************************************************/

using global_alloc_function_type = function_ref<void*(sz size)>;
380
using global_free_function_type = function_ref<void(void* ptr)>;
381

382
383
static inline void*
malloc_wrapper(sz size)
384
385
386
387
{
    return std::malloc(size);
}

388
389
static inline void
free_wrapper(void* ptr)
390
391
392
393
394
{
    if (ptr)
        std::free(ptr);
}

395
396
static inline global_alloc_function_type g_alloc_fn{ malloc_wrapper };
static inline global_free_function_type g_free_fn{ free_wrapper };
397

Gauthier Quesnel's avatar
Gauthier Quesnel committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*****************************************************************************
 *
 * Definition of Time
 *
 * TODO:
 * - enable template definition of float or [float|double,bool absolute]
 *   representation of time?
 *
 ****************************************************************************/

using time = double;

template<typename T>
struct time_domain
{};

template<>
struct time_domain<time>
{
    using time_type = time;

    static constexpr const double infinity =
      std::numeric_limits<double>::infinity();
    static constexpr const double negative_infinity =
      -std::numeric_limits<double>::infinity();
    static constexpr const double zero = 0;

425
    static constexpr bool is_infinity(time t) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
426
427
428
429
    {
        return t == infinity || t == negative_infinity;
    }

430
    static constexpr bool is_zero(time t) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    {
        return t == zero;
    }
};

/*****************************************************************************
 *
 * Small string
 *
 ****************************************************************************/

template<size_t length = 8>
class small_string
{
    char buffer_[length];
    u8 size_;

public:
Gauthier Quesnel's avatar
Gauthier Quesnel committed
449
450
    using iterator = char*;
    using const_iterator = const char*;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
    using size_type = u8;

    static_assert(length > size_t{ 1 } && length < size_t{ 254 });

    constexpr small_string() noexcept
    {
        clear();
    }

    constexpr small_string(const small_string& str) noexcept
    {
        std::copy_n(str.buffer_, str.size_, buffer_);
        buffer_[str.size_] = '\0';
        size_ = str.size_;
    }

    constexpr small_string(small_string&& str) noexcept
    {
        std::copy_n(str.buffer_, str.size_, buffer_);
        buffer_[str.size_] = '\0';
        size_ = str.size_;
        str.clear();
    }

    constexpr small_string& operator=(const small_string& str) noexcept
    {
        if (&str != this) {
            std::copy_n(str.buffer_, str.size_, buffer_);
            buffer_[str.size_] = '\0';
            size_ = str.size_;
        }

        return *this;
    }

    constexpr small_string& operator=(small_string&& str) noexcept
    {
        if (&str != this) {
            std::copy_n(str.buffer_, str.size_, buffer_);
            buffer_[str.size_] = '\0';
            size_ = str.size_;
        }

        return *this;
    }

    constexpr small_string(const char* str) noexcept
    {
        std::strncpy(buffer_, str, length - 1);
        buffer_[length - 1] = '\0';
        size_ = static_cast<u8>(std::strlen(buffer_));
    }

    constexpr small_string(const std::string_view str) noexcept
    {
        assign(str);
    }

    constexpr bool empty() const noexcept
    {
        constexpr unsigned char zero{ 0 };

        return zero == size_;
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
516
517
    constexpr void size(std::size_t sz) noexcept
    {
518
519
        size_ = static_cast<u8>(std::min(sz, length - 1));
        buffer_[size_] = '\0';
Gauthier Quesnel's avatar
Gauthier Quesnel committed
520
521
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
522
523
524
525
526
527
528
    constexpr std::size_t size() const noexcept
    {
        return size_;
    }

    constexpr std::size_t capacity() const noexcept
    {
529
        return length;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
530
531
532
533
    }

    constexpr void assign(const std::string_view str) noexcept
    {
534
        const size_t copy_length = std::min(str.size(), length - 1);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
535
536

        std::memcpy(buffer_, str.data(), copy_length);
537
538
        buffer_[copy_length] = '\0';

539
        size_ = static_cast<u8>(copy_length);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
    }

    constexpr std::string_view sv() const noexcept
    {
        return { buffer_, size_ };
    }

    constexpr void clear() noexcept
    {
        std::fill_n(buffer_, length, '\0');
        size_ = 0;
    }

    constexpr const char* c_str() const noexcept
    {
        return buffer_;
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    constexpr iterator begin() noexcept
    {
        return buffer_;
    }

    constexpr iterator end() noexcept
    {
        return buffer_ + size_;
    }

    constexpr const_iterator begin() const noexcept
    {
        return buffer_;
    }

    constexpr const_iterator end() const noexcept
    {
        return buffer_ + size_;
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
    constexpr bool operator==(const small_string& rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs.buffer_, length) == 0;
    }

    constexpr bool operator!=(const small_string& rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs.buffer_, length) != 0;
    }

    constexpr bool operator>(const small_string& rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs.buffer_, length) > 0;
    }

    constexpr bool operator<(const small_string& rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs.buffer_, length) < 0;
    }

    constexpr bool operator==(const char* rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs, length) == 0;
    }

    constexpr bool operator!=(const char* rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs, length) != 0;
    }

    constexpr bool operator>(const char* rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs, length) > 0;
    }

    constexpr bool operator<(const char* rhs) const noexcept
    {
        return std::strncmp(buffer_, rhs, length) < 0;
    }
};

/*****************************************************************************
 *
621
 * value
Gauthier Quesnel's avatar
Gauthier Quesnel committed
622
623
624
 *
 ****************************************************************************/

625
struct message
Gauthier Quesnel's avatar
Gauthier Quesnel committed
626
{
627
628
    using size_type = std::size_t;
    using difference_type = std::ptrdiff_t;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
629

630
    double real[4];
Gauthier Quesnel's avatar
Gauthier Quesnel committed
631

632
633
634
635
636
637
    constexpr size_type size() const noexcept
    {
        return real[3] ? 4u : real[2] ? 3u : real[1] ? 2u : real[0] ? 1u : 0u;
    }

    constexpr difference_type ssize() const noexcept
638
    {
639
        return real[3] ? 4 : real[2] ? 3 : real[1] ? 2 : real[0] ? 1 : 0;
640
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
641

642
    constexpr message() noexcept
643
      : real{ 0., 0., 0., 0. }
644
    {}
Gauthier Quesnel's avatar
Gauthier Quesnel committed
645

646
    constexpr message(const double v) noexcept
647
      : real{ v, 0., 0., 0. }
648
649
650
    {}

    constexpr message(const double v1, const double v2) noexcept
651
      : real{ v1, v2, 0., 0. }
652
653
654
655
656
    {}

    constexpr message(const double v1,
                      const double v2,
                      const double v3) noexcept
657
658
659
660
661
662
663
664
      : real{ v1, v2, v3, 0. }
    {}

    constexpr message(const double v1,
                      const double v2,
                      const double v3,
                      const double v4) noexcept
      : real{ v1, v2, v3, v4 }
665
    {}
Gauthier Quesnel's avatar
Gauthier Quesnel committed
666

667
    constexpr double operator[](const difference_type i) const noexcept
668
    {
669
        return real[i];
Gauthier Quesnel's avatar
Gauthier Quesnel committed
670
    }
671

672
    constexpr double& operator[](const difference_type i) noexcept
673
    {
674
        return real[i];
675
    }
676
677
678
679
680
681
682
683

    constexpr void reset() noexcept
    {
        real[0] = 0.;
        real[1] = 0.;
        real[2] = 0.;
        real[3] = 0.;
    }
684
};
Gauthier Quesnel's avatar
Gauthier Quesnel committed
685

686
687
688
689
690
691
692
693
694
695
696
697
698
/*****************************************************************************
 *
 * Flat list
 *
 ****************************************************************************/

template<typename T>
class block_allocator
{
public:
    using value_type = T;

    union block
Gauthier Quesnel's avatar
Gauthier Quesnel committed
699
    {
700
701
702
        block* next;
        typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
    };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
703

704
private:
Gauthier Quesnel's avatar
Gauthier Quesnel committed
705
    block* blocks{ nullptr };    // contains all preallocated blocks
706
707
708
709
    block* free_head{ nullptr }; // a free list
    sz size{ 0 };                // number of active elements allocated
    sz max_size{ 0 }; // number of elements allocated (with free_head)
    sz capacity{ 0 }; // capacity of the allocator
Gauthier Quesnel's avatar
Gauthier Quesnel committed
710

711
712
public:
    block_allocator() = default;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
713

714
715
    block_allocator(const block_allocator&) = delete;
    block_allocator& operator=(const block_allocator&) = delete;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
716

717
718
719
    ~block_allocator() noexcept
    {
        if (blocks)
720
            g_free_fn(blocks);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
721
722
    }

723
    status init(std::size_t new_capacity) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
724
    {
725
726
        if (new_capacity == 0)
            return status::block_allocator_bad_capacity;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
727

728
729
        if (new_capacity != capacity) {
            if (blocks)
730
731
                g_free_fn(blocks);

732
            blocks =
733
              static_cast<block*>(g_alloc_fn(new_capacity * sizeof(block)));
734
735
736
            if (blocks == nullptr)
                return status::block_allocator_not_enough_memory;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
737

738
739
740
741
        size = 0;
        max_size = 0;
        capacity = new_capacity;
        free_head = nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
742

743
        return status::success;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
744
745
    }

746
    void reset() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
747
    {
748
749
750
751
752
        if (capacity > 0) {
            size = 0;
            max_size = 0;
            free_head = nullptr;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
753
754
    }

755
    T* alloc() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
756
    {
757
758
759
760
761
762
        block* new_block = nullptr;

        if (free_head != nullptr) {
            new_block = free_head;
            free_head = free_head->next;
        } else {
763
            irt_assert(max_size < capacity);
764
            new_block = reinterpret_cast<block*>(&blocks[max_size++]);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
765
        }
766
        ++size;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
767

768
        return reinterpret_cast<T*>(new_block);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
769
770
    }

771
772
773
774
775
    bool can_alloc() noexcept
    {
        return free_head != nullptr || max_size < capacity;
    }

776
    void free(T* n) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
777
    {
778
        irt_assert(n);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
779

780
        block* ptr = reinterpret_cast<block*>(n);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
781

782
783
        ptr->next = free_head;
        free_head = ptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
784

785
        --size;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
786

787
788
789
790
        if (size == 0) {         // A special part: if it no longer exists
            max_size = 0;        // we reset the free list and the number
            free_head = nullptr; // of elements allocated.
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
791
    }
792
793
794
795
796

    bool can_alloc(size_t number) const noexcept
    {
        return number + size < capacity;
    }
797
};
Gauthier Quesnel's avatar
Gauthier Quesnel committed
798

799
800
801
802
803
template<typename T>
class flat_list
{
public:
    struct node_type
Gauthier Quesnel's avatar
Gauthier Quesnel committed
804
    {
805
806
807
        T value;
        node_type* next = nullptr;
    };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
808

809
810
811
812
public:
    using allocator_type = block_allocator<node_type>;
    using value_type = T;
    using reference = T&;
813
    using const_reference = const T&;
814
    using pointer = T*;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
815

816
    class iterator
Gauthier Quesnel's avatar
Gauthier Quesnel committed
817
    {
818
819
    private:
        node_type* node{ nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
820

821
822
823
824
825
826
    public:
        using iterator_category = std::forward_iterator_tag;
        using value_type = T;
        using pointer = T*;
        using reference = T&;
        using difference_type = std::ptrdiff_t;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
827

828
        iterator() noexcept = default;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
829

830
831
832
        iterator(node_type* n) noexcept
          : node(n)
        {}
Gauthier Quesnel's avatar
Gauthier Quesnel committed
833

834
835
836
        iterator(const iterator& other) noexcept
          : node(other.node)
        {}
Gauthier Quesnel's avatar
Gauthier Quesnel committed
837

838
839
840
841
842
        iterator& operator=(const iterator& other) noexcept
        {
            node = other.node;
            return *this;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
843

844
845
846
847
        T& operator*() noexcept
        {
            return node->value;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
848

849
850
851
852
        T* operator->() noexcept
        {
            return &node->value;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
853

854
855
856
857
        iterator operator++() noexcept
        {
            if (node != nullptr)
                node = node->next;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
858

859
860
            return *this;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
861

862
863
864
        iterator operator++(int) noexcept
        {
            iterator tmp(*this);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
865

866
867
            if (node != nullptr)
                node = node->next;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
868

869
870
            return tmp;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
871

872
873
874
875
        bool operator==(const iterator& other) const noexcept
        {
            return node == other.node;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
876

877
878
879
880
        bool operator!=(const iterator& other) const noexcept
        {
            return node != other.node;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
881

882
883
884
885
        void swap(iterator& other) noexcept
        {
            std::swap(node, other.node);
        }
886

Gauthier Quesnel's avatar
Gauthier Quesnel committed
887
        friend class flat_list<T>;
888
    };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
889

890
    class const_iterator
Gauthier Quesnel's avatar
Gauthier Quesnel committed
891
    {
892
893
    private:
        const node_type* node{ nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
894

895
896
897
898
899
900
    public:
        using iterator_category = std::forward_iterator_tag;
        using value_type = T;
        using pointer = T*;
        using reference = T&;
        using difference_type = std::ptrdiff_t;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
901

902
        const_iterator() noexcept = default;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
903

904
905
906
        const_iterator(node_type* n) noexcept
          : node(n)
        {}
Gauthier Quesnel's avatar
Gauthier Quesnel committed
907

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
        const_iterator(const const_iterator& other) noexcept
          : node(other.node)
        {}

        const_iterator& operator=(const const_iterator& other) noexcept
        {
            node = other.node;
            return *this;
        }

        const T& operator*() noexcept
        {
            return node->value;
        }

        const T* operator->() noexcept
        {
            return &node->value;
        }

        const_iterator operator++() noexcept
        {
            if (node != nullptr)
                node = node->next;

            return *this;
        }

        const_iterator operator++(int) noexcept
        {
            const_iterator tmp(*this);

            if (node != nullptr)
                node = node->next;

            return tmp;
        }

        bool operator==(const const_iterator& other) const noexcept
        {
            return node == other.node;
        }

        bool operator!=(const const_iterator& other) const noexcept
        {
            return node != other.node;
        }

        void swap(const_iterator& other) noexcept
        {
            std::swap(node, other.node);
        }
960

Gauthier Quesnel's avatar
Gauthier Quesnel committed
961
        friend class flat_list<T>;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
962
963
    };

964
965
966
private:
    allocator_type* allocator{ nullptr };
    node_type* node{ nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
967

968
969
public:
    flat_list() = default;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
970

971
972
    flat_list(allocator_type* allocator_new) noexcept
      : allocator(allocator_new)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
973
974
    {}

975
976
977
978
979
980
    flat_list(const flat_list& other) = delete;
    flat_list& operator=(const flat_list& other) = delete;

    flat_list(flat_list&& other) noexcept
      : allocator(other.allocator)
      , node(other.node)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
981
    {
982
983
        other.allocator = nullptr;
        other.node = nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
984
985
    }

986
    void set_allocator(allocator_type* allocator_new) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
987
    {
988
989
990
        clear();
        allocator = allocator_new;
        node = nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
991
992
    }

993
    flat_list& operator=(flat_list&& other) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
994
    {
995
996
997
998
999
1000
1001
1002
1003
        if (this != &other) {
            clear();
            allocator = other.allocator;
            other.allocator = nullptr;
            node = other.node;
            other.node = nullptr;
        }

        return *this;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1004
1005
    }

1006
    ~flat_list() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1007
    {
1008
        clear();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1009
1010
    }

1011
    void clear() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1012
    {
1013
1014
1015
1016
1017
1018
1019
        node_type* prev = node;

        while (node != nullptr) {
            node = node->next;
            allocator->free(prev);
            prev = node;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1020
1021
    }

1022
    bool empty() const noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1023
    {
1024
        return node == nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1025
1026
    }

1027
    iterator begin() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1028
    {
1029
1030
        return iterator(node);
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1031

1032
1033
1034
1035
    iterator end() noexcept
    {
        return iterator(nullptr);
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1036

1037
1038
1039
1040
    const_iterator begin() const noexcept
    {
        return const_iterator(node);
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1041

1042
1043
1044
    const_iterator end() const noexcept
    {
        return const_iterator(nullptr);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1045
1046
    }

1047
1048
    reference front() noexcept
    {
1049
        irt_assert(!empty());
1050
1051
1052
1053
1054
1055

        return node->value;
    }

    const_reference front() const noexcept
    {
1056
        irt_assert(!empty());
1057
1058
1059
1060

        return node->value;
    }

1061
1062
    template<typename... Args>
    iterator emplace_front(Args&&... args) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1063
    {
1064
        node_type* new_node = allocator->alloc();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1065

1066
        new (&new_node->value) T(std::forward<Args>(args)...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1067

1068
1069
        new_node->next = node;
        node = new_node;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1070

1071
        return begin();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1072
1073
    }

1074
1075
    template<typename... Args>
    iterator emplace_after(iterator it, Args&&... args) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1076
    {
1077
1078
        node_type* new_node = allocator->alloc();
        new (&new_node->value) T(std::forward<Args>(args)...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1079

1080
1081
        if (it->node == nullptr)
            return emplace_front(std::forward<Args>(args)...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1082

1083
1084
        new_node->next = it->node->next;
        it->node->next = new_node;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1085

1086
        return iterator(new_node);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1087
1088
    }

1089
1090
    template<typename... Args>
    iterator try_emplace_front(Args&&... args) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1091
    {
1092
        auto [success, new_node] = allocator->try_alloc();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1093

1094
1095
        if (!success)
            return end();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1096

1097
        new (&new_node->value) T(std::forward<Args>(args)...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1098

1099
1100
1101
1102
        new_node->next = node;
        node = new_node;

        return begin();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1103
1104
    }

1105
1106
    template<typename... Args>
    iterator try_emplace_after(iterator it, Args&&... args) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1107
    {
1108
        auto [success, new_node] = allocator->try_alloc();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1109

1110
1111
        if (!success)
            return end();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1112

1113
        new (&new_node->value) T(std::forward<Args>(args)...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1114

1115
1116
        if (it->node == nullptr)
            return emplace_front(std::forward<Args>(args)...);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1117

1118
1119
        new_node->next = it->node->next;
        it->node->next = new_node;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1120

1121
        return iterator(new_node);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1122
1123
    }

1124
    void pop_front() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1125
    {
1126
1127
        if (node == nullptr)
            return;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1128

1129
1130
        node_type* to_delete = node;
        node = node->next;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1131

1132
        if constexpr (!std::is_trivial_v<T>)
1133
            to_delete->value.~T();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1134

1135
        allocator->free(to_delete);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1136
1137
    }

1138
    iterator erase_after(iterator it) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1139
    {
1140
        irt_assert(allocator);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1141

1142
1143
        if (it.node == nullptr)
            return end();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1144

1145
1146
1147
        node_type* to_delete = it.node->next;
        if (to_delete == nullptr)
            return end();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1148

1149
1150
        node_type* next = to_delete->next;
        it.node->next = next;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1151

1152
        if constexpr (!std::is_trivial_v<T>)
1153
            to_delete->value.~T();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1154

1155
        allocator->free(to_delete);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1156

1157
        return iterator(next);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1158
1159
1160
1161
    }
};

template<typename T>
1162
class flat_double_list
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1163
{
1164
private:
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1165
1166
1167
1168
    struct node_type
    {
        T value;
        node_type* next = nullptr;
1169
        node_type* prev = nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
    };

public:
    using allocator_type = block_allocator<node_type>;
    using value_type = T;
    using reference = T&;
    using pointer = T*;

    class iterator
    {
    private:
1181
        flat_double_list* list{ nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1182
1183
1184
        node_type* node{ nullptr };

    public:
1185
        using iterator_category = std::bidirectional_iterator_tag;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1186
1187
1188
1189
1190
1191
        using value_type = T;
        using pointer = T*;
        using reference = T&;

        iterator() noexcept = default;

1192
1193
1194
        iterator(flat_double_list* lst, node_type* n) noexcept
          : list(lst)
          , node(n)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1195
1196
1197
        {}

        iterator(const iterator& other) noexcept
1198
1199
          : list(other.list)
          , node(other.node)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1200
1201
1202
1203
        {}

        iterator& operator=(const iterator& other) noexcept
        {
1204
            list = other.list;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1205
1206
1207
1208
1209
1210
1211
1212
1213
            node = other.node;
            return *this;
        }

        T& operator*() noexcept
        {
            return node->value;
        }

1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
        T* operator*() const noexcept
        {
            return node->value;
        }

        pointer operator->() noexcept
        {
            return &(node->value);
        }

        pointer operator->() const noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1225
1226
1227
1228
1229
1230
        {
            return &node->value;
        }

        iterator operator++() noexcept
        {
1231
            node = (node == nullptr) ? list->m_front : node->next;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1232
1233
1234
1235
1236
1237
1238
1239

            return *this;
        }

        iterator operator++(int) noexcept
        {
            iterator tmp(*this);

1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
            node = (node == nullptr) ? list->m_front : node->next;

            return tmp;
        }

        iterator operator--() noexcept
        {
            node = (node == nullptr) ? list->m_back : node->prev;

            return *this;
        }

        iterator operator--(int) noexcept
        {
            iterator tmp(*this);

            node = (node == nullptr) ? list->m_back : node->prev;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272

            return tmp;
        }

        bool operator==(const iterator& other) const noexcept
        {
            return node == other.node;
        }

        bool operator!=(const iterator& other) const noexcept
        {
            return node != other.node;
        }

        void swap(iterator& other) noexcept
        {
1273
            std::swap(list, other.list);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1274
1275
1276
1277
1278
1279
1280
            std::swap(node, other.node);
        }
    };

    class const_iterator
    {
    private:
1281
1282
        const flat_double_list* list{ nullptr };
        node_type* node{ nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1283
1284

    public:
1285
        using const_iterator_category = std::bidirectional_iterator_tag;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1286
1287
1288
1289
1290
1291
        using value_type = T;
        using pointer = T*;
        using reference = T&;

        const_iterator() noexcept = default;

1292
1293
1294
        const_iterator(const flat_double_list* lst, node_type* n) noexcept
          : list(lst)
          , node(n)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1295
1296
1297
        {}

        const_iterator(const const_iterator& other) noexcept
1298
1299
          : list(other.list)
          , node(other.node)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1300
1301
1302
1303
        {}

        const_iterator& operator=(const const_iterator& other) noexcept
        {
1304
            list = other.list;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
            node = other.node;
            return *this;
        }

        const T& operator*() noexcept
        {
            return node->value;
        }

        const T* operator->() noexcept
        {
1316
            return &(node->value);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1317
1318
1319
1320
        }

        const_iterator operator++() noexcept
        {
1321
            node = (node == nullptr) ? list->m_front : node->next;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1322
1323
1324
1325
1326
1327
1328
1329

            return *this;
        }

        const_iterator operator++(int) noexcept
        {
            const_iterator tmp(*this);

1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
            node = (node == nullptr) ? list->m_front : node->next;

            return tmp;
        }

        const_iterator operator--() noexcept
        {
            node = (node == nullptr) ? list->m_back : node->prev;

            return *this;
        }

        const_iterator operator--(int) noexcept
        {
            const_iterator tmp(*this);

            node = (node == nullptr) ? list->m_back : node->prev;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362

            return tmp;
        }

        bool operator==(const const_iterator& other) const noexcept
        {
            return node == other.node;
        }

        bool operator!=(const const_iterator& other) const noexcept
        {
            return node != other.node;
        }

        void swap(const_iterator& other) noexcept
        {
1363
            std::swap(list, other.list);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1364
1365
1366
1367