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
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
#[cfg(test)]
mod tests_double_map;

use core::hash::{BuildHasher, Hash};
use core::borrow::Borrow;
use std::collections::hash_map;
use std::collections::HashMap;
use std::collections::TryReserveError;
use core::fmt::{self, Debug};
use core::hint::unreachable_unchecked;
use core::mem;
use core::iter::{FromIterator, Extend};

/// A hash map with double keys implemented as wrapper above two
/// [`HashMaps`](`std::collections::HashMap`).
///
/// Internally, two [`HashMap`](`std::collections::HashMap`) are created. One of type
/// `HashMap<K1, (K2, V)>` to hold the `(K2, V)` tuple, and second one of type
/// `HashMap<K2, K1>` just for holding the primary key of type `K1`.
/// We hold the `(K2, V)` tuple inside first `Hashmap` for synchronization purpose,
/// so that we can organize checking that both primary key of type `K1` and the
/// secondary key is of type `K2` refer to the same value, and so on.
/// Keys may be the same or different type.
///
/// By default, [`DHashMap`] as [`HashMap`](`std::collections::HashMap`)
/// uses a hashing algorithm selected to provide
/// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
/// reasonable best-effort is made to generate this seed from a high quality,
/// secure source of randomness provided by the host without blocking the
/// program. Because of this, the randomness of the seed depends on the output
/// quality of the system's random number generator when the seed is created.
/// In particular, seeds generated when the system's entropy pool is abnormally
/// low such as during system boot may be of a lower quality.
///
/// The default hashing algorithm, like in [`HashMap`](`std::collections::HashMap`),
/// is currently SipHash 1-3, though this is
/// subject to change at any point in the future. While its performance is very
/// competitive for medium sized keys, other hashing algorithms will outperform
/// it for small keys like integers as well as large keys like long
/// strings, though those algorithms will typically *not* protect against
/// attacks such as HashDoS.
///
/// The hashing algorithm can be replaced on a per-[`DHashMap`] basis using the
/// [`default`](`std::default::Default::default`), [`with_hasher`](`DHashMap::with_hasher`),
/// and [`with_capacity_and_hasher`](`DHashMap::with_capacity_and_hasher`) methods.
/// There are many alternative [hashing algorithms available on crates.io].
///
/// It is required that the keys implement the [`Eq`] and
/// [`Hash`](`core::hash::Hash`) traits, although
/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
/// If you implement these yourself, it is important that the following
/// property holds:
///
/// ```text
/// k1 == k2 -> hash(k1) == hash(k2)
/// ```
///
/// In other words, if two keys are equal, their hashes must be equal.
///
/// It is a logic error for a key to be modified in such a way that the key's
/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
/// the [`Eq`] trait, changes while it is in the map. This is normally only
/// possible through [`Cell`](`std::cell::Cell`), [`RefCell`](`std::cell::RefCell`),
/// global state, I/O, or unsafe code.
/// The behavior resulting from such a logic error is not specified, but will
/// not result in undefined behavior. This could include panics, incorrect results,
/// aborts, memory leaks, and non-termination.
///
/// [hashing algorithms available on crates.io]: https://crates.io/keywords/hasher

#[derive(Clone)]
pub struct DHashMap<K1, K2, V, S = hash_map::RandomState> {
    value_map: HashMap<K1, (K2, V), S>,
    key_map: HashMap<K2, K1, S>,
}

impl<K1, K2, V> DHashMap<K1, K2, V, hash_map::RandomState> {
    /// Creates a new empty [`DHashMap`]s with [`RandomState`](std::collections::hash_map::RandomState)
    /// type of hash builder to hash keys.
    ///
    /// The primary key is of type `K1` and the secondary key is of type `K2`.
    /// The value is of type `V`.
    ///
    /// Internally, two [`HashMap`](`std::collections::HashMap`) are created. One of type
    /// `HashMap<K1, (K2, V)>` to hold the `(K2, V)` tuple, and second one of type
    /// `HashMap<K2, K1>` just for holding the primary key of type `K1`.
    /// We hold the `(K2, V)` tuple inside first `Hashmap` for synchronization purpose,
    /// so that we can organize checking both primary key of type `K1` and the
    /// secondary key is of type `K2` refer to the same value, and so on.
    ///
    /// The hash map is initially created with a capacity of 0, so it will not allocate until
    /// it is first inserted into.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// let mut map: DHashMap<u32, &str, i32> = DHashMap::new();
    ///
    /// // The created DHashMap holds none elements
    /// assert_eq!(map.len(), 0);
    ///
    /// // The created DHashMap also doesn't allocate memory
    /// assert_eq!(map.capacity(), 0);
    ///
    /// // Now we insert element inside created DHashMap
    /// map.insert(1, "One", 1);
    /// // We can see that the DHashMap holds 1 element
    /// assert_eq!(map.len(), 1);
    /// // And it also allocates some capacity (by default it starts from 3 elements)
    /// assert!(map.capacity() > 1);
    /// ```
    #[inline]
    #[must_use]
    pub fn new() -> DHashMap<K1, K2, V, hash_map::RandomState> {
        DHashMap {
            value_map: HashMap::new(),
            key_map: HashMap::new(),
        }
    }

    /// Creates an empty [`DHashMap`] with the specified capacity.
    ///
    /// The hash map will be able to hold at least `capacity` elements without
    /// reallocating. If `capacity` is 0, the hash map will not allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// let mut map: DHashMap<&str, i32, &str> = DHashMap::with_capacity(5);
    ///
    /// // The created DHashMap holds none elements
    /// assert_eq!(map.len(), 0);
    /// // But it can hold at least 5 elements without reallocating
    /// let empty_map_capacity = map.capacity();
    /// assert!(empty_map_capacity >= 5);
    ///
    /// // Now we insert some 5 elements inside created DHashMap
    /// map.insert("One",   1, "a");
    /// map.insert("Two",   2, "b");
    /// map.insert("Three", 3, "c");
    /// map.insert("Four",  4, "d");
    /// map.insert("Five",  5, "e");
    ///
    /// // We can see that the DHashMap holds 5 elements
    /// assert_eq!(map.len(), 5);
    /// // But its capacity isn't changed
    /// assert_eq!(map.capacity(), empty_map_capacity)
    /// ```
    #[inline]
    #[must_use]
    pub fn with_capacity(capacity: usize) -> DHashMap<K1, K2, V, hash_map::RandomState> {
        DHashMap {
            value_map: HashMap::with_capacity(capacity),
            key_map: HashMap::with_capacity(capacity),
        }
    }
}

impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
where
    S: Clone,
{
    /// Creates an empty [`DHashMap`] which will use the given hash builder to hash
    /// keys.
    ///
    /// The created map has the default initial capacity, witch is equal to 0, so
    /// it will not allocate until it is first inserted into.
    ///
    /// Warning: `hash_builder` is normally randomly generated, and
    /// is designed to allow [`DHashMap`] to be resistant to attacks that
    /// cause many collisions and very poor performance. Setting it
    /// manually using this function can expose a DoS attack vector.
    ///
    /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
    /// the [`DHashMap`] to be useful, see its documentation for details.
    /// It also should implement the [`Clone`] trait because we create two
    /// [`HashMap`]s inside the [`DHashMap`], so that we need to
    /// [`clone`](core::clone::Clone::clone) hash_builder for passing it inside
    /// two inner `HashMaps`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use std::collections::hash_map::RandomState;
    ///
    /// let s = RandomState::new();
    /// let mut map = DHashMap::with_hasher(s);
    ///
    /// // The created DHashMap holds none elements
    /// assert_eq!(map.len(), 0);
    ///
    /// // The created DHashMap also doesn't allocate memory
    /// assert_eq!(map.capacity(), 0);
    ///
    /// // Now we insert elements inside created DHashMap
    /// map.insert("One", 1, 2);
    /// // We can see that the DHashMap holds 1 element
    /// assert_eq!(map.len(), 1);
    /// // And it also allocates some capacity (by default it starts from 3 elements)
    /// assert!(map.capacity() > 1);
    /// ```
    #[inline]
    pub fn with_hasher(hash_builder: S) -> DHashMap<K1, K2, V, S> {
        DHashMap {
            value_map: HashMap::with_hasher(hash_builder.clone()),
            key_map: HashMap::with_hasher(hash_builder),
        }
    }

    /// Creates an empty [`DHashMap`] with the specified capacity, using `hash_builder`
    /// to hash the keys.
    ///
    /// The hash map will be able to hold at least `capacity` elements without
    /// reallocating. If `capacity` is 0, the hash map will not allocate.
    ///
    /// Warning: `hash_builder` is normally randomly generated, and
    /// is designed to allow HashMaps to be resistant to attacks that
    /// cause many collisions and very poor performance. Setting it
    /// manually using this function can expose a DoS attack vector.
    ///
    /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
    /// the [`DHashMap`] to be useful, see its documentation for details.
    /// It also should implement the [`Clone`] trait because we create two
    /// [`HashMap`]s inside the [`DHashMap`], so that we need to
    /// [`clone`](core::clone::Clone::clone) hash_builder for passing it inside
    /// two inner `HashMaps`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use std::collections::hash_map::RandomState;
    ///
    /// let s = RandomState::new();
    /// let mut map = DHashMap::with_capacity_and_hasher(5, s);
    ///
    /// // The created DHashMap holds none elements
    /// assert_eq!(map.len(), 0);
    /// // But it can hold at least 5 elements without reallocating
    /// let empty_map_capacity = map.capacity();
    /// assert!(empty_map_capacity >= 5);
    ///
    /// // Now we insert some 5 elements inside the created DHashMap
    /// map.insert("One",   1, "a");
    /// map.insert("Two",   2, "b");
    /// map.insert("Three", 3, "c");
    /// map.insert("Four",  4, "d");
    /// map.insert("Five",  5, "e");
    ///
    /// // We can see that the DHashMap holds 5 elements
    /// assert_eq!(map.len(), 5);
    /// // But its capacity isn't changed
    /// assert_eq!(map.capacity(), empty_map_capacity)
    /// ```
    #[inline]
    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> DHashMap<K1, K2, V, S> {
        DHashMap {
            value_map: HashMap::with_capacity_and_hasher(capacity, hash_builder.clone()),
            key_map: HashMap::with_capacity_and_hasher(capacity, hash_builder),
        }
    }
}

