aboutsummaryrefslogtreecommitdiff
path: root/src/linda.cpp
blob: 87aa8fa5cb8c52a98d3d3e18eff18012a9744de9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
/*
 * LINDA.CPP                        Copyright (c) 2018-2024, Benoit Germain
 *
 * Linda deep userdata.
 */

/*
===============================================================================

Copyright (C) 2018-2024 benoit Germain <bnt.germain@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

===============================================================================
*/

#include "linda.h"

#include "lane.h"
#include "lindafactory.h"
#include "tools.h"

#include <functional>

// #################################################################################################

static void check_key_types(lua_State* L_, int start_, int end_)
{
    for (int _i{ start_ }; _i <= end_; ++_i) {
        LuaType const t{ lua_type_as_enum(L_, _i) };
        switch (t) {
        case LuaType::BOOLEAN:
        case LuaType::NUMBER:
        case LuaType::STRING:
            continue;

        case LuaType::LIGHTUSERDATA:
            static constexpr std::array<std::reference_wrapper<UniqueKey const>, 3> kKeysToCheck{ kLindaBatched, kCancelError, kNilSentinel };
            for (UniqueKey const& _key : kKeysToCheck) {
                if (_key.equals(L_, _i)) {
                    raise_luaL_error(L_, "argument #%d: can't use " STRINGVIEW_FMT " as a key", _i, _key.debugName.size(), _key.debugName.data());
                    break;
                }
            }
            break;
        }
        raise_luaL_error(L_, "argument #%d: invalid key type (not a boolean, string, number or light userdata)", _i);
    }
}

// #################################################################################################

/*
 * string = linda:__tostring( linda_ud)
 *
 * Return the stringification of a linda
 *
 * Useful for concatenation or debugging purposes
 */

template <bool OPT>
[[nodiscard]] static int LindaToString(lua_State* L_, int idx_)
{
    Linda* const _linda{ ToLinda<OPT>(L_, idx_) };
    if (_linda != nullptr) {
        std::ignore = lua_pushstringview(L_, "Linda: ");
        std::string_view const _lindaName{ _linda->getName() };
        if (!_lindaName.empty()) {
            std::ignore = lua_pushstringview(L_, _lindaName);
        } else {
            lua_pushfstring(L_, "%p", _linda);
        }
        lua_concat(L_, 2);
        return 1;
    }
    return 0;
}

// #################################################################################################

template <bool OPT>
[[nodiscard]] static inline Linda* ToLinda(lua_State* L_, int idx_)
{
    Linda* const _linda{ static_cast<Linda*>(LindaFactory::Instance.toDeep(L_, idx_)) };
    if constexpr (!OPT) {
        luaL_argcheck(L_, _linda != nullptr, idx_, "expecting a linda object"); // doesn't return if linda is nullptr
        LUA_ASSERT(L_, _linda->U == universe_get(L_));
    }
    return _linda;
}

// #################################################################################################
// #################################### Linda implementation #######################################
// #################################################################################################

// Any hashing will do that maps pointers to [0..Universe::nb_keepers[ consistently.
// Pointers are often aligned by 8 or so - ignore the low order bits
// have to cast to unsigned long to avoid compilation warnings about loss of data when converting pointer-to-integer
static constexpr uintptr_t kPointerMagicShift{ 3 };

Linda::Linda(Universe* U_, LindaGroup group_, std::string_view const& name_)
: DeepPrelude{ LindaFactory::Instance }
, U{ U_ }
, keeperIndex{ (group_ ? group_ : static_cast<int>(std::bit_cast<uintptr_t>(this) >> kPointerMagicShift)) % U_->keepers->nb_keepers }
{
    setName(name_);
}

// #################################################################################################

Linda::~Linda()
{
    freeAllocatedName();
}

// #################################################################################################

void Linda::freeAllocatedName()
{
    if (std::holds_alternative<std::string_view>(nameVariant)) {
        std::string_view& _name = std::get<std::string_view>(nameVariant);
        U->internalAllocator.free(const_cast<char*>(_name.data()), _name.size());
        _name = {};
    }
}

// #################################################################################################

