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
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
//! Janet table (mutable HashMap) type.
use core::{
    cmp::Ordering,
    fmt::{self, Debug, Write},
    iter::FusedIterator,
    marker::PhantomData,
    ops::Index,
    ptr::NonNull,
};

use evil_janet::{JanetKV, JanetTable as CJanetTable};

use super::{Janet, JanetExtend, JanetStruct};
use crate::cjvg;

/// Janet [table]s are mutable data structures that map keys to values. Values are put
/// into a Janet table with a key, and can be looked up later with the same key. Tables
/// are implemented with an underlying open hash table, so they are quite fast and cache
/// friendly.
///
/// Any Janet value except Janet `nil` and Janet number that is `NaN` can be a key or a
/// value in a Janet table, and a single Janet table can have any mixture of Janet types
/// as keys and values.
///
/// To facilitate the creation of this structure, you can use the macro
/// [`table`](crate::table!).
///
/// # Examples
/// ```
/// use janetrs::{Janet, JanetTable};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
/// let mut table = JanetTable::new();
///
/// table.insert("key", 10.0);
/// table.insert(10, 20.3);
///
/// println!("{}", Janet::table(table));
/// ```
///
/// [table]: https://janet-lang.org/docs/data_structures/tables.html
#[repr(transparent)]
pub struct JanetTable<'data> {
    pub(crate) raw: *mut CJanetTable,
    phatom: PhantomData<&'data ()>,
}

impl<'data> JanetTable<'data> {
    /// Create a empty [`JanetTable`].
    ///
    /// It is initially created with capacity 1, so it will not allocate until it is
    /// second inserted into.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let table = JanetTable::new();
    /// ```
    #[inline]
    #[must_use = "function is a constructor associated function"]
    pub fn new() -> Self {
        Self {
            raw:    unsafe { evil_janet::janet_table(0) },
            phatom: PhantomData,
        }
    }

    /// Create a empty [`JanetTable`] given to Janet the specified `capacity`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let table = JanetTable::with_capacity(20);
    /// ```
    #[inline]
    #[must_use = "function is a constructor associated function"]
    pub fn with_capacity(capacity: i32) -> Self {
        Self {
            raw:    unsafe { evil_janet::janet_table(capacity) },
            phatom: PhantomData,
        }
    }

    /// Create a empty [`JanetTable`] with a prototype table set to `proto`.
    ///
    /// It is initially created with capacity 1, so it will not allocate until it is
    /// second inserted into.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{JanetTable, table};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let table = JanetTable::with_prototype(table!(":_name" => "MyClass"));
    /// ```
    #[inline]
    #[must_use = "function is a constructor associated function"]
    pub fn with_prototype(proto: JanetTable<'data>) -> Self {
        let mut t = Self::new();
        t.set_prototype(&proto);
        t
    }

    /// Create a new [`JanetTable`] with a `raw_table`.
    ///
    /// # Safety
    /// This function do not check if the given `raw_table` is `NULL` or not. Use at your
    /// own risk.
    #[inline]
    pub const unsafe fn from_raw(raw: *mut CJanetTable) -> Self {
        Self {
            raw,
            phatom: PhantomData,
        }
    }

    /// Returns the number of elements the table can hold without reallocating.
    ///
    /// This number is a lower bound; the [`JanetTable`] might be able to hold more, but
    /// is guaranteed to be able to hold at least this many.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// assert!(table.capacity() >= 20);
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn capacity(&self) -> i32 {
        unsafe { (*self.raw).capacity }
    }

    /// Returns the number of elements that was removed from the table.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(2);
    /// table.insert(10, "ten");
    /// table.insert(20, "twenty");
    ///
    /// assert_eq!(table.removed(), 0);
    /// table.remove(20);
    /// assert_eq!(table.removed(), 1);
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn removed(&self) -> i32 {
        unsafe { (*self.raw).deleted }
    }

    /// Clears the table, removing all key-value pairs. Keeps the allocated memory for
    /// reuse.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// table.clear();
    /// assert!(table.is_empty());
    /// ```
    #[cjvg("1.10.1")]
    #[inline]
    pub fn clear(&mut self) {
        unsafe { evil_janet::janet_table_clear(self.raw) }
    }

    /// Clears the table, removing all key-value pairs. Keeps the allocated memory for
    /// reuse.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// table.clear();
    /// assert!(table.is_empty());
    /// ```
    #[cjvg("1.0.0", "1.10.1")]
    #[inline]
    pub fn clear(&mut self) {
        let capacity = self.capacity();

        unsafe {
            let data = (*self.raw).data;
            for i in 0..capacity {
                let kv = data.add(i);
                (*kv).key = evil_janet::janet_wrap_nil();
                (*kv).value = evil_janet::janet_wrap_nil();
            }

            (*self.raw).count = 0;
            (*self.raw).deleted = 0;
        }
    }

    /// Returns the number of elements of the table, also referred to as its 'length'.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    ///
    /// assert_eq!(table.len(), 0);
    /// table.insert(10, "ten");
    /// assert_eq!(table.len(), 1);
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn len(&self) -> i32 {
        unsafe { (*self.raw).count }
    }

    /// Returns `true` if the table contains no elements.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetTable;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    ///
    /// assert!(table.is_empty());
    /// table.insert(10, "ten");
    /// assert!(!table.is_empty());
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the prototype table of the table.
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn prototype(&self) -> Option<Self> {
        let proto = unsafe { (*self.raw).proto };

        if proto.is_null() {
            None
        } else {
            // SAFETY: we checked that it's not a null pointer
            let proto = unsafe { JanetTable::from_raw(proto) };
            Some(proto)
        }
    }

    /// Set the prototype of the table with the values of `proto`.
    ///
    /// # Examples
    ///
    ///
    /// ```
    /// use janetrs::{table, Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! {1 => "a", 2 => "b"};
    /// let proto = table! {":_name" => "MyClass"};
    ///
    /// table.set_prototype(&proto);
    ///
    /// assert_eq!(table.prototype(), Some(proto));
    /// ```
    #[inline]
    pub fn set_prototype(&mut self, proto: &JanetTable) {
        unsafe { (*self.raw).proto = proto.raw };
    }

    /// Returns the value corresponding to the supplied `key`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(table.get(10), Some(&Janet::from("ten")));
    /// assert_eq!(table.get(11), None);
    /// ```
    #[inline]
    pub fn get(&self, key: impl Into<Janet>) -> Option<&Janet> {
        self.get_key_value(key).map(|(_, v)| v)
    }

    /// Returns the key-value pair corresponding to the supplied `key`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(
    ///     table.get_key_value(10),
    ///     Some((&Janet::integer(10), &Janet::from("ten")))
    /// );
    /// assert_eq!(table.get_key_value(11), None);
    /// ```
    #[inline]
    pub fn get_key_value(&self, key: impl Into<Janet>) -> Option<(&Janet, &Janet)> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
            // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
            // are represented in memory the same way
            // 2. A C struct are represented the same way in memory as tuple with the same number of
            // the struct fields of the same type of the struct fields
            //
            // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
            let kv: *mut (Janet, Janet) =
                unsafe { evil_janet::janet_table_find(self.raw, key.inner) as *mut _ };

