turbostore 0.1.1

A concurrent, in-memory, in-process, redis-like storage for Rust.
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
//! A concurrent, in-memory, in-process, Redis-like storage for Rust.
//!
//! Any [bitcode]-encodable and [bitcode]-decodable type can be stored using this store, without
//! being locked to a single type.
//!
//! Turbostore uses [`scc::HashMap`] under the hood, so the performance stays consistent under
//! load. This means, though, that data structures are locked on access (e.g. accessing two keys of
//! a single hashmap will lock). Locks are released as soon as possible for maximum performance.
//!
//! # Installation
//!
//! To install it, just run `cargo add turbostore`. The crate has no features and is async-only.
//!
//! A sync API may be added in the future since the underlying APIs used by this crate provide
//! both sync and async APIs in their majority.
//!
//! # Usage
//!
//! If you prefer to jump to the reference section, go to [`TurboStore`]. The API is simple and the
//! operation names will be familiar if you've used Redis in the past.
//!
//! ## Creating Keys
//!
//! Keys are of a single hashable type. [`String`] works by default, but it's prone to typos,
//! introduces storage overhead, and it requires you to implement your own key formatting, so if
//! you want more type safety in your keys (and less storage requirements, therefore), create a key
//! enum as follows:
//!
//! ```
//! use std::hash::Hash;
//!
//! // All derives are required to be able to use this type as a key.
//! #[derive(Hash, PartialEq, Eq)]
//! enum Key {
//!     // An example of using the store for user data store.
//!     UserCache(i32),
//! }
//! ```
//!
//! ## Creating the TurboStore
//!
//! To create a store using the key you just created, create a new instance of [`TurboStore<K>`]
//! using [`TurboStore::new`].
//!
//! ```
//! use turbostore::TurboStore;
//!
//! let store: TurboStore<String> = TurboStore::new();
//! ```
//!
//! *Note: This example uses [`String`] as a key type for brevity.*
//!
//! ### Preallocating Memory
//!
//! If you already know you'll have a certain amount of usage, you can preallocate space with
//! [`TurboStore::with_capacity`].
//!
//! ```
//! # use pollster::FutureExt as _;
//! #
//! # async {
//! use turbostore::{TurboStore, Duration};
//!
//! let store: TurboStore<String> = TurboStore::with_capacity(2);
//!
//! store.set("key1".into(), &"value1".to_string(), Duration::minutes(1)).await;
//! store.set("key2".into(), &"value2".to_string(), Duration::minutes(1)).await;
//! store.set("key3".into(), &"value3".to_string(), Duration::minutes(1)).await;
//! # }.block_on();
//! ```
//!
//! Each structure (KV, map, set, deque) gets its own independent capacity — so setting 3 gives 3
//! slots per type. This means that if you set the capacity to 3, you'll have preallocated space
//! for 3 KV pairs, 3 hash maps, 3 hash sets, and 3 deques.
//!
//! ## Creating Storable Data Structures
//!
//! Storable data structures are easy to implement. They must derive [`bitcode::Encode`] to be set,
//! and [`bitcode::Decode`] to be retrieved.
//!
//! ```
//! use turbostore::{Encode, Decode};
//!
//! #[derive(Encode, Decode)]
//! struct UserCache {
//!     id: i32,
//!     name: String,
//! }
//! ```
//!
//! ## TTL
//!
//! This store was mainly intended to be used as a temporary, fast-access cache. It's not limited
//! to doing only that, but many of the design choices are made based on that purpose. This library
//! may be generalized later.
//!
//! TTLs are all set based on [`chrono::Duration`] and relative to the time of the execution of the
//! function. Eviction is done both lazily and with manual calls to [`TurboStore::evict`]. This can be
//! called in loop in a background task to periodically clean up expired keys. For example:
//!
//! ```ignore
//! use std::sync::Arc;
//! use tokio::time::Duration;
//! use turbostore::TurboStore;
//!
//! let store: Arc<TurboStore<()>> = Arc::new(TurboStore::new());
//! let thread_store = store.clone();
//!
//! tokio::spawn(async move {
//!     loop {
//!         tokio::time::sleep(Duration::from_secs(2)).await;
//!         thread_store.evict().await;
//!     }
//! });
//! ```
//!
//! Turbostore is runtime-agnostic, so this can also be implemented using async-std.
//!
//! Not calling [`TurboStore::evict`] periodically will result in expired data staying in memory
//! until it's next attempted to be accessed. When the data is next attempted to be accessed after
//! being expired, TurboStore will automatically clean that value up.
//!
//! ## Data Structures
//!
//! Turbostore currently supports 3 different data structures, plus a normal KV pair storage.
//!
//! The supported data structures are:
//! - [KV Pairs](#kv-pairs) - Normal key-value pairs.
//! - [Hash Maps](#hash-maps) - Namespaced key-value pairs.
//! - [Hash Sets](#hash-sets) - Lists of unique items.
//! - [Deques](#deques) - Lists with O(1) operations on the first and last items.
//!
//! ### KV Pairs
//!
//! Turbostore supports the basic get, set, remove, pop, and other common operations on key-value
//! pairs.
//!
//! The available operations on key-value pairs are:
//! - [`TurboStore::set`] - Set a new KV pair.
//! - [`TurboStore::get`] - Get a KV pair's value.
//! - [`TurboStore::rem`] - Remove a KV pair.
//! - [`TurboStore::pop`] - Remove a KV pair and return its value.
//! - [`TurboStore::incr`] - Increment a value by x.
//! - [`TurboStore::decr`] - Decrement a value by x.
//! - [`TurboStore::expire`] - Update the TTL of a KV pair.
//! - [`TurboStore::exists`] - Checks whether a key is set.
//!
//! ### Hash Maps
//!
//! Turbostore supports storing sub-hash-maps inside the store.
//!
//! The available operations on hash maps are:
//! - [`TurboStore::hset`] - Add a KV pair to the hash map.
//! - [`TurboStore::hget`] - Get a value from a KV pair in the hash map.
//! - [`TurboStore::hrem`] - Remove a KV pair from the hash map.
//! - [`TurboStore::hpop`] - Remove and return a KV pair from the hash map.
//! - [`TurboStore::hexists`] - Check whether a key is set in the hash map.
//! - [`TurboStore::hexpire`] - Set the TTL of a KV pair in the hash map.
//! - [`TurboStore::hlen`] - Count the amount of KV pairs in the hash map.
//! - [`TurboStore::hclear`] - Empty the hash map.
//!
//! TTLs are per KV pair in a hash map, and KV pairs are expired individually.
//!
//! ### Hash Sets
//!
//! Hash sets are lists of unique items.
//!
//! The available operations on hash sets are:
//! - [`TurboStore::sadd`] - Add an item to the set.
//! - [`TurboStore::srem`] - Remove an item from the set.
//! - [`TurboStore::slen`] - Count the amount of items in the set.
//! - [`TurboStore::sclear`] - Empty the set.
//! - [`TurboStore::sttl`] - Get the expiry date and time of an item in the set.
//! - [`TurboStore::scontains`] - Check whether an item is in the set.
//! - [`TurboStore::sall`] - Get all items in the set.
//!
//! As with hash maps, hash set items have per-item TTLs and expire individually.
//!
//! ### Deques
//!
//! Deques are lists optimized for O(1) operations at both ends.
//!
//! The available operations on deques are:
//! - [`TurboStore::dappend`] - Append an item to the deque.
//! - [`TurboStore::dprepend`] - Prepend an item to the deque.
//! - [`TurboStore::dfpop`] - Remove and return the first item of the deque.
//! - [`TurboStore::dbpop`] - Remove and return the last item of the deque.
//! - [`TurboStore::dpop`] - Remove and return an item of the deque by index.
//! - [`TurboStore::dfrem`] - Remove the first item of the deque.
//! - [`TurboStore::dbrem`] - Remove the last item of the deque.
//! - [`TurboStore::drem`] - Remove an item of the deque by index.
//! - [`TurboStore::dfpeek`] - Get the first item of the deque.
//! - [`TurboStore::dbpeek`] - Get the last item of the deque.
//! - [`TurboStore::dpeek`] - Get an item of the deque by index.
//! - [`TurboStore::dlen`] - Count the amount of items in the deque.
//! - [`TurboStore::expire`] - Update the expiration time of an item in the deque.
//! - [`TurboStore::dclear`] - Empty the deque.
//! - [`TurboStore::dmap`] - Overwrite each item of the deque.
//! - [`TurboStore::dall`] - Get all items in the deque.
//! - [`TurboStore::dftruncate`] - Keep only the first x items in the deque.
//! - [`TurboStore::dbtruncate`] - Keep only the last x items in the deque.
//!
//! Note that `rem` operations are faster than `pop` operations due to the lack of need to decode
//! the removed value.
//!
//! Items in deques have each their individual TTLs and expire individually.
//!
//! ## The [`Value`] Wrapper
//!
//! Value is a wrapper that holds your data **plus metadata like the expiry time**. Currently, that
//! metadata is the expiry time of the value, which can be accessed with [`Value::expires_at`].
//!
//! ## Example
//!
//! This example shows how to set and get a value from the store. Operations with other data
//! structures and operations follow a similar encoding/decoding style, so it's easy to work with
//! them. If you've worked with Redis in the past, you'll find this crate familiar.
//!
//! ```
//! # use pollster::FutureExt as _;
//! #
//! # async {
//! use std::hash::Hash;
//! use turbostore::{TurboStore, Value, Duration, Encode, Decode};
//!
//! #[derive(Hash, PartialEq, Eq)]
//! enum Key {
//!     User(i32),
//! }
//!
//! #[derive(Debug, Encode, Decode, PartialEq, Eq, Clone)]
//! struct User {
//!     id: i32,
//!     name: String,
//!     email: String,
//! }
//!
//! let store: TurboStore<Key> = TurboStore::new();
//!
//! let user = User {
//!     id: 1,
//!     name: "John Doe".into(),
//!     email: "john@example.com".into()
//! };
//!
//! store.set(
//!     Key::User(1),
//!     &user,
//!     Duration::minutes(15)
//! ).await;
//!
//! // The first `Option` returns whether the key existed.
//! // The `Value` is the internal wrapper over values which stores metadata (e.g. expiry time).
//! // The inner `Result` is the result of decoding the value. Since types are dynamic-ish, setting
//! //   the wrong value will fail.
//! let stored_user: Value<Result<User, _>> = store.get::<User>(&Key::User(1)).await.unwrap();
//!
//! assert_eq!(*stored_user.as_ref().unwrap(), user);
//! # }.block_on();
//! ```
//!
//! # FAQ
//!
//! 1. Q: **Why is the [`Option`] and [`Result`] nesting so uncomfortable?**
//!
//!    A: The way they're nested exposes the most amount of metadata when the value fails to be
//!    decoded. E.g. with [`Result<Value<V>, Error>`], if the value fails to be decoded the value's
//!    metadata gets hidden because of [`Err`]. Using [`Value<Result<V, Error>>`] allows you to
//!    access the value's metadata even if it fails to decode.
//!
//! [bitcode]: https://docs.rs/bitcode
//!
//! # Roadmap
//!
//! Distribution both sharded and replicated is planned to be supported. Pipelines are also
//! planned, since running multiple operations is currently neither atomic across ops nor as
//! efficient as it could be (e.g. setting two items in a set fetches the set twice, once per op).
//!
//! Contributions are welcome, whether it's feedback, bug reports, or pull requests. Check out
//! [our GitHub repository](https://github.com/Nekidev/turbostore) for the source code and issue
//! tracker.

