shared-buffer-rs 0.3.1

A library which combines Arc and RefCell for Send and Sync
Documentation
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
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
/*-
 * shared-buffer-rs - a buffer managment and sharing crate.
 * 
 * Copyright (C) 2025 Aleksandr Morozov
 * 
 * The scram-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

/*! A small crate which implements a thread safe implementation to allocate
 the buffer of some size, borrow as muable in current context or thread
 and borrow as many read only references as needed which are Send+Sync.

 It acts like Arc but embeds the RefCell functionality without any
 issues with Send and Sync.

 The main purpose it to have a lock free, lightweight buffer I/O for
 writing in one side and broadcast to multiple tasks i.e threads and
 async task making sure that it can not be modifyied.
 */

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;


#[cfg(not(feature = "std"))]
use core::
{
    fmt, 
    mem, 
    ops::{Deref, DerefMut}, 
    ptr::{self, NonNull}, 
    sync::atomic::{AtomicU64, Ordering}
};

#[cfg(not(feature = "std"))]
use core::{marker::PhantomData, task::Poll, time::Duration};

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, collections::vec_deque::VecDeque, vec::Vec};

#[cfg(not(feature = "std"))]
use alloc::vec;
use crossbeam_utils::Backoff;

#[cfg(feature = "std")]
use std::
{
    collections::VecDeque, 
    ops::{Deref, DerefMut}, 
    ptr::{self, NonNull}, 
    sync::atomic::{AtomicU64, Ordering},
    fmt,
    mem
};

#[cfg(feature = "std")]
use std::{marker::PhantomData, task::Poll, time::Duration};

extern crate crossbeam_utils;

pub trait TryClone: Sized 
{
    type Error;

    fn try_clone(&self) -> Result<Self, Self::Error>;
}

/// An implementation of the `async_drop` for async.
trait LocalAsyncDrop: Send + Sync + 'static
{
    async fn async_drop(&mut self);
}

/// Use this function to drop [RBuffer] and [WBuffer] obtained via
/// `async_*`.
async 
fn async_drop<LAD: LocalAsyncDrop + Send + Sync>(mut lad: LAD)
{
    lad.async_drop().await;

    drop(lad);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RwBufferError
{
    TooManyRead,
    TooManyBase,
    ReadTryAgianLater,
    WriteTryAgianLater,
    BaseTryAgainLater,
    OutOfBuffers,
    DowngradeFailed,
    InvalidArguments,
    Busy,
}

impl fmt::Display for RwBufferError
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            Self::TooManyRead => 
                write!(f, "TooManyRead: read soft limit reached"),
            Self::TooManyBase => 
                write!(f, "TooManyBase: base soft limit reached"),
            Self::ReadTryAgianLater => 
                write!(f, "ReadTryAgianLater: shared access not available, try again later"),
            Self::WriteTryAgianLater => 
                write!(f, "WriteTryAgianLater: exclusive access not available, try again later"),
            Self::BaseTryAgainLater => 
                write!(f, "BaseTryAgainLater: failed to obtain a clone in reasonable time"),
            Self::OutOfBuffers => 
                write!(f, "OutOfBuffers: no more free bufers are left"),
            Self::DowngradeFailed => 
                write!(f, "DowngradeFailed: can not downgrade exclusive to shared, race condition"),
            Self::InvalidArguments => 
                write!(f, "InvalidArguments: arguments are not valid"),  
            Self::Busy => 
                write!(f, "RwBuffer is busy and cannot be acquired"),       
        }
    }
}

pub type RwBufferRes<T> = Result<T, RwBufferError>;

/// A read only buffer. This instance is [Send] and [Sync]
/// as it does not provide any write access.
#[derive(Debug, PartialEq, Eq)]
pub struct RBuffer
{
    /// The inner read only
    inner: NonNull<RwBufferInner>,

    /// Is set to `true` when async_drop was performed earlier.
    a_dropped: bool,
}

unsafe impl Send for RBuffer {}
unsafe impl Sync for RBuffer {}

impl RwBufType for RBuffer {}

impl RBuffer
{
    #[inline]
    fn new(inner: NonNull<RwBufferInner>) -> Self
    {
        return Self{ inner, a_dropped: false };
    }

    #[cfg(test)]
    fn get_flags(&self) -> RwBufferFlags<Self>
    {
        use core::sync::atomic::Ordering;

        let inner = unsafe{ self.inner.as_ref() };

        let flags: RwBufferFlags<Self> = inner.flags.load(Ordering::Relaxed).into();

        return flags;
    }

    /// Borrow the inner buffer as slice.
    pub
    fn as_slice(&self) -> &[u8]
    {
        let inner = unsafe { self.inner.as_ref() };

        return inner.buf.as_ref().unwrap().as_slice();
    }

    /// Attempts to consume the instance and retrive the inner buffer. This means
    /// that the instance will no longer be available.
    ///
    /// The following condition should be satisfied:
    /// 1) No more readers except current instance.
    ///
    /// 2) No base references, item should not contain base references from [RwBuffer].
    /// 
    /// # Returns
    /// 
    /// A [Result] is returned with: 
    /// 
    /// * [Result::Ok] with the consumed inner [Vec]
    /// 
    /// * [Result::Err] with the consumed instance
    pub
    fn try_inner(mut self) -> Result<Vec<u8>, Self>
    {
        let inner = unsafe { self.inner.as_ref() };

        let current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();

       // new_flags.unread();

        if current_flags.try_inner_check() == true
        {
            // in theory if at that moment only one read operation left, then no other can occure
            // because the current_flags are obtained with SeqCst, and no read can appear

            let inner = unsafe { self.inner.as_mut() };

            let buf = inner.buf.take().unwrap();
        
            drop(self);

            return Ok(buf);
        }

        return Err(self);        
    }

    fn inner(&self) -> &RwBufferInner
    {
        return unsafe { self.inner.as_ref() };
    }
}