            if kv.is_null() {
                None
            } else {
                // SAFETY: kv is safe to deref because we checked that it's not a null pointer.
                unsafe {
                    if (*kv).1.is_nil() {
                        None
                    } else {
                        Some((&(*kv).0, &(*kv).1))
                    }
                }
            }
        }
    }

    /// Returns a mutable reference to the value corresponding to the `key`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// if let Some(val) = table.get_mut(10) {
    ///     *val = Janet::boolean(true);
    /// }
    ///
    /// assert_eq!(table.get(10), Some(&Janet::boolean(true)));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, key: impl Into<Janet>) -> Option<&'data mut Janet> {
        self.get_key_value_mut(key).map(|(_, v)| v)
    }

    /// Returns the key-value pair corresponding to the supplied `key`, with a mutable
    /// reference to value.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetString, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(2);
    /// table.insert(10, "ten");
    ///
    /// let (k, v) = table.get_key_value_mut(10).unwrap();
    ///
    /// assert_eq!(&Janet::integer(10), k);
    /// assert_eq!(&mut Janet::from("ten"), v);
    ///
    /// *v = Janet::string(JanetString::new("ten but modified"));
    ///
    /// assert_eq!(
    ///     table.get_key_value_mut(10),
    ///     Some((&Janet::integer(10), &mut Janet::from("ten but modified")))
    /// );
    /// assert_eq!(table.get_key_value_mut(11), None);
    /// ```
    #[inline]
    pub fn get_key_value_mut(
        &mut self, key: impl Into<Janet>,
    ) -> Option<(&Janet, &'data mut Janet)> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
            // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
            // are represented in memory the same way
            // 2. A C struct are represented the same way in memory as tuple with the same number of
            // the struct fields of the same type of the struct fields
            //
            // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
            let kv: *mut (Janet, Janet) =
                unsafe { evil_janet::janet_table_find(self.raw, key.inner) as *mut _ };

            if kv.is_null() {
                None
            } else {
                // SAFETY: kv is safe to deref because we checked that it's not a null pointer.
                unsafe {
                    if (*kv).1.is_nil() {
                        None
                    } else {
                        Some((&(*kv).0, &mut (*kv).1))
                    }
                }
            }
        }
    }

    /// Returns a reference to the value corresponding to the `key` without checking for
    /// anything.
    ///
    /// # Safety
    /// This function doesn't check for null pointer and if the key or value as Janet nil
    #[inline]
    pub(crate) unsafe fn get_unchecked(&self, key: impl Into<Janet>) -> &'data Janet {
        self.get_key_value_unchecked(key).1
    }

    /// Returns a mutable reference to the value corresponding to the `key` without
    /// checking for anything.
    ///
    /// # Safety
    /// This function doesn't check for null pointer and if the key or value as Janet nil
    #[inline]
    pub(crate) unsafe fn get_mut_unchecked(&mut self, key: impl Into<Janet>) -> &'data mut Janet {
        self.get_key_value_mut_unchecked(key).1
    }

    /// Returns the key-value pair corresponding to the supplied `key`, with a mutable
    /// reference to value without checking for anything.
    ///
    /// # Safety
    /// This function doesn't check for null pointer and if the key or value as Janet nil
    #[inline]
    pub(crate) unsafe fn get_key_value_mut_unchecked(
        &mut self, key: impl Into<Janet>,
    ) -> (&Janet, &'data mut Janet) {
        let key = key.into();

        // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
        // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
        // are represented in memory the same way
        // 2. A C struct are represented the same way in memory as tuple with the same number of
        // the struct fields of the same type of the struct fields
        //
        // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
        let kv: *mut (Janet, Janet) = evil_janet::janet_table_find(self.raw, key.inner) as *mut _;

        (&(*kv).0, &mut (*kv).1)
    }

    /// Returns the key-value pair corresponding to the supplied `key`, with a reference
    /// to value without checking for anything.
    ///
    /// # Safety
    /// This function doesn't check for null pointer and if the key or value as Janet nil
    #[inline]
    pub(crate) unsafe fn get_key_value_unchecked(
        &self, key: impl Into<Janet>,
    ) -> (&Janet, &'data Janet) {
        let key = key.into();

        // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
        // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
        // are represented in memory the same way
        // 2. A C struct are represented the same way in memory as tuple with the same number of
        // the struct fields of the same type of the struct fields
        //
        // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
        let kv: *mut (Janet, Janet) = evil_janet::janet_table_find(self.raw, key.inner) as *mut _;

        (&(*kv).0, &(*kv).1)
    }

    /// Returns the reference to the value corresponding to the supplied `key`, with
    /// prototype lookup.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{table, Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! {1 => "a", 2 => "b"};
    /// let proto = table! {3 => "c"};
    ///
    /// table.set_prototype(&proto);
    ///
    /// assert_eq!(table.get_proto(3), Some(&Janet::from("c")));
    /// assert_eq!(table.get_proto(11), None);
    /// ```
    #[inline]
    pub fn get_proto(&self, key: impl Into<Janet>) -> Option<&Janet> {
        self.get_key_value_proto(key).map(|(_, v)| v)
    }

    /// Returns the exclusive reference to the value corresponding to the supplied `key`,
    /// with prototype lookup.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{table, Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! {1 => "a", 2 => "b"};
    /// let proto = table! {3 => "c"};
    ///
    /// table.set_prototype(&proto);
    ///
    /// assert_eq!(table.get_proto_mut(3), Some(&mut Janet::from("c")));
    /// assert_eq!(table.get_proto_mut(11), None);
    /// ```
    #[inline]
    pub fn get_proto_mut(&mut self, key: impl Into<Janet>) -> Option<&mut Janet> {
        self.get_key_value_proto_mut(key).map(|(_, v)| v)
    }

    /// Returns the key-value pair corresponding to the supplied `key` with a mutable
    /// reference to value, with prototype lookup.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{table, Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! {1 => "a", 2 => "b"};
    /// let proto = table! {3 => "c"};
    ///
    /// table.set_prototype(&proto);
    ///
    /// assert_eq!(
    ///     table.get_key_value_proto_mut(3),
    ///     Some((&Janet::integer(3), &mut Janet::from("c")))
    /// );
    /// assert_eq!(table.get_key_value_proto_mut(11), None);
    /// ```
    #[inline]
    pub fn get_key_value_proto_mut(
        &mut self, key: impl Into<Janet>,
    ) -> Option<(&Janet, &mut Janet)> {
        let key = key.into();

        macro_rules! proto_lookup {
            () => {
                let mut proto = unsafe { (*self.raw).proto };
                let mut depth = 0;
                return loop {
                    if proto.is_null() {
                        break None;
                    } else {
                        // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
                        // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so
                        // both types are represented in memory the same way
                        // 2. A C struct are represented the same way in memory as tuple with the
                        // same number of the struct fields of the same type
                        // of the struct fields
                        //
                        // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet,
                        // Janet)`
                        let kv: *mut (Janet, Janet) =
                            unsafe { evil_janet::janet_table_find(proto, key.inner) as *mut _ };

                        if kv.is_null() {
                            if depth < evil_janet::JANET_MAX_PROTO_DEPTH {
                                depth += 1;
                                proto = unsafe { (*proto).proto };
                                continue;
                            } else {
                                break None;
                            }
                        } else {
                            // SAFETY: kv is safe to deref because we checked that it's not a null
                            // pointer.
                            unsafe {
                                if (*kv).1.is_nil() {
                                    if depth < evil_janet::JANET_MAX_PROTO_DEPTH {
                                        depth += 1;
                                        proto = (*proto).proto;
                                        continue;
                                    } else {
                                        break None;
                                    }
                                } else {
                                    break Some((&(*kv).0, &mut (*kv).1));
                                }
                            }
                        }
                    }
                }
            };
        }

        if !key.is_nil() {
            // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
            // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
            // are represented in memory the same way
            // 2. A C struct are represented the same way in memory as tuple with the same number of
            // the struct fields of the same type of the struct fields
            //
            // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
            let kv: *mut (Janet, Janet) =
                unsafe { evil_janet::janet_table_find(self.raw, key.inner) as *mut _ };

            if kv.is_null() {
                proto_lookup!();
            } else {
                // SAFETY: kv is safe to deref because we checked that it's not a null pointer.
                #[allow(unused_unsafe)]
                unsafe {
                    if (*kv).1.is_nil() {
                        proto_lookup!();
                    } else {
                        return Some((&(*kv).0, &mut (*kv).1));
                    }
                }
            }
        }

        None
    }

    /// Returns the key-value pair corresponding to the supplied `key` with prototype
    /// lookup.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{table, Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! {1 => "a", 2 => "b"};
    /// let proto = table! {3 => "c"};
    ///
    /// table.set_prototype(&proto);
    ///
    /// assert_eq!(
    ///     table.get_key_value_proto(3),
    ///     Some((&Janet::integer(3), &Janet::from("c")))
    /// );
    /// assert_eq!(table.get_key_value_proto(11), None);
    /// ```
    #[inline]
    pub fn get_key_value_proto(&self, key: impl Into<Janet>) -> Option<(&Janet, &Janet)> {
        let key = key.into();
        match self.get_key_value(key) {
            val @ Some(_) => val,
            None => {
                let mut proto = unsafe { (*self.raw).proto };
                let mut depth = 0;
                loop {
                    if proto.is_null() {
                        break None;
                    } else {
                        // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
                        // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so
                        // both types are represented in memory the same way
                        // 2. A C struct are represented the same way in memory as tuple with the
                        // same number of the struct fields of the same type
                        // of the struct fields
                        //
                        // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet,
                        // Janet)`
                        let kv: *mut (Janet, Janet) =
                            unsafe { evil_janet::janet_table_find(proto, key.inner) as *mut _ };

                        if kv.is_null() {
                            if depth < evil_janet::JANET_MAX_PROTO_DEPTH {
                                depth += 1;
                                proto = unsafe { (*proto).proto };
                                continue;
                            } else {
                                break None;
                            }
                        } else {
                            // SAFETY: kv is safe to deref because we checked that it's not a null
                            // pointer.
                            unsafe {
                                if (*kv).1.is_nil() {
                                    if depth < evil_janet::JANET_MAX_PROTO_DEPTH {
                                        depth += 1;
                                        proto = (*proto).proto;
                                        continue;
                                    } else {
                                        break None;
                                    }
                                } else {
                                    break Some((&(*kv).0, &(*kv).1));
                                }
                            }
                        }
                    }
                }
            },
        }
    }

    /// Returns the value corresponding to the supplied `key` checking prototype
    /// tables.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(table.get_owned(10), Some(Janet::from("ten")));
    /// assert_eq!(table.get_owned(11), None);
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn get_owned(&self, key: impl Into<Janet>) -> Option<Janet> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            let val: Janet = unsafe { evil_janet::janet_table_get(self.raw, key.inner).into() };
            if val.is_nil() { None } else { Some(val) }
        }
    }

    /// Returns the key-value pair corresponding to the supplied `key` checking
    /// prototype tables.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(
    ///     table.get_owned_key_value(10),
    ///     Some((Janet::integer(10), Janet::from("ten")))
    /// );
    /// assert_eq!(table.get_owned_key_value(11), None);
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn get_owned_key_value(&self, key: impl Into<Janet>) -> Option<(Janet, Janet)> {
        let key = key.into();
        self.get_owned(key).map(|v| (key, v))
    }

    /// Returns the value corresponding to the supplied `key` without checking
    /// prototype tables.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(table.raw_get_owned(10), Some(Janet::from("ten")));
    /// assert_eq!(table.raw_get_owned(11), None);
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn raw_get_owned(&self, key: impl Into<Janet>) -> Option<Janet> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            let val: Janet = unsafe { evil_janet::janet_table_rawget(self.raw, key.inner).into() };
            if val.is_nil() { None } else { Some(val) }
        }
    }

    /// Returns the key-value pair corresponding to the supplied `key` without
    /// checking prototype tables.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(
    ///     table.raw_get_owned_key_value(10),
    ///     Some((Janet::integer(10), Janet::from("ten")))
    /// );
    /// assert_eq!(table.raw_get_owned_key_value(11), None);
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn raw_get_owned_key_value(&self, key: impl Into<Janet>) -> Option<(Janet, Janet)> {
        let key = key.into();
        self.raw_get_owned(key).map(|v| (key, v))
    }

    /// Find the bucket that contains the given `key`. Will also return bucket where `key`
    /// should go if not in the table.
    ///
    /// Notice that if there is no key-value pair in the table, this function will return
    /// a tuple of mutable references to Janet `nil`.
    // TODO: @GrayJack: Fow now lets allow dead code, if we get to 1.0.0 without it we can remove
    // the function entire function.
    #[allow(dead_code)]
    #[cfg_attr(feature = "inline-more", inline)]
    pub(crate) fn find(&mut self, key: impl Into<Janet>) -> Option<(&mut Janet, &mut Janet)> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
            // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
            // are represented in memory the same way
            // 2. A C struct are represented the same way in memory as tuple with the same number of
            // the struct fields of the same type of the struct fields
            //
            // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
            let kv: *mut (Janet, Janet) =
                unsafe { evil_janet::janet_table_find(self.raw, key.inner) as *mut _ };

            if kv.is_null() {
                None
            } else {
                // SAFETY: This is safe because we have a exclusive access to the structure
                unsafe { Some((&mut (*kv).0, &mut (*kv).1)) }
            }
        }
    }

    /// Removes `key` from the table, returning the value of the `key`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(table.remove(10), Some(Janet::from("ten")));
    /// assert_eq!(table.remove(10), None);
    /// ```
    #[cjvg("1.11.0")]
    #[inline]
    pub fn remove(&mut self, key: impl Into<Janet>) -> Option<Janet> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            let value: Janet =
                unsafe { evil_janet::janet_table_remove(self.raw, key.inner).into() };

            if value.is_nil() { None } else { Some(value) }
        }
    }

    /// Removes `key` from the table, returning the value of the `key`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::with_capacity(20);
    /// table.insert(10, "ten");
    ///
    /// assert_eq!(table.remove(10), Some(Janet::from("ten")));
    /// assert_eq!(table.remove(10), None);
    /// ```
    #[cjvg("1.0.0", "1.11.0")]
    #[inline]
    pub fn remove(&mut self, key: impl Into<Janet>) -> Option<Janet> {
        let key = key.into();

        if key.is_nil() {
            None
        } else {
            // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
            // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
            // are represented in memory the same way
            // 2. A C struct are represented the same way in memory as tuple with the same number of
            // the struct fields of the same type of the struct fields
            //
            // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
            let kv: *mut (Janet, Janet) =
                unsafe { janet_table_find(self.raw, key.inner) as *mut _ };

            if kv.is_null() {
                None
            } else {
                unsafe {
                    let ret = (*kv).1;
                    if ret.is_nil() {
                        None
                    } else {
                        (*self.raw).count -= 1;
                        (*self.raw).deleted += 1;

                        (*kv).0 = Janet::nil();
                        (*kv).1 = Janet::boolean(false);

                        Some(ret)
                    }
                }
            }
        }
    }

    /// Inserts a key-value pair into the table.
    ///
    /// If the table did not have this `key` present or if the `key` is a Janet `nil`,
    /// None is returned.
    ///
    /// If the map did have this key present, the value is updated, and the old value is
    /// returned.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    ///
    /// assert!(table.is_empty());
    /// assert_eq!(table.insert(37, "a"), None);
    /// assert!(!table.is_empty());
    ///
    /// table.insert(37, "b");
    /// assert_eq!(table.insert(37, "c"), Some(Janet::from("b")));
    /// assert_eq!(table.get(37), Some(&Janet::from("c")));
    /// ```
    #[inline]
    pub fn insert(&mut self, key: impl Into<Janet>, value: impl Into<Janet>) -> Option<Janet> {
        let (key, value) = (key.into(), value.into());

        // Ignore if key is nil
        if key.is_nil() {
            return None;
        }

        let old_value = self.get_owned(key);

        unsafe { evil_janet::janet_table_put(self.raw, key.inner, value.inner) };

        old_value
    }

    /// Tries to insert a key-value pair into the map, and returns
    /// a mutable reference to the value in the entry.
    ///
    /// # Errors
    ///
    /// If the map already had this key present, nothing is updated, and
    /// an error containing the occupied entry and the value is returned.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut map = JanetTable::new();
    /// assert_eq!(map.try_insert(37, "a").unwrap(), &Janet::from("a"));
    ///
    /// let err = map.try_insert(37, "b").unwrap_err();
    /// assert_eq!(err.entry.key(), &Janet::from(37));
    /// assert_eq!(err.entry.get(), &Janet::from("a"));
    /// assert_eq!(err.value, Janet::from("b"));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn try_insert(
        &mut self, key: impl Into<Janet>, value: impl Into<Janet>,
    ) -> Result<&mut Janet, OccupiedError<'_, 'data>> {
        match self.entry(key) {
            Entry::Occupied(entry) => Err(OccupiedError {
                entry,
                value: value.into(),
            }),
            Entry::Vacant(entry) => Ok(entry.insert(value)),
        }
    }

    /// Returns `true` if the table contains a value for the specified `key`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.insert(10, "ten");
    ///
    /// assert!(table.contains_key(10));
    /// assert!(!table.contains_key(11));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn contains_key(&self, key: impl Into<Janet>) -> bool {
        self.get(key).is_some()
    }

    /// Returns `true` if the table contais a given value.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.insert(10, "ten");
    ///
    /// assert!(table.contains("ten"));
    /// assert!(!table.contains(11));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn contains(&self, value: impl Into<Janet>) -> bool {
        let value = value.into();
        self.values().any(|&v| v == value)
    }

    /// Creates a iterator over the reference of the table keys.
    ///
    /// # Examples
    /// ```
    /// use janetrs::table;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let table = table! { 1 => "10", true => 10.0};
    ///
    /// for key in table.keys() {
    ///     println!("Key: {}", key);
    /// }
    /// ```
    #[inline]
    pub fn keys(&self) -> Keys<'_, '_> {
        Keys { inner: self.iter() }
    }

    /// Creates a iterator over the reference of the table values.
    ///
    /// # Examples
    /// ```
    /// use janetrs::table;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let table = table! { 1 => "10", true => 10.0};
    ///
    /// for val in table.values() {
    ///     println!("Value: {}", val);
    /// }
    /// ```
    #[inline]
    pub fn values(&self) -> Values<'_, '_> {
        Values { inner: self.iter() }
    }

    /// Creates a iterator over the mutable reference of the table values.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{table, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! { 1 => "10", true => 10.0};
    ///
    /// for val in table.values_mut() {
    ///     *val = Janet::number(100.0);
    /// }
    ///
    /// assert!(table.values().all(|v| *v == Janet::number(100.0)));
    /// ```
    #[inline]
    pub fn values_mut(&mut self) -> ValuesMut<'_, '_> {
        ValuesMut {
            inner: self.iter_mut(),
        }
    }

    /// Creates a iterator over the reference of the table key-value pairs.
    ///
    /// # Examples
    /// ```
    /// use janetrs::table;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let table = table! { 1 => "10", true => 10.0};
    ///
    /// for (k, v) in table.iter() {
    ///     println!("Key: {}\tValue: {}", k, v);
    /// }
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<'_, '_> {
        Iter {
            table: self,
            kv:    unsafe { (*self.raw).data },
            end:   unsafe { (*self.raw).data.offset(self.capacity() as isize) },
        }
    }

    /// Creates a iterator over the reference of the table keys and mutable reference
    /// of the table values.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{table, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = table! { 1 => "10", true => 10.0};
    ///
    /// for (k, val) in table.iter_mut() {
    ///     *val = Janet::number(100.0);
    /// }
    ///
    /// assert!(table.values().all(|v| *v == Janet::number(100.0)));
    /// ```
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<'_, '_> {
        let cap = self.capacity() as isize;

        IterMut {
            table: self,
            kv:    unsafe { (*self.raw).data },
            end:   unsafe { (*self.raw).data.offset(cap) },
        }
    }

    /// Return a raw pointer to the buffer raw structure.
    ///
    /// The caller must ensure that the buffer outlives the pointer this function returns,
    /// or else it will end up pointing to garbage.
    ///
    /// If you need to mutate the contents of the slice, use [`as_mut_ptr`].
    ///
    /// [`as_mut_ptr`]: ./struct.JanetTable.html#method.as_mut_raw
    #[inline]
    #[must_use]
    pub const fn as_raw(&self) -> *const CJanetTable {
        self.raw
    }

    /// Return a raw mutable pointer to the buffer raw structure.
    ///
    /// The caller must ensure that the buffer outlives the pointer this function returns,
    /// or else it will end up pointing to garbage.
    #[inline]
    pub fn as_mut_raw(&mut self) -> *mut CJanetTable {
        self.raw
    }
}