use std::{
    collections::VecDeque,
    hash::Hash,
    ops::{Deref, Neg},
};

pub use bitcode::{Decode, DecodeOwned, Encode};
pub use chrono::{DateTime, Duration, Utc};
use scc::HashMap;

use crate::math::{SaturatingAdd, SaturatingSub};

mod math;

/// A TurboStore value.
pub struct Value<T> {
    /// The date and time this value expires at.
    pub expires_at: DateTime<Utc>,

    /// The inner value of the item.
    pub value: T,
}

impl<T> Deref for Value<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> Value<T> {
    /// Returns whether the value is already expired.
    ///
    /// Arguments:
    /// * `now` - The current datetime. Passed as an argument so that `Utc::now()` doesn't have to
    ///   be called on multiple iterations.
    ///
    /// Returns:
    /// [`bool`] - Whether the value has already expired.
    fn is_expired(&self, now: &DateTime<Utc>) -> bool {
        self.expires_at <= *now
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// The value could not be decoded to the specified type.
    Decoding,
}

/// A fast concurrent storage, in-memory and redis-like.
pub struct TurboStore<K: Hash + Eq> {
    pairs: HashMap<K, Value<Vec<u8>>>,
    maps: HashMap<K, HashMap<K, Value<Vec<u8>>>>,
    sets: HashMap<K, HashMap<Vec<u8>, Value<()>>>,
    deques: HashMap<K, VecDeque<Value<Vec<u8>>>>,
}

impl<K> TurboStore<K>
where
    K: Hash + Eq,
{
    /// Creates a new store with capacity.
    ///
    /// Returns:
    /// [`TurboStore`] - The new store instance.
    pub fn new() -> Self {
        Self {
            pairs: HashMap::new(),
            maps: HashMap::new(),
            sets: HashMap::new(),
            deques: HashMap::new(),
        }
    }

    /// Creates a new store with capacity.
    ///
    /// Arguments:
    /// * `capacity` - The amount of key-value pairs for whose space should be preallocated.
    ///
    /// Returns:
    /// [`TurboStore`] - The new store instance.
    pub fn with_capacity(capacity: usize) -> Self {
        // TODO: Allow fine-grained capacity setting.

        Self {
            pairs: HashMap::with_capacity(capacity),
            maps: HashMap::with_capacity(capacity),
            sets: HashMap::with_capacity(capacity),
            deques: HashMap::with_capacity(capacity),
        }
    }

    /// Cleans up all expired keys.
    pub async fn evict(&self) {
        let now = Utc::now();

        self.pairs.retain_async(|_, v| !v.is_expired(&now)).await;

        self.maps
            .retain_async(|_, map| {
                map.retain(|_, v| !v.is_expired(&now));

                !map.is_empty()
            })
            .await;

        self.sets
            .retain_async(|_, set| {
                set.retain(|_, v| !v.is_expired(&now));

                !set.is_empty()
            })
            .await;

        self.deques
            .retain_async(|_, deque| {
                deque.retain(|i| !i.is_expired(&now));

                !deque.is_empty()
            })
            .await;
    }

    /// Sets a new KV pair.
    ///
    /// If the key already exists, the value is overwritten with the new value and TTL.
    ///
    /// Arguments:
    /// * `key` - The key of the KV pair.
    /// * `value` - The value of the KV pair.
    /// * `ttl` - The TTL of the KV pair.
    pub async fn set<V>(&self, key: K, value: &V, ttl: Duration)
    where
        V: Encode,
    {
        let expires_at = Utc::now() + ttl;

        let encoded: Vec<u8> = bitcode::encode(value);

        self.pairs
            .upsert_async(
                key,
                Value {
                    value: encoded,
                    expires_at,
                },
            )
            .await;
    }

    /// Increments a KV pair's value.
    ///
    /// The TTL is overwritten on every increment.
    ///
    /// Integer overflows are saturated, they cannot go past `type::MAX` nor under `type::MIN`.
    ///
    /// Arguments:
    /// * `key` - The key of the KV pair.
    /// * `by` - The amount to increment by.
    /// * `ttl` - The TTL of the KV pair.
    pub async fn incr<V>(&self, key: K, by: V, ttl: Duration) -> Result<V, Error>
    where
        V: Encode + DecodeOwned + SaturatingAdd<Output = V>,
    {
        let expires_at = Utc::now() + ttl;

        let value = self.pairs.get_async(&key).await;

        if let Some(mut value) = value {
            let decoded = bitcode::decode::<V>(&value).map_err(|_| Error::Decoding)?;

            let new_value = decoded.saturating_add(&by);

            *value = Value {
                value: bitcode::encode(&new_value),
                expires_at,
            };

            Ok(new_value)
        } else {
            self.pairs
                .upsert_async(
                    key,
                    Value {
                        value: bitcode::encode(&by),
                        expires_at,
                    },
                )
                .await;

            Ok(by)
        }
    }

    /// Decrements a KV pair's value.
    ///
    /// The TTL is overwritten on every decrement.
    ///
    /// Integer overflows are saturated, they cannot go past `type::MAX` nor under `type::MIN`.
    ///
    /// Arguments:
    /// * `key` - The key of the KV pair.
    /// * `by` - The amount to decrement by.
    /// * `ttl` - The TTL of the KV pair.
    pub async fn decr<V>(&self, key: K, by: V, ttl: Duration) -> Result<V, Error>
    where
        V: Encode + DecodeOwned + SaturatingSub<Output = V> + Neg<Output = V>,
    {
        let expires_at = Utc::now() + ttl;

        let value = self.pairs.get_async(&key).await;

        if let Some(mut value) = value {
            let decoded = bitcode::decode::<V>(&value).map_err(|_| Error::Decoding)?;

            let new_value = decoded.saturating_sub(&by);

            *value = Value {
                value: bitcode::encode(&new_value),
                expires_at,
            };

            Ok(new_value)
        } else {
            let new_value = -by;

            self.pairs
                .upsert_async(
                    key,
                    Value {
                        value: bitcode::encode(&new_value),
                        expires_at,
                    },
                )
                .await;

            Ok(new_value)
        }
    }

    /// Gets the value of a KV pair by key.
    ///
    /// Arguments:
    /// * `key` - The key whose value to retrieve.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the value is non-existent or expired, or `Some(Value(Err(Error::Decoding)))` if
    /// the key exists and is not expired but the value could not be decoded to the specified type.
    pub async fn get<V>(&self, key: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let value = self.pairs.get_async(key).await?;

        if value.is_expired(&Utc::now()) {
            // Removing with a reference alive causes a deadlock.
            drop(value);
            self.pairs.remove_async(key).await;
            return None;
        }

        Some(Value {
            value: bitcode::decode(&value).map_err(|_| Error::Decoding),
            expires_at: value.expires_at,
        })
    }

    /// Removes a KV pair by key.
    ///
    /// Arguments:
    /// * `key` - The key of the KV pair to delete.
    ///
    /// Returns:
    /// [`bool`] - Whether a KV pair got deleted.
    pub async fn rem(&self, key: &K) -> bool {
        self.pairs.remove_async(key).await.is_some()
    }

    /// Removes a KV pair by key and returns the pair (pop).
    ///
    /// Arguments:
    /// * `key` - The key of the KV pair to pop.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the value is non-existent or expired, or `Some(Value(Err(Error::Decoding)))` if
    /// the key exists and is not expired but the value could not be decoded to the specified type.
    pub async fn pop<V>(&self, key: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let (_key, value) = self.pairs.remove_async(key).await?;

        if value.is_expired(&Utc::now()) {
            return None;
        }

        Some(Value {
            value: bitcode::decode(&value).map_err(|_| Error::Decoding),
            expires_at: value.expires_at,
        })
    }

    /// Update the expiration datetime of a KV pair.
    ///
    /// Arguments:
    /// * `key` - The key of the KV to update the expiration datetime for.
    /// * `ttl` - The TTL of the KV pair since the moment this function is called.
    ///
    /// Returns:
    /// [`bool`] - `true` if a key's expiration datetime was updated, `false` if no KV for the
    /// provided key existed.
    pub async fn expire(&self, key: K, ttl: Duration) -> bool {
        let expires_at = Utc::now() + ttl;

        let maybe_new_value = self.pairs.get_async(&key).await.map(|value| Value {
            value: value.value.clone(),
            expires_at,
        });

        match maybe_new_value {
            None => false,
            Some(new_value) => {
                self.pairs.upsert_async(key, new_value).await;
                true
            }
        }
    }

    /// Returns whether a KV pair for a key exists.
    ///
    /// Arguments:
    /// * `key` - The key to find.
    ///
    /// Returns:
    /// [`bool`] - Whether a KV pair for that key exists.
    pub async fn exists(&self, key: &K) -> bool {
        let expired = match self.pairs.get_async(key).await {
            None => return false,
            Some(inner) => inner.is_expired(&Utc::now()),
        };

        if expired {
            self.pairs.remove_async(key).await;
            return false;
        }

        true
    }

    /// Inserts a value into a set by the set's key.
    ///
    /// If no set exists yet, a new set with a preallocated `capacity` is automatically created.
    ///
    /// If the item is already in the set, the TTL is updated to match the new `ttl`.
    ///
    /// Arguments:
    /// * `skey` - The key of the set to add the value to.
    /// * `item` - The value to add to the set.
    /// * `ttl` - The amount of time this item should exist for.
    /// * `capacity` - In case the set does not yet exist, a new set with this capacity will be
    ///   created. This is the minimum number of items that should fit in the preallocated space.
    pub async fn sadd<V>(&self, skey: K, item: V, ttl: Duration, capacity: usize)
    where
        V: Encode,
    {
        let expires_at = Utc::now() + ttl;

        let set = self.sets.get_async(&skey).await;

        let encoded = bitcode::encode(&item);
        let value = Value {
            value: (),
            expires_at,
        };

        if let Some(set) = set {
            set.upsert_async(encoded, value).await;
        } else {
            let set = HashMap::with_capacity(capacity.max(1));

            set.upsert_async(encoded, value).await;
            self.sets.upsert_async(skey, set).await;
        }
    }

    /// Removes an item from a set.
    ///
    /// Arguments:
    /// * `skey` - The key of the set to remove the item from.
    /// * `item` - The item to remove from the set.
    pub async fn srem<V>(&self, skey: &K, item: &V)
    where
        V: Encode,
    {
        let set = match self.sets.get_async(skey).await {
            None => return,
            Some(v) => v,
        };

        let encoded = bitcode::encode(item);

        let result = set.remove_async(&encoded).await;

        if result.is_some() && set.is_empty() {
            // Removing with a reference still alive causes a deadlock.
            drop(set);
            self.sets.remove_async(skey).await;
        }
    }

    /// Returns the amount of items in a set.
    ///
    /// Internally, this iterates through all the items in the set to make sure no item being
    /// counted has expired, so the call gets more expensive the more items in the set.
    ///
    /// Arguments:
    /// * `skey` - The key of the set.
    ///
    /// Returns:
    /// [`usize`] - The amount of items in the set, or 0 if the set doesn't exist.
    pub async fn slen(&self, skey: &K) -> usize {
        let set = match self.sets.get_async(skey).await {
            None => return 0,
            Some(v) => v,
        };

        let now = Utc::now();

        // Returning `.len()` without this check first would cause expired keys to be counted too.
        set.retain_async(|_k, v| !v.is_expired(&now)).await;

        set.len()
    }

    /// Empties a set.
    ///
    /// Arguments:
    /// * `skey` - The key of the set to empty.
    pub async fn sclear(&self, skey: &K) {
        self.sets.remove_async(skey).await;
    }

    /// Returns the expiry datetime of an item in a set.
    ///
    /// Arguments:
    /// * `skey` - The key of the set to find the item in.
    /// * `item` - The item whose expiry datetime to find in the set.
    ///
    /// Returns:
    /// [`Option<DateTime<Utc>>`] - `Some(DateTime<Utc>)` if the item is in the set and hasn't
    /// expired, or [`None`] otherwise.
    pub async fn sttl<V>(&self, skey: &K, item: &V) -> Option<DateTime<Utc>>
    where
        V: Encode,
    {
        let set = self.sets.get_async(skey).await?;

        let encoded = bitcode::encode(item);

        let item = set.get_async(&encoded).await?;

        if item.is_expired(&Utc::now()) {
            set.remove_async(&encoded).await;

            if set.is_empty() {
                // Drop everything before removing, as keeping references while removing causes a
                // deadlock.
                drop(item);
                drop(set);
                self.sets.remove_async(skey).await;
            }

            return None;
        }

        Some(item.expires_at)
    }

    /// Updates the TTL of an item in a set.
    ///
    /// If the item does not exist in the set, nothing happens.
    ///
    /// Arguments:
    /// * `skey` - The key of the set whose item the TTL to update.
    /// * `item` - The item whose TTL to update.
    /// * `ttl` - The new TTL of the item since this function is called.
    pub async fn sexpire<V>(&self, skey: &K, item: &V, ttl: Duration)
    where
        V: Encode,
    {
        let set = match self.sets.get_async(skey).await {
            None => return,
            Some(v) => v,
        };

        let encoded = bitcode::encode(item);

        let item = match set.get_async(&encoded).await {
            None => return,
            Some(v) => v,
        };

        let now = Utc::now();

        if item.is_expired(&now) {
            set.remove_async(&encoded).await;

            if set.is_empty() {
                // Drop everything before removing, as keeping references while removing causes a
                // deadlock.
                drop(item);
                drop(set);
                self.sets.remove_async(skey).await;
            }

            return;
        }

        let expires_at = now + ttl;

        set.upsert_async(
            encoded,
            Value {
                value: (),
                expires_at,
            },
        )
        .await;
    }

    /// Checks whether an item is in a set.
    ///
    /// Arguments:
    /// * `skey` - The key of the set in which to check for the item's existance.
    /// * `item` - The item to check for its existance in the set.
    ///
    /// Returns:
    /// [`bool`] - Whether the item is in the set.
    pub async fn scontains<V>(&self, skey: &K, item: &V) -> bool
    where
        V: Encode,
    {
        let set = match self.sets.get_async(skey).await {
            None => return false,
            Some(v) => v,
        };

        let encoded = bitcode::encode(item);

        let value = match set.get_async(&encoded).await {
            None => return false,
            Some(v) => v,
        };

        if value.is_expired(&Utc::now()) {
            set.remove_async(&encoded).await;

            if set.is_empty() {
                // Drop everything before removing, as keeping references while removing causes a
                // deadlock.
                drop(value);
                drop(set);
                self.sets.remove_async(skey).await;
            }

            return false;
        }

        true
    }

    /// Returns all members in a set.
    ///
    /// Arguments:
    /// * `skey` - The set's key.
    ///
    /// Returns:
    /// [`Vec<Value<Result<V, Error>>>`] - An array with all the items in the set, each of them
    /// containing the result of their decoding individually.
    pub async fn sall<V>(&self, skey: &K) -> Vec<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let set = match self.sets.get_async(skey).await {
            None => return Vec::default(),
            Some(v) => v,
        };

        let mut values = Vec::with_capacity(set.len());

        let now = Utc::now();

        set.retain_async(|k, v| {
            if v.is_expired(&now) {
                return false;
            }

            let decoded = bitcode::decode::<V>(k).map_err(|_| Error::Decoding);

            values.push(Value {
                value: decoded,
                expires_at: v.expires_at,
            });

            true
        })
        .await;

        values
    }