impl LocalAsyncDrop for RBuffer
{
    async fn async_drop(&mut self) 
    {
        self.a_dropped = true;

        std::future::poll_fn(
            |cx|
            {
                let inner = self.inner();

                let current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
                let mut new_flags = current_flags.clone();

                new_flags.unread();

                let res = 
                    inner
                        .flags
                        .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

                if let Ok(flags) = res.map(|v| <u64 as Into<RwBufferFlags<Self>>>::into(v))
                {
                    if flags.is_drop_inplace() == true
                    {
                        // call descrutor
                        unsafe { ptr::drop_in_place(self.inner.as_ptr()) };
                    }

                    return Poll::Ready(());
                }

                cx.waker().wake_by_ref();

                return Poll::Pending;
            }
        )
        .await;
    }
}

impl Deref for RBuffer
{
    type Target = Vec<u8>;

    fn deref(&self) -> &Vec<u8>
    {
        let inner = self.inner();

        return inner.buf.as_ref().unwrap();
    }
}

impl Clone for RBuffer
{
    /// Attempts to clone the RBuffer incrementing the `read` reference. 
    /// Would block until the clone is obtained. Should not block for long 
    /// time. Because this crate is experimental, it will panic if it will
    /// not be able to obtain clone.
    /// 
    /// # Returns 
    /// 
    /// Returns the new [RBuffer] instance.
    /// 
    /// # Panic
    /// 
    /// Panics if too many references were created. The reference count
    /// is limited to max::u32 - 10. Or will panic if will not be able to obtain 
    /// a clone of the [RBuffer] in reasonable time as this must not block
    /// for a long time.
    fn clone(&self) -> Self 
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.read().unwrap();

        let backoff = Backoff::new();
        let mut parked = false;

        loop
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                return Self{ inner: self.inner, a_dropped: self.a_dropped };
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.read().unwrap();

            if backoff.is_completed() == false
            {
                backoff.snooze();
            }
            else
            {
                if parked == false
                {
                    // last attempt
                    std::thread::park_timeout(Duration::from_millis(1));

                    parked = true;
                }
                else
                {
                    panic!("can not obtain a clone of RBuffer!");
                }
            }
        }
    }
}

impl TryClone for RBuffer
{
    type Error = RwBufferError;

    /// Attempts to clone the RBuffer incrementing the `read` reference.
    /// 
    /// # Returns 
    /// 
    /// Returns the new [Result] where on success a clone of [RBuffer] instance is
    /// returned, otherwise the:
    /// 
    /// * [RwBufferError::ReadTryAgianLater] - is returned if it failed to acquire the read clone
    ///     in reasonable time.
    /// 
    /// * [RwBufferError::TooManyRead] - is returned if limit was reached.
    fn try_clone(&self) -> Result<Self, Self::Error> 
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.read()?;

        let backoff = Backoff::new();

        loop
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                return Ok(Self{ inner: self.inner, a_dropped: self.a_dropped });
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.read()?;

            if backoff.is_completed() == false
            {
                backoff.snooze();
            }
            else
            {
                break;
            }
        }

        return Err(RwBufferError::ReadTryAgianLater);
    }
}

impl Drop for RBuffer
{
    /// Should completly drop the instance (with data) only, if there is no more
    /// readers or it is not referenced in the base.
    /// 
    /// # Panic
    /// 
    /// May panic if it will not be able to drop the instance in reasonable time i.e in 
    /// 1000 attempts.
    fn drop(&mut self)
    {
        if self.a_dropped == true
        {
            return;
        }

        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.unread();

        let backoff = Backoff::new();
        
        for _ in 0..1000
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(flags) = res.map(|v| <u64 as Into<RwBufferFlags<Self>>>::into(v))
            {
                if flags.is_drop_inplace() == true
                {
                    // call descrutor
                    unsafe { ptr::drop_in_place(self.inner.as_ptr()) };
                }

                return;
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.unread();

            backoff.snooze();
        }

        // todo... solve this situation somehow
        panic!("assertion trap: RBuffer::drop can not drop RBuffer in reasonable time!");
    }
}

/// A Write and Read buffer. An exclusive instance which can not be copied or
/// clonned. Once writing is complete, the instance can be dropped or downgraded to
/// Read-only instance. This instance is NOT [Send] and [Sync]. 
#[derive(Debug, PartialEq, Eq)]
pub struct WBuffer
{
    /// A pointer to the leaked buffer instance.
    buf: NonNull<RwBufferInner>,

    /// Is set to `true` when `downgrade` is called.
    downgraded: bool,
}

unsafe impl Send for WBuffer{}
unsafe impl Sync for WBuffer{}

impl RwBufType for WBuffer{}

impl WBuffer
{
    #[inline]
    fn new(inner: NonNull<RwBufferInner>) -> Self
    {
        return Self{ buf: inner, downgraded: false };
    }

    /// Attempts to downgrade the `write` instance into the `read` instance by consuming the
    /// [WBuffer]. 
    /// 
    /// Can not be performed vice-versa (at least in this version). In normal conditions
    /// should never return Error.
    /// 
    /// # Returns 
    /// 
    /// A [Result] is returned with the [RBuffer] on success. The [Result::Err] is returned 
    /// if it failed to downgrade instance in resonable time.
    pub
    fn downgrade(mut self) ->  Result<RBuffer, Self>
    {
        let inner = unsafe { self.buf.as_ref() };

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.downgrade();

        let backoff = Backoff::new();

        while backoff.is_completed() == false
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                self.downgraded = true;

                return Ok(RBuffer::new(self.buf.clone()));
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.downgrade();

            backoff.snooze();
        }

        return Err(self);
    }

    pub
    fn as_slice(&self) -> &[u8]
    {
        let inner = unsafe { self.buf.as_ref() };

        return inner.buf.as_ref().unwrap()
    }
}

impl Deref for WBuffer
{
    type Target = Vec<u8>;

    fn deref(&self) -> &Vec<u8>
    {
        let inner = unsafe { self.buf.as_ref() };

        return inner.buf.as_ref().unwrap();
    }
}

impl DerefMut for WBuffer
{
    fn deref_mut(&mut self) -> &mut Vec<u8>
    {
        let inner = unsafe { self.buf.as_mut() };

        return inner.buf.as_mut().unwrap();
    }
}