impl<'data> JanetTable<'data> {
    /// Gets the given `key`'s corresponding entry in the table for in-place manipulation.
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn entry(&mut self, key: impl Into<Janet>) -> Entry<'_, 'data> {
        let key = key.into();

        if self.get(key).is_some() {
            // SAFETY: We just checked that the table has the key, so there is no way that the
            // pointer will be NULL
            //
            // It's also safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
            // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
            // are represented in memory the same way
            // 2. A C struct are represented the same way in memory as tuple with the same number of
            // the struct fields of the same type of the struct fields
            //
            // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
            let elem = unsafe {
                NonNull::new_unchecked(evil_janet::janet_table_find(self.raw, key.inner) as *mut _)
            };

            Entry::Occupied(OccupiedEntry {
                key: Some(key),
                elem,
                table: self,
            })
        } else {
            Entry::Vacant(VacantEntry { key, table: self })
        }
    }
}

impl Debug for JanetTable<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_char('@')?;
        f.debug_map().entries(self.iter()).finish()
    }
}

impl Clone for JanetTable<'_> {
    #[inline]
    fn clone(&self) -> Self {
        JanetTable {
            raw:    unsafe { evil_janet::janet_table_clone(self.raw) },
            phatom: PhantomData,
        }
    }
}

impl PartialOrd for JanetTable<'_> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for JanetTable<'_> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.raw.cmp(&other.raw)
    }
}