    /// Inserts a new value to a map.
    ///
    /// If there's already a value with this key in the map, the original value and its TTL are
    /// overwritten.
    ///
    /// Arguments:
    /// * `hkey` - The key of the hashmap to which insert the new value.
    /// * `key` - The key of the KV pair being inserted to the hashmap.
    /// * `value` - The value of the KV pair to insert to the hashmap.
    /// * `ttl` - The amount of time this key will live from the moment the function is run.
    /// * `capacity` - If a new hashmap is created, this value is the amount of KV pairs that will
    ///   fit in the preallocated space.
    pub async fn hset<V>(&self, hkey: K, key: K, value: V, ttl: Duration, capacity: usize)
    where
        V: Encode,
    {
        let map = self.maps.get_async(&hkey).await;

        let expires_at = Utc::now() + ttl;

        let encoded = bitcode::encode(&value);
        let value = Value {
            value: encoded,
            expires_at,
        };

        if let Some(map) = map {
            map.upsert_async(key, value).await;
        } else {
            let map = HashMap::with_capacity(std::cmp::max(capacity, 1));

            map.upsert_async(key, value).await;
            self.maps.upsert_async(hkey, map).await;
        }
    }

    /// Returns the value for a key in a map.
    ///
    /// Arguments:
    /// * `hkey` - The key of the map to get the value from.
    /// * `key` - The key whose value to get in the map.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the value is non-existent or expired, or `Some(Value(Err(Error::Decoding)))` if
    /// the key exists and is not expired but the value could not be decoded to the specified type.
    pub async fn hget<V>(&self, hkey: &K, key: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let map = self.maps.get_async(hkey).await?;

        let value = map.get_async(key).await?;

        if value.is_expired(&Utc::now()) {
            map.remove_async(key).await;

            if map.is_empty() {
                // Drop everything before removing, as keeping references while removing causes a
                // deadlock.
                drop(value);
                drop(map);
                self.maps.remove_async(hkey).await;
            }

            return None;
        }

        Some(Value {
            value: bitcode::decode(&value).map_err(|_| Error::Decoding),
            expires_at: value.expires_at,
        })
    }