impl Drop for WBuffer
{
    /// The instance may perform `drop_in_place` if there is no `base` references.
    fn drop(&mut self)
    {
        if self.downgraded == true
        {
            return;
        }

        let inner = unsafe { self.buf.as_ref() };

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.unwrite();

        let backoff = Backoff::new();

        for _ in 0..1000
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(flags) = res.map(|v| <u64 as Into<RwBufferFlags<Self>>>::into(v))
            {
                if flags.is_drop_inplace() == true
                {
                    // call descrutor
                    unsafe { ptr::drop_in_place(self.buf.as_ptr()) };
                }

                return;
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.unwrite();

            backoff.snooze();
        }

        // todo... solve this situation somehow

        panic!("assertion trap: WBuffer::drop can not drop RBuffer in reasonable time!");
    }
}

impl LocalAsyncDrop for WBuffer
{
    async 
    fn async_drop(&mut self) 
    {
        self.downgraded = true;

        std::future::poll_fn(
            move |cx|
            {
                let inner = unsafe { self.buf.as_ref() };

                let current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
                let mut new_flags = current_flags.clone();

                new_flags.unwrite();

                let res = 
                    inner
                        .flags
                        .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

                if let Ok(flags) = res.map(|v| <u64 as Into<RwBufferFlags<Self>>>::into(v))
                {
                    if flags.is_drop_inplace() == true
                    {
                        // call descrutor
                        unsafe { ptr::drop_in_place(self.buf.as_ptr()) };
                    }

                    return Poll::Ready(());
                }

                cx.waker().wake_by_ref();

                return Poll::Pending;
            }
        )
        .await;
    }
}

trait RwBufType {}

/// Internal structure which represents the status. It can not be
/// larger than 8-byte to fit into [AtomicU64].
#[repr(align(8))]
#[derive(Debug, PartialEq, Eq)]
struct RwBufferFlags<TP>
{
    /// A reader refs counter. If larger than 0, no writes possible.
    read: u32, // = 4

    /// An exclusive write lock. When true, no reades should present.
    write: bool, // = 1

    /// A base refs i.e which holds the data.
    /// If this value is zero, means the instance can be dropped in place
    /// when `write` is false and `read` equals 0.
    base: u16, // = 2

    /// Unused
    unused0: u8, // = 1,

    _p: PhantomData<TP>,
}


impl<TP: RwBufType> From<u64> for RwBufferFlags<TP>
{
    fn from(value: u64) -> Self
    {
        return unsafe { mem::transmute(value) };
    }
}

impl<TP: RwBufType> From<RwBufferFlags<TP>> for u64
{
    fn from(value: RwBufferFlags<TP>) -> Self
    {
        return unsafe { mem::transmute(value) };
    }
}

impl<TP: RwBufType> Default for RwBufferFlags<TP>
{
    fn default() -> RwBufferFlags<TP>
    {
        return
            Self
            {
                read: 0,
                write: false,
                base: 1,
                unused0: 0,
                _p: PhantomData
            };
    }
}

impl Copy for RwBufferFlags<WBuffer>{}

impl Clone for RwBufferFlags<WBuffer>
{
    fn clone(&self) -> Self 
    {
        return 
            Self 
            { 
                read: self.read.clone(), 
                write: self.write.clone(), 
                base: self.base.clone(), 
                unused0: self.unused0.clone(), 
                _p: PhantomData
            }
    }
}

impl Copy for RwBufferFlags<RBuffer>{}

impl Clone for RwBufferFlags<RBuffer>
{
    fn clone(&self) -> Self 
    {
        return 
            Self 
            { 
                read: self.read.clone(), 
                write: self.write.clone(), 
                base: self.base.clone(), 
                unused0: self.unused0.clone(), 
                _p: PhantomData
            }
    }
}

impl Copy for RwBufferFlags<RwBuffer>{}

impl Clone for RwBufferFlags<RwBuffer>
{
    fn clone(&self) -> Self 
    {
        return 
            Self 
            { 
                read: self.read.clone(), 
                write: self.write.clone(), 
                base: self.base.clone(), 
                unused0: self.unused0.clone(), 
                _p: PhantomData
            }
    }
}

impl RwBufferFlags<WBuffer>
{
    #[inline]
    fn write(&mut self) -> RwBufferRes<()>
    {
        if self.read == 0
        {
            self.write = true;

            return Ok(());
        }
        else
        {
            return Err(RwBufferError::WriteTryAgianLater);
        }
    }

    #[inline]
    fn downgrade(&mut self) 
    {
        self.write = false;
        self.read += 1;
    }

     #[inline]
    fn unwrite(&mut self)
    {
        self.write = false;
    }
}

impl RwBufferFlags<RBuffer>
{
    #[inline]
    fn try_inner_check(&self) -> bool
    {
        return self.read == 1 && self.write == false && self.base == 0;
    }

    #[inline]
    fn unread(&mut self)
    {
        self.read -= 1;
    }

    #[inline]
    fn read(&mut self) -> RwBufferRes<()>
    {
        if self.write == false
        {
            self.read += 1;

            if self.read <= Self::MAX_READ_REFS
            {
                return Ok(());
            }
            
            return Err(RwBufferError::TooManyRead);
        }

        return Err(RwBufferError::ReadTryAgianLater);
    }
}

impl RwBufferFlags<RwBuffer>
{
    #[inline]
    fn make_pre_unused() -> Self
    {
        return Self{ read: 0, write: false, base: 1, unused0: 0, _p: PhantomData };
    }

    #[inline]
    fn read(&mut self) -> RwBufferRes<()>
    {
        if self.write == false
        {
            self.read += 1;

            if self.read <= Self::MAX_READ_REFS
            {
                return Ok(());
            }
            
            return Err(RwBufferError::TooManyRead);
        }

        return Err(RwBufferError::ReadTryAgianLater);
    }

    #[inline]
    fn write(&mut self) -> RwBufferRes<()>
    {
        if self.read == 0
        {
            self.write = true;

            return Ok(());
        }
        else
        {
            return Err(RwBufferError::WriteTryAgianLater);
        }
    }
    