impl PartialEq for JanetTable<'_> {
    #[inline]
    #[allow(clippy::unconditional_recursion)] // false positive
    fn eq(&self, other: &Self) -> bool {
        self.raw.eq(&other.raw)
    }
}

impl Eq for JanetTable<'_> {}

impl super::DeepEq for JanetTable<'_> {
    #[inline]
    fn deep_eq(&self, other: &Self) -> bool {
        if self.len() == other.len() {
            return self.iter().all(|(s_key, s_val)| {
                if let Some(o_val) = other.get(s_key) {
                    s_val.deep_eq(o_val)
                } else {
                    false
                }
            });
        }
        false
    }
}

impl super::DeepEq<JanetStruct<'_>> for JanetTable<'_> {
    #[inline]
    fn deep_eq(&self, other: &JanetStruct<'_>) -> bool {
        if self.len() == other.len() {
            return self.iter().all(|(s_key, s_val)| {
                if let Some(o_val) = other.get(s_key) {
                    s_val.deep_eq(o_val)
                } else {
                    false
                }
            });
        }
        false
    }
}

impl Extend<(Janet, Janet)> for JanetTable<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn extend<T: IntoIterator<Item = (Janet, Janet)>>(&mut self, iter: T) {
        iter.into_iter().for_each(|(k, v)| {
            self.insert(k, v);
        })
    }
}