impl<K1, K2, V, S> DHashMap<K1, K2, V, S> {
    /// Returns the number of elements the map can hold without reallocating.
    ///
    /// This number is a lower bound; the `DHashMap<K1, K2, V>` collection might
    /// be able to hold more, but is guaranteed to be able to hold at least this many.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// let map = DHashMap::<i32, &str, &str>::with_capacity(16);
    ///
    /// // The created DHashMap can hold at least 16 elements
    /// assert!(map.capacity() >= 16);
    /// // But for now it doesn't hold any elements
    /// assert_eq!(map.len(), 0);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        // we only take it into account because it contains the most important part of
        // hashtable - the value
        self.value_map.capacity()
    }

    /// Returns the number of elements in the map.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut a = DHashMap::new();
    /// // The created DHashMap doesn't hold any elements
    /// assert_eq!(a.len(), 0);
    /// // We insert one element
    /// a.insert(1, "Breakfast", "Pancakes");
    /// // And can be sure that DHashMap holds one element
    /// assert_eq!(a.len(), 1);
    ///
    /// let mut map = DHashMap::new();
    /// map.insert(1, "Breakfast", "Pancakes");
    /// map.insert(2, "Lunch", "Sandwich");
    /// assert_eq!(map.len(), 2);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        // we only take it into account because it contains the most important part of
        // hashtable - the value
        self.value_map.len()
    }

    /// Returns `true` if the map contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut a = DHashMap::new();
    /// // The created DHashMap doesn't hold any elements, so it's empty
    /// assert!(a.is_empty() && a.len() == 0);
    /// // We insert one element
    /// a.insert(1, "a", "One");
    /// // And can be sure that DHashMap is not empty but holds one element
    /// assert!(!a.is_empty() && a.len() == 1);
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        // we only take it into account because it contains the most important part of
        // hashtable - the value
        self.value_map.is_empty()
    }

    /// Clears the map, removing all keys-value tuples.
    /// Keeps the allocated memory for reuse.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut a = DHashMap::new();
    /// a.insert(1, "Breakfast", "Pancakes");
    /// a.insert(2, "Lunch", "Sandwich");
    ///
    /// // We can that see DHashMap holds two elements
    /// assert_eq!(a.len(), 2);
    /// let capacity_before_clearing = a.capacity();
    ///
    /// a.clear();
    ///
    /// // And now the map is empty and contains no elements
    /// assert!(a.is_empty() && a.len() == 0);
    /// // But map capacity is equal to the old one
    /// assert_eq!(a.capacity(), capacity_before_clearing);
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.value_map.clear();
        self.key_map.clear();
    }

    /// Returns a reference to the map's [`BuildHasher`].
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use std::collections::hash_map::RandomState;
    ///
    /// let hasher = RandomState::new();
    /// let map: DHashMap<i32, i32, i32> = DHashMap::with_hasher(hasher);
    /// let hasher: &RandomState = map.hasher();
    /// ```
    #[inline]
    pub fn hasher(&self) -> &S {
        self.value_map.hasher()
    }
}

impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
where
    K1: Eq + Hash,
    K2: Eq + Hash,
    S: BuildHasher,
{
    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the `DHashMap<K1, K2, V>`. The collection may reserve more space to avoid
    /// frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the new allocation size overflows `usize::Max / 2`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// let mut a = DHashMap::<&str, i128, &str>::new();
    /// a.insert("apple",  1, "a");
    /// a.insert("banana", 2, "b");
    /// a.insert("cherry", 3, "c");
    ///
    /// // We reserve space for additional 10 elements
    /// a.reserve(10);
    /// // And can see that created DHashMap can hold at least 13 elements
    /// assert!(a.capacity() >= 13);
    /// ```
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.value_map.reserve(additional);
        self.key_map.reserve(additional);
    }

    /// Tries to reserve capacity for at least `additional` more elements to be inserted
    /// in the given `DHashMap<K1, K2, V>`. The collection may reserve more space to avoid
    /// frequent reallocations.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an error
    /// is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::TryReserveError;
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<i32, &str, isize> = DHashMap::new();
    /// map.try_reserve(20).expect("something go wrong");
    ///
    /// // So everything is Ok
    /// let capacity = map.capacity();
    /// assert!(capacity >= 20);
    ///
    /// // Let's check that it returns error if it can not reserve asked capacity
    /// let result = map.try_reserve(usize::MAX);
    /// match result {
    ///     Err(_) => println!("It is ok, error was expected"),
    ///     Ok(_) => unreachable!(),
    /// }
    /// // And capacity of the map isn't changed
    /// assert_eq!(map.capacity(), capacity);
    /// ```
    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.value_map.try_reserve(additional)?;
        self.key_map.try_reserve(additional)
    }

    /// Shrinks the capacity of the map as much as possible. It will drop
    /// down as much as possible while maintaining the internal rules
    /// and possibly leaving some space in accordance with the resize policy.
    ///
    /// Note that in general case the capacity is not *guaranteed* to shrink,
    /// but a zero-length DHashMap should generally shrink to capacity zero.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// let mut a = DHashMap::<i32, &str, &str>::with_capacity(16);
    ///
    /// // This DHashMap can hold at least 16 elements
    /// let capacity_before_shrink = a.capacity();
    /// assert!(capacity_before_shrink >= 16);
    ///
    /// // And after shrinking, map capacity is less than before
    /// a.shrink_to_fit();
    /// assert!(a.capacity() < capacity_before_shrink);
    ///
    /// // If we reserve some memory and insert some elements
    /// a.reserve(10);
    /// a.insert(1, "a", "One");
    /// a.insert(2, "b", "Two");
    /// assert!(a.capacity() >= 10);
    ///
    /// // After applying shrink_to_fit method, the capacity less than
    /// // reserved before, but inserted elements are still inside map
    /// a.shrink_to_fit();
    /// assert!(a.capacity() >= 2 && a.capacity() < 10);
    /// assert_eq!(a.get_key1(&1), Some(&"One"));
    /// assert_eq!(a.get_key1(&2), Some(&"Two"))
    /// ```
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.value_map.shrink_to_fit();
        self.key_map.shrink_to_fit();
    }

    /// Shrinks the capacity of the map with a lower limit. It will drop
    /// down no lower than the supplied limit while maintaining the internal rules
    /// and possibly leaving some space in accordance with the resize policy.
    ///
    /// If the current capacity is less than the lower limit, this is a no-op.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<i32, i32, i32> = DHashMap::with_capacity(100);
    /// map.insert(1, 2, 3);
    /// map.insert(4, 5, 6);
    /// map.insert(7, 8, 9);
    /// assert!(map.capacity() >= 100);
    ///
    /// // We have only 3 elements inside map, so it works
    /// map.shrink_to(10);
    /// assert!(map.capacity() >= 10 && map.capacity() < 100);
    ///
    /// // If we try shrink_to the capacity, that less than elements quantity inside map
    /// map.shrink_to(0);
    /// // So it works partially, but the resulting capacity is not less than quantity
    /// // of elements inside the map
    /// assert!(map.capacity() >= 3  && map.capacity() < 10);
    /// ```
    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.value_map.shrink_to(min_capacity);
        self.key_map.shrink_to(min_capacity);
    }

    /// Returns a reference to the value corresponding to the given primary key (key #1).
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map = DHashMap::new();
    /// map.insert(1, "a", "One");
    /// assert_eq!(map.get_key1(&1), Some(&"One"));
    /// assert_eq!(map.get_key1(&2), None);
    /// ```
    #[inline]
    pub fn get_key1<Q: ?Sized>(&self, k1: &Q) -> Option<&V>
    where
        K1: Borrow<Q>,
        Q: Hash + Eq,
    {
        let (_, value) = self.value_map.get(k1)?;
        Some(value)
    }

    /// Returns a reference to the value corresponding to the given secondary key (key #2).
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map = DHashMap::new();
    /// map.insert(1, "a", "One");
    /// assert_eq!(map.get_key2(&"a"), Some(&"One"));
    /// assert_eq!(map.get_key2(&"b"), None);
    /// ```
    #[inline]
    pub fn get_key2<Q: ?Sized>(&self, k2: &Q) -> Option<&V>
    where
        K2: Borrow<Q>,
        Q: Hash + Eq,
    {
        let key = self.key_map.get(k2)?;
        let (_, value) = self.value_map.get(key)?;
        Some(value)
    }

    /// Returns a mutable reference to the value corresponding to
    /// the given primary key `(key #1)`.
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map = DHashMap::new();
    /// map.insert(1, "a", "One");
    /// if let Some(x) = map.get_mut_key1(&1) {
    ///     *x = "First";
    /// }
    /// assert_eq!(map.get_key1(&1), Some(&"First"));
    /// ```
    #[inline]
    pub fn get_mut_key1<Q: ?Sized>(&mut self, k1: &Q) -> Option<&mut V>
    where
        K1: Borrow<Q>,
        Q: Hash + Eq,
    {
        let (_, value) = self.value_map.get_mut(k1)?;
        Some(value)
    }

    /// Returns a mutable reference to the value corresponding to
    /// the given secondary key `(key #2)`.
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map = DHashMap::new();
    /// map.insert(1, "a", "One");
    /// if let Some(x) = map.get_mut_key2(&"a") {
    ///     *x = "First";
    /// }
    /// assert_eq!(map.get_key2(&"a"), Some(&"First"));
    /// ```
    #[inline]
    pub fn get_mut_key2<Q: ?Sized>(&mut self, k2: &Q) -> Option<&mut V>
    where
        K2: Borrow<Q>,
        Q: Hash + Eq,
    {
        let key = self.key_map.get(k2)?;
        let (_, value) = self.value_map.get_mut(key)?;
        Some(value)
    }

    /// Removes element from the map using a primary key `(key #1)`,
    /// returning the value corresponding to the key if the key was
    /// previously in the map. Keeps the allocated memory for reuse.
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Note
    ///
    /// This method removes not only value, but whole element includng
    /// primary `K1` and secondary `K2` keys
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// // We create map with three elements
    /// let mut map = DHashMap::new();
    /// map.insert(1, "One", String::from("Eins"));
    /// map.insert(2, "Two", String::from("Zwei"));
    /// map.insert(3, "Three", String::from("Drei"));
    ///
    /// // We can see that DHashMap holds three elements
    /// assert!(map.len() == 3 && map.capacity() >= 3);
    ///
    /// // Also we reserve memory for holdind additionally at least 20 elements,
    /// // so that DHashMap can hold 23 elements or more
    /// map.reserve(20);
    /// let capacity_before_remove = map.capacity();
    ///
    /// // We remove element with key #1 from the map and get corresponding value
    /// assert_eq!(map.remove_key1(&1), Some("Eins".to_owned()));
    /// // If we try to remove the same element with key #1 twise we get None,
    /// // because that element was already removed
    /// assert_eq!(map.remove_key1(&1), None);
    ///
    /// // Now we remove all elements one by one, and can see that map holds nothing
    /// map.remove_key1(&2);
    /// map.remove_key1(&3);
    /// assert_eq!(map.len(), 0);
    ///
    /// // But map capacity is equal to the old one and can hold at least 23 elements
    /// assert!(map.capacity() == capacity_before_remove && map.capacity() >= 23);
    /// ```
    #[inline]
    pub fn remove_key1<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
    where
        K1: Borrow<Q>,
        Q: Hash + Eq,
    {
        let (key, value) = self.value_map.remove(key)?;
        self.key_map.remove(&key);
        Some(value)
    }

    /// Removes element from the map using a secondary key `(key #2)`,
    /// returning the value corresponding to the key if the key was
    /// previously in the map. Keeps the allocated memory for reuse.
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Note
    ///
    /// This method removes not only value, but whole element includng
    /// primary `K1` and secondary `K2` keys
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// // We create map with three elements
    /// let mut map = DHashMap::new();
    /// map.insert(1, "One", String::from("Eins"));
    /// map.insert(2, "Two", String::from("Zwei"));
    /// map.insert(3, "Three", String::from("Drei"));
    ///
    /// // We can see that DHashMap holds three elements
    /// assert!(map.len() == 3 && map.capacity() >= 3);
    ///
    /// // Also we reserve memory for holdind additionally at least 20 elements,
    /// // so that DHashMap can hold 23 elements or more
    /// map.reserve(20);
    /// let capacity_before_remove = map.capacity();
    ///
    /// // We remove element with key #1 from the map and get corresponding value
    /// assert_eq!(map.remove_key2(&"One"), Some("Eins".to_owned()));
    /// // If we try to remove the same element with key #1 twise we get None,
    /// // because that element was already removed
    /// assert_eq!(map.remove_key2(&"One"), None);
    ///
    /// // Now we remove all elements one by one, and can see that map holds nothing
    /// map.remove_key2(&"Two");
    /// map.remove_key2(&"Three");
    /// assert_eq!(map.len(), 0);
    ///
    /// // But map capacity is equal to the old one and can hold at least 23 elements
    /// assert!(map.capacity() == capacity_before_remove && map.capacity() >= 23);
    /// ```
    #[inline]
    pub fn remove_key2<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
    where
        K2: Borrow<Q>,
        Q: Hash + Eq,
    {
        let key = self.key_map.remove(key)?;
        let (_, value) = self.value_map.remove(&key)?;
        Some(value)
    }
}

impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
where
    K1: Eq + Hash + Clone,
    K2: Eq + Hash + Clone,
    S: BuildHasher,
{
    /// Tries to get the given keys' corresponding entry in the map for in-place
    /// manipulation.
    ///
    /// Returns [`Entry`] enum if `all` of the following is `true`:
    /// - Both key #1 and key #2 are vacant.
    /// - If both key #1 and key #2 exist, they refer to the same value.
    ///
    /// When the above statements are `false`, [`entry`](DHashMap::entry) method returns
    /// [`EntryError`] structure which contains the [`ErrorKind`] enum, and the values
    /// of provided keys that were not used for creation entry (that can be used for
    /// another purpose).
    ///
    /// Depending on the points below, different [`ErrorKind`] variants may be returned:
    /// - When key #1 is vacant, but key #2 already exists with some value, the
    /// returned [`ErrorKind`] variant is [`ErrorKind::VacantK1AndOccupiedK2`].
    /// - When key #1 already exists with some value, but key #2 is vacant, the
    /// returned [`ErrorKind`] variant is [`ErrorKind::OccupiedK1AndVacantK2`].
    /// - When both key #1 and key #2 already exist with some values, but point
    /// to different entries (values) the returned [`ErrorKind`] variant is
    /// [`ErrorKind::KeysPointsToDiffEntries`].
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::ErrorKind;
    ///
    /// let mut letters = DHashMap::new();
    ///
    /// for ch in "a short treatise on fungi".chars() {
    ///     if let Ok(entry) = letters.entry(ch.clone(), ch) {
    ///         let counter = entry.or_insert(0);
    ///         *counter += 1;
    ///     }
    /// }
    ///
    /// assert_eq!(letters.get_key1(&'s'), Some(&2));
    /// assert_eq!(letters.get_key1(&'t'), Some(&3));
    /// assert_eq!(letters.get_key1(&'u'), Some(&1));
    /// assert_eq!(letters.get_key1(&'y'), None);
    ///
    /// // Return `ErrorKind::OccupiedK1AndVacantK2` if key #1 already
    /// // exists with some value, but key #2 is vacant.
    /// let error_kind = letters.entry('s', 'y').unwrap_err().error;
    /// assert_eq!(error_kind, ErrorKind::OccupiedK1AndVacantK2);
    ///
    /// // Return `ErrorKind::VacantK1AndOccupiedK2` if key #1 is vacant,
    /// // but key #2 already exists with some value.
    /// let error_kind = letters.entry('y', 's').unwrap_err().error;
    /// assert_eq!(error_kind, ErrorKind::VacantK1AndOccupiedK2);
    ///
    /// // Return `ErrorKind::KeysPointsToDiffEntries` if both
    /// // key #1 and key #2 already exist with some values,
    /// // but point to different entries (values).
    /// let error_kind = letters.entry('s', 't').unwrap_err().error;
    /// assert_eq!(error_kind, ErrorKind::KeysPointsToDiffEntries);
    /// ```
    #[inline]
    pub fn entry(&mut self, k1: K1, k2: K2) -> Result<Entry<'_, K1, K2, V>, EntryError<K1, K2>> {
        // I don't like the way this function is done. But it looks like Hashmap::entry
        // (which internally uses hashbrown::rustc_entry::HashMap::rustc_entry) calls
        // self.reserve(1) when no key is found (vacant). It seems this one will lead
        // to constant allocation and deallocation, given that value_map.entry and
        // key_map.entry may not be vacant and occupied at the same time, so I'll
        // leave the implementation this way for now
        match self.value_map.get(&k1) {
            None => match self.key_map.get(&k2) {
                None => {
                    // SAFETY: We already check that both key vacant
                    Ok( unsafe { self.map_vacant_entry(k1, k2) } )
                }
                // Error: Vacant key #1 of type K1 and occupied key # 2 of type K2
                Some(_) => Err(EntryError {
                    error: ErrorKind::VacantK1AndOccupiedK2,
                    keys: (k1, k2),
                }),
            },
            Some((key2_exist, _)) => match self.key_map.get(&k2) {
                Some(key1_exist) => {
                    return if k1 == *key1_exist && k2 == *key2_exist {
                        // SAFETY: We already check that both key exist and refer to the same value
                        Ok( unsafe { self.map_occupied_entry(k1, k2) } )
                    } else {
                        // Error: key #1 and key # 2 refer to different entries / values
                        Err(EntryError {
                            error: ErrorKind::KeysPointsToDiffEntries,
                            keys: (k1, k2),
                        })
                    };
                }
                None => Err(EntryError {
                    error: ErrorKind::OccupiedK1AndVacantK2,
                    keys: (k1, k2),
                }),
            },
        }
    }

    // This function used only inside this crate. Return Entry::Occupied
    // because we know exactly that both entry are occupied
    #[inline(always)]
    unsafe fn map_occupied_entry(&mut self, k1: K1, k2: K2) -> Entry<'_, K1, K2, V> {
        let raw_v = self.value_map.entry(k1);
        let raw_k = self.key_map.entry(k2);
        match raw_v {
            hash_map::Entry::Occupied(base_v) => match raw_k {
                hash_map::Entry::Occupied(base_k) => {
                    Entry::Occupied(OccupiedEntry { base_v, base_k })
                }
                _ => unreachable_unchecked(),
            },
            _ => unreachable_unchecked(),
        }
    }

    // This function used only inside this crate. Return Entry::Vacant
    // because we know exactly that both entry are vacant
    #[inline(always)]
    unsafe fn map_vacant_entry(&mut self, k1: K1, k2: K2) -> Entry<'_, K1, K2, V> {
        let raw_v = self.value_map.entry(k1);
        let raw_k = self.key_map.entry(k2);
        match raw_v {
            hash_map::Entry::Vacant(base_v) => match raw_k {
                hash_map::Entry::Vacant(base_k) => {
                    Entry::Vacant(VacantEntry { base_v, base_k })
                },
                _ => unreachable_unchecked(),
            },
            _ => unreachable_unchecked(),
        }
    }

    /// Inserts given keys and value into the map **`without checking`**. Update the value
    /// if key #1 of type `K1` already presents with returning old value.
    ///
    /// If the map did not have these keys present, [`None`] is returned.
    ///
    /// # Warning
    ///
    /// **Using this method can lead to unsynchronization between key #1 and key #1,
    /// so that they can refer to different values.** It also can lead to different
    /// quantity of keys, so that quantity of keys #2 `K2` can be ***less*** than
    /// quantity of keys #1 `K1`.
    ///
    /// If the map did have these keys vacant or **present** and **both keys refer to
    /// the same value** it is ***Ok***, the value is updated, and the old value is
    /// returned inside `Some(V)` variant.
    ///
    /// **But** for this method, it doesn't matter if key # 2 exists or not,
    /// it returns updated value also if the map contains only key #1.
    /// It is ***because*** this method **doesn't check** that:
    /// - key #1 is vacant, but key #2 already exists with some value;
    /// - key #1 already exists with some value, but key #2 is vacant;
    /// - both key #1 and key #2 already exist with some values, but
    /// point to different entries (values).
    ///
    /// The keys are not updated, though; this matters for types that can
    /// be `==` without being identical. See the [std module-level documentation]
    /// for more.
    ///
    /// # Note
    ///
    /// Using this method is cheaper than using another insertion
    /// [`entry`](DHashMap::entry), [`insert`](DHashMap::insert) and
    /// [`try_insert`](DHashMap::try_insert) methods.
    ///
    /// Links between keys #1 `K1` and the values that they refer are adequate.
    /// **Unsynchronization** between key #1 and key #2, lead only to that the key # 2
    /// may refer to unexpected value.
    ///
    /// It is recommended to use this method only if you are sure that
    /// key #1 and key #2 are unique. For example if key #1 of type `K1` is generated
    /// automatically and you check only that there is no key #2 of type `K2`.
    ///
    /// [std module-level documentation]: std::collections#insert-and-complex-keys
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use core::hash::Hash;
    ///
    /// let mut map = DHashMap::new();
    ///
    /// // Returns None if keys are vacant
    /// assert_eq!(map.insert_unchecked(1, "a", "One"), None);
    /// assert_eq!(map.is_empty(), false);
    ///
    /// // If the map did have these keys present, the value is updated,
    /// // and the old value is returned inside `Some(V)` variants
    /// map.insert_unchecked(2, "b", "Two");
    /// assert_eq!(map.insert_unchecked(2, "b", "Second"), Some("Two"));
    /// assert_eq!(map.get_key1(&2), Some(&"Second"));
    ///
    /// // But method does not care about key #2
    /// assert_eq!(map.insert_unchecked(1, "b", "First"), Some("One"));
    /// // So key # 2 refers to unexpected value, and now we have double second keys
    /// // referring to the same value
    /// assert_eq!(map.get_key2(&"a"), Some(&"First"));
    /// assert_eq!(map.get_key2(&"b"), Some(&"First"));
    ///
    /// // But it can be safe if you generate one key automatically, and check
    /// // existence only other key. It can be for example like that:
    /// #[derive(Copy, Clone, PartialEq, Eq, Hash)]
    /// pub struct PupilID(usize);
    ///
    /// pub struct Pupil {
    ///     name: String
    /// }
    ///
    /// pub struct Class {
    ///     pupils: DHashMap<PupilID, String, Pupil>,
    ///     len: usize,
    /// }
    ///
    /// impl Class {
    ///     pub fn new() -> Class {
    ///         Self{
    ///             pupils: DHashMap::new(),
    ///             len: 0
    ///         }
    ///     }
    ///     pub fn contains_name(&self, name: &String) -> bool {
    ///         self.pupils.get_key2(name).is_some()
    ///     }
    ///     pub fn add_pupil(&mut self, name: String) -> Option<PupilID> {
    ///         if !self.contains_name(&name) {
    ///             let len = &mut self.len;
    ///             let id = PupilID(*len);
    ///             self.pupils.insert_unchecked( id, name.clone(), Pupil { name } );
    ///             *len += 1;
    ///             Some(id)
    ///         } else {
    ///             None
    ///         }
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn insert_unchecked(&mut self, k1: K1, k2: K2, v: V) -> Option<V> {
        self.key_map.insert(k2.clone(), k1.clone());
        let (_, v) = self.value_map.insert(k1, (k2, v))?;
        Some(v)
    }

    /// Tries to insert given keys and value into the map. Update the value
    /// if keys are already present and refer to the same value with returning
    /// old value.
    ///
    /// If the map did not have these keys present, [`None`] is returned.
    ///
    /// If the map did have these key **present**, and **both keys refer to
    /// the same value**, the value is updated, and the old value is returned
    /// inside `Some(Ok(V))` variants. The key is not updated, though; this
    /// matters for types that can be `==` without being identical.
    /// See the [std module-level documentation] for more.
    ///
    /// The [`insert`](DHashMap::insert) method returns [`InsertError`] structure
    /// (inside of `Some(Err(_))` variants):
    /// - when key #1 is vacant, but key #2 already exists with some value;
    /// - when key #1 already exists with some value, but key #2 is vacant;
    /// - when both key #1 and key #2 already exist with some values, but
    /// point to different entries (values).
    ///
    /// The above mentioned error kinds can be matched through the [`ErrorKind`] enum.
    /// Returned [`InsertError`] structure also contains provided keys and value
    /// that were not inserted and can be used for another purpose.
    ///
    /// [std module-level documentation]: std::collections#insert-and-complex-keys
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::{InsertError, ErrorKind};
    /// let mut map = DHashMap::new();
    ///
    /// // Returns None if keys are vacant
    /// assert_eq!(map.insert(1, "a", "One"), None);
    /// assert_eq!(map.is_empty(), false);
    ///
    /// // If the map did have these keys present, and both keys refer to
    /// // the same value, the value is updated, and the old value is returned
    /// // inside `Some(Ok(V))` variants
    /// map.insert(2, "b", "Two");
    /// assert_eq!(map.insert(2, "b", "Second"), Some(Ok("Two")));
    /// assert_eq!(map.get_key1(&2), Some(&"Second"));
    ///
    /// // Returns `ErrorKind::OccupiedK1AndVacantK2` if key #1 already
    /// // exists with some value, but key #2 is vacant. Error structure
    /// // also contains provided keys and value
    /// match map.insert(1, "c", "value") {
    ///     Some(Err(InsertError{ error, keys, value })) => {
    ///         assert_eq!(error, ErrorKind::OccupiedK1AndVacantK2);
    ///         assert_eq!(keys, (1, "c"));
    ///         assert_eq!(value, "value");
    ///     }
    ///     _ => unreachable!(),
    /// }
    ///
    /// // Returns `ErrorKind::VacantK1AndOccupiedK2` if key #1 is vacant,
    /// // but key #2 already exists with some value.
    /// let error_kind = map.insert(3, "a", "value").unwrap().unwrap_err().error;
    /// assert_eq!(error_kind, ErrorKind::VacantK1AndOccupiedK2);
    ///
    /// // Returns `ErrorKind::KeysPointsToDiffEntries` if both
    /// // key #1 and key #2 already exist with some values,
    /// // but point to different entries (values).
    /// let error_kind = map.insert(1, "b", "value").unwrap().unwrap_err().error;
    /// assert_eq!(error_kind, ErrorKind::KeysPointsToDiffEntries);
    /// ```
    #[inline]
    pub fn insert(&mut self, k1: K1, k2: K2, v: V) -> Option<Result<V, InsertError<K1, K2, V>>> {
        match self.entry(k1, k2) {
            Ok(entry) => match entry {
                Entry::Occupied(mut entry) => {
                    let v = entry.insert(v);
                    Some(Ok(v))
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                    None
                }
            },
            Err(EntryError { error, keys }) => Some(Err(InsertError {
                error,
                keys,
                value: v,
            })),
        }
    }

    /// Tries to insert given keys and value into the map, and returns
    /// a mutable reference to the value in the entry if the map did not
    /// have these keys present.
    ///
    /// If the map did have these keys **present**, and **both keys refer to
    /// the same value**, ***nothing*** is updated, and a [`TryInsertError::Occupied`]
    /// enum variant error containing [`OccupiedError`] structure is returned.
    /// The [`OccupiedError`] contains the occupied entry [`OccupiedEntry`],
    /// and the value that was not inserted.
    ///
    /// The [`try_insert`](DHashMap::try_insert) method return [`InsertError`] structure
    /// (inside of [`TryInsertError::Insert`] variant):
    /// - when key #1 is vacant, but key #2 already exists with some value;
    /// - when key #1 already exists with some value, but key #2 is vacant;
    /// - when both key #1 and key #2 already exist with some values, but
    /// point to different entries (values).
    ///
    /// The above mentioned error kinds can be matched through the [`ErrorKind`] enum.
    /// Returned [`InsertError`] structure also contains provided keys and value
    /// that were not inserted and can be used for another purpose.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::{TryInsertError, OccupiedError, InsertError, ErrorKind};
    ///
    ///
    /// let mut map = DHashMap::new();
    ///
    /// // Returns mutable reference to the value if keys are vacant
    /// let value = map.try_insert(1, "a", "One").unwrap();
    /// assert_eq!(value, &"One");
    /// *value = "First";
    /// assert_eq!(map.get_key1(&1), Some(&"First"));
    ///
    /// // If the map did have these keys present, and both keys refer to
    /// // the same value, nothing is updated, and the provided value
    /// // is returned inside `Err(TryInsertError::Occupied(_))` variants
    /// map.try_insert(2, "b", "Two");
    /// match map.try_insert(2, "b", "Second") {
    ///     Err(error) => match error {
    ///         TryInsertError::Occupied(OccupiedError{ entry, value }) => {
    ///             assert_eq!(entry.keys(), (&2, &"b"));
    ///             assert_eq!(entry.get(), &"Two");
    ///             assert_eq!(value, "Second");
    ///         }
    ///         _ => unreachable!(),
    ///     }
    ///     _ => unreachable!(),
    /// }
    /// assert_eq!(map.get_key1(&2), Some(&"Two"));
    ///
    /// // Returns `ErrorKind::OccupiedK1AndVacantK2` if key #1 already
    /// // exists with some value, but key #2 is vacant. Error structure
    /// // also contains provided keys and value
    /// match map.try_insert(1, "c", "value") {
    ///     Err(error) => match error {
    ///         TryInsertError::Insert(InsertError{ error, keys, value }) => {
    ///             assert_eq!(error, ErrorKind::OccupiedK1AndVacantK2);
    ///             assert_eq!(keys, (1, "c"));
    ///             assert_eq!(value, "value");
    ///         }
    ///         _ => unreachable!()
    ///     }
    ///     _ => unreachable!(),
    /// }
    ///
    /// // Returns `ErrorKind::VacantK1AndOccupiedK2` if key #1 is vacant,
    /// // but key #2 already exists with some value.
    /// match map.try_insert(3, "a", "value") {
    ///     Err(error) => match error {
    ///         TryInsertError::Insert(InsertError{ error, .. }) => {
    ///             assert_eq!(error, ErrorKind::VacantK1AndOccupiedK2);
    ///         }
    ///         _ => unreachable!()
    ///     }
    ///     _ => unreachable!(),
    /// }
    ///
    /// // Returns `ErrorKind::KeysPointsToDiffEntries` if both
    /// // key #1 and key #2 already exist with some values,
    /// // but point to different entries (values).
    /// match map.try_insert(1, "b", "value") {
    ///     Err(error) => match error {
    ///         TryInsertError::Insert(InsertError{ error, .. }) => {
    ///             assert_eq!(error, ErrorKind::KeysPointsToDiffEntries);
    ///         }
    ///         _ => unreachable!()
    ///     }
    ///     _ => unreachable!(),
    /// }
    /// ```
    #[inline]
    pub fn try_insert(
        &mut self,
        k1: K1,
        k2: K2,
        v: V,
    ) -> Result<&mut V, TryInsertError<K1, K2, V>> {
        match self.entry(k1, k2) {
            Ok(entry) => match entry {
                Entry::Occupied(entry) => {
                    Err(TryInsertError::Occupied(OccupiedError { entry, value: v }))
                }
                Entry::Vacant(entry) => Ok(entry.insert(v)),
            },
            Err(EntryError { error, keys }) => Err(TryInsertError::Insert(InsertError {
                error,
                keys,
                value: v,
            })),
        }
    }
}