    /// Removes a KV pair from a map.
    ///
    /// Arguments:
    /// * `hkey` - The key of the map in which to remove the pair.
    /// * `key` - The key of the KV pair to remove.
    pub async fn hrem(&self, hkey: &K, key: &K) {
        let map = match self.maps.get_async(hkey).await {
            None => return,
            Some(v) => v,
        };

        map.remove_async(key).await;
    }

    /// Removes a KV pair from a map and returns the value.
    ///
    /// Arguments:
    /// * `hkey` - The key of the map to remove the KV pair from.
    /// * `key` - The key of the KV pair to remove.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the value is non-existent or expired, or `Some(Value(Err(Error::Decoding)))` if
    /// the key exists and is not expired but the value could not be decoded to the specified type.
    pub async fn hpop<V>(&self, hkey: &K, key: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let map = self.maps.get_async(hkey).await?;

        let (_key, value) = map.remove_async(key).await?;

        if map.is_empty() {
            // No dropping here since `_key` and `value` aren't locks (they're removed from the
            // map).
            self.maps.remove_async(hkey).await;
        }

        // Dropping the lock early to allow other threads to start using the value ASAP.
        drop(map);

        if value.is_expired(&Utc::now()) {
            return None;
        }

        Some(Value {
            value: bitcode::decode(&value).map_err(|_| Error::Decoding),
            expires_at: value.expires_at,
        })
    }