impl<'a> Extend<(&'a Janet, &'a Janet)> for JanetTable<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn extend<T: IntoIterator<Item = (&'a Janet, &'a Janet)>>(&mut self, iter: T) {
        iter.into_iter().for_each(|(&k, &v)| {
            self.insert(k, v);
        })
    }
}

impl JanetExtend<JanetTable<'_>> for JanetTable<'_> {
    /// Extend the table with all key-value pairs of the `other` table.
    #[inline]
    fn extend(&mut self, other: JanetTable<'_>) {
        unsafe { evil_janet::janet_table_merge_table(self.raw, other.raw) }
    }
}

impl Default for JanetTable<'_> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl From<JanetStruct<'_>> for JanetTable<'_> {
    #[inline]
    fn from(val: JanetStruct<'_>) -> Self {
        val.into_iter().collect()
    }
}

impl From<&JanetStruct<'_>> for JanetTable<'_> {
    #[inline]
    fn from(val: &JanetStruct<'_>) -> Self {
        val.into_iter().collect()
    }
}

impl<T: Into<Janet>> Index<T> for JanetTable<'_> {
    type Output = Janet;

    /// Get a reference to the value of a given `key`.
    ///
    /// It is recommended to use [`get`] method or the [`entry`] API.
    ///
    /// # Janet Panics
    /// Panics if the table does not have the `key`.
    ///
    /// [`get`]: #method.get.html
    /// [`entry`]: #method.entry.html
    #[inline]
    fn index(&self, key: T) -> &Self::Output {
        self.get(key)
            .unwrap_or_else(|| crate::jpanic!("no entry found for key"))
    }
}

impl<'data> IntoIterator for JanetTable<'data> {
    type IntoIter = IntoIter<'data>;
    type Item = (Janet, Janet);

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let cap = self.capacity() as isize;
        let kv = unsafe { (*self.raw).data };
        let end = unsafe { (*self.raw).data.offset(cap) };

        IntoIter {
            table: self,
            kv,
            end,
        }
    }
}

impl<'a, 'data> IntoIterator for &'a JanetTable<'data> {
    type IntoIter = Iter<'a, 'data>;
    type Item = (&'a Janet, &'a Janet);

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let cap = self.capacity() as isize;

        Iter {
            table: self,
            kv:    unsafe { (*self.raw).data },
            end:   unsafe { (*self.raw).data.offset(cap) },
        }
    }
}

impl<'a, 'data> IntoIterator for &'a mut JanetTable<'data> {
    type IntoIter = IterMut<'a, 'data>;
    type Item = (&'a Janet, &'data mut Janet);

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let cap = self.capacity() as isize;

        IterMut {
            table: self,
            kv:    unsafe { (*self.raw).data },
            end:   unsafe { (*self.raw).data.offset(cap) },
        }
    }
}

impl<U, J> FromIterator<(U, J)> for JanetTable<'_>
where
    U: Into<Janet>,
    J: Into<Janet>,
{
    #[cfg_attr(feature = "inline-more", inline)]
    fn from_iter<T: IntoIterator<Item = (U, J)>>(iter: T) -> Self {
        let iter = iter.into_iter();
        let (lower, upper) = iter.size_hint();

        let mut new = if let Some(upper) = upper {
            Self::with_capacity(upper as i32)
        } else {
            Self::with_capacity(lower as i32)
        };

        for (k, v) in iter {
            let _ = new.insert(k, v);
        }
        new
    }
}

/// 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 [`JanetTable`].
///
/// [`entry`]: ./struct.JanetTable.html#method.entry
#[derive(Debug)]
pub enum Entry<'a, 'data> {
    Occupied(OccupiedEntry<'a, 'data>),
    Vacant(VacantEntry<'a, 'data>),
}

impl<'a, 'data> Entry<'a, 'data> {
    /// Provides in-place mutable access to an occupied entry before any potential inserts
    /// into the table.
    #[inline]
    #[must_use]
    pub fn and_modify<F>(self, f: F) -> Self
    where F: FnOnce(&mut Janet) {
        match self {
            Self::Occupied(mut entry) => {
                f(entry.get_mut());
                Self::Occupied(entry)
            },
            Self::Vacant(entry) => Self::Vacant(entry),
        }
    }

    /// Sets the value of the entry, and returns an [`OccupiedEntry`].
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// let entry = table.entry("Hey").insert(10);
    ///
    /// assert_eq!(entry.key(), Janet::from("Hey"));
    /// ```
    #[inline]
    pub fn insert(self, value: impl Into<Janet>) -> OccupiedEntry<'a, 'data> {
        match self {
            Self::Occupied(mut entry) => {
                entry.insert(value);
                entry
            },
            Self::Vacant(entry) => entry.insert_entry(value),
        }
    }

    /// Returns a reference to this entry's key.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    ///
    /// assert_eq!(table.entry("Hey").key(), Janet::from("Hey"));
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn key(&self) -> &Janet {
        match self {
            Self::Occupied(ref entry) => entry.key(),
            Self::Vacant(ref entry) => entry.key(),
        }
    }