impl<K1, K2, V, S> FromIterator<(K1, K2, V)> for DHashMap<K1, K2, V, S>
where
    K1: Eq + Hash + Clone,
    K2: Eq + Hash + Clone,
    S: BuildHasher + Default + Clone,
{
    fn from_iter<T: IntoIterator<Item = (K1, K2, V)>>(iter: T) -> DHashMap<K1, K2, V, S> {
        let mut map = DHashMap::with_hasher(Default::default());
        map.extend(iter);
        map
    }
}

/// Inserts all new keys and values from the iterator. Replace values with existing
/// keys with new values returned from the iterator.
impl<K1, K2, V, S> Extend<(K1, K2, V)> for DHashMap<K1, K2, V, S>
where
    K1: Eq + Hash + Clone,
    K2: Eq + Hash + Clone,
    S: BuildHasher,
{
    #[inline]
    fn extend<T: IntoIterator<Item = (K1, K2, V)>>(&mut self, iter: T) {
        // Keys may be already present or show multiple times in the iterator.
        // Reserve the entire hint lower bound if the map is empty.
        // Otherwise reserve half the hint (rounded up), so the map
        // will only resize twice in the worst case.
        let iter = iter.into_iter();
        let reserve = if self.is_empty() {
            iter.size_hint().0
        } else {
            (iter.size_hint().0 + 1) / 2
        };
        self.reserve(reserve);
        iter.for_each(move |(k1, k2, v)| {
            self.insert(k1, k2, v);
        });
    }
}

/// Inserts all new keys and values from the iterator. Replace values with existing
/// keys with new values returned from the iterator. The keys and values must
/// implement [`Copy`] trait.
impl<'a, K1, K2, V, S> Extend<(&'a K1, &'a K2, &'a V)> for DHashMap<K1, K2, V, S>
where
    K1: Eq + Hash + Copy,
    K2: Eq + Hash + Copy,
    V: Copy,
    S: BuildHasher,
{
    #[inline]
    fn extend<T: IntoIterator<Item = (&'a K1, &'a K2, &'a V)>>(&mut self, iter: T) {
        self.extend(iter.into_iter().map(|(&k1, &k2, &v)| (k1, k2, v)))
    }
}

/// A view into an occupied entry in a [`DHashMap`].
/// It is part of the [`Entry`] enum and [`OccupiedError`] struct.
#[derive(Debug)]
pub struct OccupiedEntry<'a, K1: 'a, K2: 'a, V: 'a> {
    base_v: hash_map::OccupiedEntry<'a, K1, (K2, V)>,
    base_k: hash_map::OccupiedEntry<'a, K2, K1>,
}

impl<'a, K1, K2, V> OccupiedEntry<'a, K1, K2, V> {
    /// Gets a reference to the key #1 of type `K1` in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             assert_eq!(oc_entry.key1(), &"poneyland");
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn key1(&self) -> &K1 {
        self.base_v.key()
    }

    /// Gets a reference to the key #2 of type `K2` in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             assert_eq!(oc_entry.key2(), &0);
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn key2(&self) -> &K2 {
        self.base_k.key()
    }

    /// Gets a reference to the keys of type `K1` and `K2` in the entry.
    /// Return tuple of type `(&'a K1, &'a K2)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             assert_eq!(oc_entry.keys(), (&"poneyland", &0));
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn keys(&self) -> (&K1, &K2) {
        (self.base_v.key(), self.base_k.key())
    }