    #[inline]
    fn base(&mut self) -> RwBufferRes<()>
    {
        self.base += 1;

        if self.base <= Self::MAX_BASE_REFS
        {
            return Ok(());
        }

        return Err(RwBufferError::TooManyBase);
    }

    #[inline]
    fn unbase(&mut self) -> bool
    {
        self.base -= 1;

        return self.base != 0;
    }
}

impl<TP: RwBufType> RwBufferFlags<TP>
{
    /// A soft limit on the amount of references for reading instances.
    pub const MAX_READ_REFS: u32 = u32::MAX - 2;

    /// A soft limit on the amount of references for base instances.
    pub const MAX_BASE_REFS: u16 = u16::MAX - 2;

    

    #[inline]
    fn is_free(&self) -> bool
    {
        return self.write == false && self.read == 0 && self.base == 1;
    }

   

   

    #[inline]
    fn is_drop_inplace(&self) -> bool
    {
        return self.read == 0 && self.write == false && self.base == 0;
    }

    

    

   
}

#[derive(Debug)]
pub struct RwBufferInner
{
    /// A [RwBufferFlags] represented as atomic u64.
    flags: AtomicU64,

    /// A buffer.
    buf: Option<Vec<u8>>,
}

impl RwBufferInner
{
    fn new(buf_size: usize) -> Self
    {
        return
            Self
            {
                flags: 
                    AtomicU64::new(RwBufferFlags::<RwBuffer>::default().into()),
                buf: 
                    Some(vec![0_u8; buf_size])
            };
    }
}

/// A base instance which holds the `leaked` pointer to [RwBufferInner].
/// 
/// This instance can provide either an exclusive write access or 
/// multiple read access, but not at the same time. Can be used to store
/// the instance. This instance is [Send] and [Sync] because the insternals
/// are guarded by ordered atomic operations.
#[derive(Debug, PartialEq, Eq)]
pub struct RwBuffer(NonNull<RwBufferInner>);

unsafe impl Send for RwBuffer {}
unsafe impl Sync for RwBuffer {}

impl RwBufType for RwBuffer {}

impl RwBuffer
{
    #[inline]
    fn new(buf_size: usize) -> Self
    {
        let status = Box::new(RwBufferInner::new(buf_size));

        return Self(Box::leak(status).into());
    }

    #[inline]
    fn inner(&self) -> &RwBufferInner
    {
        return unsafe { self.0.as_ref() };
    }

    /// Checks if this instance satisfies the following conditions:
    /// 
    /// * No exclusive write access
    /// 
    /// * No read access
    /// 
    /// * There is only one base reference.
    /// 
    /// But since check everything may have been already changed.
    /// 
    /// # Returns 
    /// 
    /// * - `true` if instance satisfies the conditions above.
    /// 
    /// * - `false` if does not satisfy the conditions above.
    #[inline]
    pub
    fn is_free(&self) -> bool
    {
        let inner = self.inner();

        let flags: RwBufferFlags<Self> = inner.flags.load(Ordering::Relaxed).into();

        return flags.is_free();
    }

    /// Accures the instance, if it satisfy the following conditions:
    /// 
    /// * No exclusive write access
    /// 
    /// * No read access
    /// 
    /// * There is only one base reference.
    /// 
    /// # Returns 
    /// 
    /// The [Result] is retuerned with the clonned [RwBuffer] instance or
    /// [Result::Err] with the following errors:
    /// 
    /// * [RwBufferError::Busy] - the instance have already been taken.
    /// 
    /// * [RwBufferError::TooManyBase] - too many base references are already around.
    #[inline]
    pub(crate) 
    fn acqiure_if_free(&self) -> RwBufferRes<Self>
    {
        let inner = self.inner();

        let current_flags: RwBufferFlags<Self> = RwBufferFlags::make_pre_unused();
        let mut new_flags = current_flags.clone();
        
        new_flags.base()?;

        let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

        if let Ok(_) = res
        {
            return Ok(Self(self.0.clone()));
        }

        return Err(RwBufferError::Busy);
    }

    /// Attemts to make an exclusive (write) access to the buffer.
    /// 
    /// Would block for short period of time and return error.
    /// 
    /// # Returns
    /// 
    /// A [Result] in form of [RwBufferRes] is returned with:
    /// 
    /// * [Result::Ok] with the [WBuffer] instance
    /// 
    /// * [Result::Err] may be returned a [RwBufferError::WriteTryAgianLater] in case 
    ///     if the there is/are an active `read` references or acquite exc. lock failed.
    pub
    fn write(&self) -> RwBufferRes<WBuffer>
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.write()?;

        let backoff = Backoff::new();

        while backoff.is_completed() == false
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                return Ok(WBuffer::new(self.0.clone()));
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.write()?;