    /// 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 janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    ///
    /// table.entry(10).or_insert(true);
    /// assert_eq!(table.get(10), Some(&Janet::boolean(true)));
    ///
    /// *table.entry(10).or_insert(10) = Janet::boolean(false);
    /// assert_eq!(table.get(10), Some(&Janet::boolean(false)));
    /// ```
    #[inline]
    pub fn or_insert(self, default: impl Into<Janet>) -> &'a mut Janet {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::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 janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    ///
    /// table.entry(10).or_insert_with(|| Janet::boolean(true));
    /// assert_eq!(table.get(10), Some(&Janet::boolean(true)));
    /// ```
    #[inline]
    pub fn or_insert_with<F>(self, default: F) -> &'a mut Janet
    where F: FnOnce() -> Janet {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(default()),
        }
    }

    /// Ensures a value is in the entry by inserting, if empty, the result of the
    /// `default` function, which takes the key as its argument, and returns a mutable
    /// reference to the value in the entry.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetTable};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    ///
    /// table
    ///     .entry("abc")
    ///     .or_insert_with_key(|key| Janet::from(key.len().unwrap_or(0)));
    /// assert_eq!(table.get("abc"), Some(&Janet::integer(3)));
    /// ```
    #[inline]
    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut Janet
    where F: FnOnce(&Janet) -> Janet {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => {
                let value = default(entry.key());
                entry.insert(value)
            },
        }
    }
}

/// A view into an occupied entry in a [`JanetTable`]. It is part of the [`Entry`] enum.
#[derive(Debug)]
pub struct OccupiedEntry<'a, 'data> {
    key:   Option<Janet>,
    elem:  NonNull<(Janet, Janet)>,
    table: &'a mut JanetTable<'data>,
}

impl<'a, 'data> OccupiedEntry<'a, 'data> {
    /// Gets a reference to the value in the entry.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.entry(10).or_insert(true);
    ///
    /// if let Entry::Occupied(o) = table.entry("poneyland") {
    ///     assert_eq!(o.get(), &Janet::boolean(true));
    /// }
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn get(&self) -> &Janet {
        // SAFETY: This is safe because `OccupiedEntry` cannot be created by a user and all
        // functions that creates then must create then with the `elem` field not NULL
        unsafe { &(*self.elem.as_ptr()).1 }
    }

    /// 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`].
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.entry(10).or_insert(true);
    ///
    /// assert_eq!(table.get(10), Some(&Janet::boolean(true)));
    /// if let Entry::Occupied(mut o) = table.entry(10) {
    ///     *o.get_mut() = Janet::number(10.0);
    ///     assert_eq!(o.get(), &Janet::number(10.0));
    ///
    ///     // We can use the same Entry multiple times.
    ///     *o.get_mut() = Janet::number(11.0);
    /// }
    ///
    /// assert_eq!(table.get(10), Some(&Janet::number(11.0)));
    /// ```
    ///
    /// [`into_mut`]: ./struct.OccupiedEntry.html#method.into_mut
    #[inline]
    pub fn get_mut(&mut self) -> &mut Janet {
        // SAFETY: This is safe to not check if the pointer is not null because `OccupiedEntry`
        // cannot be created by a user and all functions that creates then must create
        // then with the `elem` field not NULL
        // This is also safe to do return as exclusive borrow because we have a exclusive access
        // to the value
        unsafe { &mut (*self.elem.as_ptr()).1 }
    }

    /// Sets the value of the entry, and returns the entry's old value.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.entry(10).or_insert(true);
    ///
    /// if let Entry::Occupied(mut o) = table.entry(10) {
    ///     assert_eq!(o.insert(Janet::number(10.0)), &Janet::boolean(true));
    /// }
    ///
    /// assert_eq!(table.get(10), Some(&Janet::number(10.0)));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn insert(&mut self, value: impl Into<Janet>) -> Janet {
        let mut value = value.into();
        let old_value = self.get_mut();
        core::mem::swap(&mut value, old_value);
        value
    }

    /// Converts the [`OccupiedEntry`] into a mutable reference to the value in the entry
    /// with a lifetime bound to the table itself.
    ///
    /// If you need multiple references to the [`OccupiedEntry`], see [`get_mut`].
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.entry(10).or_insert(true);
    ///
    /// if let Entry::Occupied(o) = table.entry(10) {
    ///     *o.into_mut() = Janet::integer(11);
    /// }
    ///
    /// assert_eq!(table.get(10), Some(&Janet::integer(11)));
    /// ```
    ///
    /// [`get_mut`]: #method.get_mut
    #[inline]
    pub fn into_mut(self) -> &'a mut Janet {
        unsafe { &mut (*self.elem.as_ptr()).1 }
    }

    /// Gets a reference to the key in the entry.
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn key(&self) -> &Janet {
        unsafe { &(*self.elem.as_ptr()).0 }
    }

    /// Takes the value out of the entry, and returns it.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// table.entry(10).or_insert(true);
    ///
    /// if let Entry::Occupied(o) = table.entry(10) {
    ///     assert_eq!(o.remove(), Janet::boolean(true));
    /// }
    ///
    /// assert!(!table.contains_key(10));
    /// ```
    #[inline]
    pub fn remove(self) -> Janet {
        self.remove_entry().1
    }

    /// Take the ownership of the key and value from the table.
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn remove_entry(self) -> (Janet, Janet) {
        // SAFETY: Safe to deref because `elem` is not null
        let copy = unsafe { *self.elem.as_ptr() };
        self.table.remove(copy.0);
        copy
    }

    /// Replaces the entry, returning the old key and value. The new key in the table will
    /// be the key used to create this entry.
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn replace_entry(self, value: impl Into<Janet>) -> (Janet, Janet) {
        let value = value.into();

        // SAFETY: Safe to deref because `elem` is not null
        let mut entry = unsafe { *self.elem.as_ptr() };

        let old_key = core::mem::replace(&mut entry.0, self.key.unwrap());
        let old_value = core::mem::replace(&mut entry.1, value);

        (old_key, old_value)
    }

    /// Replaces the key in the table with the key used to create this entry.
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn replace_key(self) -> Janet {
        // SAFETY: Safe to deref because `elem` is not null
        let mut entry = unsafe { *self.elem.as_ptr() };
        core::mem::replace(&mut entry.0, self.key.unwrap())
    }
}

/// A view into a vacant entry in a [`JanetTable`]. It is part of the [`Entry`] enum.
#[derive(Debug)]
pub struct VacantEntry<'a, 'data> {
    key:   Janet,
    table: &'a mut JanetTable<'data>,
}

impl<'a, 'data> VacantEntry<'a, 'data> {
    /// Sets the `value` of the entry with the [`VacantEntry`]'s key, and returns a
    /// mutable reference to it.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    ///
    /// if let Entry::Vacant(o) = table.entry(10) {
    ///     o.insert(20);
    /// }
    ///
    /// assert_eq!(table.get(10), Some(&Janet::integer(20)));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn insert(self, value: impl Into<Janet>) -> &'a mut Janet {
        let value = value.into();
        self.table.insert(self.key, value);