    /// Take the ownership of the keys and value from the map.
    /// Keeps the allocated memory for reuse.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// // So lets create some map and insert some element
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 10);
    /// map.insert("bearland",  1, 11);
    ///
    /// // And also reserve some space for additional elements
    /// map.reserve(15);
    /// // Now our map can hold at least 17 elements
    /// let capacity_before_entries_remove = map.capacity();
    /// assert!(capacity_before_entries_remove >= 17);
    ///
    /// assert!(map.get_key1("poneyland") == Some(&10) && map.get_key2(&0) == Some(&10));
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             // We delete the entry from the map.
    ///             let tuple = oc_entry.remove_entry();
    ///             assert_eq!(tuple, ("poneyland", 0, 10));
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// assert!(map.get_key1("poneyland") == None && map.get_key2(&0) == None);
    ///
    /// assert!(map.get_key1("bearland") == Some(&11) && map.get_key2(&1) == Some(&11));
    /// if let Ok(entry) = map.entry("bearland", 1) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             // We delete the entry from the map.
    ///             let tuple = oc_entry.remove_entry();
    ///             assert_eq!(tuple, ("bearland",  1, 11));
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// assert!(map.get_key1("bearland") == None && map.get_key2(&1) == None);
    ///
    /// // But the capacity of our map isn't changed and still equals to the capacity before
    /// // using `remove_entry` method
    /// assert_eq!(map.capacity(), capacity_before_entries_remove);
    /// ```
    #[inline]
    pub fn remove_entry(self) -> (K1, K2, V) {
        self.base_k.remove_entry();
        let (k1, (k2, v)) = self.base_v.remove_entry();
        (k1, k2, v)
    }

    /// Gets a reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             assert_eq!(oc_entry.get(), &12);
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn get(&self) -> &V {
        let (_, v) = self.base_v.get();
        v
    }

    /// Gets a mutable reference to the value in the entry.
    ///
    /// If you need a reference to the `OccupiedEntry` which may outlive the
    /// destruction of the `Entry` value, see [`into_mut`](`OccupiedEntry::into_mut`).
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    /// assert_eq!(map.get_key1("poneyland"), Some(&12));
    /// assert_eq!(map.get_key2(&0),          Some(&12));
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(mut oc_entry) => {
    ///             *oc_entry.get_mut() += 10;
    ///             assert_eq!(oc_entry.get(), &22);
    ///
    ///             // We can use the same Entry multiple times.
    ///             *oc_entry.get_mut() += 2;
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// assert_eq!(map.get_key1("poneyland"), Some(&24));
    /// assert_eq!(map.get_key2(&0),          Some(&24));
    /// ```
    #[inline]
    pub fn get_mut(&mut self) -> &mut V {
        let (_, v) = self.base_v.get_mut();
        v
    }

    /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
    /// with a lifetime bound to the map itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    /// assert_eq!(map.get_key1("poneyland"), Some(&12));
    /// assert_eq!(map.get_key2(&0),          Some(&12));
    ///
    /// // Let's create a variable that outlives the OccupiedEntry (with some initial value)
    /// let mut value: &mut i32 = &mut 0;
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             // So we can convert the OccupiedEntry into a mutable reference to the value.
    ///             value = oc_entry.into_mut();
    ///             *value += 10;
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// // We can use the same reference outside the created oc_entry (OccupiedEntry) scope.
    /// *value += 20;
    /// assert_eq!(map.get_key1("poneyland"), Some(&42)); // 12 + 10 + 20
    /// assert_eq!(map.get_key2(&0),          Some(&42));
    /// ```
    #[inline]
    pub fn into_mut(self) -> &'a mut V {
        let (_, v) = self.base_v.into_mut();
        v
    }

    /// Sets the value of the entry, and returns the entry's old value.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 12);
    /// assert_eq!(map.get_key1("poneyland"), Some(&12));
    /// assert_eq!(map.get_key2(&0),          Some(&12));
    ///
    /// // Let's create a variable that holds value
    /// let mut owner: i32 = 100;
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(mut oc_entry) => {
    ///             // So we can swap our created owner value with value inside the map.
    ///             owner = oc_entry.insert(owner);
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// assert_eq!(owner, 12);
    /// assert_eq!(map.get_key1("poneyland"), Some(&100));
    /// assert_eq!(map.get_key2(&0),          Some(&100));
    /// ```
    #[inline]
    pub fn insert(&mut self, mut value: V) -> V {
        let old_value = self.get_mut();
        mem::swap(&mut value, old_value);
        value
    }

    /// Take the value out of the entry (map), and return it.
    /// Keeps the allocated memory for reuse.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// // So lets create some map and insert some element
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    /// map.insert("poneyland", 0, 10);
    /// map.insert("bearland",  1, 11);
    ///
    /// // And also reserve some space for additional elements
    /// map.reserve(15);
    /// // Now our map can hold at least 17 elements
    /// let capacity_before_remove = map.capacity();
    /// assert!(capacity_before_remove >= 17);
    ///
    /// assert!(map.get_key1("poneyland") == Some(&10) && map.get_key2(&0) == Some(&10));
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             // We delete the entry from the map.
    ///             let value = oc_entry.remove();
    ///             assert_eq!(value, 10);
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// assert!(map.get_key1("poneyland") == None && map.get_key2(&0) == None);
    ///
    /// assert!(map.get_key1("bearland") == Some(&11) && map.get_key2(&1) == Some(&11));
    /// if let Ok(entry) = map.entry("bearland", 1) {
    ///     match entry {
    ///         Entry::Occupied(oc_entry) => {
    ///             // We delete the entry from the map.
    ///             let value = oc_entry.remove();
    ///             assert_eq!(value, 11);
    ///         }
    ///         Entry::Vacant(_) => panic!("Something go wrong!!!")
    ///     }
    /// }
    /// assert!(map.get_key1("bearland") == None && map.get_key2(&1) == None);
    ///
    /// // But the capacity of our map isn't changed and still equals to the capacity before
    /// // using `remove_entry` method
    /// assert_eq!(map.capacity(), capacity_before_remove);
    /// ```
    #[inline]
    pub fn remove(self) -> V {
        self.remove_entry().2
    }
}

/// A view into a vacant entry in a [`DHashMap`].
/// It is part of the [`Entry`] enum.
#[derive(Debug)]
pub struct VacantEntry<'a, K1: 'a, K2: 'a, V: 'a> {
    base_v: hash_map::VacantEntry<'a, K1, (K2, V)>,
    base_k: hash_map::VacantEntry<'a, K2, K1>,
}

impl<'a, K1: 'a, K2: 'a, V: 'a> VacantEntry<'a, K1, K2, V>
where
    K1: Clone,
    K2: Clone,
{
    /// Gets a reference to the key #1 of type `K1` that would be used
    /// when inserting a value through the `VacantEntry`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(_) => panic!("Something go wrong!!!"),
    ///         Entry::Vacant(vac_entry) => assert_eq!(vac_entry.key1(), &"poneyland"),
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn key1(&self) -> &K1 {
        self.base_v.key()
    }

    /// Gets a reference to the key #2 of type `K2` that would be used
    /// when inserting a value through the `VacantEntry`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(_) => panic!("Something go wrong!!!"),
    ///         Entry::Vacant(vac_entry) => assert_eq!(vac_entry.key2(), &0),
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn key2(&self) -> &K2 {
        self.base_k.key()
    }

    /// Gets a reference to the keys of type `K1` and `K2` that would be used
    /// when inserting a value through the `VacantEntry`.
    /// Return tuple of type `(&'a K1, &'a K2)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(_) => panic!("Something go wrong!!!"),
    ///         Entry::Vacant(vac_entry) => {
    ///             assert_eq!(vac_entry.keys(), (&"poneyland", &0))
    ///         }
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn keys(&self) -> (&K1, &K2) {
        (self.base_v.key(), self.base_k.key())
    }

    /// Take the ownership of the keys from the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// // So lets create some map and also reserve some space for additional elements
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::with_capacity(3);
    ///
    /// let capacity_before_into_keys = map.capacity();
    /// assert!(capacity_before_into_keys >= 3);
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(_) => panic!("Something go wrong!!!"),
    ///         Entry::Vacant(vac_entry) => {
    ///             // We take the keys from the entry.
    ///             let tuple = vac_entry.into_keys();
    ///             assert_eq!(tuple, ("poneyland", 0));
    ///         }
    ///     }
    /// }
    ///
    /// if let Ok(entry) = map.entry("bearland", 1) {
    ///     match entry {
    ///         Entry::Occupied(_) => panic!("Something go wrong!!!"),
    ///         Entry::Vacant(vac_entry) => {
    ///             // We take the keys from the entry.
    ///             let tuple = vac_entry.into_keys();
    ///             assert_eq!(tuple, ("bearland", 1));
    ///         }
    ///     }
    /// }
    ///
    /// map.entry("some_key", 2);
    /// map.entry("another_key", 3);
    ///
    /// // The capacity of our map is not changed
    /// assert_eq!(map.capacity(), capacity_before_into_keys);
    /// ```
    #[inline]
    pub fn into_keys(self) -> (K1, K2) {
        (self.base_v.into_key(), self.base_k.into_key())
    }

    /// Sets the value of the entry with the `VacantEntry`'s keys,
    /// and returns a mutable reference to it.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    /// use double_map::dhash_map::Entry;
    ///
    /// // So lets create some map
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// if let Ok(entry) = map.entry("poneyland", 0) {
    ///     match entry {
    ///         Entry::Occupied(_) => panic!("Something go wrong!!!"),
    ///         Entry::Vacant(vac_entry) => {
    ///             vac_entry.insert(37);
    ///         }
    ///     }
    /// }
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&37));
    /// ```
    #[inline]
    pub fn insert(self, value: V) -> &'a mut V {
        let k2 = self.base_k.key().clone();
        self.base_k.insert(self.base_v.key().clone());
        let (_, v) = self.base_v.insert((k2, value));
        v
    }
}