std::string_view Linda::getName() const
{
    if (std::holds_alternative<std::string_view>(nameVariant)) {
        std::string_view const& _name = std::get<std::string_view>(nameVariant);
        return _name;
    }
    if (std::holds_alternative<EmbeddedName>(nameVariant)) {
        char const* const _name{ std::get<EmbeddedName>(nameVariant).data() };
        return std::string_view{ _name, strlen(_name) };
    }
    return std::string_view{};
}

// #################################################################################################

// used to perform all linda operations that access keepers
int Linda::ProtectedCall(lua_State* L_, lua_CFunction f_)
{
    Linda* const _linda{ ToLinda<false>(L_, 1) };

    // acquire the keeper
    Keeper* const _K{ _linda->acquireKeeper() };
    lua_State* const _KL{ _K ? _K->L : nullptr };
    if (_KL == nullptr)
        return 0;
    // if we didn't do anything wrong, the keeper stack should be clean
    LUA_ASSERT(L_, lua_gettop(_KL) == 0);

    // push the function to be called and move it before the arguments
    lua_pushcfunction(L_, f_);
    lua_insert(L_, 1);
    // do a protected call
    LuaError const _rc{ lua_pcall(L_, lua_gettop(L_) - 1, LUA_MULTRET, 0) };
    // whatever happens, the keeper state stack must be empty when we are done
    lua_settop(_KL, 0);

    // release the keeper
    _linda->releaseKeeper(_K);

    // if there was an error, forward it
    if (_rc != LuaError::OK) {
        raise_lua_error(L_);
    }
    // return whatever the actual operation provided
    return lua_gettop(L_);
}

// #################################################################################################

void Linda::setName(std::string_view const& name_)
{
    // keep default
    if (name_.empty()) {
        return;
    }

    // if we currently hold an allocated name, free it
    freeAllocatedName();
    if (name_.size() <= kEmbeddedNameLength) {
        // grab our internal buffer
        EmbeddedName& _name = nameVariant.emplace<EmbeddedName>();
        // copy the string in it
        memcpy(_name.data(), name_.data(), name_.size());
    } else {
        // allocate an external buffer
        char* const _nameBuffer{ static_cast<char*>(U->internalAllocator.alloc(name_.size())) };
        // copy the string in it
        memcpy(_nameBuffer, name_.data(), name_.size());
        nameVariant.emplace<std::string_view>(_nameBuffer, name_.size());
    }
}

// #################################################################################################
// ########################################## Lua API ##############################################
// #################################################################################################

/*
 * (void) = linda_cancel( linda_ud, "read"|"write"|"both"|"none")
 *
 * Signal linda so that waiting threads wake up as if their own lane was cancelled
 */
LUAG_FUNC(linda_cancel)
{
    Linda* const _linda{ ToLinda<false>(L_, 1) };
    char const* _who{ luaL_optstring(L_, 2, "both") };
    // make sure we got 3 arguments: the linda, a key and a limit
    luaL_argcheck(L_, lua_gettop(L_) <= 2, 2, "wrong number of arguments");

    _linda->cancelRequest = CancelRequest::Soft;
    if (strcmp(_who, "both") == 0) { // tell everyone writers to wake up
        _linda->writeHappened.notify_all();
        _linda->readHappened.notify_all();
    } else if (strcmp(_who, "none") == 0) { // reset flag
        _linda->cancelRequest = CancelRequest::None;
    } else if (strcmp(_who, "read") == 0) { // tell blocked readers to wake up
        _linda->writeHappened.notify_all();
    } else if (strcmp(_who, "write") == 0) { // tell blocked writers to wake up
        _linda->readHappened.notify_all();
    } else {
        raise_luaL_error(L_, "unknown wake hint '%s'", _who);
    }
    return 0;
}

// #################################################################################################

/*
 * string = linda:__concat( a, b)
 *
 * Return the concatenation of a pair of items, one of them being a linda
 *
 * Useful for concatenation or debugging purposes
 */