        // SAFETY: We just inserted the key-value pair, therefore it certainly is in the table.
        unsafe { self.table.get_mut_unchecked(self.key) }
    }

    /// Sets the `value` of the entry with the [`VacantEntry`]'s key, and return a
    /// [`OccupiedEntry`].
    #[cfg_attr(feature = "inline-more", inline)]
    fn insert_entry(self, value: impl Into<Janet>) -> OccupiedEntry<'a, 'data> {
        let value = value.into();

        self.table.insert(self.key, value);

        // SAFETY: We inserted the key-value pair in the table in the line above, that means we
        // will always find the pair in the table, so there is no way that the pointer
        // will be NULL
        //
        //
        // It's also safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
        // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both types
        // are represented in memory the same way
        // 2. A C struct are represented the same way in memory as tuple with the same number of
        // the struct fields of the same type of the struct fields
        //
        // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
        let elem = unsafe {
            NonNull::new_unchecked(
                evil_janet::janet_table_find(self.table.raw, self.key.inner) as *mut _
            )
        };

        OccupiedEntry {
            key: None,
            elem,
            table: self.table,
        }
    }

    /// Take ownership of the key.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{
    ///     table::{Entry, JanetTable},
    ///     Janet,
    /// };
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut table = JanetTable::new();
    /// let key = Janet::number(101.5);
    ///
    /// if let Entry::Vacant(o) = table.entry(key) {
    ///     let key2 = o.into_key();
    ///     assert_eq!(key, key2);
    /// }
    /// ```
    #[inline]
    pub const fn into_key(self) -> Janet {
        self.key
    }

    /// Gets a reference to the key that would be used when inserting a value through the
    /// [`VacantEntry`].
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub const fn key(&self) -> &Janet {
        &self.key
    }
}


/// The error returned by [`try_insert`](JanetTable::try_insert) when the key already
/// exists.
///
/// Contains the occupied entry, and the value that was not inserted.
pub struct OccupiedError<'a, 'data> {
    /// The entry in the map that was already occupied.
    pub entry: OccupiedEntry<'a, 'data>,
    /// The value which was not inserted, because the entry was already occupied.
    pub value: Janet,
}

impl Debug for OccupiedError<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OccupiedError")
            .field("key", self.entry.key())
            .field("old_value", self.entry.get())
            .field("new_value", &self.value)
            .finish()
    }
}

impl<'a, 'data> fmt::Display for OccupiedError<'a, 'data> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "failed to insert {:?}, key {:?} already exists with value {:?}",
            self.value,
            self.entry.key(),
            self.entry.get()
        ))
    }
}

#[cfg(feature = "std")]
#[cfg_attr(_doc, doc(cfg(feature = "std")))]
impl std::error::Error for OccupiedError<'_, '_> {}

/// An iterator over a reference to the [`JanetTable`] key-value pairs.
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a, 'data> {
    table: &'a JanetTable<'data>,
    kv:    *const JanetKV,
    end:   *const JanetKV,
}

impl Debug for Iter<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.table.iter()).finish()
    }
}

impl<'a, 'data> Iterator for Iter<'a, 'data> {
    type Item = (&'a Janet, &'a Janet);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            while self.kv < self.end {
                // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
                // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both
                // types are represented in memory the same way
                // 2. A C struct are represented the same way in memory as tuple with the same
                // number of the struct fields of the same type of the struct fields
                // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
                // It's safe to get the data at the `self.offset` because we checked it's in the
                // bounds
                let ptr = self.kv as *const (Janet, Janet);

                if !(*ptr).0.is_nil() {
                    // Add for the next before returning
                    self.kv = self.kv.add(1);
                    return Some((&(*ptr).0, &(*ptr).1));
                }
                self.kv = self.kv.add(1);
            }
        }

        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = self.end as usize - self.kv as usize;
        (exact, Some(exact))
    }
}

impl ExactSizeIterator for Iter<'_, '_> {}

impl FusedIterator for Iter<'_, '_> {}

/// An iterator over a reference to the [`JanetTable`] keys.
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Keys<'a, 'data> {
    inner: Iter<'a, 'data>,
}

impl Debug for Keys<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.inner.table.keys()).finish()
    }
}

impl<'a> Iterator for Keys<'a, '_> {
    type Item = &'a Janet;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, _)| k)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for Keys<'_, '_> {}

impl FusedIterator for Keys<'_, '_> {}

/// An iterator over a reference to the [`JanetTable`] values.
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Values<'a, 'data> {
    inner: Iter<'a, 'data>,
}

impl<'a> Iterator for Values<'a, '_> {
    type Item = &'a Janet;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(_, v)| v)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl Debug for Values<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.inner.table.values()).finish()
    }
}

impl ExactSizeIterator for Values<'_, '_> {}

impl FusedIterator for Values<'_, '_> {}

/// An iterator over a mutable reference to the [`JanetTable`] key-value pairs.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IterMut<'a, 'data> {
    table: &'a JanetTable<'data>,
    kv:    *mut JanetKV,
    end:   *mut JanetKV,
}

impl Debug for IterMut<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.table.iter()).finish()
    }
}

impl<'a, 'data> Iterator for IterMut<'a, 'data> {
    type Item = (&'a Janet, &'data mut Janet);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            while self.kv < self.end {
                // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
                // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both
                // types are represented in memory the same way
                // 2. A C struct are represented the same way in memory as tuple with the same
                // number of the struct fields of the same type of the struct fields
                // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
                // It's safe to get the data at the `self.offset` because we checked it's in the
                // bounds
                let ptr = self.kv as *mut (Janet, Janet);

                if !(*ptr).0.is_nil() {
                    // Add for the next before returning
                    self.kv = self.kv.add(1);
                    return Some((&(*ptr).0, &mut (*ptr).1));
                }
                self.kv = self.kv.add(1);
            }
        }

        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = self.end as usize - self.kv as usize;
        (exact, Some(exact))
    }
}

impl ExactSizeIterator for IterMut<'_, '_> {}

impl FusedIterator for IterMut<'_, '_> {}

/// An Iterator over a mutable reference to the [`JanetTable`] values.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct ValuesMut<'a, 'data> {
    inner: IterMut<'a, 'data>,
}

impl Debug for ValuesMut<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.inner.table.clone()).finish()
    }
}

impl<'data> Iterator for ValuesMut<'_, 'data> {
    type Item = &'data mut Janet;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(_, v)| v)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ValuesMut<'_, '_> {}

impl FusedIterator for ValuesMut<'_, '_> {}

/// An iterator that moves out of a [`JanetTable`].
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IntoIter<'data> {
    table: JanetTable<'data>,
    kv:    *mut JanetKV,
    end:   *mut JanetKV,
}

impl Debug for IntoIter<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.table.iter()).finish()
    }
}

impl Iterator for IntoIter<'_> {
    type Item = (Janet, Janet);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            while self.kv < self.end {
                // SAFETY: It's safe to to cast `*JanetKV` to `*(Janet, Janet)` because:
                // 1. `Janet` contains a `evil_janet::Janet` and it is repr(transparent) so both
                // types are represented in memory the same way
                // 2. A C struct are represented the same way in memory as tuple with the same
                // number of the struct fields of the same type of the struct fields
                // So, `JanetKV === (evil_janet::Janet, evil_janet::Janet) === (Janet, Janet)`
                // It's safe to get the data at the `self.offset` because we checked it's in the
                // bounds
                let ptr = self.kv as *mut (Janet, Janet);

                if !(*ptr).0.is_nil() {
                    // Add for the next before returning
                    self.kv = self.kv.add(1);
                    return Some(((*ptr).0, (*ptr).1));
                }
                self.kv = self.kv.add(1);
            }
        }

        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = self.end as usize - self.kv as usize;
        (exact, Some(exact))
    }
}