    /// Checks whether a key exists in a map.
    ///
    /// Arguments:
    /// * `hkey` - The key of the map in which to check for the key's existance.
    ///
    /// Returns:
    /// [`bool`] - Whether the key exists or not.
    pub async fn hexists(&self, hkey: &K, key: &K) -> bool {
        let map = match self.maps.get_async(hkey).await {
            None => return false,
            Some(v) => v,
        };

        let value = match map.get_async(key).await {
            None => return false,
            Some(v) => v,
        };

        if value.is_expired(&Utc::now()) {
            map.remove_async(key).await;

            if map.is_empty() {
                // Drop everything before removing, as keeping references while removing causes a
                // deadlock.
                drop(value);
                drop(map);
                self.maps.remove_async(hkey).await;
            }

            return false;
        }

        true
    }

    /// Overwrites the TTL of a key in a map.
    ///
    /// If no KV pair for such key exists in the map, nothing happens.
    ///
    /// Arguments:
    /// * `hkey` - The key of the map in which to update the key's TTL.
    /// * `key` - The key for which to overwrite the TTL.
    /// * `ttl` - The remaining time the key has before it expires.
    pub async fn hexpire(&self, hkey: &K, key: K, ttl: Duration) {
        let map = match self.maps.get_async(hkey).await {
            None => return,
            Some(v) => v,
        };

        let value = match map.get_async(&key).await {
            None => return,
            Some(v) => v,
        };

        let now = Utc::now();

        if value.is_expired(&now) {
            map.remove_async(&key).await;

            if map.is_empty() {
                // Drop everything before removing, as keeping references while removing causes a
                // deadlock.
                drop(value);
                drop(map);
                self.maps.remove_async(hkey).await;
            }

            return;
        }

        map.upsert_async(
            key,
            Value {
                // Cannot use std::mem::take because that'd update the original value in the map
                // too, and we don't want that.
                value: value.value.clone(),
                expires_at: now + ttl,
            },
        )
        .await;
    }