LUAG_FUNC(linda_concat)
{                                                                                                  // L_: linda1? linda2?
    bool _atLeastOneLinda{ false };
    // Lua semantics enforce that one of the 2 arguments is a Linda, but not necessarily both.
    if (LindaToString<true>(L_, 1)) {
        _atLeastOneLinda = true;
        lua_replace(L_, 1);
    }
    if (LindaToString<true>(L_, 2)) {
        _atLeastOneLinda = true;
        lua_replace(L_, 2);
    }
    if (!_atLeastOneLinda) { // should not be possible
        raise_luaL_error(L_, "internal error: linda_concat called on non-Linda");
    }
    lua_concat(L_, 2);
    return 1;
}

// #################################################################################################

/*
 * [val] = linda_count( linda_ud, [key [, ...]])
 *
 * Get a count of the pending elements in the specified keys
 */
LUAG_FUNC(linda_count)
{
    auto _count = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        // make sure the keys are of a valid type
        check_key_types(L_, 2, lua_gettop(L_));

        Keeper* const _K{ _linda->whichKeeper() };
        KeeperCallResult const _pushed{ keeper_call(_K->L, KEEPER_API(count), L_, _linda, 2) };
        return OptionalValue(_pushed, L_, "tried to count an invalid key");
    };
    return Linda::ProtectedCall(L_, _count);
}

// #################################################################################################

/*
 * lightuserdata= linda_deep( linda_ud )
 *
 * Return the 'deep' userdata pointer, identifying the Linda.
 *
 * This is needed for using Lindas as key indices (timer system needs it);
 * separately created proxies of the same underlying deep object will have
 * different userdata and won't be known to be essentially the same deep one
 * without this.
 */
LUAG_FUNC(linda_deep)
{
    Linda* const _linda{ ToLinda<false>(L_, 1) };
    lua_pushlightuserdata(L_, _linda); // just the address
    return 1;
}

// #################################################################################################

/*
 * table = linda:dump()
 * return a table listing all pending data inside the linda
 */
LUAG_FUNC(linda_dump)
{
    auto _dump = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        return keeper_push_linda_storage(*_linda, DestState{ L_ });
    };
    return Linda::ProtectedCall(L_, _dump);
}

// #################################################################################################

/*
 * [val [, ...]] = linda_get( linda_ud, key_num|str|bool|lightuserdata [, count = 1])
 *
 * Get one or more values from Linda.
 */
LUAG_FUNC(linda_get)
{
    auto get = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        lua_Integer const _count{ luaL_optinteger(L_, 3, 1) };
        luaL_argcheck(L_, _count >= 1, 3, "count should be >= 1");
        luaL_argcheck(L_, lua_gettop(L_) <= 3, 4, "too many arguments");
        // make sure the key is of a valid type (throws an error if not the case)
        check_key_types(L_, 2, 2);

        KeeperCallResult _pushed;
        if (_linda->cancelRequest == CancelRequest::None) {
            Keeper* const _K{ _linda->whichKeeper() };
            _pushed = keeper_call(_K->L, KEEPER_API(get), L_, _linda, 2);
        } else { // linda is cancelled
            // do nothing and return lanes.cancel_error
            kCancelError.pushKey(L_);
            _pushed.emplace(1);
        }
        // an error can be raised if we attempt to read an unregistered function
        return OptionalValue(_pushed, L_, "tried to copy unsupported types");
    };
    return Linda::ProtectedCall(L_, get);
}

// #################################################################################################

/*
 * [true] = linda_limit( linda_ud, key_num|str|bool|lightuserdata, [int])
 *
 * Set limit to 1 Linda keys.
 * Optionally wake threads waiting to write on the linda, in case the limit enables them to do so
 * Limit can be 0 to completely block everything, nil to reset
 */