            backoff.snooze();
        }

        return Err(RwBufferError::WriteTryAgianLater);
    }

    /// Attempts to gain an exclusive access in async way.
    /// 
    /// # Return
    /// 
    /// Return the same result as [RwBuffer::write].
    pub async 
    fn write_async(&self) -> RwBufferRes<WBuffer>
    {
        return 
            std::future::poll_fn(
                |cx|
                {
                    let inner = self.inner();

                    let current_flags: RwBufferFlags<WBuffer> = inner.flags.load(Ordering::SeqCst).into();
                    let mut new_flags = current_flags.clone();

                    if let Err(e) = new_flags.write()
                    {
                        return Poll::Ready(Err(e));
                    }

                    let res = 
                        inner
                            .flags
                            .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

                    if let Ok(_) = res
                    {
                        return Poll::Ready( Ok( WBuffer::new(self.0.clone()) ) );
                    }

                    cx.waker().wake_by_ref();

                    return Poll::Pending;
                }
            )
            .await;
    }
    

    /// Attemts to make a shared (read) access to the buffer.
    /// 
    /// Would block for short period of time and return error.
    /// 
    /// # Returns
    /// 
    /// A [Result] in form of [RwBufferRes] is returned with:
    /// 
    /// * [Result::Ok] with the [RBuffer] instance
    /// 
    /// * [Result::Err] with error type is returned:
    /// 
    /// - [RwBufferError::TooManyRead] is returned when the soft limit of
    ///     references was reached.
    /// 
    /// - [RwBufferError::ReadTryAgianLater] is returned if there is an 
    ///     active exclusive access.
    pub
    fn read(&self) -> RwBufferRes<RBuffer>
    {

        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.read()?;

        let backoff = Backoff::new();

        while backoff.is_completed() == false
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                return Ok(RBuffer::new(self.0.clone()));
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.read()?;

            backoff.snooze();
        }

        return Err(RwBufferError::ReadTryAgianLater);
    }

    /// Attempts to gain an shared access in async way.
    /// 
    /// # Return
    /// 
    /// Return the same result as [RwBuffer::read].
    pub async 
    fn read_async(&self) -> RwBufferRes<RBuffer>
    {
        return 
            std::future::poll_fn(
                |cx|
                {
                    let inner = self.inner();

                    let current_flags: RwBufferFlags<RBuffer> = inner.flags.load(Ordering::SeqCst).into();
                    let mut new_flags = current_flags.clone();

                    match new_flags.read()
                    {
                        Ok(_) => {},
                        Err(RwBufferError::TooManyRead) => 
                            return Poll::Ready(Err(RwBufferError::TooManyRead)),
                        Err(RwBufferError::ReadTryAgianLater) =>
                        {
                            cx.waker().wake_by_ref();

                            return Poll::Pending;
                        },
                        Err(e) =>
                            panic!("assertion trap: unknown error {} in Future for AsyncRBuffer", e)
                    }

                    let res = 
                        inner
                            .flags
                            .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

                    if let Ok(_) = res
                    {
                        return Poll::Ready( Ok( RBuffer::new(self.0.clone()) ) );
                    }

                    cx.waker().wake_by_ref();

                    return Poll::Pending;
                }
            )
            .await;
    }

    #[cfg(test)]
    fn get_flags(&self) -> RwBufferFlags<Self>
    {
        let inner = self.inner();

        let flags: RwBufferFlags<Self> = inner.flags.load(Ordering::Acquire).into();

        return flags;
    }

    /// Clones the freshly created instance which is visible for current thread only!
    /// 
    /// # Returns 
    /// 
    /// A [Result] is returned with error [RwBufferError::TooManyBase] if too many copies 
    /// of base are made.
    fn clone_single(&self) -> RwBufferRes<Self>
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::Relaxed).into();

        current_flags.base()?;

        inner.flags.store(current_flags.into(), Ordering::Relaxed);

        return Ok(Self(self.0));
    }
}

impl Clone for RwBuffer
{
    /// Clones the instance and increasing the `base` ref count.
    /// 
    /// Will `panic` if a soft limit of refs were reached.
    fn clone(&self) -> Self
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.base().unwrap();

        let backoff = Backoff::new();
        let mut parked = false;

        loop
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                return Self(self.0);
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.base().unwrap();

            if backoff.is_completed() == false
            {
                backoff.snooze();
            }
            else
            {
                if parked == false
                {
                    // last attempt
                    std::thread::park_timeout(Duration::from_millis(1));

                    parked = true;
                }
                else
                {
                    panic!("can not obtain a clone of RBuffer!");
                }
            }
        }
    }
}

impl TryClone for RwBuffer
{
    type Error = RwBufferError;

    /// Attempts to clone the [RwBuffer] incrementing the `base` reference.
    /// 
    /// # Returns 
    /// 
    /// Returns the new [Result] where on success a clone of [RBuffer] instance is
    /// returned, otherwise the:
    /// 
    /// * [RwBufferError::BaseTryAgainLater] - is returned if it failed to acquire the base clone
    ///     in reasonable time.
    /// 
    /// * [RwBufferError::TooManyBase] - is returned if limit was reached.
    fn try_clone(&self) -> Result<Self, Self::Error> 
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.base()?;

        let backoff = Backoff::new();

        while backoff.is_completed() == false
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(_) = res
            {
                return Ok(Self(self.0));
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.base()?;

            backoff.snooze();
        }

        return Err(RwBufferError::BaseTryAgainLater);
    }
}

impl Drop for RwBuffer
{
    /// Drops the RwBuffer instance. In case if there is no readers and
    /// writers, then drop immidiatly the inner data.
    /// In case if there is any readers or writing, then drop only wrapper which
    /// is the zero reader.
    fn drop(&mut self)
    {
        let inner = self.inner();

        let mut current_flags: RwBufferFlags<Self> = inner.flags.load(Ordering::SeqCst).into();
        let mut new_flags = current_flags.clone();

        new_flags.unbase();

        let backoff = Backoff::new();

        for _ in 0..1000
        {
            let res = 
                inner
                    .flags
                    .compare_exchange_weak(current_flags.into(), new_flags.into(), Ordering::SeqCst, Ordering::Acquire);

            if let Ok(flags) = res.map(|v| <u64 as Into<RwBufferFlags<Self>>>::into(v))
            {
                if flags.is_drop_inplace() == true
                {
                    // call descrutor
                    unsafe { ptr::drop_in_place(self.0.as_ptr()) };
                }

                return;
            }

            current_flags = res.err().unwrap().into();
            new_flags = current_flags.clone();

            new_flags.unbase();

            backoff.snooze();
        }

        // todo... solve this situation somehow
        panic!("assertion trap: RwBuffer::drop can not drop RwBuffer in reasonable time!");
    }
}

/// An instance which controls the allocation of the new buffers or
/// reusage of already created and free instances. This instance is
/// not thread safe. The external mutex should be used.
#[derive(Debug)]
pub struct RwBuffers
{
    /// A buffer length in bytes. Not aligned.
    buf_len: usize,

    /// A maximum slots for new buffers.
    bufs_cnt_lim: usize,

    /// A list of buffers.
    buffs: VecDeque<RwBuffer>

}

