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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2020-2023 Gothel Software e.K.
* Copyright (c) 2020 ZAFENA AB
*
* 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.
*/
#ifndef JAU_RINGBUFFER_HPP_
#define JAU_RINGBUFFER_HPP_
#include <type_traits>
#include <atomic>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdint>
#include <jau/debug.hpp>
#include <jau/basic_types.hpp>
#include <jau/ordered_atomic.hpp>
#include <jau/fraction_type.hpp>
#include <jau/callocator.hpp>
namespace jau {
#if 0
#define _DEBUG_DUMP(...) { dump(stderr, __VA_ARGS__); }
#define _DEBUG_DUMP2(a, ...) { a.dump(stderr, __VA_ARGS__); }
#define _DEBUG_PRINT(...) { fprintf(stderr, __VA_ARGS__); }
#else
#define _DEBUG_DUMP(...)
#define _DEBUG_DUMP2(a, ...)
#define _DEBUG_PRINT(...)
#endif
/** @defgroup DataStructs Data Structures
* Data structures, notably
* - \ref ringbuffer
* - \ref darray
* - cow_darray
* - cow_vector
*
* @{
*/
/**
* Ring buffer implementation, a.k.a circular buffer,
* exposing <i>lock-free</i>
* {@link #get() get*(..)} and {@link #put(Object) put*(..)} methods.
*
* This data structure is also supporting \ref Concurrency.
*
* Implementation utilizes the <i>Always Keep One Slot Open</i>,
* hence implementation maintains an internal array of `capacity` <i>plus one</i>!
*
* ### Characteristics
* - Read position points to the last read element.
* - Write position points to the last written element.
*
* <table border="1">
* <tr><td>Empty</td><td>writePos == readPos</td><td>size == 0</td></tr>
* <tr><td>Full</td><td>writePos == readPos - 1</td><td>size == capacity</td></tr>
* </table>
* <pre>
* Empty [RW][][ ][ ][ ][ ][ ][ ] ; W==R
* Avail [ ][ ][R][.][.][.][.][W] ; W > R
* Avail [.][.][.][W][ ][ ][R][.] ; W < R - 1
* Full [.][.][.][.][.][W][R][.] ; W==R-1
* </pre>
*
*
* ### Thread Safety
* Thread safety is guaranteed, considering the mode of operation as described below.
*
* @anchor ringbuffer_single_pc
* #### One producer-thread and one consumer-thread
* Expects one producer-thread at a time and one consumer-thread at a time concurrently.
* Threads can be different or the same.
*
* This is the default mode with the least std::mutex operations.
* - Only blocking producer put() and consumer get() waiting for
* free slots or available data will utilize lock and wait for the corresponding operation.
* - Otherwise implementation is <i>lock-free</i> and relies on SC-DRF via atomic memory barriers.
*
* See setMultiPCEnabled().
*
* Implementation is thread safe if:
* - {@link #put() put*(..)} operations from one producer-thread at a time.
* - {@link #get() get*(..)} operations from one consumer-thread at a time.
* - {@link #put() put*(..)} producer and {@link #get() get*(..)} consumer threads can be different or the same.
*
* @anchor ringbuffer_multi_pc
* #### Multiple producer-threads and multiple consumer-threads
* Expects multiple producer-threads and multiple consumer-threads concurrently.
* Threads can be different or the same.
*
* This operation mode utilizes a specific multi-producer and -consumer lock,
* synchronizing {@link #put() put*(..)} and {@link #get() get*(..)} operations separately.
*
* Use setMultiPCEnabled() to enable or disable multiple producer and consumer mode.
*
* Implementation is thread safe if:
* - {@link #put() put*(..)} operations concurrently from multiple threads.
* - {@link #get() get*(..)} operations concurrently from multiple threads.
* - {@link #put() put*(..)} producer and {@link #get() get*(..)} consumer threads can be different or the same.
*
* #### Interruption of Consumer and Producer
* To allow an application to unblock a potentially blocked producer (writer)
* or consumer (reader) thread once,
* one can call interruptWriter() or interruptReader() respectively.
*
* #### Marking End of Input Stream (EOS)
* To allow an application to mark the end of input stream,
* i.e. the producer (write) has completed filling the ringbuffer,
* one can call set_end_of_input().
*
* Calling set_end_of_input(true) will unblock all read-operations from this point onwards.
* A potentially currently blocked reader thread is also interrupted and hence unblocked.
*
* #### See also
* - Sequentially Consistent (SC) ordering or SC-DRF (data race free) <https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering>
* - std::memory_order <https://en.cppreference.com/w/cpp/atomic/memory_order>
* - jau::sc_atomic_critical
* - setMultiPCEnabled()
* - interruptReader()
* - interruptWriter()
* - set_end_of_input()
*
* @anchor ringbuffer_ntt_params
* ### Non-Type Template Parameter (NTTP) controlling Value_type memory
* See @ref darray_ntt_params.
*
* #### use_memmove
* `use_memmove` see @ref darray_memmove.
*
* #### use_memcpy
* `use_memcpy` has more strict requirements than `use_memmove`,
* i.e. strictly relies on Value_type being `std::is_trivially_copyable_v<Value_type>`.
*
* It allows to merely use memory operations w/o the need for constructor or destructor.
*
* See [Trivial destructor](https://en.cppreference.com/w/cpp/language/destructor#Trivial_destructor)
* being key requirement to [TriviallyCopyable](https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable).
* > A trivial destructor is a destructor that performs no action.
* > Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage.
* > All data types compatible with the C language (POD types) are trivially destructible.`
*
* #### use_secmem
* `use_secmem` see @ref darray_secmem.
*
* @see @ref darray_ntt_params
* @see jau::sc_atomic_critical
*/
template <typename Value_type, typename Size_type,
bool use_memmove = std::is_trivially_copyable_v<Value_type> || is_container_memmove_compliant_v<Value_type>,
bool use_memcpy = std::is_trivially_copyable_v<Value_type>,
bool use_secmem = is_enforcing_secmem_v<Value_type>
>
class ringbuffer {
public:
constexpr static const bool uses_memmove = use_memmove;
constexpr static const bool uses_memcpy = use_memcpy;
constexpr static const bool uses_secmem = use_secmem;
// typedefs' for C++ named requirements: Container (ex iterator)
typedef Value_type value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef Size_type size_type;
typedef typename std::make_signed<size_type>::type difference_type;
typedef jau::callocator<Value_type> allocator_type;
private:
constexpr static const bool is_integral = std::is_integral_v<Value_type>;
typedef std::remove_const_t<Value_type> value_type_mutable;
/** Required to create and move immutable elements, aka const */
typedef value_type_mutable* pointer_mutable;
static constexpr void* voidptr_cast(const_pointer p) { return reinterpret_cast<void*>( const_cast<pointer_mutable>( p ) ); }
/** SC atomic integral scalar jau::nsize_t. Memory-Model (MM) guaranteed sequential consistency (SC) between acquire (read) and release (write) */
typedef ordered_atomic<Size_type, std::memory_order_seq_cst> sc_atomic_Size_type;
/** Relaxed non-SC atomic integral scalar jau::nsize_t. Memory-Model (MM) only guarantees the atomic value, _no_ sequential consistency (SC) between acquire (read) and release (write). */
typedef ordered_atomic<Size_type, std::memory_order_relaxed> relaxed_atomic_Size_type;
/**
* Flagging whether multiple-producer and -consumer are enabled,
* see @ref ringbuffer_multi_pc and @ref ringbuffer_single_pc.
*
* Defaults to `false`.
*/
bool multi_pc_enabled = false;
/** synchronizes write-operations (put*), i.e. modifying the writePos. */
mutable std::mutex syncWrite, syncMultiWrite; // Memory-Model (MM) guaranteed sequential consistency (SC) between acquire and release
std::condition_variable cvWrite;
/** synchronizes read-operations (get*), i.e. modifying the readPos. */
mutable std::mutex syncRead, syncMultiRead; // Memory-Model (MM) guaranteed sequential consistency (SC) between acquire and release
std::condition_variable cvRead;
jau::relaxed_atomic_bool interrupted_read = false;
jau::relaxed_atomic_bool interrupted_write = false;
jau::relaxed_atomic_bool end_of_input = false;
allocator_type alloc_inst;
/* const */ Size_type capacityPlusOne; // not final due to grow
/* const */ Value_type * array; // Synchronized due to MM's data-race-free SC (SC-DRF) between [atomic] acquire/release
sc_atomic_Size_type readPos; // Memory-Model (MM) guaranteed sequential consistency (SC) between acquire (read) and release (write)
sc_atomic_Size_type writePos; // ditto
constexpr Value_type * newArray(const Size_type count) noexcept {
if( 0 < count ) {
value_type * m = alloc_inst.allocate(count);
if( nullptr == m ) {
// Avoid exception, abort!
ABORT("Error: bad_alloc: alloc %zu elements * %zu bytes/element = %zu bytes failed",
count, sizeof(value_type), (count * sizeof(value_type)));
}
_DEBUG_DUMP("newArray ...");
_DEBUG_PRINT("newArray %" PRIu64 "\n", count);
return m;
} else {
_DEBUG_DUMP("newArray ...");
_DEBUG_PRINT("newArray %" PRIu64 "\n", count);
return nullptr;
}
}
constexpr void freeArray(Value_type ** a, const Size_type count) noexcept {
_DEBUG_DUMP("freeArray(def)");
_DEBUG_PRINT("freeArray %p\n", *a);
if( nullptr != *a ) {
alloc_inst.deallocate(*a, count);
*a = nullptr;
} else {
ABORT("ringbuffer::freeArray with nullptr");
}
}
constexpr void dtor_one(const Size_type pos) {
( array + pos )->~value_type(); // placement new -> manual destruction!
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(array + pos), sizeof(value_type));
}
}
constexpr void dtor_one(pointer elem) {
( elem )->~value_type(); // placement new -> manual destruction!
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(elem), sizeof(value_type));
}
}
Size_type waitForElementsImpl(const Size_type min_count, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
Size_type available = size();
if( available < min_count && min_count < capacityPlusOne && !end_of_input ) {
interrupted_read = false;
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ putImpl via same lock
available = size();
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_read && !end_of_input && min_count > available ) {
if( fractions_i64::zero == timeout ) {
cvWrite.wait(lockWrite);
available = size();
} else {
std::cv_status s = wait_until(cvWrite, lockWrite, timeout_time );
available = size();
if( std::cv_status::timeout == s && min_count > available ) {
timeout_occurred = true;
return available;
}
}
}
if( interrupted_read ) { // interruption or end_of_input may happen after delivering last data chunk
interrupted_read = false;
}
}
return available;
}
Size_type waitForFreeSlotsImpl(const Size_type min_count, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
Size_type available = freeSlots();
if( min_count > available && min_count < capacityPlusOne ) {
interrupted_write = false;
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ getImpl via same lock
available = freeSlots();
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_write && min_count > available ) {
if( fractions_i64::zero == timeout ) {
cvRead.wait(lockRead);
available = freeSlots();
} else {
std::cv_status s = wait_until(cvRead, lockRead, timeout_time );
available = freeSlots();
if( std::cv_status::timeout == s && min_count > available ) {
timeout_occurred = true;
return available;
}
}
}
if( interrupted_write ) {
interrupted_write = false;
}
}
return available;
}
/**
* clear all elements, zero size.
*
* Moves readPos == writePos compatible with put*() when waiting for available
*/
constexpr void clearImpl() noexcept {
const Size_type size_ = size();
if( 0 < size_ ) {
if constexpr ( use_memcpy ) {
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[0]), capacityPlusOne*sizeof(Value_type));
}
readPos = writePos.load();
} else {
Size_type localReadPos = readPos;
for(Size_type i=0; i<size_; i++) {
localReadPos = (localReadPos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
( array + localReadPos )->~value_type(); // placement new -> manual destruction!
}
if( writePos != localReadPos ) {
// Avoid exception, abort!
ABORT("copy segment error: this %s, readPos %d/%d; writePos %d", toString().c_str(), readPos.load(), localReadPos, writePos.load());
}
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[0]), capacityPlusOne*sizeof(Value_type));
}
readPos = localReadPos;
}
}
}
constexpr void clearAndZeroMemImpl() noexcept {
if constexpr ( use_memcpy ) {
::explicit_bzero(voidptr_cast(&array[0]), capacityPlusOne*sizeof(Value_type));
readPos = writePos.load();
} else {
const Size_type size_ = size();
Size_type localReadPos = readPos;
for(Size_type i=0; i<size_; i++) {
localReadPos = (localReadPos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
( array + localReadPos )->~value_type(); // placement new -> manual destruction!
}
if( writePos != localReadPos ) {
// Avoid exception, abort!
ABORT("copy segment error: this %s, readPos %d/%d; writePos %d", toString().c_str(), readPos.load(), localReadPos, writePos.load());
}
::explicit_bzero(voidptr_cast(&array[0]), capacityPlusOne*sizeof(Value_type));
readPos = localReadPos;
}
}
void cloneFrom(const bool allocArrayAndCapacity, const ringbuffer & source) noexcept {
if( allocArrayAndCapacity ) {
if( nullptr != array ) {
clearImpl();
freeArray(&array, capacityPlusOne);
}
capacityPlusOne = source.capacityPlusOne;
array = newArray(capacityPlusOne);
} else if( capacityPlusOne != source.capacityPlusOne ) {
ABORT( ("capacityPlusOne not equal: this "+toString()+", source "+source.toString() ).c_str() );
} else {
clearImpl();
}
readPos = source.readPos.load();
writePos = source.writePos.load();
if constexpr ( uses_memcpy ) {
::memcpy(voidptr_cast(&array[0]),
&source.array[0],
capacityPlusOne*sizeof(Value_type));
} else {
const Size_type size_ = size();
Size_type localWritePos = readPos;
for(Size_type i=0; i<size_; i++) {
localWritePos = (localWritePos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
new (const_cast<pointer_mutable>(array + localWritePos)) value_type( source.array[localWritePos] ); // placement new
}
if( writePos != localWritePos ) {
ABORT( ("copy segment error: this "+toString()+", localWritePos "+std::to_string(localWritePos)+"; source "+source.toString()).c_str() );
}
}
}
ringbuffer& assignCopyImpl(const ringbuffer &_source) noexcept {
if( this == &_source ) {
return *this;
}
if( capacityPlusOne != _source.capacityPlusOne ) {
cloneFrom(true, _source);
} else {
cloneFrom(false, _source);
}
_DEBUG_DUMP("assignment(copy.this)");
_DEBUG_DUMP2(_source, "assignment(copy.source)");
return *this;
}
void resetImpl(const Value_type * copyFrom, const Size_type copyFromCount) noexcept {
// fill with copyFrom elements
if( nullptr != copyFrom && 0 < copyFromCount ) {
if( copyFromCount > capacityPlusOne-1 ) {
// new blank resized array
if( nullptr != array ) {
clearImpl();
freeArray(&array, capacityPlusOne);
}
capacityPlusOne = copyFromCount + 1;
array = newArray(capacityPlusOne);
readPos = 0;
writePos = 0;
} else {
clearImpl();
}
if constexpr ( uses_memcpy ) {
::memcpy(voidptr_cast(&array[0]),
copyFrom,
copyFromCount*sizeof(Value_type));
readPos = capacityPlusOne - 1; // last read-pos
writePos = copyFromCount - 1; // last write-pos
} else {
Size_type localWritePos = writePos;
for(Size_type i=0; i<copyFromCount; i++) {
localWritePos = (localWritePos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
new (const_cast<pointer_mutable>(array + localWritePos)) value_type( copyFrom[i] ); // placement new
}
writePos = localWritePos;
}
} else {
clearImpl();
}
}
bool peekImpl(Value_type& dest, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
if( !std::is_copy_constructible_v<Value_type> ) {
ABORT("Value_type is not copy constructible");
return false;
}
if( 1 >= capacityPlusOne ) {
return false;
}
const Size_type oldReadPos = readPos; // SC-DRF acquire atomic readPos, sync'ing with putImpl
Size_type localReadPos = oldReadPos;
if( localReadPos == writePos ) {
if( blocking && !end_of_input ) {
interrupted_read = false;
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ putImpl via same lock
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_read && !end_of_input && localReadPos == writePos ) {
if( fractions_i64::zero == timeout ) {
cvWrite.wait(lockWrite);
} else {
std::cv_status s = wait_until(cvWrite, lockWrite, timeout_time );
if( std::cv_status::timeout == s && localReadPos == writePos ) {
timeout_occurred = true;
return false;
}
}
}
if( interrupted_read || end_of_input ) {
interrupted_read = false;
if( localReadPos == writePos ) { // interruption or end_of_input may happen after delivering last data chunk
return false;
}
}
} else {
return false;
}
}
localReadPos = (localReadPos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if constexpr ( !is_integral && uses_memmove ) {
// must not dtor after memcpy; memcpy OK, not overlapping
::memcpy(voidptr_cast(&dest),
&array[localReadPos],
sizeof(Value_type));
} else {
dest = array[localReadPos];
}
readPos = oldReadPos; // SC-DRF release atomic readPos (complete acquire-release even @ peek)
return true;
}
bool moveOutImpl(Value_type& dest, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
if( 1 >= capacityPlusOne ) {
return false;
}
const Size_type oldReadPos = readPos; // SC-DRF acquire atomic readPos, sync'ing with putImpl
Size_type localReadPos = oldReadPos;
if( localReadPos == writePos ) {
if( blocking && !end_of_input ) {
interrupted_read = false;
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ putImpl via same lock
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_read && !end_of_input && localReadPos == writePos ) {
if( fractions_i64::zero == timeout ) {
cvWrite.wait(lockWrite);
} else {
std::cv_status s = wait_until(cvWrite, lockWrite, timeout_time );
if( std::cv_status::timeout == s && localReadPos == writePos ) {
timeout_occurred = true;
return false;
}
}
}
if( interrupted_read || end_of_input ) {
interrupted_read = false;
if( localReadPos == writePos ) { // interruption or end_of_input may happen after delivering last data chunk
return false;
}
}
} else {
return false;
}
}
localReadPos = (localReadPos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if constexpr ( is_integral ) {
dest = array[localReadPos];
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[localReadPos]), sizeof(Value_type));
}
} else if constexpr ( uses_memmove ) {
// must not dtor after memcpy; memcpy OK, not overlapping
::memcpy(voidptr_cast(&dest),
&array[localReadPos],
sizeof(Value_type));
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[localReadPos]), sizeof(Value_type));
}
} else {
dest = std::move( array[localReadPos] );
dtor_one( localReadPos );
}
{
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ putImpl via same lock
readPos = localReadPos; // SC-DRF release atomic readPos
}
cvRead.notify_all(); // notify waiting putter, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
return true;
}
Size_type moveOutImpl(Value_type *dest, const Size_type dest_len, const Size_type min_count_, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
const Size_type min_count = std::min(dest_len, min_count_);
Value_type *iter_out = dest;
if( min_count >= capacityPlusOne ) {
return 0;
}
if( 0 == min_count ) {
return 0;
}
const Size_type oldReadPos = readPos; // SC-DRF acquire atomic readPos, sync'ing with putImpl
Size_type localReadPos = oldReadPos;
Size_type available = size();
if( min_count > available ) {
if( blocking && !end_of_input ) {
interrupted_read = false;
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ putImpl via same lock
available = size();
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_read && !end_of_input && min_count > available ) {
if( fractions_i64::zero == timeout ) {
cvWrite.wait(lockWrite);
available = size();
} else {
std::cv_status s = wait_until(cvWrite, lockWrite, timeout_time );
available = size();
if( std::cv_status::timeout == s && min_count > available ) {
timeout_occurred = true;
return 0;
}
}
}
if( interrupted_read || end_of_input ) {
interrupted_read = false;
if( min_count > available ) { // interruption or end_of_input may happen after delivering last data chunk
return 0;
}
}
} else {
return 0;
}
}
const Size_type count = std::min(dest_len, available);
/**
* Empty [RW][][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] ; W==R
* Avail [ ][ ][R][.][.][.][.][W][ ][ ][ ][ ][ ][ ][ ] ; W > R
* Avail [.][.][.][W][ ][ ][R][.][.][.][.][.][.][.][.] ; W < R - 1
* Full [.][.][.][.][.][W][R][.][.][.][.][.][.][.][.] ; W==R-1
*/
// Since available > 0, we can exclude Empty case.
Size_type togo_count = count;
const Size_type localWritePos = writePos;
if( localReadPos > localWritePos ) {
// we have a tail
localReadPos = ( localReadPos + 1 ) % capacityPlusOne; // next-read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
const Size_type tail_count = std::min(togo_count, capacityPlusOne - localReadPos);
if constexpr ( uses_memmove ) {
// must not dtor after memcpy; memcpy OK, not overlapping
::memcpy(voidptr_cast(iter_out),
&array[localReadPos],
tail_count*sizeof(Value_type));
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[localReadPos]), tail_count*sizeof(Value_type));
}
} else {
for(Size_type i=0; i<tail_count; i++) {
iter_out[i] = std::move( array[localReadPos+i] );
dtor_one( localReadPos + i ); // manual destruction, even after std::move (object still exists)
}
}
localReadPos = ( localReadPos + tail_count - 1 ) % capacityPlusOne; // last read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
togo_count -= tail_count;
iter_out += tail_count;
}
if( togo_count > 0 ) {
// we have a head
localReadPos = ( localReadPos + 1 ) % capacityPlusOne; // next-read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if constexpr ( uses_memmove ) {
// must not dtor after memcpy; memcpy OK, not overlapping
::memcpy(voidptr_cast(iter_out),
&array[localReadPos],
togo_count*sizeof(Value_type));
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[localReadPos]), togo_count*sizeof(Value_type));
}
} else {
for(Size_type i=0; i<togo_count; i++) {
iter_out[i] = std::move( array[localReadPos+i] );
dtor_one( localReadPos + i ); // manual destruction, even after std::move (object still exists)
}
}
localReadPos = ( localReadPos + togo_count - 1 ) % capacityPlusOne; // last read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
}
{
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ putImpl via same lock
readPos = localReadPos; // SC-DRF release atomic readPos
}
cvRead.notify_all(); // notify waiting putter, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
return count;
}
Size_type dropImpl (Size_type count, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
if( count >= capacityPlusOne ) {
if( blocking ) {
return 0;
}
count = capacityPlusOne-1; // claim theoretical maximum for non-blocking
}
if( 0 == count ) {
return 0;
}
const Size_type oldReadPos = readPos; // SC-DRF acquire atomic readPos, sync'ing with putImpl
Size_type localReadPos = oldReadPos;
Size_type available = size();
if( count > available ) {
if( blocking && !end_of_input ) {
interrupted_read = false;
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ putImpl via same lock
available = size();
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_read && !end_of_input && count > available ) {
if( fractions_i64::zero == timeout ) {
cvWrite.wait(lockWrite);
available = size();
} else {
std::cv_status s = wait_until(cvWrite, lockWrite, timeout_time );
available = size();
if( std::cv_status::timeout == s && count > available ) {
timeout_occurred = true;
return 0;
}
}
}
if( interrupted_read || end_of_input ) {
interrupted_read = false;
if( count > available ) { // interruption or end_of_input may happen after delivering last data chunk
return 0;
}
}
} else {
count = available; // drop all available for non-blocking
}
}
/**
* Empty [RW][][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] ; W==R
* Avail [ ][ ][R][.][.][.][.][W][ ][ ][ ][ ][ ][ ][ ] ; W > R
* Avail [.][.][.][W][ ][ ][R][.][.][.][.][.][.][.][.] ; W < R - 1
* Full [.][.][.][.][.][W][R][.][.][.][.][.][.][.][.] ; W==R-1
*/
// Since available > 0, we can exclude Empty case.
Size_type togo_count = count;
const Size_type localWritePos = writePos;
if( localReadPos > localWritePos ) {
// we have a tail
localReadPos = ( localReadPos + 1 ) % capacityPlusOne; // next-read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
const Size_type tail_count = std::min(togo_count, capacityPlusOne - localReadPos);
if constexpr ( uses_memcpy ) {
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[localReadPos]), tail_count*sizeof(Value_type));
}
} else {
for(Size_type i=0; i<tail_count; i++) {
dtor_one( localReadPos+i );
}
}
localReadPos = ( localReadPos + tail_count - 1 ) % capacityPlusOne; // last read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
togo_count -= tail_count;
}
if( togo_count > 0 ) {
// we have a head
localReadPos = ( localReadPos + 1 ) % capacityPlusOne; // next-read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if constexpr ( uses_memcpy ) {
if constexpr ( uses_secmem ) {
::explicit_bzero(voidptr_cast(&array[localReadPos]), togo_count*sizeof(Value_type));
}
} else {
for(Size_type i=0; i<togo_count; i++) {
dtor_one( localReadPos+i );
}
}
localReadPos = ( localReadPos + togo_count - 1 ) % capacityPlusOne; // last read-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
}
{
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ putImpl via same lock
readPos = localReadPos; // SC-DRF release atomic readPos
}
cvRead.notify_all(); // notify waiting putter, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
return count;
}
bool moveIntoImpl(Value_type &&e, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
if( 1 >= capacityPlusOne ) {
return false;
}
Size_type localWritePos = writePos; // SC-DRF acquire atomic writePos, sync'ing with getImpl
localWritePos = (localWritePos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if( localWritePos == readPos ) {
if( blocking ) {
interrupted_write = false;
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ getImpl via same lock
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_write && localWritePos == readPos ) {
if( fractions_i64::zero == timeout ) {
cvRead.wait(lockRead);
} else {
std::cv_status s = wait_until(cvRead, lockRead, timeout_time );
if( std::cv_status::timeout == s && localWritePos == readPos ) {
timeout_occurred = true;
return false;
}
}
}
if( interrupted_write ) {
interrupted_write = false;
return false;
}
} else {
return false;
}
}
if constexpr ( is_integral ) {
array[localWritePos] = e;
} else if constexpr ( uses_memcpy ) {
::memcpy(voidptr_cast(&array[localWritePos]),
&e,
sizeof(Value_type));
} else {
new (const_cast<pointer_mutable>(array + localWritePos)) value_type( std::move(e) ); // placement new
}
{
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ getImpl via same lock
writePos = localWritePos; // SC-DRF release atomic writePos
}
cvWrite.notify_all(); // notify waiting getter, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
return true;
}
bool copyIntoImpl(const Value_type &e, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
if( !std::is_copy_constructible_v<Value_type> ) {
ABORT("Value_type is not copy constructible");
return false;
}
if( 1 >= capacityPlusOne ) {
return false;
}
Size_type localWritePos = writePos; // SC-DRF acquire atomic writePos, sync'ing with getImpl
localWritePos = (localWritePos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if( localWritePos == readPos ) {
if( blocking ) {
interrupted_write = false;
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ getImpl via same lock
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_write && localWritePos == readPos ) {
if( fractions_i64::zero == timeout ) {
cvRead.wait(lockRead);
} else {
std::cv_status s = wait_until(cvRead, lockRead, timeout_time );
if( std::cv_status::timeout == s && localWritePos == readPos ) {
timeout_occurred = true;
return false;
}
}
}
if( interrupted_write ) {
interrupted_write = false;
return false;
}
} else {
return false;
}
}
if constexpr ( is_integral ) {
array[localWritePos] = e;
} else if constexpr ( uses_memcpy ) {
::memcpy(voidptr_cast(&array[localWritePos]),
&e,
sizeof(Value_type));
} else {
new (const_cast<pointer_mutable>(array + localWritePos)) value_type( e ); // placement new
}
{
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ getImpl via same lock
writePos = localWritePos; // SC-DRF release atomic writePos
}
cvWrite.notify_all(); // notify waiting getter, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
return true;
}
bool copyIntoImpl(const Value_type *first, const Value_type* last, const bool blocking, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
timeout_occurred = false;
if( !std::is_copy_constructible_v<Value_type> ) {
ABORT("Value_type is not copy constructible");
return false;
}
const Value_type *iter_in = first;
const Size_type total_count = last - first;
if( total_count >= capacityPlusOne ) {
return false;
}
if( 0 == total_count ) {
return true;
}
Size_type localWritePos = writePos; // SC-DRF acquire atomic writePos, sync'ing with getImpl
Size_type available = freeSlots();
if( total_count > available ) {
if( blocking ) {
interrupted_write = false;
std::unique_lock<std::mutex> lockRead(syncRead); // SC-DRF w/ getImpl via same lock
available = freeSlots();
const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(timeout);
while( !interrupted_write && total_count > available ) {
if( fractions_i64::zero == timeout ) {
cvRead.wait(lockRead);
available = freeSlots();
} else {
std::cv_status s = wait_until(cvRead, lockRead, timeout_time );
available = freeSlots();
if( std::cv_status::timeout == s && total_count > available ) {
timeout_occurred = true;
return false;
}
}
}
if( interrupted_write ) {
interrupted_write = false;
return false;
}
} else {
return false;
}
}
/**
* Empty [RW][][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] ; W==R
* Avail [ ][ ][R][.][.][.][.][W][ ][ ][ ][ ][ ][ ][ ] ; W > R
* Avail [.][.][.][W][ ][ ][R][.][.][.][.][.][.][.][.] ; W < R - 1
* Full [.][.][.][.][.][W][R][.][.][.][.][.][.][.][.] ; W==R-1
*/
// Since available > 0, we can exclude Full case.
Size_type togo_count = total_count;
const Size_type localReadPos = readPos;
if( localWritePos >= localReadPos ) { // Empty at any position or W > R case
// we have a tail
localWritePos = ( localWritePos + 1 ) % capacityPlusOne; // next-write-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
const Size_type tail_count = std::min(togo_count, capacityPlusOne - localWritePos);
if constexpr ( uses_memcpy ) {
::memcpy(voidptr_cast(&array[localWritePos]),
iter_in,
tail_count*sizeof(Value_type));
} else {
for(Size_type i=0; i<tail_count; i++) {
new (const_cast<pointer_mutable>(array + localWritePos + i)) value_type( iter_in[i] ); // placement new
}
}
localWritePos = ( localWritePos + tail_count - 1 ) % capacityPlusOne; // last write-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
togo_count -= tail_count;
iter_in += tail_count;
}
if( togo_count > 0 ) {
// we have a head
localWritePos = ( localWritePos + 1 ) % capacityPlusOne; // next-write-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
if constexpr ( uses_memcpy ) {
memcpy(voidptr_cast(&array[localWritePos]),
iter_in,
togo_count*sizeof(Value_type));
} else {
for(Size_type i=0; i<togo_count; i++) {
new (const_cast<pointer_mutable>(array + localWritePos + i)) value_type( iter_in[i] ); // placement new
}
}
localWritePos = ( localWritePos + togo_count - 1 ) % capacityPlusOne; // last write-pos // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
}
{
std::unique_lock<std::mutex> lockWrite(syncWrite); // SC-DRF w/ getImpl via same lock
writePos = localWritePos; // SC-DRF release atomic writePos
}
cvWrite.notify_all(); // notify waiting getter, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
return true;
}
void recapacityImpl(const Size_type newCapacity) {
const Size_type size_ = size();
if( capacityPlusOne == newCapacity+1 ) {
return;
}
if( size_ > newCapacity ) {
throw IllegalArgumentException("amount "+std::to_string(newCapacity)+" < size, "+toString(), E_FILE_LINE);
}
// save current data
const Size_type oldCapacityPlusOne = capacityPlusOne;
Value_type * oldArray = array;
Size_type oldReadPos = readPos;
// new blank resized array, starting at position 0
capacityPlusOne = newCapacity + 1;
array = newArray(capacityPlusOne);
readPos = 0;
writePos = 0;
// copy saved data
if( nullptr != oldArray && 0 < size_ ) {
Size_type localWritePos = writePos;
for(Size_type i=0; i<size_; i++) {
localWritePos = (localWritePos + 1) % capacityPlusOne; // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
oldReadPos = (oldReadPos + 1) % oldCapacityPlusOne;
new (const_cast<pointer_mutable>( array + localWritePos )) value_type( std::move( oldArray[oldReadPos] ) ); // placement new
dtor_one( oldArray + oldReadPos ); // manual destruction, even after std::move (object still exists)
}
writePos = localWritePos;
}
freeArray(&oldArray, oldCapacityPlusOne); // and release
}
void closeImpl(const bool zeromem) noexcept {
if( zeromem ) {
clearAndZeroMemImpl();
} else {
clearImpl();
}
freeArray(&array, capacityPlusOne);
capacityPlusOne = 1;
array = newArray(capacityPlusOne);
readPos = 0;
writePos = 0;
}
public:
/** Returns a short string representation incl. size/capacity and internal r/w index (impl. dependent). */
std::string toString() const noexcept {
const std::string e_s = isEmpty() ? ", empty" : "";
const std::string f_s = isFull() ? ", full" : "";
const std::string mode_s = getMultiPCEnabled() ? ", mpc" : ", one";
return "ringbuffer<?>[size "+std::to_string(size())+" / "+std::to_string(capacityPlusOne-1)+
", writePos "+std::to_string(writePos)+", readPos "+std::to_string(readPos)+e_s+f_s+mode_s+"]";
}
/** Debug functionality - Dumps the contents of the internal array. */
void dump(FILE *stream, const std::string& prefix) const noexcept {
fprintf(stream, "%s %s, array %p\n", prefix.c_str(), toString().c_str(), array);
}
std::string get_info() const noexcept {
const std::string e_s = isEmpty() ? ", empty" : "";
const std::string f_s = isFull() ? ", full" : "";
const std::string mode_s = getMultiPCEnabled() ? ", mpc" : ", one";
std::string res("ringbuffer<?>[this "+jau::to_hexstring(this)+
", size "+std::to_string(size())+" / "+std::to_string(capacityPlusOne-1)+
", "+e_s+f_s+mode_s+", type[integral "+std::to_string(is_integral)+
", trivialCpy "+std::to_string(std::is_trivially_copyable_v<Value_type>)+
"], uses[mmove "+std::to_string(uses_memmove)+
", mcpy "+std::to_string(uses_memcpy)+
", smem "+std::to_string(uses_secmem)+
"]]");
return res;
}
/**
* Create a full ring buffer instance w/ the given array's net capacity and content.
* <p>
* Example for a 10 element Integer array:
* <pre>
* Integer[] source = new Integer[10];
* // fill source with content ..
* ringbuffer<Integer> rb = new ringbuffer<Integer>(source);
* </pre>
* </p>
* <p>
* {@link #isFull()} returns true on the newly created full ring buffer.
* </p>
* <p>
* Implementation will allocate an internal array with size of array `copyFrom` <i>plus one</i>,
* and copy all elements from array `copyFrom` into the internal array.
* </p>
* @param copyFrom mandatory source array determining ring buffer's net {@link #capacity()} and initial content.
* @throws IllegalArgumentException if `copyFrom` is `nullptr`
*/
ringbuffer(const std::vector<Value_type> & copyFrom) noexcept
: capacityPlusOne(copyFrom.size() + 1), array(newArray(capacityPlusOne)),
readPos(0), writePos(0)
{
resetImpl(copyFrom.data(), copyFrom.size());
_DEBUG_DUMP("ctor(vector<Value_type>)");
}
/**
* @param copyFrom
* @param copyFromSize
*/
ringbuffer(const Value_type * copyFrom, const Size_type copyFromSize) noexcept
: capacityPlusOne(copyFromSize + 1), array(newArray(capacityPlusOne)),
readPos(0), writePos(0)
{
resetImpl(copyFrom, copyFromSize);
_DEBUG_DUMP("ctor(Value_type*, len)");
}
/**
* Create an empty ring buffer instance w/ the given net `capacity`.
* <p>
* Example for a 10 element Integer array:
* <pre>
* ringbuffer<Integer> rb = new ringbuffer<Integer>(10, Integer[].class);
* </pre>
* </p>
* <p>
* {@link #isEmpty()} returns true on the newly created empty ring buffer.
* </p>
* <p>
* Implementation will allocate an internal array of size `capacity` <i>plus one</i>.
* </p>
* @param arrayType the array type of the created empty internal array.
* @param capacity the initial net capacity of the ring buffer
*/
ringbuffer(const Size_type capacity) noexcept
: capacityPlusOne(capacity + 1), array(newArray(capacityPlusOne)),
readPos(0), writePos(0)
{
_DEBUG_DUMP("ctor(capacity)");
}
~ringbuffer() noexcept {
_DEBUG_DUMP("dtor(def)");
if( nullptr != array ) {
clearImpl();
freeArray(&array, capacityPlusOne);
}
}
ringbuffer(const ringbuffer &_source) noexcept
: capacityPlusOne(_source.capacityPlusOne), array(newArray(capacityPlusOne)),
readPos(0), writePos(0)
{
std::unique_lock<std::mutex> lockMultiReadS(_source.syncMultiRead, std::defer_lock); // utilize std::lock(r, w), allowing mixed order waiting on read/write ops
std::unique_lock<std::mutex> lockMultiWriteS(_source.syncMultiWrite, std::defer_lock); // otherwise RAII-style relinquish via destructor
std::lock(lockMultiReadS, lockMultiWriteS); // *this instance does not exist yet
cloneFrom(false, _source);
_DEBUG_DUMP("ctor(copy.this)");
_DEBUG_DUMP2(_source, "ctor(copy.source)");
}
ringbuffer& operator=(const ringbuffer &_source) noexcept {
if( this == &_source ) {
return *this;
}
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiReadS(_source.syncMultiRead, std::defer_lock); // utilize std::lock(r, w), allowing mixed order waiting on read/write ops
std::unique_lock<std::mutex> lockMultiWriteS(_source.syncMultiWrite, std::defer_lock); // otherwise RAII-style relinquish via destructor
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::lock(lockMultiReadS, lockMultiWriteS, lockMultiRead, lockMultiWrite);
return assignCopyImpl(_source);
} else {
std::unique_lock<std::mutex> lockReadS(_source.syncRead, std::defer_lock); // utilize std::lock(r, w), allowing mixed order waiting on read/write ops
std::unique_lock<std::mutex> lockWriteS(_source.syncWrite, std::defer_lock); // otherwise RAII-style relinquish via destructor
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockReadS, lockWriteS, lockRead, lockWrite);
return assignCopyImpl(_source);
}
}
ringbuffer(ringbuffer &&o) noexcept = default;
ringbuffer& operator=(ringbuffer &&o) noexcept = default;
/**
* Return whether multiple producer and consumer are enabled,
* see @ref ringbuffer_multi_pc and @ref ringbuffer_single_pc.
*
* Defaults to `false`.
* @see @ref ringbuffer_multi_pc
* @see @ref ringbuffer_single_pc
* @see getMultiPCEnabled()
* @see setMultiPCEnabled()
*/
constexpr bool getMultiPCEnabled() const { return multi_pc_enabled; }
/**
* Enable or disable capability to handle multiple producer and consumer,
* see @ref ringbuffer_multi_pc and @ref ringbuffer_single_pc.
*
* Defaults to `false`.
* @see @ref ringbuffer_multi_pc
* @see @ref ringbuffer_single_pc
* @see getMultiPCEnabled()
* @see setMultiPCEnabled()
*/
constexpr_non_literal_var void setMultiPCEnabled(const bool v) {
/**
* Using just 'constexpr_non_literal_var' because
* clang: 'unique_lock<std::mutex>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
*/
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockMultiRead, lockMultiWrite, lockRead, lockWrite);
multi_pc_enabled=v;
} else {
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockRead, lockWrite);
multi_pc_enabled=v;
}
}
/** Returns the net capacity of this ring buffer. */
Size_type capacity() const noexcept { return capacityPlusOne - 1; }
/** Returns the number of free slots available to put. */
Size_type freeSlots() const noexcept { return capacityPlusOne - 1 - size(); }
/** Returns true if this ring buffer is empty, otherwise false. */
bool isEmpty() const noexcept { return writePos == readPos; /* 0 == size */ }
/** Returns true if this ring buffer is full, otherwise false. */
bool isFull() const noexcept {
return ( writePos + 1 ) % capacityPlusOne == readPos; /* W == R - 1 */ // NOLINT(clang-analyzer-core.DivideZero): always capacityPlusOne > 0
}
/** Returns the number of elements in this ring buffer. */
Size_type size() const noexcept {
const Size_type R = readPos;
const Size_type W = writePos;
// W >= R: W - R
// W < R: C+1 - R - 1 + W + 1 = C+1 - R + W
return W >= R ? W - R : capacityPlusOne - R + W;
}
/**
* Blocks until at least `count` elements have been put
* for subsequent get() and getBlocking().
*
* @param min_count minimum number of put slots
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return the number of put elements, available for get() and getBlocking()
*/
[[nodiscard]] Size_type waitForElements(const Size_type min_count, const fraction_i64& timeout, bool& timeout_occured) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return waitForElementsImpl(min_count, timeout, timeout_occured);
} else {
return waitForElementsImpl(min_count, timeout, timeout_occured);
}
}
/**
* Blocks until at least `count` free slots become available
* for subsequent put() and putBlocking().
*
* @param min_count minimum number of free slots
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return the number of free slots, available for put() and putBlocking()
*/
[[nodiscard]] Size_type waitForFreeSlots(const Size_type min_count, const fraction_i64& timeout, bool& timeout_occured) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return waitForFreeSlotsImpl(min_count, timeout, timeout_occured);
} else {
return waitForFreeSlotsImpl(min_count, timeout, timeout_occured);
}
}
/**
* Releasing all elements available, i.e. size() at the time of the call
*
* It is the user's obligation to ensure thread safety when using @ref ringbuffer_single_pc,
* as implementation can only synchronize on the blocked put() and get() std::mutex.
*
* Assuming no concurrent put() operation, after the call:
* - {@link #isEmpty()} will return `true`
* - {@link #size()} shall return `0`
*
* @param zeromem pass true to zero ringbuffer memory after releasing elements, otherwise non template type parameter use_secmem determines the behavior (default), see @ref ringbuffer_ntt_params.
* @see @ref ringbuffer_ntt_params
*/
void clear(const bool zeromem=false) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockMultiRead, lockMultiWrite, lockRead, lockWrite);
if( zeromem ) {
clearAndZeroMemImpl();
} else {
clearImpl();
}
} else {
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockRead, lockWrite);
if( zeromem ) {
clearAndZeroMemImpl();
} else {
clearImpl();
}
}
cvRead.notify_all(); // notify waiting writer, have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
}
/**
* Close this ringbuffer by releasing all elements available
* and resizing capacity to zero.
* Essentially causing all read and write operations to fail.
*
* Potential writer and reader thread will be
* - notified, allowing them to be woken up
* - interrupted to abort the write and read operation
*
* Subsequent write and read operations will fail and not block.
*
* After the call:
* - {@link #isEmpty()} will return `true`
* - {@link #size()} shall return `0`
* - {@link #capacity()} shall return `0`
* - {@link #freeSlots()} shall return `0`
*/
void close(const bool zeromem=false) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockMultiRead, lockMultiWrite, lockRead, lockWrite);
closeImpl(zeromem);
interrupted_read = true;
interrupted_write = true;
end_of_input = true;
} else {
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockRead, lockWrite);
closeImpl(zeromem);
interrupted_write = true;
interrupted_read = true;
end_of_input = true;
}
// have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
cvRead.notify_all(); // notify waiting writer
cvWrite.notify_all(); // notify waiting reader
}
/**
* Clears all elements and add all `copyFrom` elements thereafter, as if reconstructing this ringbuffer instance.
*
* It is the user's obligation to ensure thread safety when using @ref ringbuffer_single_pc,
* as implementation can only synchronize on the blocked put() and get() std::mutex.
*
* @param copyFrom Mandatory array w/ length {@link #capacity()} to be copied into the internal array.
*
* @see getMultiPCEnabled()
* @see setMultiPCEnabled()
* @see @ref ringbuffer_multi_pc
* @see @ref ringbuffer_single_pc
*/
void reset(const Value_type * copyFrom, const Size_type copyFromCount) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockMultiRead, lockMultiWrite, lockRead, lockWrite);
resetImpl(copyFrom, copyFromCount);
} else {
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockRead, lockWrite);
resetImpl(copyFrom, copyFromCount);
}
}
/**
* Clears all elements and add all `copyFrom` elements thereafter, as if reconstructing this ringbuffer instance.
*
* It is the user's obligation to ensure thread safety when using @ref ringbuffer_single_pc,
* as implementation can only synchronize on the blocked put() and get() std::mutex.
*
* @param copyFrom
*
* @see getMultiPCEnabled()
* @see setMultiPCEnabled()
* @see @ref ringbuffer_multi_pc
* @see @ref ringbuffer_single_pc
*/
void reset(const std::vector<Value_type> & copyFrom) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockMultiRead, lockMultiWrite, lockRead, lockWrite);
resetImpl(copyFrom.data(), copyFrom.size());
} else {
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockRead, lockWrite);
resetImpl(copyFrom.data(), copyFrom.size());
}
}
/**
* Resizes this ring buffer's capacity.
*
* New capacity must be greater than current size.
*
* It is the user's obligation to ensure thread safety when using @ref ringbuffer_single_pc,
* as implementation can only synchronize on the blocked put() and get() std::mutex.
*
* @param newCapacity
*
* @see getMultiPCEnabled()
* @see setMultiPCEnabled()
* @see @ref ringbuffer_multi_pc
* @see @ref ringbuffer_single_pc
*/
void recapacity(const Size_type newCapacity) {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock);
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockMultiRead, lockMultiWrite, lockRead, lockWrite);
recapacityImpl(newCapacity);
} else {
std::unique_lock<std::mutex> lockRead(syncRead, std::defer_lock); // same for *this instance!
std::unique_lock<std::mutex> lockWrite(syncWrite, std::defer_lock);
std::lock(lockRead, lockWrite);
recapacityImpl(newCapacity);
}
}
/**
* Interrupt a potentially blocked reader once.
*
* Call this method to unblock a potentially blocked reader thread once.
*/
void interruptReader() noexcept { interrupted_read = true; cvWrite.notify_all(); }
/**
* Set `End of Input` from writer thread, unblocking all read-operations and a potentially currently blocked reader thread.
*
* Call this method with `true` after concluding writing input data will unblock all read-operations from this point onwards.
* A potentially currently blocked reader thread is also interrupted and hence unblocked.
*/
void set_end_of_input(const bool v=true) noexcept {
end_of_input = v;
if( v ) {
cvWrite.notify_all();
}
}
/**
* Interrupt a potentially blocked writer once.
*
* Call this method to unblock a potentially blocked writer thread once.
*/
void interruptWriter() noexcept { interrupted_write = true; cvRead.notify_all(); }
/**
* Peeks the next element at the read position w/o modifying pointer, nor blocking.
*
* Method is non blocking and returns immediately;.
*
* @param result storage for the resulting value if successful, otherwise unchanged.
* @return true if successful, otherwise false.
*/
[[nodiscard]] bool peek(Value_type& result) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return peekImpl(result, false, fractions_i64::zero, timeout_occured_dummy);
} else {
return peekImpl(result, false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Peeks the next element at the read position w/o modifying pointer, but with blocking.
*
* @param result storage for the resulting value if successful, otherwise unchanged.
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return true if successful, otherwise false.
*/
[[nodiscard]] bool peekBlocking(Value_type& result, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return peekImpl(result, true, timeout, timeout_occurred);
} else {
return peekImpl(result, true, timeout, timeout_occurred);
}
}
/**
* Peeks the next element at the read position w/o modifying pointer, but with blocking.
*
* @param result storage for the resulting value if successful, otherwise unchanged.
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return true if successful, otherwise false.
*/
[[nodiscard]] bool peekBlocking(Value_type& result, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return peekBlocking(result, timeout, timeout_occurred);
}
/**
* Dequeues the oldest enqueued element, if available.
*
* The ring buffer slot will be released and its value moved to the caller's `result` storage, if successful.
*
* Method is non blocking and returns immediately;.
*
* @param result storage for the resulting value if successful, otherwise unchanged.
* @return true if successful, otherwise false.
*/
[[nodiscard]] bool get(Value_type& result) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return moveOutImpl(result, false, fractions_i64::zero, timeout_occured_dummy);
} else {
return moveOutImpl(result, false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Dequeues the oldest enqueued element.
*
* The ring buffer slot will be released and its value moved to the caller's `result` storage, if successful.
*
* @param result storage for the resulting value if successful, otherwise unchanged.
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return true if successful, otherwise false.
*/
[[nodiscard]] bool getBlocking(Value_type& result, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return moveOutImpl(result, true, timeout, timeout_occurred);
} else {
return moveOutImpl(result, true, timeout, timeout_occurred);
}
}
/**
* Dequeues the oldest enqueued element.
*
* The ring buffer slot will be released and its value moved to the caller's `result` storage, if successful.
*
* @param result storage for the resulting value if successful, otherwise unchanged.
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return true if successful, otherwise false.
*/
[[nodiscard]] bool getBlocking(Value_type& result, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return getBlocking(result, timeout, timeout_occurred);
}
/**
* Dequeues the oldest enqueued `min(dest_len, size()>=min_count)` elements by copying them into the given consecutive 'dest' storage.
*
* The ring buffer slots will be released and its value moved to the caller's `dest` storage, if successful.
*
* Method is non blocking and returns immediately;.
*
* @param dest pointer to first storage element of `dest_len` consecutive elements to store the values, if successful.
* @param dest_len number of consecutive elements in `dest`, hence maximum number of elements to return.
* @param min_count minimum number of consecutive elements to return.
* @return actual number of elements returned
*/
[[nodiscard]] Size_type get(Value_type *dest, const Size_type dest_len, const Size_type min_count) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return moveOutImpl(dest, dest_len, min_count, false, fractions_i64::zero, timeout_occured_dummy);
} else {
return moveOutImpl(dest, dest_len, min_count, false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Dequeues the oldest enqueued `min(dest_len, size()>=min_count)` elements by copying them into the given consecutive 'dest' storage.
*
* The ring buffer slots will be released and its value moved to the caller's `dest` storage, if successful.
*
* @param dest pointer to first storage element of `dest_len` consecutive elements to store the values, if successful.
* @param dest_len number of consecutive elements in `dest`, hence maximum number of elements to return.
* @param min_count minimum number of consecutive elements to return
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return actual number of elements returned
*/
[[nodiscard]] Size_type getBlocking(Value_type *dest, const Size_type dest_len, const Size_type min_count, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead); // acquire syncMultiRead, _not_ sync'ing w/ putImpl
return moveOutImpl(dest, dest_len, min_count, true, timeout, timeout_occurred);
} else {
return moveOutImpl(dest, dest_len, min_count, true, timeout, timeout_occurred);
}
}
/**
* Dequeues the oldest enqueued `min(dest_len, size()>=min_count)` elements by copying them into the given consecutive 'dest' storage.
*
* The ring buffer slots will be released and its value moved to the caller's `dest` storage, if successful.
*
* @param dest pointer to first storage element of `dest_len` consecutive elements to store the values, if successful.
* @param dest_len number of consecutive elements in `dest`, hence maximum number of elements to return.
* @param min_count minimum number of consecutive elements to return
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return actual number of elements returned
*/
[[nodiscard]] Size_type getBlocking(Value_type *dest, const Size_type dest_len, const Size_type min_count, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return getBlocking(dest, dest_len, min_count, timeout, timeout_occurred);
}
/**
* Drops up to `max_count` oldest enqueued elements,
* but may drop less if not available.
*
* Method is non blocking and returns immediately;.
*
* @param max_count maximum number of elements to drop from ringbuffer.
* @return number of elements dropped
*/
Size_type drop(const Size_type max_count) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // utilize std::lock(r, w), allowing mixed order waiting on read/write ops
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock); // otherwise RAII-style relinquish via destructor
std::lock(lockMultiRead, lockMultiWrite);
return dropImpl(max_count, false, fractions_i64::zero, timeout_occured_dummy);
} else {
return dropImpl(max_count, false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Drops exactly `count` oldest enqueued elements,
* will block until they become available.
*
* In `count` elements are not available to drop even after
* blocking for `timeoutMS`, no element will be dropped.
*
* @param count number of elements to drop from ringbuffer.
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return true if successful, otherwise false
*/
bool dropBlocking(const Size_type count, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiRead(syncMultiRead, std::defer_lock); // utilize std::lock(r, w), allowing mixed order waiting on read/write ops
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite, std::defer_lock); // otherwise RAII-style relinquish via destructor
std::lock(lockMultiRead, lockMultiWrite);
return 0 != dropImpl(count, true, timeout, timeout_occurred);
} else {
return 0 != dropImpl(count, true, timeout, timeout_occurred);
}
}
/**
* Drops exactly `count` oldest enqueued elements,
* will block until they become available.
*
* In `count` elements are not available to drop even after
* blocking for `timeoutMS`, no element will be dropped.
*
* @param count number of elements to drop from ringbuffer.
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return true if successful, otherwise false
*/
bool dropBlocking(const Size_type count, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return dropBlocking(count, timeout, timeout_occurred);
}
/**
* Enqueues the given element by moving it into this ringbuffer storage.
*
* Returns true if successful, otherwise false in case buffer is full.
*
* Method is non blocking and returns immediately;.
*
* @param e value to be moved into this ringbuffer
* @return true if successful, otherwise false
*/
[[nodiscard]] bool put(Value_type && e) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return moveIntoImpl(std::move(e), false, fractions_i64::zero, timeout_occured_dummy);
} else {
return moveIntoImpl(std::move(e), false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Enqueues the given element by moving it into this ringbuffer storage.
*
* @param e value to be moved into this ringbuffer
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return true if successful, otherwise false in case timeout occurred or otherwise.
*/
[[nodiscard]] bool putBlocking(Value_type && e, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return moveIntoImpl(std::move(e), true, timeout, timeout_occurred);
} else {
return moveIntoImpl(std::move(e), true, timeout, timeout_occurred);
}
}
/**
* Enqueues the given element by moving it into this ringbuffer storage.
*
* @param e value to be moved into this ringbuffer
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return true if successful, otherwise false in case timeout occurred or otherwise.
*/
[[nodiscard]] bool putBlocking(Value_type && e, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return putBlocking(std::move(e), timeout, timeout_occurred);
}
/**
* Enqueues the given element by copying it into this ringbuffer storage.
*
* Returns true if successful, otherwise false in case buffer is full.
*
* Method is non blocking and returns immediately;.
*
* @return true if successful, otherwise false
*/
[[nodiscard]] bool put(const Value_type & e) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return copyIntoImpl(e, false, fractions_i64::zero, timeout_occured_dummy);
} else {
return copyIntoImpl(e, false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Enqueues the given element by copying it into this ringbuffer storage.
*
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return true if successful, otherwise false in case timeout occurred or otherwise.
*/
[[nodiscard]] bool putBlocking(const Value_type & e, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return copyIntoImpl(e, true, timeout, timeout_occurred);
} else {
return copyIntoImpl(e, true, timeout, timeout_occurred);
}
}
/**
* Enqueues the given element by copying it into this ringbuffer storage.
*
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return true if successful, otherwise false in case timeout occurred or otherwise.
*/
[[nodiscard]] bool putBlocking(const Value_type & e, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return putBlocking(e, timeout, timeout_occurred);
}
/**
* Enqueues the given range of consecutive elements by copying it into this ringbuffer storage.
*
* Returns true if successful, otherwise false in case buffer is full.
*
* Method is non blocking and returns immediately;.
*
* @param first pointer to first consecutive element to range of value_type [first, last)
* @param last pointer to last consecutive element to range of value_type [first, last)
* @return true if successful, otherwise false
*/
[[nodiscard]] bool put(const Value_type *first, const Value_type* last) noexcept {
bool timeout_occured_dummy;
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return copyIntoImpl(first, last, false, fractions_i64::zero, timeout_occured_dummy);
} else {
return copyIntoImpl(first, last, false, fractions_i64::zero, timeout_occured_dummy);
}
}
/**
* Enqueues the given range of consecutive elementa by copying it into this ringbuffer storage.
*
* @param first pointer to first consecutive element to range of value_type [first, last)
* @param last pointer to last consecutive element to range of value_type [first, last)
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @param timeout_occurred result value set to true if a timeout has occurred
* @return true if successful, otherwise false in case timeout occurred or otherwise.
*/
[[nodiscard]] bool putBlocking(const Value_type *first, const Value_type* last, const fraction_i64& timeout, bool& timeout_occurred) noexcept {
if( multi_pc_enabled ) {
std::unique_lock<std::mutex> lockMultiWrite(syncMultiWrite); // acquire syncMultiWrite, _not_ sync'ing w/ getImpl
return copyIntoImpl(first, last, true, timeout, timeout_occurred);
} else {
return copyIntoImpl(first, last, true, timeout, timeout_occurred);
}
}
/**
* Enqueues the given range of consecutive elementa by copying it into this ringbuffer storage.
*
* @param first pointer to first consecutive element to range of value_type [first, last)
* @param last pointer to last consecutive element to range of value_type [first, last)
* @param timeout maximum duration in fractions of seconds to wait, where fractions_i64::zero waits infinitely
* @return true if successful, otherwise false in case timeout occurred or otherwise.
*/
[[nodiscard]] bool putBlocking(const Value_type *first, const Value_type* last, const fraction_i64& timeout) noexcept {
bool timeout_occurred;
return putBlocking(first, last, timeout, timeout_occurred);
}
};
/**@}*/
} /* namespace jau */
/** \example test_lfringbuffer01.cpp
* This C++ unit test validates jau::ringbuffer w/o parallel processing.
* <p>
* With test_lfringbuffer11.cpp, this work verifies jau::ringbuffer correctness
* </p>
*/
/** \example test_lfringbuffer11.cpp
* This C++ unit test validates jau::ringbuffer with parallel processing.
* <p>
* With test_lfringbuffer01.cpp, this work verifies jau::ringbuffer correctness
* </p>
*/
#endif /* JAU_RINGBUFFER_HPP_ */
|