LUAG_FUNC(linda_limit)
{
    auto _limit = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        // make sure we got 3 arguments: the linda, a key and a limit
        int const _nargs{ lua_gettop(L_) };
        luaL_argcheck(L_, _nargs == 2 || _nargs == 3, 2, "wrong number of arguments");
        // make sure we got a numeric limit
        lua_Integer const _limit{ luaL_optinteger(L_, 3, 0) };
        if (_limit < 0) {
            raise_luaL_argerror(L_, 3, "limit must be >= 0");
        }
        // make sure the key is of a valid type
        check_key_types(L_, 2, 2);

        KeeperCallResult _pushed;
        if (_linda->cancelRequest == CancelRequest::None) {
            Keeper* const _K{ _linda->whichKeeper() };
            _pushed = keeper_call(_K->L, KEEPER_API(limit), L_, _linda, 2);
            LUA_ASSERT(L_, _pushed.has_value() && (_pushed.value() == 0 || _pushed.value() == 1)); // no error, optional boolean value saying if we should wake blocked writer threads
            if (_pushed.value() == 1) {
                LUA_ASSERT(L_, lua_type(L_, -1) == LUA_TBOOLEAN && lua_toboolean(L_, -1) == 1);
                _linda->readHappened.notify_all(); // To be done from within the 'K' locking area
            }
        } else { // linda is cancelled
            // do nothing and return lanes.cancel_error
            kCancelError.pushKey(L_);
            _pushed.emplace(1);
        }
        // propagate pushed boolean if any
        return _pushed.value();
    };
    return Linda::ProtectedCall(L_, _limit);
}

// #################################################################################################

/*
 * 2 modes of operation
 * [val, key]= linda_receive( linda_ud, [timeout_secs_num=nil], key_num|str|bool|lightuserdata [, ...] )
 * Consumes a single value from the Linda, in any key.
 * Returns: received value (which is consumed from the slot), and the key which had it

 * [val1, ... valCOUNT]= linda_receive( linda_ud, [timeout_secs_num=-1], linda.batched, key_num|str|bool|lightuserdata, min_COUNT[, max_COUNT])
 * Consumes between min_COUNT and max_COUNT values from the linda, from a single key.
 * returns the actual consumed values, or nil if there weren't enough values to consume
 *
 */