    /// Returns the amount of keys in a map.
    ///
    /// Arguments:
    /// * `hkey` - The map whose length to return.
    ///
    /// Returns:
    /// [`usize`] - The amount of keys in the map.
    pub async fn hlen(&self, hkey: &K) -> usize {
        let map = match self.maps.get_async(hkey).await {
            None => return 0,
            Some(v) => v,
        };

        let now = Utc::now();

        // Returning `.len()` without this check first would cause expired keys to be counted too.
        // Consider caching the length of the map using atomic ops (which has to be updated every
        // time an item is added or removed).
        map.retain_async(|_k, v| !v.is_expired(&now)).await;

        if map.is_empty() {
            // Drop before removing as not doing so causes a deadlock.
            drop(map);
            self.maps.remove_async(hkey).await;
            return 0;
        }

        map.len()
    }

    /// Empties all keys in a map.
    ///
    /// Arguments:
    /// * `hkey` - The key of the map to empty.
    pub async fn hclear(&self, hkey: &K) {
        self.maps.remove_async(hkey).await;
    }

    /// Appends (adds to the end) an item to the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `value` - The value to append to the deque.
    /// * `ttl` - The time this value will be valid for since the call of this function.
    /// * `capacity` - If a new deque is created, this is the amount of items that will fit
    ///   (at least) in the preallocated space.
    pub async fn dappend<V>(&self, dkey: K, value: V, ttl: Duration, capacity: usize)
    where
        V: Encode,
    {
        let deque = self.deques.get_async(&dkey).await;

        let encoded = bitcode::encode(&value);
        let value = Value {
            value: encoded,
            expires_at: Utc::now() + ttl,
        };

        if let Some(mut deque) = deque {
            deque.push_back(value);
        } else {
            let mut deque = VecDeque::with_capacity(capacity.max(1));

            deque.push_back(value);
            self.deques.upsert_async(dkey, deque).await;
        }
    }

    /// Prepends (adds to the front) an item to the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `value` - The value to prepend to the deque.
    /// * `ttl` - The time this value will be valid for since the call of this function.
    /// * `capacity` - If a new deque is created, this is the amount of items that will fit
    ///   (at least) in the preallocated space.
    pub async fn dprepend<V>(&self, dkey: K, value: V, ttl: Duration, capacity: usize)
    where
        V: Encode,
    {
        let deque = self.deques.get_async(&dkey).await;

        let encoded = bitcode::encode(&value);
        let value = Value {
            value: encoded,
            expires_at: Utc::now() + ttl,
        };

        if let Some(mut deque) = deque {
            deque.push_front(value);
        } else {
            let mut deque = VecDeque::with_capacity(capacity.max(1));

            deque.push_front(value);
            self.deques.upsert_async(dkey, deque).await;
        }
    }

    /// Removes and returns the first item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the deque is empty, or `Some(Value(Err(Error::Decoding)))` if the key exists and
    /// is not expired but the value could not be decoded to the specified type.
    pub async fn dfpop<V>(&self, dkey: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = self.deques.get_async(dkey).await?;

        let now = Utc::now();

        let value = loop {
            let value = deque.pop_front()?;

            if value.is_expired(&now) {
                continue;
            }

            break Some(value);
        }?;

        if deque.is_empty() {
            // Cannot call remove_async while having a reference to the item, as it causes a
            // deadlock. Dropping the reference also allows other threads to start using the deque,
            // which is better for concurrency. (Waiting would cause every other thread trying to
            // access the deque to have to wait for the decoding to finish).
            drop(deque);
            self.deques.remove_async(dkey).await;
        } else {
            // Cannot drop earlier because of this if's condition.
            drop(deque);
        }

        let decoded = bitcode::decode::<V>(&value).map_err(|_| Error::Decoding);

        Some(Value {
            value: decoded,
            expires_at: value.expires_at,
        })
    }

    /// Removes and returns the last item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the deque is empty, or `Some(Value(Err(Error::Decoding)))` if the key exists and
    /// is not expired but the value could not be decoded to the specified type.
    pub async fn dbpop<V>(&self, dkey: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = self.deques.get_async(dkey).await?;

        let now = Utc::now();

        let value = loop {
            let value = deque.pop_back()?;

            if value.is_expired(&now) {
                continue;
            }

            break Some(value);
        }?;

        if deque.is_empty() {
            // Cannot call remove_async while having a reference to the item, as it causes a
            // deadlock. Dropping the reference also allows other threads to start using the deque,
            // which is better for concurrency. (Waiting would cause every other thread trying to
            // access the deque to have to wait for the decoding to finish).
            drop(deque);
            self.deques.remove_async(dkey).await;
        } else {
            // Cannot drop earlier because of this if's condition.
            drop(deque);
        }

        let decoded = bitcode::decode::<V>(&value).map_err(|_| Error::Decoding);

        Some(Value {
            value: decoded,
            expires_at: value.expires_at,
        })
    }

    /// Removes and returns an item of the deque.
    ///
    /// In case of a non-existent index, this function does nothing (and returns [`None`]).
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `index` - The index of the item to pop in the deque.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the deque is empty, or `Some(Value(Err(Error::Decoding)))` if the key exists and
    /// is not expired but the value could not be decoded to the specified type.
    pub async fn dpop<V>(&self, dkey: &K, index: usize) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = self.deques.get_async(dkey).await?;

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        let value = deque.drain(index..=index).next()?;

        if deque.is_empty() {
            // Drop before removing as not doing so causes a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
        } else {
            // Early dropping to allow other threads to start using the deque early.
            drop(deque);
        }

        let decoded = bitcode::decode::<V>(&value).map_err(|_| Error::Decoding);