impl RwBuffers
{
    /// Creates new instance wshich holds the base reference in the 
    /// inner storage with the capacity bounds.
    /// 
    /// # Arguments
    /// 
    /// * `buf_len` - a [usize] length of each buffer instance in bytes where
    ///     the payload is located.
    /// 
    /// * `pre_init_cnt` - a [usize] an initial pre allocated slots with created instances.
    /// 
    /// * `bufs_cnt_lim` - a maximum amount of the available slots. Determines the 
    ///     capacity bounds.
    /// 
    /// # Returns
    /// 
    /// A [Result] in form of [RwBufferRes] is returned with:
    /// 
    /// * [Result::Ok] with the [RwBuffers] instance
    /// 
    /// * [Result::Err] with error type is returned:
    /// 
    /// - [RwBufferError::InvalidArguments] is returned when the arguments are
    ///     incorrect. 
    pub
    fn new(buf_len: usize, pre_init_cnt: usize, bufs_cnt_lim: usize) -> RwBufferRes<Self>
    {
        if pre_init_cnt > bufs_cnt_lim
        {
            return Err(RwBufferError::InvalidArguments);
        }
        else if buf_len == 0
        {
            return Err(RwBufferError::InvalidArguments);
        }

        let buffs: VecDeque<RwBuffer> = 
            if pre_init_cnt > 0
            {
                let mut buffs = VecDeque::with_capacity(bufs_cnt_lim);

                for _ in 0..pre_init_cnt
                {
                    buffs.push_back(RwBuffer::new(buf_len));
                }

                buffs
            }
            else
            {
                VecDeque::with_capacity(bufs_cnt_lim)
            };

        return Ok(
            Self
            {
                buf_len: buf_len,
                bufs_cnt_lim: bufs_cnt_lim,
                buffs: buffs,
            }
        )
    }

    /// Same as `new` but without any limits. Unbounded storage.
    /// 
    /// # Arguments
    /// 
    /// * `buf_len` - a [usize] length of each buffer instance in bytes where
    ///     the payload is located.
    /// 
    /// * `pre_init_cnt` - a [usize] an initial pre allocated slots with created instances.
    /// 
    /// # Returns
    /// 
    /// Returns the instance.
    pub
    fn new_unbounded(buf_len: usize, pre_init_cnt: usize) -> Self
    {
        let mut buffs = VecDeque::with_capacity(pre_init_cnt);

        for _ in 0..pre_init_cnt
        {
            buffs.push_back(RwBuffer::new(buf_len));
        }

        return
            Self
            {
                buf_len: buf_len,
                bufs_cnt_lim: 0,
                buffs: buffs,
            };
    }

    /// Allocates either a new buffer or reuse the free. If the instance
    /// is created with bounds then in case if no free slots available
    /// returns error.
    /// 
    /// # Returns
    /// 
    /// A [Result] in form of [RwBufferRes] is returned with:
    /// 
    /// * [Result::Ok] with the [RwBuffers] instance
    /// 
    /// * [Result::Err] with error codes:
    ///  
    /// 
    /// * [RwBufferError::OutOfBuffers] - if limit was reached.
    /// 
    /// * [RwBufferError::TooManyBase] - should not appear, but if would
    ///     it means that there is a bug somewhere in the code.
    pub
    fn allocate(&mut self) -> RwBufferRes<RwBuffer>
    {
        // check the list if any available
        for buf in self.buffs.iter()
        {
            if let Ok(rwbuf) = buf.acqiure_if_free()
            {
                return Ok(rwbuf);
            }
        }

        if self.bufs_cnt_lim == 0 || self.buffs.len() < self.bufs_cnt_lim
        {
            let buf = RwBuffer::new(self.buf_len);
            let c_buf = buf.clone_single()?;

            self.buffs.push_back(buf);

            return Ok(c_buf);
        }

        return Err(RwBufferError::OutOfBuffers);
    }

    /// Allocates a buffer "in place" i.e finds the next allocated but unused
    /// buffer and removes it from the list or alloactes new buffer without
    /// adding it to the list. Should never return error.
    /// 
    /// # Returns
    /// 
    /// A [RwBuffer] is returned.
    pub
    fn allocate_in_place(&mut self) -> RwBuffer
    {
        let mut idx = Option::None;

        for (i, item) in self.buffs.iter().enumerate()
        {
            if let Ok(_) = self.buffs[i].acqiure_if_free()
            {
                idx = Some(i);

                break;
            }
        }

        return 
            idx
                .map_or(
                    RwBuffer::new(self.buf_len), 
                    |f| self.buffs.remove(f).unwrap()
                );

    }

    /// Retains the buffer list by removing any unused buffers as many times
    /// as set in the argument `cnt`. It does not guaranty than the selected 
    /// amount will be freed.
    /// 
    /// # Arguments
    /// 
    /// * `cnt` - how many slots to clean before exit.
    /// 
    /// # Returns 
    /// 
    /// A [usize] is returned which indicates how many instances was removed
    /// before the `cnt` was reached. 
    pub
    fn compact(&mut self, mut cnt: usize) -> usize
    {
        let p_cnt = cnt;

        self
            .buffs
            .retain(
                |buf|
                {
                    if buf.is_free() == true
                    {
                        cnt -= 1;

                        return false;
                    }

                    return true;
                }
            );

        return p_cnt - cnt;
    }

    #[cfg(test)]
    fn get_flags_by_index(&self, index: usize) -> Option<RwBufferFlags<RwBuffer>>
    {
        return Some(self.buffs.get(index)?.get_flags());
    }
}

#[cfg(feature = "std")]
#[cfg(test)]
mod tests
{
    use std::time::{Duration, Instant};

    use tokio::task;

    use super::*;