LUAG_FUNC(linda_receive)
{
    auto _receive = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        int _key_i{ 2 }; // index of first key, if timeout not there

        std::chrono::time_point<std::chrono::steady_clock> _until{ std::chrono::time_point<std::chrono::steady_clock>::max() };
        if (lua_type(L_, 2) == LUA_TNUMBER) { // we don't want to use lua_isnumber() because of autocoercion
            lua_Duration const _duration{ lua_tonumber(L_, 2) };
            if (_duration.count() >= 0.0) {
                _until = std::chrono::steady_clock::now() + std::chrono::duration_cast<std::chrono::steady_clock::duration>(_duration);
            } else {
                raise_luaL_argerror(L_, 2, "duration cannot be < 0");
            }
            ++_key_i;
        } else if (lua_isnil(L_, 2)) { // alternate explicit "infinite timeout" by passing nil before the key
            ++_key_i;
        }

        keeper_api_t _selected_keeper_receive{ nullptr };
        int _expected_pushed_min{ 0 }, _expected_pushed_max{ 0 };
        // are we in batched mode?
        kLindaBatched.pushKey(L_);
        int const _is_batched{ lua501_equal(L_, _key_i, -1) };
        lua_pop(L_, 1);
        if (_is_batched) {
            // no need to pass linda.batched in the keeper state
            ++_key_i;
            // make sure the keys are of a valid type
            check_key_types(L_, _key_i, _key_i);
            // receive multiple values from a single slot
            _selected_keeper_receive = KEEPER_API(receive_batched);
            // we expect a user-defined amount of return value
            _expected_pushed_min = (int) luaL_checkinteger(L_, _key_i + 1);
            _expected_pushed_max = (int) luaL_optinteger(L_, _key_i + 2, _expected_pushed_min);
            // don't forget to count the key in addition to the values
            ++_expected_pushed_min;
            ++_expected_pushed_max;
            if (_expected_pushed_min > _expected_pushed_max) {
                raise_luaL_error(L_, "batched min/max error");
            }
        } else {
            // make sure the keys are of a valid type
            check_key_types(L_, _key_i, lua_gettop(L_));
            // receive a single value, checking multiple slots
            _selected_keeper_receive = KEEPER_API(receive);
            // we expect a single (value, key) pair of returned values
            _expected_pushed_min = _expected_pushed_max = 2;
        }

        Lane* const _lane{ kLanePointerRegKey.readLightUserDataValue<Lane>(L_) };
        Keeper* const _K{ _linda->whichKeeper() };
        KeeperState const _KL{ _K ? _K->L : nullptr };
        if (_KL == nullptr)
            return 0;

        CancelRequest _cancel{ CancelRequest::None };
        KeeperCallResult _pushed;
        STACK_CHECK_START_REL(_KL, 0);
        for (bool _try_again{ true };;) {
            if (_lane != nullptr) {
                _cancel = _lane->cancelRequest;
            }
            _cancel = (_cancel != CancelRequest::None) ? _cancel : _linda->cancelRequest;
            // if user wants to cancel, or looped because of a timeout, the call returns without sending anything
            if (!_try_again || _cancel != CancelRequest::None) {
                _pushed.emplace(0);
                break;
            }

            // all arguments of receive() but the first are passed to the keeper's receive function
            _pushed = keeper_call(_KL, _selected_keeper_receive, L_, _linda, _key_i);
            if (!_pushed.has_value()) {
                break;
            }
            if (_pushed.value() > 0) {
                LUA_ASSERT(L_, _pushed.value() >= _expected_pushed_min && _pushed.value() <= _expected_pushed_max);
                _linda->readHappened.notify_all();
                break;
            }

            if (std::chrono::steady_clock::now() >= _until) {
                break; /* instant timeout */
            }

            // nothing received, wait until timeout or signalled that we should try again
            {
                Lane::Status _prev_status{ Lane::Error }; // prevent 'might be used uninitialized' warnings
                if (_lane != nullptr) {
                    // change status of lane to "waiting"
                    _prev_status = _lane->status; // Running, most likely
                    LUA_ASSERT(L_, _prev_status == Lane::Running); // but check, just in case
                    _lane->status = Lane::Waiting;
                    LUA_ASSERT(L_, _lane->waiting_on == nullptr);
                    _lane->waiting_on = &_linda->writeHappened;
                }
                // not enough data to read: wakeup when data was sent, or when timeout is reached
                std::unique_lock<std::mutex> _keeper_lock{ _K->mutex, std::adopt_lock };
                std::cv_status const _status{ _linda->writeHappened.wait_until(_keeper_lock, _until) };
                _keeper_lock.release();                              // we don't want to release the lock!
                _try_again = (_status == std::cv_status::no_timeout); // detect spurious wakeups
                if (_lane != nullptr) {
                    _lane->waiting_on = nullptr;
                    _lane->status = _prev_status;
                }
            }
        }
        STACK_CHECK(_KL, 0);

        if (!_pushed.has_value()) {
            raise_luaL_error(L_, "tried to copy unsupported types");
        }

        switch (_cancel) {
        case CancelRequest::Soft:
            // if user wants to soft-cancel, the call returns kCancelError
            kCancelError.pushKey(L_);
            return 1;

        case CancelRequest::Hard:
            // raise an error interrupting execution only in case of hard cancel
            raise_cancel_error(L_); // raises an error and doesn't return

        default:
            return _pushed.value();
        }
    };
    return Linda::ProtectedCall(L_, _receive);
}

// #################################################################################################

/*
 * bool= linda:linda_send([timeout_secs=nil,] key_num|str|bool|lightuserdata, ...)
 *
 * Send one or more values to a Linda. If there is a limit, all values must fit.
 *
 * Returns:  'true' if the value was queued
 *           'false' for timeout (only happens when the queue size is limited)
 *           nil, kCancelError if cancelled
 */