impl ExactSizeIterator for IntoIter<'_> {}

impl FusedIterator for IntoIter<'_> {}

#[cfg(all(test, any(feature = "amalgation", feature = "link-system")))]
mod tests {
    use super::*;
    use crate::{client::JanetClient, table, JanetString};

    #[test]
    fn index() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::new();
        table.entry(10).or_insert("abc");

        assert_eq!(&Janet::from("abc"), table[10]);
        Ok(())
    }

    #[test]
    fn creation() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let table = JanetTable::new();
        assert_eq!(1, table.capacity());

        let table = JanetTable::with_capacity(10);
        assert_eq!(16, table.capacity());
        Ok(())
    }

    #[test]
    fn insert() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::new();

        assert_eq!(None, table.insert(Janet::nil(), true));
        assert_eq!(None, table.insert(0, true));
        assert_eq!(Some(Janet::boolean(true)), table.insert(0, false));
        Ok(())
    }

    #[test]
    fn length() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::new();
        assert_eq!(0, table.len());

        assert_eq!(None, table.insert(0, true));
        assert_eq!(1, table.len());
        Ok(())
    }

    #[test]
    fn get() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);
        table.insert(10, 10.1);

        assert_eq!(None, table.get(Janet::nil()));
        assert_eq!(None, table.get(11));
        assert_eq!(Some(&Janet::number(10.1)), table.get(10));
        Ok(())
    }

    #[test]
    fn get_mut() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);
        table.insert(10, "ten");

        let (k, v) = table.get_key_value_mut(10).unwrap();

        assert_eq!(&Janet::integer(10), k);
        assert_eq!(&mut Janet::from("ten"), v);

        *v = Janet::string(JanetString::new("ten but modified"));

        assert_eq!(
            table.get_key_value_mut(10),
            Some((&Janet::integer(10), &mut Janet::from("ten but modified")))
        );
        assert_eq!(table.get(11), None);
        Ok(())
    }

    #[test]
    fn get_owned() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);
        table.insert(10, 10.1);

        assert_eq!(None, table.get_owned(Janet::nil()));
        assert_eq!(None, table.get_owned(11));
        assert_eq!(Some(Janet::number(10.1)), table.get_owned(10));
        Ok(())
    }

    #[test]
    fn raw_get_owned() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);
        table.insert(10, 10.1);

        assert_eq!(None, table.raw_get_owned(Janet::nil()));
        assert_eq!(None, table.raw_get_owned(11));
        assert_eq!(Some(Janet::number(10.1)), table.raw_get_owned(10));
        Ok(())
    }

    #[test]
    fn find() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);
        table.insert(10, 10.1);

        assert_eq!(None, table.find(Janet::nil()));
        assert_eq!(Some((&mut Janet::nil(), &mut Janet::nil())), table.find(11));
        assert_eq!(
            Some((&mut Janet::integer(10), &mut Janet::number(10.1))),
            table.find(10)
        );
        Ok(())
    }

    #[test]
    fn remove() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);
        table.insert(10, 10.5);
        table.insert(12, 1);

        assert_eq!(2, table.len());

        assert_eq!(None, table.remove(Janet::nil()));
        assert_eq!(0, table.removed());
        assert_eq!(2, table.len());

        assert_eq!(None, table.remove(13));
        assert_eq!(0, table.removed());
        assert_eq!(2, table.len());

        assert_eq!(Some(Janet::number(10.5)), table.remove(10));
        assert_eq!(1, table.removed());
        assert_eq!(1, table.len());

        assert_eq!(Some(Janet::integer(1)), table.remove(12));
        assert_eq!(2, table.removed());
        assert!(table.is_empty());
        Ok(())
    }

    #[test]
    fn entry_api_vacant_or_insert() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);

        let val = table.entry(10).or_insert(78.9);
        assert_eq!(&mut Janet::number(78.9), val);
        assert_eq!(1, table.len());

        let val = table.entry(20).or_insert("default");
        assert_eq!(&mut Janet::from("default"), val);
        assert_eq!(2, table.len());
        Ok(())
    }

    #[test]
    fn entry_api_occupied_or_insert() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);

        table.insert(10, "dez");
        table.insert(11, "onze");

        assert_eq!(&mut Janet::from("dez"), table.entry(10).or_insert(10));
        assert_eq!(&mut Janet::from("onze"), table.entry(11).or_insert(11));
        Ok(())
    }

    #[test]
    fn entry_api_and_modify() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);

        table.insert(10, "dez");

        {
            let test_occupied = table
                .entry(10)
                .and_modify(|j| {
                    *j = Janet::boolean(true);
                })
                .or_insert(false);

            assert_eq!(&mut Janet::boolean(true), test_occupied);
        }

        let test_vacant = table
            .entry(11)
            .and_modify(|j| {
                *j = Janet::boolean(true);
            })
            .or_insert(false);

        assert_eq!(&mut Janet::boolean(false), test_vacant);
        Ok(())
    }

    #[test]
    fn entry_api_key() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);

        table.insert(10, "dez");

        {
            let entry = table.entry(10);
            let test_occupied = entry.key();
            assert_eq!(&Janet::integer(10), test_occupied);
        }


        let entry = table.entry(11);
        let test_vacant = entry.key();
        assert_eq!(&Janet::integer(11), test_vacant);
        Ok(())
    }

    #[test]
    fn entry_api_insert() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut table = JanetTable::with_capacity(2);

        let mut entry = table.entry(10).insert("dez");

        assert_eq!(&Janet::integer(10), entry.key());
        assert_eq!(&Janet::from("dez"), entry.get());
        assert_eq!(&mut Janet::from("dez"), entry.get_mut());
        assert_eq!(Janet::from("dez"), entry.insert("não dez"));
        assert_eq!(&Janet::integer(10), entry.key());
        assert_eq!(&Janet::from("não dez"), entry.get());
        assert_eq!(&mut Janet::from("não dez"), entry.get_mut());
        Ok(())
    }

    #[test]
    fn iter() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let table = table! {10 => "dez", 11 => "onze"};
        let mut iter = table.iter();

        assert_eq!(
            iter.next(),
            Some((&Janet::integer(10), &Janet::from("dez")))
        );
        assert_eq!(
            iter.next(),
            Some((&Janet::integer(11), &Janet::from("onze")))
        );
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next(), None);
        Ok(())
    }

    #[test]
    fn itermut() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let mut table = table! {10 => "dez", 11 => "onze"};
        let mut iter = table.iter_mut();

        assert_eq!(
            iter.next(),
            Some((&Janet::integer(10), &mut Janet::from("dez")))
        );
        assert_eq!(
            iter.next(),
            Some((&Janet::integer(11), &mut Janet::from("onze")))
        );
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next(), None);
        Ok(())
    }

    #[test]
    fn intoiter() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let table = table! {10 => "dez", 11 => "onze"};
        let mut iter = table.into_iter();

        assert_eq!(iter.next(), Some((Janet::integer(10), Janet::from("dez"))));
        assert_eq!(iter.next(), Some((Janet::integer(11), Janet::from("onze"))));
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next(), None);
        Ok(())
    }
}