/// A view into a single entry in a map, which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`DHashMap`].
///
/// [`entry`]: DHashMap::entry
#[derive(Debug)]
pub enum Entry<'a, K1: 'a, K2: 'a, V: 'a> {
    /// An occupied entry.
    Occupied(OccupiedEntry<'a, K1, K2, V>),
    /// A vacant entry.
    Vacant(VacantEntry<'a, K1, K2, V>),
}

impl<'a, K1, K2, V> Entry<'a, K1, K2, V>
where
    K1: Eq + Hash + Clone,
    K2: Eq + Hash + Clone,
{
    /// Ensures a value is in the entry by inserting the default if empty, and returns
    /// a mutable reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// match map.entry("poneyland", 0) {
    ///     Ok(entry) => {
    ///         entry.or_insert(3);
    ///     }
    ///     Err(_) => unreachable!(),
    /// }
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&3));
    ///
    /// map.entry("poneyland", 0).map(|entry| *entry.or_insert(10) *= 2);
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&6));
    /// ```
    #[inline]
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default),
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default function if empty,
    /// and returns a mutable reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, u32, String> = DHashMap::new();
    /// let s = "hoho".to_owned();
    ///
    /// match map.entry("poneyland", 0) {
    ///     Ok(entry) => {
    ///         entry.or_insert_with(|| s);
    ///     }
    ///     Err(_) => unreachable!(),
    /// }
    /// assert_eq!(map.get_key1("poneyland"), Some(&"hoho".to_owned()));
    ///
    /// let k = "another string".to_owned();
    /// map.entry("poneyland", 0).map(|entry| entry.or_insert_with(|| k).push_str("ho"));
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&"hohoho".to_owned()));
    /// ```
    #[inline]
    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default()),
        }
    }

    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
    /// This method allows generating key-derived (with using key # 1 `K1`) value for
    /// insertion by providing the default function a reference to the key that was moved
    /// during the `.entry(key)` method call.
    ///
    /// The reference to the moved key is provided so that cloning or copying the key is
    /// unnecessary, unlike with `.or_insert_with(|| ... )`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, usize, u64> = DHashMap::new();
    ///
    ///  match map.entry("poneyland", 0) {
    ///     Ok(entry) => {
    ///         entry.or_insert_with_key1(|k1| k1.chars().count() as u64);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&9));
    ///
    /// map.entry("bearland", 1).map(
    ///     |ent| ent.or_insert_with_key1(|k1| (k1.chars().count() * 2) as u64)
    /// );
    /// assert_eq!(map.get_key1(&"bearland"), Some(&16));
    /// ```
    #[inline]
    pub fn or_insert_with_key1<F: FnOnce(&K1) -> V>(self, default: F) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let value = default(entry.key1());
                entry.insert(value)
            }
        }
    }

    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
    /// This method allows generating key-derived (with using key # 2 `K2`) value for
    /// insertion by providing the default function a reference to the key that was moved
    /// during the `.entry(key)` method call.
    ///
    /// The reference to the moved key is provided so that cloning or copying the key is
    /// unnecessary, unlike with `.or_insert_with(|| ... )`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, usize, u64> = DHashMap::new();
    ///
    ///  match map.entry("poneyland", 10) {
    ///     Ok(entry) => {
    ///         entry.or_insert_with_key2(|k2| (k2 + 10) as u64);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&20));
    ///
    /// map.entry("bearland", 11).map(
    ///     |ent| ent.or_insert_with_key2(|k1| (k1 * 3) as u64)
    /// );
    /// assert_eq!(map.get_key1(&"bearland"), Some(&33));
    /// ```
    #[inline]
    pub fn or_insert_with_key2<F: FnOnce(&K2) -> V>(self, default: F) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let value = default(entry.key2());
                entry.insert(value)
            }
        }
    }

    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
    /// This method allows generating key-derived (with using key #1 of type `K1` and
    /// key # 2 of type `K2`) values for insertion by providing the default function
    /// a reference to the keys that were moved during the `.entry(key)` method call.
    ///
    /// The reference to the moved keys is provided so that cloning or copying the key is
    /// unnecessary, unlike with `.or_insert_with(|| ... )`.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, usize, u64> = DHashMap::new();
    ///
    ///  match map.entry("poneyland", 10) {
    ///     Ok(entry) => {
    ///         entry.or_insert_with_keys(|k1, k2| (k1.chars().count() + k2) as u64);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&19));
    ///
    /// map.entry("bearland", 11).map(
    ///     |ent| ent.or_insert_with_keys(|k1, k2| (k1.chars().count() + k2 * 3) as u64)
    /// );
    /// assert_eq!(map.get_key1(&"bearland"), Some(&41));
    /// ```
    #[inline]
    pub fn or_insert_with_keys<F: FnOnce(&K1, &K2) -> V>(self, default: F) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let value = default(entry.key1(), entry.key2());
                entry.insert(value)
            }
        }
    }

    /// Returns a reference to this entry's first key (key #1).
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// // It is VacantEntry
    /// match map.entry("poneyland", 0) {
    ///     Ok(entry) => {
    ///         // key equal to provided one
    ///         assert_eq!(entry.key1(), &"poneyland");
    ///         // we insert some value
    ///         entry.or_insert(25);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// // As we can see, now this element exists
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&25));
    ///
    /// // So now it is OccupiedEntry
    /// match map.entry("poneyland", 0) {
    ///     Ok(entry) => {
    ///         // And key equals to provided one too
    ///         assert_eq!(entry.key1(), &"poneyland");
    ///         entry.or_insert(25);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// ```
    #[inline]
    pub fn key1(&self) -> &K1 {
        match *self {
            Entry::Occupied(ref entry) => entry.key1(),
            Entry::Vacant(ref entry) => entry.key1(),
        }
    }

    /// Returns a reference to this entry's second key (key #2).
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// // It is VacantEntry
    /// match map.entry("poneyland", 10) {
    ///     Ok(entry) => {
    ///         // key equal to provided one
    ///         assert_eq!(entry.key2(), &10);
    ///         // we insert some value
    ///         entry.or_insert(25);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// // As we can see, now this element exists
    /// assert_eq!(map.get_key2(&10), Some(&25));
    ///
    /// // So now it is OccupiedEntry
    /// match map.entry("poneyland", 10) {
    ///     Ok(entry) => {
    ///         // And key equals to provided one too
    ///         assert_eq!(entry.key2(), &10);
    ///         entry.or_insert(25);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// ```
    #[inline]
    pub fn key2(&self) -> &K2 {
        match *self {
            Entry::Occupied(ref entry) => entry.key2(),
            Entry::Vacant(ref entry) => entry.key2(),
        }
    }

    /// Returns a reference to this entry's keys.
    /// Return tuple of type (&'a K1, &'a K2).
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
    ///
    /// // It is VacantEntry
    /// match map.entry("poneyland", 10) {
    ///     Ok(entry) => {
    ///         // keys equal to provided one
    ///         assert_eq!(entry.keys(), (&"poneyland", &10));
    ///         // we insert some value
    ///         entry.or_insert(25);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// // As we can see, now this element exists
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&25));
    ///
    /// // So now it is OccupiedEntry
    /// match map.entry("poneyland", 10) {
    ///     Ok(entry) => {
    ///         // And keys equal to provided one too
    ///         assert_eq!(entry.keys(), (&"poneyland", &10));
    ///         entry.or_insert(25);
    ///     },
    ///     Err(_) => unreachable!(),
    /// }
    /// ```
    #[inline]
    pub fn keys(&self) -> (&K1, &K2) {
        match *self {
            Entry::Occupied(ref entry) => entry.keys(),
            Entry::Vacant(ref entry) => entry.keys(),
        }
    }

    /// Provides in-place mutable access to an occupied entry before any
    /// potential inserts into the map.
    ///
    /// # Examples
    ///
    /// ```
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, u32, u32> = DHashMap::new();
    ///
    /// map.entry("poneyland", 1).map( |entry|
    ///    entry.and_modify(|value| { *value += 100 })
    ///    .or_insert(42)
    /// );
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&42));
    ///
    /// map.entry("poneyland", 1).map( |entry|
    ///    entry.and_modify(|value| { *value += 100 })
    ///    .or_insert(42)
    /// );
    /// assert_eq!(map.get_key1(&"poneyland"), Some(&142));
    /// ```
    #[inline]
    pub fn and_modify<F>(self, f: F) -> Self
    where
        F: FnOnce(&mut V),
    {
        match self {
            Entry::Occupied(mut entry) => {
                f(entry.get_mut());
                Entry::Occupied(entry)
            }
            Entry::Vacant(entry) => Entry::Vacant(entry),
        }
    }
}