LUAG_FUNC(linda_send)
{
    auto _send = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        int _key_i{ 2 }; // index of first key, if timeout not there

        std::chrono::time_point<std::chrono::steady_clock> _until{ std::chrono::time_point<std::chrono::steady_clock>::max() };
        if (lua_type(L_, 2) == LUA_TNUMBER) { // we don't want to use lua_isnumber() because of autocoercion
            lua_Duration const _duration{ lua_tonumber(L_, 2) };
            if (_duration.count() >= 0.0) {
                _until = std::chrono::steady_clock::now() + std::chrono::duration_cast<std::chrono::steady_clock::duration>(_duration);
            } else {
                raise_luaL_argerror(L_, 2, "duration cannot be < 0");
            }
            ++_key_i;
        } else if (lua_isnil(L_, 2)) { // alternate explicit "infinite timeout" by passing nil before the key
            ++_key_i;
        }

        // make sure the key is of a valid type
        check_key_types(L_, _key_i, _key_i);

        STACK_GROW(L_, 1);

        // make sure there is something to send
        if (lua_gettop(L_) == _key_i) {
            raise_luaL_error(L_, "no data to send");
        }

        bool _ret{ false };
        CancelRequest _cancel{ CancelRequest::None };
        KeeperCallResult _pushed;
        {
            Lane* const _lane{ kLanePointerRegKey.readLightUserDataValue<Lane>(L_) };
            Keeper* const _K{ _linda->whichKeeper() };
            KeeperState const _KL{ _K ? _K->L : nullptr };
            if (_KL == nullptr)
                return 0;

            STACK_CHECK_START_REL(_KL, 0);
            for (bool _try_again{ true };;) {
                if (_lane != nullptr) {
                    _cancel = _lane->cancelRequest;
                }
                _cancel = (_cancel != CancelRequest::None) ? _cancel : _linda->cancelRequest;
                // if user wants to cancel, or looped because of a timeout, the call returns without sending anything
                if (!_try_again || _cancel != CancelRequest::None) {
                    _pushed.emplace(0);
                    break;
                }

                STACK_CHECK(_KL, 0);
                _pushed = keeper_call(_KL, KEEPER_API(send), L_, _linda, _key_i);
                if (!_pushed.has_value()) {
                    break;
                }
                LUA_ASSERT(L_, _pushed.value() == 1);

                _ret = lua_toboolean(L_, -1) ? true : false;
                lua_pop(L_, 1);

                if (_ret) {
                    // Wake up ALL waiting threads
                    _linda->writeHappened.notify_all();
                    break;
                }

                // instant timout to bypass the wait syscall
                if (std::chrono::steady_clock::now() >= _until) {
                    break; /* no wait; instant timeout */
                }

                // storage limit hit, wait until timeout or signalled that we should try again
                {
                    Lane::Status _prev_status{ Lane::Error }; // prevent 'might be used uninitialized' warnings
                    if (_lane != nullptr) {
                        // change status of lane to "waiting"
                        _prev_status = _lane->status; // Running, most likely
                        LUA_ASSERT(L_, _prev_status == Lane::Running); // but check, just in case
                        _lane->status = Lane::Waiting;
                        LUA_ASSERT(L_, _lane->waiting_on == nullptr);
                        _lane->waiting_on = &_linda->readHappened;
                    }
                    // could not send because no room: wait until some data was read before trying again, or until timeout is reached
                    std::unique_lock<std::mutex> _keeper_lock{ _K->mutex, std::adopt_lock };
                    std::cv_status const status{ _linda->readHappened.wait_until(_keeper_lock, _until) };
                    _keeper_lock.release(); // we don't want to release the lock!
                    _try_again = (status == std::cv_status::no_timeout); // detect spurious wakeups
                    if (_lane != nullptr) {
                        _lane->waiting_on = nullptr;
                        _lane->status = _prev_status;
                    }
                }
            }
            STACK_CHECK(_KL, 0);
        }

        if (!_pushed.has_value()) {
            raise_luaL_error(L_, "tried to copy unsupported types");
        }

        switch (_cancel) {
        case CancelRequest::Soft:
            // if user wants to soft-cancel, the call returns lanes.cancel_error
            kCancelError.pushKey(L_);
            return 1;

        case CancelRequest::Hard:
            // raise an error interrupting execution only in case of hard cancel
            raise_cancel_error(L_); // raises an error and doesn't return

        default:
            lua_pushboolean(L_, _ret); // true (success) or false (timeout)
            return 1;
        }
    };
    return Linda::ProtectedCall(L_, _send);
}

// #################################################################################################

/*
 * [true|lanes.cancel_error] = linda_set( linda_ud, key_num|str|bool|lightuserdata [, value [, ...]])
 *
 * Set one or more value to Linda. Ignores limits.
 *
 * Existing slot value is replaced, and possible queued entries removed.
 */