    #[test]
    fn simple_test()
    {
        let mut bufs = RwBuffers::new(4096, 1, 2).unwrap();

        let buf0_res = bufs.allocate();
        assert_eq!(buf0_res.is_ok(), true, "{:?}", buf0_res.err().unwrap());

        let buf0 = buf0_res.unwrap();

        let buf0_w = buf0.write();
        assert_eq!(buf0_w.is_ok(), true, "{:?}", buf0_w.err().unwrap());
        assert_eq!(buf0.read(), Err(RwBufferError::ReadTryAgianLater));
        drop(buf0_w);

        let buf0_r = buf0.read();
        assert_eq!(buf0_r.is_ok(), true, "{:?}", buf0_r.err().unwrap());
        assert_eq!(buf0.write(), Err(RwBufferError::WriteTryAgianLater));

        let buf0_1 = buf0.clone();
        assert_eq!(buf0_1.write(), Err(RwBufferError::WriteTryAgianLater));

        let flags0 = buf0.get_flags();
        let flags0_1 = buf0_1.get_flags();

        assert_eq!(flags0, flags0_1);
        assert_eq!(flags0.base, 3);
        assert_eq!(flags0.read, 1);
        assert_eq!(flags0.write, false);
    }

    #[test]
    fn simple_test_dopped_in_place()
    {
        let mut bufs = RwBuffers::new(4096, 1, 2).unwrap();

        let buf0_res = bufs.allocate();
        assert_eq!(buf0_res.is_ok(), true, "{:?}", buf0_res.err().unwrap());

        let buf0 = buf0_res.unwrap();

        println!("{:?}", buf0.get_flags());

        let buf0_w = buf0.write();
        assert_eq!(buf0_w.is_ok(), true, "{:?}", buf0_w.err().unwrap());
        assert_eq!(buf0.read(), Err(RwBufferError::ReadTryAgianLater));

        drop(buf0);

        let buf0_flags = bufs.get_flags_by_index(0);
        assert_eq!(buf0_flags.is_some(), true, "no flags");
        let buf0_flags = buf0_flags.unwrap();

        println!("{:?}", buf0_flags);

        assert_eq!(buf0_flags.base, 1);
        assert_eq!(buf0_flags.read, 0);
        assert_eq!(buf0_flags.write, true);

        drop(buf0_w.unwrap());

        let buf0_flags = bufs.get_flags_by_index(0);
        assert_eq!(buf0_flags.is_some(), true, "no flags");
        let buf0_flags = buf0_flags.unwrap();

        println!("{:?}", buf0_flags);

        assert_eq!(buf0_flags.base, 1);
        assert_eq!(buf0_flags.read, 0);
        assert_eq!(buf0_flags.write, false);

    }

    #[test]
    fn simple_test_dropped_in_place_downgrade()
    {
        let mut bufs = RwBuffers::new(4096, 1, 2).unwrap();

        let buf0_res = bufs.allocate();
        assert_eq!(buf0_res.is_ok(), true, "{:?}", buf0_res.err().unwrap());

        let buf0 = buf0_res.unwrap();

        println!("{:?}", buf0.get_flags());

        let buf0_w = buf0.write();
        assert_eq!(buf0_w.is_ok(), true, "{:?}", buf0_w.err().unwrap());
        assert_eq!(buf0.read(), Err(RwBufferError::ReadTryAgianLater));

        drop(buf0);

        let buf0_rd = buf0_w.unwrap().downgrade();
        assert_eq!(buf0_rd.is_ok(), true, "{:?}", buf0_rd.err().unwrap());

        let buf0_flags = bufs.get_flags_by_index(0);
        assert_eq!(buf0_flags.is_some(), true, "no flags");
        let buf0_flags = buf0_flags.unwrap();

        println!("{:?}", buf0_flags);

        assert_eq!(buf0_flags.base, 1);
        assert_eq!(buf0_flags.read, 1);
        assert_eq!(buf0_flags.write, false);

    }

    #[test]
    fn simple_test_drop_in_place_downgrade()
    {
        let mut bufs = RwBuffers::new(4096, 1, 2).unwrap();

        let buf0_w = 
            {
                let buf0 = bufs.allocate_in_place();

                println!("1: {:?}", buf0.get_flags());

                let buf0_w = buf0.write();
                assert_eq!(buf0_w.is_ok(), true, "{:?}", buf0_w.err().unwrap());
                assert_eq!(buf0.read(), Err(RwBufferError::ReadTryAgianLater));

                drop(buf0);

                buf0_w
            };

        let buf0_rd = buf0_w.unwrap().downgrade();
        assert_eq!(buf0_rd.is_ok(), true, "{:?}", buf0_rd.err().unwrap());

        let buf0_flags = bufs.get_flags_by_index(0);
        assert_eq!(buf0_flags.is_some(), false, "flags");

        let buf0_rd = buf0_rd.unwrap();
        let buf0_flags = buf0_rd.get_flags();

        println!("2: {:?}", buf0_flags);

        assert_eq!(buf0_flags.base, 0);
        assert_eq!(buf0_flags.read, 1);
        assert_eq!(buf0_flags.write, false);
    }

    #[test]
    fn timing_test()
    {
        let mut bufs = RwBuffers::new(4096, 1, 2).unwrap();

        for _ in 0..10
        {
            let inst = Instant::now();
            let buf0_res = bufs.allocate_in_place();
            let end = inst.elapsed();

            println!("alloc: {:?}", end);
            drop(buf0_res);
        }

        let buf0_res = bufs.allocate();
        assert_eq!(buf0_res.is_ok(), true, "{:?}", buf0_res.err().unwrap());

        let buf0 = buf0_res.unwrap();

        for _ in 0..10
        {
            let inst = Instant::now();
            let buf0_w = buf0.write();
            let end = inst.elapsed();

            println!("write: {:?}", end);

            assert_eq!(buf0_w.is_ok(), true, "{:?}", buf0_w.err().unwrap());
            assert_eq!(buf0.read(), Err(RwBufferError::ReadTryAgianLater));
            drop(buf0_w);
        }

        for _ in 0..10
        {
            let inst = Instant::now();
            let buf0_r = buf0.read();
            let end = inst.elapsed();

            println!("read: {:?}", end);

            assert_eq!(buf0_r.is_ok(), true, "{:?}", buf0_r.err().unwrap());
            assert_eq!(buf0.write(), Err(RwBufferError::WriteTryAgianLater));
            drop(buf0_r);
        }
    }