        Some(Value {
            value: decoded,
            expires_at: value.expires_at,
        })
    }

    /// Removes the first item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    pub async fn dfrem(&self, dkey: &K) {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        let now = Utc::now();

        loop {
            let value = match deque.pop_front() {
                Some(v) => v,
                None => {
                    // Drop before removing as not doing so causes a deadlock.
                    drop(deque);
                    self.deques.remove_async(dkey).await;

                    break;
                }
            };

            if !value.is_expired(&now) {
                break;
            }
        }
    }

    /// Removes the last item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    pub async fn dbrem(&self, dkey: &K) {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        let now = Utc::now();

        loop {
            let value = match deque.pop_back() {
                Some(v) => v,
                None => {
                    // Drop before removing as not doing so causes a deadlock.
                    drop(deque);
                    self.deques.remove_async(dkey).await;

                    break;
                }
            };

            if !value.is_expired(&now) {
                break;
            }
        }
    }

    /// Removes an item of the deque.
    ///
    /// In case of a non-existent index, this function does nothing.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `index` - The index of the item in the deque.
    pub async fn drem(&self, dkey: &K, index: usize) {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        deque.drain(index..=index);

        if deque.is_empty() {
            // Drop before removing, as not doing so causes a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
        }
    }

    /// Returns the first item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the deque is empty, or `Some(Value(Err(Error::Decoding)))` if the key exists and
    /// is not expired but the value could not be decoded to the specified type.
    pub async fn dfpeek<V>(&self, dkey: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = self.deques.get_async(dkey).await?;

        let now = Utc::now();

        let value = loop {
            let value = match deque.front() {
                Some(v) => v,
                None => {
                    drop(deque);
                    self.deques.remove_async(dkey).await;
                    return None;
                }
            };

            if value.is_expired(&now) {
                deque.pop_front();
                continue;
            }

            break Some(value);
        }?;

        let decoded = bitcode::decode::<V>(value).map_err(|_| Error::Decoding);

        Some(Value {
            value: decoded,
            expires_at: value.expires_at,
        })
    }

    /// Returns the last item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the deque is empty, or `Some(Value(Err(Error::Decoding)))` if the key exists and
    /// is not expired but the value could not be decoded to the specified type.
    pub async fn dbpeek<V>(&self, dkey: &K) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = self.deques.get_async(dkey).await?;

        let now = Utc::now();

        let value = loop {
            let value = match deque.back() {
                Some(v) => v,
                None => {
                    drop(deque);
                    self.deques.remove_async(dkey).await;
                    return None;
                }
            };

            if value.is_expired(&now) {
                deque.pop_back();
                continue;
            }

            break Some(value);
        }?;

        let decoded = bitcode::decode::<V>(value).map_err(|_| Error::Decoding);

        Some(Value {
            value: decoded,
            expires_at: value.expires_at,
        })
    }

    /// Returns an item of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `index` - The index of the item in the deque to return.
    ///
    /// Returns:
    /// [`Option<Value<Result<V, Error>>>`] - `Some(Ok(V))` if there is a non-expired value,
    /// `None` if the deque is empty, or `Some(Value(Err(Error::Decoding)))` if the key exists and
    /// is not expired but the value could not be decoded to the specified type.
    pub async fn dpeek<V>(&self, dkey: &K, index: usize) -> Option<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = self.deques.get_async(dkey).await?;

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
            return None;
        }

        let item = (*deque).get(index)?;

        let decoded = bitcode::decode::<V>(item).map_err(|_| Error::Decoding);

        Some(Value {
            value: decoded,
            expires_at: item.expires_at,
        })
    }

    /// Returns the amount of items in a deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    ///
    /// Returns:
    /// [`usize`] - The amount of items in the deque.
    pub async fn dlen(&self, dkey: &K) -> usize {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return 0,
        };

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
            return 0;
        }

        deque.len()
    }

    /// Updates the expiration time of an item in a deque.
    ///
    /// If the item is non-existent (invalid index/empty deque) this function does nothing.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `index` - The index of the item in the deque to update the TTL for.
    /// * `ttl` - The remaining time left to live of the item in the deque.
    pub async fn dexpire(&self, dkey: &K, index: usize, ttl: Duration) {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
            return;
        }

        let item = match (*deque).get_mut(index) {
            Some(v) => v,
            None => return,
        };

        item.expires_at = now + ttl;
    }

    /// Removes all values in a deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    pub async fn dclear(&self, dkey: &K) {
        self.deques.remove_async(dkey).await;
    }

    /// Runs a function over each of the items in a deque and overrides their values with the
    /// returned value of the function.
    ///
    /// The function takes one `item` argument, it being [`Value<Result<V, Error>>`]. The function
    /// returns [`Option<Value<V>>`] (which is not the same as the `item` argument's type). The
    /// [Result] type of the [Value]'s inner value may be an error if the inner value cannot be
    /// decoded into the provided data type.
    ///
    /// The function returns either [None], meaning that the value stays as-is, or
    /// [`Some<Value<Result<T, Error>>>`] which replaces the old value with the function's returned
    /// value. You may update the value's expiry time even if the inner value failed to decode by
    /// setting the original value to the returned [Value]'s inner value.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `f` - The function to be called for each item in the deque.
    pub async fn dmap<V>(
        &self,
        dkey: &K,
        f: impl Fn(Value<Result<V, Error>>) -> Option<Value<Result<V, Error>>>,
    ) where
        V: Encode + DecodeOwned,
    {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        let now = Utc::now();

        deque.retain_mut(|v| {
            if v.is_expired(&now) {
                return false;
            }

            let decoded = bitcode::decode::<V>(v).map_err(|_| Error::Decoding);

            let new_value = f(Value {
                value: decoded,
                expires_at: v.expires_at,
            });

            if let Some(new_value) = new_value {
                if let Ok(inner) = new_value.value {
                    let encoded = bitcode::encode(&inner);

                    *v = Value {
                        value: encoded,
                        expires_at: new_value.expires_at,
                    };
                } else {
                    v.expires_at = new_value.expires_at;
                }
            }

            true
        });

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
        }
    }

    /// Returns all items in a deque.
    ///
    /// This function returns a cloned version of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    ///
    /// Returns:
    /// [`VecDeque<Value<Result<V, Error>>>`] - The deque with its values, each with its own inner
    /// decoding result. This will be an empty deque if the deque does not exist.
    pub async fn dall<V>(&self, dkey: &K) -> VecDeque<Value<Result<V, Error>>>
    where
        V: DecodeOwned,
    {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return VecDeque::new(),
        };

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
            return VecDeque::new();
        }

        (*deque)
            .iter()
            .map(|i| {
                let decoded = bitcode::decode::<V>(i).map_err(|_| Error::Decoding);

                Value {
                    value: decoded,
                    expires_at: i.expires_at,
                }
            })
            .collect()
    }

    /// Retains only the first `len` items of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `len` - The amount of items to retain.
    pub async fn dftruncate(&self, dkey: &K, len: usize) {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
            return;
        }

        deque.truncate(len);
    }

    /// Retains only the last `len` items of the deque.
    ///
    /// Arguments:
    /// * `dkey` - The key of the deque.
    /// * `len` - The amount of items to retain.
    pub async fn dbtruncate(&self, dkey: &K, len: usize) {
        let mut deque = match self.deques.get_async(dkey).await {
            Some(v) => v,
            None => return,
        };

        // Not removing all expired items before draining would cause issues with indexes being
        // misplaced because of having counted expired items too.
        let now = Utc::now();
        deque.retain(|i| !i.is_expired(&now));

        if deque.is_empty() {
            // Drop before removing not to cause a deadlock.
            drop(deque);
            self.deques.remove_async(dkey).await;
            return;
        }

        let idx = (deque.len() - len).max(0);
        deque.drain(..idx);
    }
}