impl<'a, K1, K2, V: Default> Entry<'a, K1, K2, V>
where
    K1: Eq + Hash + Clone,
    K2: Eq + Hash + Clone,
{
    /// Ensures a value is in the entry by inserting the default value if empty,
    /// and returns a mutable reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() {
    /// use double_map::DHashMap;
    ///
    /// let mut map: DHashMap<&str, usize, Option<u32>> = DHashMap::new();
    /// map.entry("poneyland", 1).map(|entry| entry.or_default());
    ///
    /// assert_eq!(map.get_key1(&"poneyland"), Option::<&Option<u32>>::Some(&None));
    /// # }
    /// ```
    #[inline]
    pub fn or_default(self) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(Default::default()),
        }
    }
}

/// A view into an error kind returned by [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
/// [`try_insert`](DHashMap::try_insert) methods of the [`DHashMap`].
/// It is part of the [`EntryError`] structure, [`InsertError`] structure and [`TryInsertError`]
/// enum.
///
/// Explains why [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
/// [`try_insert`](DHashMap::try_insert) methods fail.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
    /// Returns when key #1 is vacant, but key #2 already exists with some value.
    VacantK1AndOccupiedK2,
    /// Returns when key #1 already exists with some value, but key #2 is vacant.
    OccupiedK1AndVacantK2,
    /// Returns when both key #1 and key #2 already exist with some values, but point
    /// to different entries (values).
    KeysPointsToDiffEntries,
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let error_txt = match *self {
            ErrorKind::OccupiedK1AndVacantK2 => "occupied key #1 but vacant key #2",
            ErrorKind::VacantK1AndOccupiedK2 => "vacant key #1 but occupied key #2",
            ErrorKind::KeysPointsToDiffEntries => {
                "key #1 and key #2 exist, but point to different entries"
            }
        };
        write!(f, "{}", error_txt)
    }
}

impl std::error::Error for ErrorKind {}

/// The error returned by [`entry`](DHashMap::entry) method when there is no way to distinguish
/// which entry should be returned. For more information about error kinds look at [`ErrorKind`]
/// enum.
///
/// Contains the [`ErrorKind`] enum, and the values of provided keys (that can be used for another
/// purpose).
#[derive(Debug, PartialEq)]
pub struct EntryError<K1, K2> {
    /// A view into an error kind returned by [`entry`](DHashMap::entry),
    /// [`insert`](DHashMap::insert), [`try_insert`](DHashMap::try_insert) methods of the [`DHashMap`].
    /// It is part of the [`EntryError`] structure, [`InsertError`] structure and [`TryInsertError`]
    /// enum. Explains [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
    /// [`try_insert`](DHashMap::try_insert) methods fail. For more information about error
    /// kind look at [`ErrorKind`] enum.
    pub error: ErrorKind,
    /// The provided values of keys that were returned because of error. For more information about
    /// error kind look at [`ErrorKind`] enum.
    pub keys: (K1, K2),
}

impl<K1: Debug, K2: Debug> fmt::Display for EntryError<K1, K2> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let key_txt = match self.error {
            ErrorKind::VacantK1AndOccupiedK2 => format!(
                "key #1 = {:?} - vacant, but key #2 = {:?} - exists",
                self.keys.0, self.keys.1
            ),
            ErrorKind::OccupiedK1AndVacantK2 => format!(
                "key #1 = {:?} - exists, but key #2 = {:?} - vacant",
                self.keys.0, self.keys.1
            ),
            ErrorKind::KeysPointsToDiffEntries => format!(
                "key #1 = {:?} and key #2 = {:?} point to different entries",
                self.keys.0, self.keys.1
            ),
        };
        write!(f, "failed to get entry, because {}", key_txt)
    }
}

impl<K1: Debug, K2: Debug> std::error::Error for EntryError<K1, K2> {}

/// The error returned by [`insert`](DHashMap::insert) method (and also
/// [`try_insert`](DHashMap::try_insert) method) when there is no way to distinguish
/// how given value with key #1 and key #2 should be inserted. It is also part of the
/// [`TryInsertError`] enum which is returned by [`try_insert`](DHashMap::try_insert) method
/// of [`DHashMap`]. For more information about error kinds look at [`ErrorKind`] enum.
///
/// Contains the [`ErrorKind`] enum, the provided keys and value that were not inserted.
/// These returned keys and value can be used for another purpose.
#[derive(Debug, PartialEq)]
pub struct InsertError<K1, K2, V> {
    /// A view into an error kind returned by [`entry`](DHashMap::entry),
    /// [`insert`](DHashMap::insert), [`try_insert`](DHashMap::try_insert) methods of the [`DHashMap`].
    /// It is part of the [`EntryError`] structure, [`InsertError`] structure and [`TryInsertError`]
    /// enum. Explains [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
    /// [`try_insert`](DHashMap::try_insert) methods fail. For more information about error
    /// kind look at [`ErrorKind`] enum.
    pub error: ErrorKind,
    /// The provided keys that were returned because of error. For more information about
    /// error kind look at [`ErrorKind`] enum.
    pub keys: (K1, K2),
    /// The value which was not inserted because of the error. For more information about error
    /// kind look at [`ErrorKind`] enum.
    pub value: V,
}

impl<K1: Debug, K2: Debug, V: Debug> fmt::Display for InsertError<K1, K2, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let key_txt = match self.error {
            ErrorKind::VacantK1AndOccupiedK2 => format!(
                "key #1 = {:?} - vacant, but key #2 = {:?} - exists",
                self.keys.0, self.keys.1
            ),
            ErrorKind::OccupiedK1AndVacantK2 => format!(
                "key #1 = {:?} - exists, but key #2 = {:?} - vacant",
                self.keys.0, self.keys.1
            ),
            ErrorKind::KeysPointsToDiffEntries => format!(
                "key #1 = {:?} and key #2 = {:?} point to different entries",
                self.keys.0, self.keys.1
            ),
        };
        write!(
            f,
            "failed to insert {:?}, because of {}",
            self.value, key_txt
        )
    }
}

impl<K1: Debug, K2: Debug, V: Debug> std::error::Error for InsertError<K1, K2, V> {}

/// The error returned by [`try_insert`](DHashMap::try_insert) (as a part of the [`TryInsertError`]
/// enum) when the keys already exist and point to the same value.
///
/// Contains the occupied entry, and the value that was not inserted. It is part of the
/// [`TryInsertError`] enum.
#[derive(Debug)]
pub struct OccupiedError<'a, K1: 'a, K2: 'a, V: 'a> {
    /// The entry in the map that was already occupied. It contains [`OccupiedEntry`] structure
    /// which is also a part of the [`Entry`] enum.
    pub entry: OccupiedEntry<'a, K1, K2, V>,
    /// The value which was not inserted, because the entry was already occupied.
    pub value: V,
}

impl<'a, K1, K2, V> fmt::Display for OccupiedError<'a, K1, K2, V>
where
    K1: Eq + Hash + Clone + Debug,
    K2: Eq + Hash + Clone + Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "failed to insert {:?}, key #1 = {:?} and key #2 = {:?} already exist with value {:?}",
            self.value,
            self.entry.key1(),
            self.entry.key2(),
            self.entry.get(),
        )
    }
}

impl<'a, K1, K2, V> std::error::Error for OccupiedError<'a, K1, K2, V>
where
    K1: Eq + Hash + Clone + Debug,
    K2: Eq + Hash + Clone + Debug,
    V: Debug,
{
}

/// The error returned by [`try_insert`](DHashMap::try_insert) method when the keys already exist
/// and point to the same value (look at [`OccupiedError`]) or there is no way to distinguish how
/// given value with key #1 and key #2 should be inserted. For more information about error kinds
/// look at [`OccupiedError`], [`InsertError`] structures and [`ErrorKind`] enum.
///
/// Depending of error kind, this enum can contain:
/// - When there is [`TryInsertError::Occupied`] variant, it contains the occupied entry, and
/// the value that was not inserted (through [`OccupiedError`] structure).
/// - When there is [`TryInsertError::Insert`] variant, it contains the [`ErrorKind`] enum,
/// the provided keys and value that were not inserted (through [`InsertError`] structure).
#[derive(Debug)]
pub enum TryInsertError<'a, K1: 'a, K2: 'a, V: 'a> {
    /// The error kind returned by [`try_insert`](DHashMap::try_insert) when the keys already
    /// exist and point to the same value. Contains the [`OccupiedError`] structure.
    Occupied(OccupiedError<'a, K1, K2, V>),
    /// The error kind returned by [`try_insert`](DHashMap::try_insert) method when there is no
    /// way to distinguish how given value with key #1 and key #2 should be inserted. For more
    /// information about error kinds look at [`InsertError`] structure and [`ErrorKind`] enum.
    ///
    /// Contains the [`InsertError`] structure.
    Insert(InsertError<K1, K2, V>),
}

impl<'a, K1, K2, V> fmt::Display for TryInsertError<'a, K1, K2, V>
where
    K1: Eq + Hash + Clone + Debug,
    K2: Eq + Hash + Clone + Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let txt = match self {
            TryInsertError::Occupied(error) => error.to_string(),
            TryInsertError::Insert(error) => error.to_string(),
        };
        write!(f, "{}", txt)
    }
}

impl<'a, K1, K2, V> std::error::Error for TryInsertError<'a, K1, K2, V>
where
    K1: Eq + Hash + Clone + Debug,
    K2: Eq + Hash + Clone + Debug,
    V: Debug,
{
}