    #[test]
    fn simple_test_mth()
    {
        let mut bufs = RwBuffers::new(4096, 1, 3).unwrap();

        let buf0 = bufs.allocate().unwrap();

        let buf0_rd = buf0.write().unwrap().downgrade().unwrap();

        let join1=
            std::thread::spawn(move ||
                {
                    println!("{:?}", buf0_rd);

                    std::thread::sleep(Duration::from_secs(2));

                    return;
                }
            );

        let buf1_rd = buf0.read().unwrap();

        let join2=
            std::thread::spawn(move ||
                {
                    println!("{:?}", buf1_rd);

                    std::thread::sleep(Duration::from_secs(2));

                    return;
                }
            );

        let flags = buf0.get_flags();

        assert_eq!(flags.base, 2);
        assert_eq!(flags.read, 2);
        assert_eq!(flags.write, false);

        let _ = join1.join();
        let _ = join2.join();

        let flags = buf0.get_flags();

        assert_eq!(flags.base, 2);
        assert_eq!(flags.read, 0);
        assert_eq!(flags.write, false);
    }

    #[test]
    fn simple_test_concurent()
    {
        let mut bufs = RwBuffers::new(4096, 1, 3).unwrap();

        let buf0 = bufs.allocate().unwrap();

        let buf0_w = buf0.write().unwrap();


        let join1=
            std::thread::spawn(move ||
                {
                    std::thread::park();

                    println!("{:?}", buf0_w);

                    std::thread::sleep(Duration::from_secs(3));

                    return;
                }
            );

        join1.thread().unpark();
        let s = Instant::now();

        let buf1_rd = 
            loop
            {
                match buf0.read()
                {
                    Ok(r) => break r,
                    Err(e) =>
                    {
                        assert_eq!(e, RwBufferError::ReadTryAgianLater);
                        //println!("try again later!");

                        continue;
                    }
                }
            };

        let e = s.elapsed();

        println!("read await {:?} {}", e, e.as_millis());

        assert_eq!(e.as_millis(), 3000);

        let _ = join1.join();

      
        let flags = buf0.get_flags();

        assert_eq!(flags.base, 2);
        assert_eq!(flags.read, 1);
        assert_eq!(flags.write, false);

        drop(buf1_rd);

        let flags = buf0.get_flags();

        assert_eq!(flags.base, 2);
        assert_eq!(flags.read, 0);
        assert_eq!(flags.write, false);
    }

    #[test]
    fn test_try_into_read()
    {
        let mut bufs = RwBuffers::new(4096, 1, 2).unwrap();

        let buf0 = bufs.allocate_in_place();

        println!("{:?}", buf0.get_flags());

        let buf0_w = buf0.write();
        assert_eq!(buf0_w.is_ok(), true, "{:?}", buf0_w.err().unwrap());
        assert_eq!(buf0.read(), Err(RwBufferError::ReadTryAgianLater));

        drop(buf0);

        let buf0_rd = buf0_w.unwrap().downgrade();
        assert_eq!(buf0_rd.is_ok(), true, "{:?}", buf0_rd.err().unwrap());

        let buf0_flags = bufs.get_flags_by_index(0);
        assert_eq!(buf0_flags.is_some(), false, "flags");

        let buf0_rd = buf0_rd.unwrap();
        let buf0_flags = buf0_rd.get_flags();

        println!("{:?}", buf0_flags);

        assert_eq!(buf0_flags.base, 0);
        assert_eq!(buf0_flags.read, 1);
        assert_eq!(buf0_flags.write, false);

        let inst = Instant::now();
        let ve = buf0_rd.try_inner();
        let end = inst.elapsed();

        println!("try inner: {:?}", end);
        assert_eq!(ve.is_ok(), true);


    }

    #[tokio::test]
    async fn test_multithreading()
    {

        let mut bufs = RwBuffers::new(4096, 1, 3).unwrap();

        let buf0 = bufs.allocate().unwrap();

        let mut buf0_write = buf0.write().unwrap();
        
        buf0_write.as_mut_slice()[0] = 5;
        buf0_write.as_mut_slice()[1] = 4;

        println!("{}", buf0_write[0]);

        let buf0_r = buf0_write.downgrade().unwrap();

        let join1=
            tokio::task::spawn(async move
                {
                    println!("thread[1]:{}", buf0_r[0]);

                    tokio::time::sleep(Duration::from_millis(200)).await;

                    return;
                }
            );

        let buf0_r = buf0.read().unwrap();

        // drop base
        drop(buf0);

        let join2=
            tokio::task::spawn(async move
                {
                    println!("thread[2]: {}", buf0_r[0]);
                    println!("thread[2]: {}", buf0_r[1]);

                    tokio::time::sleep(Duration::from_millis(200)).await;

                    return;
                }
            );

        let _ = join1.await;
        let _ = join2.await;

        return;
    }

    #[tokio::test]
    async fn test_multithreading_async()
    {

        let mut bufs = RwBuffers::new(4096, 1, 3).unwrap();

        let buf0 = bufs.allocate().unwrap();

        let buf0_w = buf0.write_async().await.unwrap();

        let task_hndl = 
            task::spawn(async move
                {
                    tokio::task::yield_now().await;

                    println!("{:?}", buf0_w);

                    tokio::time::sleep(Duration::from_secs(3)).await;

                    async_drop(buf0_w).await;
                    return;
                }
            );

        let s = tokio::time::Instant::now();

        let buf1_rd = buf0.read_async().await.unwrap();

        let e = s.elapsed();

        println!("read await {:?} {}", e, e.as_millis());

        assert_eq!(e.as_millis(), 3000);

        let _ = task_hndl.await;

      
        let flags = buf0.get_flags();

        assert_eq!(flags.base, 2);
        assert_eq!(flags.read, 1);
        assert_eq!(flags.write, false);

        async_drop(buf1_rd).await;

        let flags = buf0.get_flags();

        assert_eq!(flags.base, 2);
        assert_eq!(flags.read, 0);
        assert_eq!(flags.write, false);
    }
}