impl<K> Default for TurboStore<K>
where
    K: Hash + Eq,
{
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Encode, Decode, PartialEq, Eq, Clone)]
    struct TestValue {
        number: i32,
        string: String,
    }

    #[pollster::test]
    async fn test_kv_operations() {
        let store: TurboStore<i32> = TurboStore::with_capacity(2);

        let value_1 = TestValue {
            number: 123,
            string: "Hello world!".into(),
        };
        let value_2 = TestValue {
            number: 456,
            string: "Bye bye world!".into(),
        };

        store.set(1, &value_1, Duration::minutes(1)).await;

        // Test the insert happening twice and being properly overwritten.
        store.set(2, &value_1, Duration::minutes(1)).await;
        store.set(2, &value_2, Duration::minutes(1)).await;

        let retrieved_1 = store
            .get::<TestValue>(&1)
            .await
            .expect("There was no KV pair with key 1");

        let now = Utc::now();
        // Leave a threshold for the code up to have time to execute.
        assert!(
            retrieved_1.expires_at > now + Duration::seconds(59)
                && retrieved_1.expires_at <= now + Duration::minutes(1),
            "The expiry time for key 1 was not between 1 minute and 59 seconds in the future."
        );

        assert_eq!(
            retrieved_1
                .as_ref()
                .expect("The retrieved KV 1 failed to be decoded"),
            &value_1,
            "The retrieved value for key 1 was not the same value than the one set previously."
        );

        store.expire(1, Duration::seconds(30)).await;

        let popped_1 = store
            .pop::<TestValue>(&1)
            .await
            .expect("There was no value to pop for key 1");

        let now = Utc::now();
        // Leave a threshold for the code up to have time to execute.
        assert!(
            popped_1.expires_at > now + Duration::seconds(29)
                && popped_1.expires_at <= now + Duration::seconds(30),
            "The expiry time for key 1 was not between 29 and 30 seconds in the future, even after its TTL was updated."
        );

        assert_eq!(
            popped_1
                .as_ref()
                .expect("The popped KV 1 failed to be decoded"),
            &value_1,
            "The retrieved value for key 1 was not the same value than the one set previously."
        );

        let retrieved_after_popped_1 = store.get::<TestValue>(&1).await;

        assert!(
            retrieved_after_popped_1.is_none(),
            "The value for key 1 was there even after popped."
        );

        assert!(
            store.exists(&2).await,
            "The key 2 did not exist even after it was added."
        );

        store.rem(&2).await;

        assert!(
            !store.exists(&2).await,
            "The key 2 existed even after it was removed."
        );

        let retrieved_after_removed_2 = store.get::<TestValue>(&2).await;

        assert!(
            retrieved_after_removed_2.is_none(),
            "The value for key 2 was there even after removed."
        );

        store.set(1, &1, Duration::minutes(1)).await;

        let incr_1 = store
            .get::<i32>(&1)
            .await
            .expect("There was no value for key 1 after setting to a previously-removed key");

        let now = Utc::now();
        // Leave a threshold for the code up to have time to execute.
        assert!(
            incr_1.expires_at > now + Duration::seconds(59)
                && popped_1.expires_at <= now + Duration::minutes(1),
            "The expiry time for key 1 was not between 59 seconds and a minute in the future after setting to a previously-removed key."
        );

        assert_eq!(
            incr_1.as_ref().expect(
                "The value could not be decoded into i32 after setting to a previously-removed key"
            ),
            &1,
            "The value of key 1 was not 1 after setting to a previously-removed key"
        );

        store
            .incr(1, 2, Duration::minutes(5))
            .await
            .expect("INCR failed to run because the old value could not be decoded");

        let incr_1 = store
            .get::<i32>(&1)
            .await
            .expect("There was no value for key 1 after incrementing");

        assert_eq!(
            incr_1
                .as_ref()
                .expect("The value could not be decoded into i32 after incrementing"),
            &3,
            "The value of key 1 was not properly incremented by INCR"
        );

        assert!(
            incr_1.expires_at > now + Duration::seconds(60 * 4 + 59)
                && popped_1.expires_at <= now + Duration::minutes(5),
            "The expiry time for key 1 was not between 4:59 min and 5:00 min in the future after setting to a previously-removed key."
        );

        store
            .decr(1, 1, Duration::minutes(1))
            .await
            .expect("Could not decode the old value to i32 before decrementing");

        let incr_1 = store
            .get::<i32>(&1)
            .await
            .expect("There was no value for key 1 after decrementing after incrementing");

        let now = Utc::now();
        // Leave a threshold for the code up to have time to execute.
        assert!(
            incr_1.expires_at > now + Duration::seconds(59)
                && popped_1.expires_at <= now + Duration::minutes(1),
            "The expiry time for key 1 was not between 59 seconds and a minute in the future after decrementing after incrementing."
        );

        assert_eq!(
            incr_1.as_ref().expect(
                "The value could not be decoded into i32 after decrementing after incrementing"
            ),
            &2,
            "The value of key 1 was not 1 after decrementing after incrementing"
        );

        store.set(1, &0, Duration::minutes(1)).await;

        store
            .decr(1, i32::MAX, Duration::minutes(1))
            .await
            .expect("Could not decode the old value when decrementing by i32::MAX");
        store.decr(1, i32::MAX, Duration::minutes(1)).await.expect(
            "Could not decode the old value when decrementing by i32::MAX for the second time",
        );

        let decr_1 = store
            .get::<i32>(&1)
            .await
            .expect("There was no value for key 1 after decrementing after incrementing");

        assert_eq!(
            decr_1
                .as_ref()
                .expect("The value could not be decoded into i32 after decrementing by i32::MAX"),
            &i32::MIN,
            "The value of key 1 was not saturated to i32::MIN after decrementing by i32::MAX"
        );

        store.set(1, &0, Duration::minutes(1)).await;

        store
            .incr(1, i32::MAX, Duration::minutes(1))
            .await
            .expect("Could not decode the old value when incrementing by i32::MAX");
        store.incr(1, i32::MAX, Duration::minutes(1)).await.expect(
            "Could not decode the old value when incrementing by i32::MAX for the second time",
        );

        let incr_1 = store
            .get::<i32>(&1)
            .await
            .expect("There was no value for key 1 after incrementing after resetting");

        assert_eq!(
            incr_1
                .as_ref()
                .expect("The value could not be decoded into i32 after incrementing by i32::MAX"),
            &i32::MAX,
            "The value of key 1 was not saturated to i32::MAX after incrementing by i32::MAX"
        );
    }
}