LUAG_FUNC(linda_set)
{
    auto set = [](lua_State* L_) {
        Linda* const _linda{ ToLinda<false>(L_, 1) };
        bool const _has_value{ lua_gettop(L_) > 2 };
        // make sure the key is of a valid type (throws an error if not the case)
        check_key_types(L_, 2, 2);

        Keeper* const _K{ _linda->whichKeeper() };
        KeeperCallResult _pushed;
        if (_linda->cancelRequest == CancelRequest::None) {
            _pushed = keeper_call(_K->L, KEEPER_API(set), L_, _linda, 2);
            if (_pushed.has_value()) { // no error?
                LUA_ASSERT(L_, _pushed.value() == 0 || _pushed.value() == 1);

                if (_has_value) {
                    // we put some data in the slot, tell readers that they should wake
                    _linda->writeHappened.notify_all(); // To be done from within the 'K' locking area
                }
                if (_pushed.value() == 1) {
                    // the key was full, but it is no longer the case, tell writers they should wake
                    LUA_ASSERT(L_, lua_type(L_, -1) == LUA_TBOOLEAN && lua_toboolean(L_, -1) == 1);
                    _linda->readHappened.notify_all(); // To be done from within the 'K' locking area
                }
            }
        } else { // linda is cancelled
            // do nothing and return lanes.cancel_error
            kCancelError.pushKey(L_);
            _pushed.emplace(1);
        }

        // must trigger any error after keeper state has been released
        return OptionalValue(_pushed, L_, "tried to copy unsupported types");
    };
    return Linda::ProtectedCall(L_, set);
}

// #################################################################################################

LUAG_FUNC(linda_tostring)
{
    return LindaToString<false>(L_, 1);
}

// #################################################################################################

/*
 * table/string = linda:__towatch()
 * return a table listing all pending data inside the linda, or the stringified linda if empty
 */
LUAG_FUNC(linda_towatch)
{
    Linda* const _linda{ ToLinda<false>(L_, 1) };
    int _pushed{ keeper_push_linda_storage(*_linda, DestState{ L_ }) };
    if (_pushed == 0) {
        // if the linda is empty, don't return nil
        _pushed = LindaToString<false>(L_, 1);
    }
    return _pushed;
}

// #################################################################################################

namespace {
    namespace local {
        static luaL_Reg const sLindaMT[] = {
            { "__concat", LG_linda_concat },
            { "__tostring", LG_linda_tostring },
            { "__towatch", LG_linda_towatch }, // Decoda __towatch support
            { "cancel", LG_linda_cancel },
            { "count", LG_linda_count },
            { "deep", LG_linda_deep },
            { "dump", LG_linda_dump },
            { "get", LG_linda_get },
            { "limit", LG_linda_limit },
            { "receive", LG_linda_receive },
            { "send", LG_linda_send },
            { "set", LG_linda_set },
            { nullptr, nullptr }
        };
    } // namespace local
} // namespace
// it's somewhat awkward to instanciate the LindaFactory here instead of lindafactory.cpp,
// but that's necessary to provide s_LindaMT without exposing it outside linda.cpp.
/*static*/ LindaFactory LindaFactory::Instance{ local::sLindaMT };

// #################################################################################################
// #################################################################################################

/*
 * ud = lanes.linda( [name[,group]])
 *
 * returns a linda object, or raises an error if creation failed
 */
LUAG_FUNC(linda)
{
    int const _top{ lua_gettop(L_) };
    luaL_argcheck(L_, _top <= 2, _top, "too many arguments");
    if (_top == 1) {
        LuaType const _t{ lua_type_as_enum(L_, 1) };
        luaL_argcheck(L_, _t == LuaType::STRING || _t == LuaType::NUMBER, 1, "wrong parameter (should be a string or a number)");
    } else if (_top == 2) {
        luaL_checktype(L_, 1, LUA_TSTRING);
        luaL_checktype(L_, 2, LUA_TNUMBER);
    }
    return LindaFactory::Instance.pushDeepUserdata(DestState{ L_ }, 0);
}