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
//! This module should have all Janet type structures.
//!
//! # Lifetimes
//! There is some commom naming patterns when looking at the type definitions
//!
//!  - `'data` is the lifetime of data that is owned by the Janet GC.
use core::{
    cmp::Ordering,
    convert::TryFrom,
    fmt::{self, Display, Write},
};

use alloc::{string::String, vec::Vec};

#[cfg(feature = "std")]
use std::error;

use const_fn::const_fn;

use evil_janet::{Janet as CJanet, JanetType as CJanetType};

pub mod array;
pub mod buffer;
pub mod fiber;
pub mod function;
#[path = "types/abstract.rs"]
pub mod janet_abstract;
pub mod pointer;
pub mod string;
pub mod structs;
pub mod symbol;
pub mod table;
pub mod tuple;

pub use array::JanetArray;
pub use buffer::JanetBuffer;
pub use fiber::JanetFiber;
pub use function::{JanetCFunction, JanetFunction};
pub use janet_abstract::{IsJanetAbstract, JanetAbstract};
pub use pointer::JanetPointer;
pub use string::JanetString;
pub use structs::JanetStruct;
pub use symbol::{JanetKeyword, JanetSymbol};
pub use table::JanetTable;
pub use tuple::JanetTuple;

use crate::env::JanetEnvironment;

/// A trait to express a deep equality.
///
/// A deep equality is to check equality of the collections by value. That is needed
/// because the [`PartialEq`] for Janet mutable data structures are simply check is the
/// inner pointer are the same.
///
/// Using this trait to check for equality is probably much slower than [`PartialEq`]
/// implementations.
pub trait DeepEq<Rhs = Self> {
    fn deep_eq(&self, other: &Rhs) -> bool;
}


/// The error when converting [`Janet`]s to C Janet types.
///
/// This error only occurs when the [`Janet`] and the type it was being converted doesn't
/// match.
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
pub struct JanetConversionError;

#[cfg(feature = "std")]
impl error::Error for JanetConversionError {}

impl Display for JanetConversionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad("Error converting Janet to concrete type")
    }
}

/// `Janet` is the central structure of the Janet Language.
///
/// All possible Janet types are represented at some point as this structure, either to
/// receive as argumenst ou return something to Janet VM.
///
/// ## Creating new values
/// With exception to `Janet` [`nil`](Janet::nil) value the best way to create a `Janet`
/// value is to use the [`Janet::wrap`] function, it can receive anything that can be
/// turned [`Into`] `Janet`. For the `nil` value, there is a nice function for that, the
/// [`Janet::nil`] function.
///
/// It is also possible to use the [`From`] trait to convert as well.
///
/// ### Examples
///
/// ```
/// use janetrs::Janet;
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let j_nil = Janet::nil();
/// let jnt = Janet::wrap(10); // A Number Janet
/// let jnt_str = Janet::wrap("Hello"); // A JanetString Janet
/// let from_jnt = Janet::from(true); // A boolean Janet
/// ```
///
/// ## Extracting/Unwraping Janet values
///
/// To extract/unwrap the `Janet` value you can use the [`Janet::unwrap`] method, that
/// will return a [`TaggedJanet`] that you can pattern match to use the extracted value.
///
/// ### Example
///
/// ```
/// use janetrs::{Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let jnt = Janet::wrap(10); // A Number Janet
///
/// match jnt.unwrap() {
///     TaggedJanet::Abstract(jabstract) => {},
///     TaggedJanet::Array(array) => {},
///     TaggedJanet::Boolean(boolean) => {},
///     TaggedJanet::Buffer(buffer) => {},
///     TaggedJanet::CFunction(c_fun) => {},
///     TaggedJanet::Fiber(fiber) => {},
///     TaggedJanet::Function(func) => {},
///     TaggedJanet::Keyword(keyword) => {},
///     TaggedJanet::Nil => {},
///     TaggedJanet::Number(num) => {},
///     TaggedJanet::Pointer(ptr) => {},
///     TaggedJanet::String(string) => {},
///     TaggedJanet::Struct(st) => {},
///     TaggedJanet::Symbol(symbol) => {},
///     TaggedJanet::Table(table) => {},
///     TaggedJanet::Tuple(tuple) => {},
/// };
/// ```
///
/// To extract/unwrap the `Janet` value you can use the [`Janet::try_unwrap`] method, that
/// will return a [`Result`] either with the resulted type of and conversion error.
///
/// It is possible to use the [`TryFrom`] trait, but that requires to include the trait in
/// the context.
///
/// ### Example
///
/// ```
/// use janetrs::{Janet, JanetString};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let jnt = Janet::wrap(10); // A Number Janet
///
/// let res_num: Result<f64, _> = jnt.try_unwrap();
/// assert!(res_num.is_ok());
///
/// let res_string = jnt.try_unwrap::<JanetString>();
/// assert!(res_string.is_err());
/// ```
// allow this lint here because it is complaining about manually implementing PartialOrd between
// Janet and &Janet
#[allow(clippy::derive_ord_xor_partial_ord)]
#[allow(clippy::derive_hash_xor_eq)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Janet {
    pub(crate) inner: CJanet,
}

impl Janet {
    /// Create a nil [`Janet`].
    #[inline]
    pub fn nil() -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_nil() },
        }
    }

    /// Create a boolean [`Janet`] with `value`.
    #[inline]
    pub fn boolean(value: bool) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_boolean(value.into()) },
        }
    }

    /// Create a number [`Janet`] with `value`.
    #[inline]
    pub fn number(value: f64) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_number(value) },
        }
    }

    /// Create a number [`Janet`] with a [`i32`] `value`.
    #[inline]
    pub fn integer(value: i32) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_integer(value) },
        }
    }

    /// Create a abstract integer [`Janet`] with `value`.
    #[inline]
    pub fn int64(value: i64) -> Self {
        Self::j_abstract(JanetAbstract::new(value))
    }

    /// Create a abstract integer [`Janet`] with `value`.
    #[inline]
    pub fn uint64(value: u64) -> Self {
        Self::j_abstract(JanetAbstract::new(value))
    }

    /// Create a array [`Janet`] with `value`.
    #[inline]
    pub fn array(value: JanetArray<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_array(value.raw) },
        }
    }

    /// Create a buffer [`Janet`] with `value`.
    #[inline]
    pub fn buffer(value: JanetBuffer<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_buffer(value.raw) },
        }
    }

    /// Create a table [`Janet`] with `value`.
    #[inline]
    pub fn table(value: JanetTable<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_table(value.raw) },
        }
    }

    /// Create a tuple [`Janet`] with `value`.
    #[inline]
    pub fn tuple(value: JanetTuple<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_tuple(value.raw) },
        }
    }

    /// Create a string [`Janet`] with `value`.
    #[inline]
    pub fn string(value: JanetString<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_string(value.raw) },
        }
    }

    /// Create a struct [`Janet`] with `value`.
    #[inline]
    pub fn structs(value: JanetStruct<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_struct(value.raw) },
        }
    }

    /// Create a symbol [`Janet`] with `value`.
    #[inline]
    pub fn symbol(value: JanetSymbol<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_symbol(value.raw) },
        }
    }

    /// Create a keyword [`Janet`] with `value`.
    #[inline]
    pub fn keyword(value: JanetKeyword<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_keyword(value.raw) },
        }
    }

    /// Create a fiber [`Janet`] with `value`.
    #[inline]
    pub fn fiber(value: JanetFiber<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_fiber(value.raw) },
        }
    }

    /// Create a function [`Janet`] with `value`.
    #[inline]
    pub fn function(value: JanetFunction<'_>) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_function(value.raw) },
        }
    }

    /// Create a C function [`Janet`] with `value`.
    #[inline]
    pub fn c_function(value: JanetCFunction) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_cfunction(value) },
        }
    }

    /// Create a pointer [`Janet`] with `value`.
    #[inline]
    pub fn pointer(value: JanetPointer) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_pointer(value.as_ptr()) },
        }
    }

    /// Create as abstract [`Janet`] with `value`.
    #[inline]
    pub fn j_abstract(value: JanetAbstract) -> Self {
        Self {
            inner: unsafe { evil_janet::janet_wrap_abstract(value.raw) },
        }
    }

    /// Get a dynamic [keywrord](self::JanetKeyword) binding from the environment if it
    /// exists.
    #[inline]
    pub fn dynamic(key: impl AsRef<[u8]>) -> Option<Self> {
        let mut key: JanetBuffer = key.as_ref().into();
        key.push('\0');
        // let mut key = String::from(key.to_str().ok()?);
        // key.push('\0');

        let janet = Janet::from(unsafe { evil_janet::janet_dyn(key.as_ptr() as *const _) });

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

    /// Resolve a `symbol` in the core environment.
    #[inline]
    pub fn from_core<'a>(symbol: impl Into<JanetSymbol<'a>>) -> Option<Self> {
        let env = JanetEnvironment::default();
        env.resolve(symbol)
    }

    /// Wraps a value into a [`Janet`].
    #[inline]
    pub fn wrap(value: impl Into<Janet>) -> Self {
        value.into()
    }

    /// Unwrap the [`Janet`] value into a enum that holds the type value
    #[inline]
    pub fn unwrap<'data>(self) -> TaggedJanet<'data> {
        self.into()
    }

    /// Tries to unwrap the [`Janet`] into a concrete type that implements
    /// [`TryFrom`]<[`Janet`]>.
    #[inline]
    pub fn try_unwrap<T: TryFrom<Self>>(self) -> Result<T, T::Error> {
        T::try_from(self)
    }

    /// Return `true` if [`Janet`] is nil type.
    #[inline]
    pub fn is_nil(&self) -> bool {
        matches!(self.kind(), JanetType::Nil)
    }

    /// Returns the length of a [`Janet`] if it is of a applicable type (Abstract, Array,
    /// Buffer, Keyword, Struct, Symbol, Table, Tuple).
    ///
    /// Janet Panics:
    /// If the `Janet` value is a Janet Abstract and the method to get the
    /// length (janet) panics, this function janet panics as well.
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn len(&self) -> Option<i32> {
        match self.unwrap() {
            TaggedJanet::Array(x) => Some(x.len()),
            TaggedJanet::Buffer(x) => Some(x.len()),
            TaggedJanet::Keyword(x) => Some(x.len()),
            TaggedJanet::String(x) => Some(x.len()),
            TaggedJanet::Struct(x) => Some(x.len()),
            TaggedJanet::Symbol(x) => Some(x.len()),
            TaggedJanet::Table(x) => Some(x.len()),
            TaggedJanet::Tuple(x) => Some(x.len()),
            TaggedJanet::Abstract(_) => {
                self.get_method("length")
                    .and_then(|method: Janet| match method.unwrap() {
                        // I think Abstract methods can only be a C function because as far a
                        // I(GrayJack) know, a JanetFunction cannot be created (as in written) by
                        // the public Janet C API.
                        TaggedJanet::CFunction(fun) => fun,
                        _ => None,
                    })
                    .map(|f| {
                        // Safety: We are trusting that am Abstract Janet method through a C
                        // function will not cause UB. It can janet panic
                        unsafe { f(1, [self.inner].as_mut_ptr()) }.into()
                    })
                    .and_then(|len: Janet| match len.unwrap() {
                        TaggedJanet::Number(x) => {
                            if x >= i32::MIN as f64
                                && x <= i32::MAX as f64
                                && (x - x as i32 as f64).abs() < f64::EPSILON
                            {
                                Some(x as i32)
                            } else {
                                None
                            }
                        },
                        _ => None,
                    })
            },
            _ => None,
        }
    }

    /// Returns `true` if `Janet` has a applicable type (Abstract, Array, Buffer, Keyword,
    /// Struct, Symbol, Table, Tuple) and the length of it is zero, and `false` otherwise.
    ///
    /// Janet Panic:
    /// This function may panic for the same reason as [`Janet::len`]
    #[inline]
    pub fn is_empty(&self) -> bool {
        matches!(self.len(), Some(0))
    }

    /// Returns `true` if the `Janet` value are truthy.
    #[inline]
    pub fn is_truthy(&self) -> bool {
        unsafe { evil_janet::janet_truthy(self.inner) == 0 }
    }

    /// Retuns a `Janet` value containing the requested method if it exists.
    #[inline]
    pub fn get_method(&self, method_name: &str) -> Option<Janet> {
        let method_name: Janet = JanetKeyword::from(method_name).into();
        let method: Janet = unsafe { evil_janet::janet_get(self.inner, method_name.inner) }.into();

        if method.is_nil() {
            return None;
        }
        Some(method)
    }

    /// Retuns `true` if the `Janet` has a method callled `method_name`
    #[inline]
    pub fn has_method(&self, method_name: &str) -> bool {
        self.get_method(method_name).is_some()
    }

    /// Returns the type of [`Janet`] object.
    #[inline]
    pub fn kind(&self) -> JanetType {
        unsafe { evil_janet::janet_type(self.inner) }.into()
    }

    /// Returns the raw data of the data
    #[inline]
    pub const fn raw_data(&self) -> CJanet {
        self.inner
    }
}

impl fmt::Debug for Janet {
    #[cfg_attr(feature = "inline-more", inline)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Janet").field(&self.unwrap()).finish()
    }
}

macro_rules! struct_table_display {
    ($id:ident, $f:expr) => {
        let len = $id.len();
        if len > 10 {
            let keys: JanetTuple = $id.keys().collect();
            for i in 0..3 {
                // SAFETY: We are in-bounds
                let key = unsafe { keys.get_unchecked(i) };
                let value = unsafe { $id.get_unchecked(key) };

                fmt::Display::fmt(key, $f)?;
                $f.write_str(" : ")?;
                fmt::Display::fmt(value, $f)?;
                $f.write_str(", ")?;
            }

            $f.write_str("..., ")?;

            for i in len - 4..len - 2 {
                // SAFETY: We are in-bounds
                let key = unsafe { keys.get_unchecked(i) };
                let value = unsafe { $id.get_unchecked(key) };

                fmt::Display::fmt(key, $f)?;
                $f.write_str(" : ")?;
                fmt::Display::fmt(value, $f)?;
                $f.write_str(", ")?;
            }

            // SAFETY: We are in-bounds
            let key = unsafe { keys.get_unchecked(len - 1) };
            let value = unsafe { $id.get_unchecked(key) };

            fmt::Display::fmt(key, $f)?;
            $f.write_str(" : ")?;
            fmt::Display::fmt(value, $f)?;
        } else {
            let mut count = $id.len();
            for (key, value) in &$id {
                fmt::Display::fmt(key, $f)?;
                $f.write_str(" : ")?;
                fmt::Display::fmt(value, $f)?;

                if count != 1 {
                    $f.write_str(", ")?;
                }

                count -= 1;
            }
        }
    };
}

macro_rules! array_tuple_display {
    ($id:ident, $f:expr) => {
        let mut len = $id.len();
        if len > 10 {
            // Make sure we don't mutate len past this point.
            let len = len;

            for i in 0..5 {
                // SAFETY: We are in-bounds
                let it = unsafe { $id.get_unchecked(i) };
                fmt::Display::fmt(it, $f)?;
                $f.write_str(", ")?;
            }

            $f.write_str("..., ")?;

            for i in len - 5..len - 1 {
                // SAFETY: We are in-bounds
                let it = unsafe { $id.get_unchecked(i) };
                fmt::Display::fmt(it, $f)?;
                $f.write_str(", ")?;
            }

            // SAFETY: We are in-bounds
            let it = unsafe { $id.get_unchecked(len) };
            fmt::Display::fmt(it, $f)?;
        } else {
            for it in &$id {
                fmt::Display::fmt(it, $f)?;

                if len != 1 {
                    $f.write_str(", ")?;
                }

                len -= 1;
            }
        }
    };
}

impl fmt::Display for Janet {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.unwrap() {
            TaggedJanet::Boolean(b) => fmt::Display::fmt(&b, f),
            TaggedJanet::Buffer(s) => fmt::Display::fmt(&s, f),
            TaggedJanet::Number(n) => fmt::Display::fmt(&n, f),
            TaggedJanet::String(s) => fmt::Display::fmt(&s, f),
            TaggedJanet::Abstract(a) => {
                // Special cases for integers
                if let Ok(int) = a.get::<i64>() {
                    return fmt::Display::fmt(int, f);
                }

                if let Ok(int) = a.get::<u64>() {
                    return fmt::Display::fmt(int, f);
                }

                // If the abstract has tostring function
                if let Some(tostring) = a.type_info().tostring {
                    let buff = JanetBuffer::with_capacity(30);
                    unsafe { tostring(a.raw, buff.raw) }
                    return fmt::Display::fmt(&buff, f);
                }

                // In case there is no tostring function, default to this
                f.write_str("<Abstract>")
            },
            TaggedJanet::Array(arr) => {
                f.write_str("@[")?;
                array_tuple_display!(arr, f);
                f.write_char(']')
            },
            TaggedJanet::CFunction(_) => f.write_str("<C function>"),
            TaggedJanet::Fiber(fiber) => {
                f.write_str("<Fiber ")?;
                fmt::Debug::fmt(&fiber.as_raw(), f)?;
                f.write_char('>')
            },
            TaggedJanet::Function(_) => f.write_str("<Function>"),
            TaggedJanet::Keyword(key) => fmt::Display::fmt(&key, f),
            TaggedJanet::Nil => f.write_str("nil"),
            TaggedJanet::Pointer(ptr) => {
                f.write_char('<')?;
                fmt::Pointer::fmt(&ptr, f)?;
                f.write_char('>')
            },
            TaggedJanet::Struct(st) => {
                f.write_char('{')?;
                struct_table_display!(st, f);
                f.write_char('}')
            },
            TaggedJanet::Symbol(sym) => fmt::Display::fmt(&sym, f),
            TaggedJanet::Table(table) => {
                // Classes in Janet are just tables with prototype with special keywords
                // If a vailable we printo the class name
                if let Some(proto) = table.prototype() {
                    if let Some(name) = proto.get(JanetKeyword::new("_name")) {
                        match name.unwrap() {
                            TaggedJanet::Buffer(s) => {
                                f.write_char('@')?;
                                fmt::Display::fmt(&s, f)?
                            },
                            TaggedJanet::String(s) => {
                                f.write_char('@')?;
                                fmt::Display::fmt(&s, f)?
                            },
                            TaggedJanet::Symbol(s) => {
                                f.write_char('@')?;
                                fmt::Display::fmt(&s, f)?
                            },
                            _ => f.write_char('@')?,
                        }
                    } else {
                        f.write_char('@')?;
                    }
                } else {
                    f.write_char('@')?;
                }
                f.write_char('{')?;
                struct_table_display!(table, f);
                f.write_char('}')
            },
            TaggedJanet::Tuple(tup) => {
                f.write_char('[')?;
                array_tuple_display!(tup, f);
                f.write_char(']')
            },
        }
    }
}

#[cfg(feature = "std")]
impl error::Error for Janet {}

impl PartialEq<&Janet> for Janet {
    #[inline]
    fn eq(&self, other: &&Janet) -> bool {
        self.eq(*other)
    }
}

impl PartialOrd<&Janet> for Janet {
    #[inline]
    fn partial_cmp(&self, other: &&Janet) -> Option<Ordering> {
        self.partial_cmp(*other)
    }
}

impl PartialEq<Janet> for &Janet {
    #[inline]
    fn eq(&self, other: &Janet) -> bool {
        (*self).eq(other)
    }
}

impl PartialOrd<Janet> for &Janet {
    #[inline]
    fn partial_cmp(&self, other: &Janet) -> Option<Ordering> {
        (*self).partial_cmp(other)
    }
}

impl DeepEq for Janet {
    #[inline]
    fn deep_eq(&self, other: &Self) -> bool {
        // HACK: The left side of the match binding doesn't require `ref` since Rust 1.49
        // `binding by-move and by-ref in the same pattern is unstable`
        // If bump the minimal rust version to >= 1.49, remove the first ref of the patterns
        match (self.unwrap(), other.unwrap()) {
            (TaggedJanet::Array(ref s), TaggedJanet::Array(ref o)) => s.deep_eq(o),
            (TaggedJanet::Array(ref s), TaggedJanet::Tuple(ref o)) => s.deep_eq(o),
            (TaggedJanet::Tuple(ref s), TaggedJanet::Array(ref o)) => s.deep_eq(o),
            (TaggedJanet::Buffer(ref s), TaggedJanet::Buffer(ref o)) => s.deep_eq(o),
            (TaggedJanet::Buffer(ref s), TaggedJanet::String(ref o)) => s.deep_eq(o),
            (TaggedJanet::String(ref s), TaggedJanet::Buffer(ref o)) => s.deep_eq(o),
            (TaggedJanet::Struct(ref s), TaggedJanet::Struct(ref o)) => s.deep_eq(o),
            (TaggedJanet::Struct(ref s), TaggedJanet::Table(ref o)) => s.deep_eq(o),
            (TaggedJanet::Table(ref s), TaggedJanet::Struct(ref o)) => s.deep_eq(o),
            (TaggedJanet::Table(ref s), TaggedJanet::Table(ref o)) => s.deep_eq(o),
            _ => self.eq(other),
        }
    }
}

impl From<CJanet> for Janet {
    #[inline]
    fn from(val: CJanet) -> Self {
        Self { inner: val }
    }
}

impl From<&CJanet> for Janet {
    #[inline]
    fn from(val: &CJanet) -> Self {
        Self { inner: *val }
    }
}

impl From<&Janet> for Janet {
    #[inline]
    fn from(val: &Janet) -> Self {
        *val
    }
}

impl From<i32> for Janet {
    #[inline]
    fn from(val: i32) -> Self {
        Self::integer(val)
    }
}

impl From<&i32> for Janet {
    #[inline]
    fn from(val: &i32) -> Self {
        Self::integer(*val)
    }
}

impl TryFrom<Janet> for i32 {
    type Error = JanetConversionError;

    #[inline]
    fn try_from(value: Janet) -> Result<Self, Self::Error> {
        if matches!(value.kind(), JanetType::Number) {
            Ok(unsafe { evil_janet::janet_unwrap_integer(value.inner) })
        } else {
            Err(JanetConversionError)
        }
    }
}

impl From<i64> for Janet {
    #[inline]
    fn from(val: i64) -> Self {
        Self::int64(val)
    }
}

impl From<&i64> for Janet {
    #[inline]
    fn from(val: &i64) -> Self {
        Self::int64(*val)
    }
}

impl TryFrom<Janet> for i64 {
    type Error = JanetConversionError;

    #[inline]
    fn try_from(value: Janet) -> Result<Self, Self::Error> {
        if let TaggedJanet::Abstract(x) = value.unwrap() {
            if x.is::<Self>() {
                Ok(unsafe { *x.cast() })
            } else {
                Err(JanetConversionError)
            }
        } else {
            Err(JanetConversionError)
        }
    }
}

impl From<u64> for Janet {
    #[inline]
    fn from(val: u64) -> Self {
        Self::uint64(val)
    }
}

impl From<&u64> for Janet {
    #[inline]
    fn from(val: &u64) -> Self {
        Self::uint64(*val)
    }
}

impl TryFrom<Janet> for u64 {
    type Error = JanetConversionError;

    #[inline]
    fn try_from(value: Janet) -> Result<Self, Self::Error> {
        if let TaggedJanet::Abstract(x) = value.unwrap() {
            if x.is::<Self>() {
                Ok(unsafe { *x.cast() })
            } else {
                Err(JanetConversionError)
            }
        } else {
            Err(JanetConversionError)
        }
    }
}

impl From<&str> for Janet {
    #[inline]
    fn from(val: &str) -> Self {
        if let Some(val) = val.strip_prefix(':') {
            let s = JanetKeyword::new(val);
            Self::keyword(s)
        } else {
            let s = JanetString::new(val);
            Self::string(s)
        }
    }
}

impl From<char> for Janet {
    #[inline]
    fn from(val: char) -> Self {
        let s = JanetString::from(val);
        Self::string(s)
    }
}

impl From<&char> for Janet {
    #[inline]
    fn from(val: &char) -> Self {
        let s = JanetString::from(val);
        Self::string(s)
    }
}

impl From<JanetCFunction> for Janet {
    fn from(val: JanetCFunction) -> Self {
        Self::c_function(val)
    }
}

impl From<Janet> for CJanet {
    #[inline]
    fn from(val: Janet) -> Self {
        val.inner
    }
}

impl From<&Janet> for CJanet {
    #[inline]
    fn from(val: &Janet) -> Self {
        val.inner
    }
}

impl PartialEq<CJanet> for Janet {
    #[inline]
    fn eq(&self, other: &CJanet) -> bool {
        self.inner.eq(other)
    }
}

impl PartialEq<Janet> for CJanet {
    #[inline]
    fn eq(&self, other: &Janet) -> bool {
        self.eq(&other.inner)
    }
}

impl PartialOrd<CJanet> for Janet {
    #[inline]
    fn partial_cmp(&self, other: &CJanet) -> Option<Ordering> {
        self.inner.partial_cmp(other)
    }
}

impl PartialOrd<Janet> for CJanet {
    #[inline]
    fn partial_cmp(&self, other: &Janet) -> Option<Ordering> {
        self.partial_cmp(&other.inner)
    }
}

impl PartialEq<&CJanet> for Janet {
    #[inline]
    fn eq(&self, other: &&CJanet) -> bool {
        self.inner.eq(*other)
    }
}

impl PartialEq<&Janet> for CJanet {
    #[inline]
    fn eq(&self, other: &&Janet) -> bool {
        self.eq(&(*other).inner)
    }
}

impl PartialOrd<&CJanet> for Janet {
    #[inline]
    fn partial_cmp(&self, other: &&CJanet) -> Option<Ordering> {
        self.inner.partial_cmp(*other)
    }
}

impl PartialOrd<&Janet> for CJanet {
    #[inline]
    fn partial_cmp(&self, other: &&Janet) -> Option<Ordering> {
        self.partial_cmp(&(*other).inner)
    }
}

macro_rules! from_for_janet {
    ($ty:ty, $fn_name:ident) => {
        impl From<$ty> for Janet {
            #[inline]
            fn from(val: $ty) -> Self {
                Self::$fn_name(val)
            }
        }
    };

    (clone $ty:ty, $fn_name:ident) => {
        impl From<$ty> for Janet {
            #[inline]
            fn from(val: $ty) -> Self {
                Self::$fn_name(val.clone())
            }
        }
    };

    (deref $ty:ty, $fn_name:ident) => {
        impl From<$ty> for Janet {
            #[inline]
            fn from(val: $ty) -> Self {
                Self::$fn_name(*val)
            }
        }
    };
}

macro_rules! try_from_janet {
    ($ty:ty, $kind:path) => {
        impl TryFrom<Janet> for $ty {
            type Error = JanetConversionError;

            #[inline]
            fn try_from(value: Janet) -> Result<Self, Self::Error> {
                if let $kind(x) = value.unwrap() {
                    Ok(x)
                } else {
                    Err(JanetConversionError)
                }
            }
        }
    };
}

from_for_janet!(JanetPointer, pointer);
try_from_janet!(JanetPointer, TaggedJanet::Pointer);

from_for_janet!(JanetAbstract, j_abstract);
try_from_janet!(JanetAbstract, TaggedJanet::Abstract);

from_for_janet!(JanetTable<'_>, table);
from_for_janet!(clone &JanetTable<'_>, table);
try_from_janet!(JanetTable<'_>, TaggedJanet::Table);

from_for_janet!(JanetArray<'_>, array);
from_for_janet!(clone &JanetArray<'_>, array);
try_from_janet!(JanetArray<'_>, TaggedJanet::Array);

from_for_janet!(JanetBuffer<'_>, buffer);
from_for_janet!(clone &JanetBuffer<'_>, buffer);
try_from_janet!(JanetBuffer<'_>, TaggedJanet::Buffer);

from_for_janet!(JanetTuple<'_>, tuple);
from_for_janet!(clone &JanetTuple<'_>, tuple);
try_from_janet!(JanetTuple<'_>, TaggedJanet::Tuple);

from_for_janet!(JanetString<'_>, string);
from_for_janet!(clone &JanetString<'_>, string);
try_from_janet!(JanetString<'_>, TaggedJanet::String);

from_for_janet!(JanetStruct<'_>, structs);
from_for_janet!(clone &JanetStruct<'_>, structs);
try_from_janet!(JanetStruct<'_>, TaggedJanet::Struct);

from_for_janet!(JanetSymbol<'_>, symbol);
from_for_janet!(clone &JanetSymbol<'_>, symbol);
try_from_janet!(JanetSymbol<'_>, TaggedJanet::Symbol);

from_for_janet!(JanetKeyword<'_>, keyword);
from_for_janet!(clone &JanetKeyword<'_>, keyword);
try_from_janet!(JanetKeyword<'_>, TaggedJanet::Keyword);

from_for_janet!(JanetFunction<'_>, function);
try_from_janet!(JanetFunction<'_>, TaggedJanet::Function);

from_for_janet!(JanetFiber<'_>, fiber);
try_from_janet!(JanetFiber<'_>, TaggedJanet::Fiber);

try_from_janet!(JanetCFunction, TaggedJanet::CFunction);

from_for_janet!(bool, boolean);
from_for_janet!(deref & bool, boolean);
try_from_janet!(bool, TaggedJanet::Boolean);

from_for_janet!(f64, number);
from_for_janet!(deref & f64, number);
try_from_janet!(f64, TaggedJanet::Number);

macro_rules! janet_unwrap_unchecked {
    (abstracts $janet:expr) => {
        unsafe { JanetAbstract::from_raw(evil_janet::janet_unwrap_abstract($janet.into())) }
    };

    (array $janet:expr) => {
        unsafe { JanetArray::from_raw(evil_janet::janet_unwrap_array($janet.into())) }
    };

    (boolean $janet:expr) => {
        unsafe { evil_janet::janet_unwrap_boolean($janet.inner) } != 0
    };

    (buffer $janet:expr) => {
        unsafe { JanetBuffer::from_raw(evil_janet::janet_unwrap_buffer($janet.into())) }
    };

    (cfunc $janet:expr) => {
        unsafe { evil_janet::janet_unwrap_cfunction($janet.into()) }
    };

    (fiber $janet:expr) => {
        unsafe { JanetFiber::from_raw(evil_janet::janet_unwrap_fiber($janet.into())) }
    };

    (function $janet:expr) => {
        unsafe { JanetFunction::from_raw(evil_janet::janet_unwrap_function($janet.into())) }
    };

    (keyword $janet:expr) => {
        unsafe { JanetKeyword::from_raw(evil_janet::janet_unwrap_keyword($janet.into())) }
    };

    (number $janet:expr) => {
        unsafe { evil_janet::janet_unwrap_number($janet.into()) }
    };

    (pointer $janet:expr) => {
        unsafe { JanetPointer::new(evil_janet::janet_unwrap_pointer($janet.into())) }
    };

    (string $janet:expr) => {
        unsafe { JanetString::from_raw(evil_janet::janet_unwrap_string($janet.into())) }
    };

    (structs $janet:expr) => {
        unsafe { JanetStruct::from_raw(evil_janet::janet_unwrap_struct($janet.into())) }
    };

    (symbol $janet:expr) => {
        unsafe { JanetSymbol::from_raw(evil_janet::janet_unwrap_symbol($janet.into())) }
    };

    (table $janet:expr) => {
        unsafe { JanetTable::from_raw(evil_janet::janet_unwrap_table($janet.into())) }
    };

    (tuple $janet:expr) => {
        unsafe { JanetTuple::from_raw(evil_janet::janet_unwrap_tuple($janet.into())) }
    };
}

/// Janet type in the form of a Tagged Union.
#[derive(Debug)]
pub enum TaggedJanet<'data> {
    Abstract(JanetAbstract),
    Array(JanetArray<'data>),
    Boolean(bool),
    Buffer(JanetBuffer<'data>),
    CFunction(JanetCFunction),
    Fiber(JanetFiber<'data>),
    Function(JanetFunction<'data>),
    Keyword(JanetKeyword<'data>),
    Nil,
    Number(f64),
    Pointer(JanetPointer),
    String(JanetString<'data>),
    Struct(JanetStruct<'data>),
    Symbol(JanetSymbol<'data>),
    Table(JanetTable<'data>),
    Tuple(JanetTuple<'data>),
}

impl From<Janet> for TaggedJanet<'_> {
    #[inline]
    fn from(val: Janet) -> Self {
        match val.kind() {
            JanetType::Abstract => Self::Abstract(janet_unwrap_unchecked!(abstracts val)),
            JanetType::Array => Self::Array(janet_unwrap_unchecked!(array val)),
            JanetType::Boolean => Self::Boolean(janet_unwrap_unchecked!(boolean val)),
            JanetType::Buffer => Self::Buffer(janet_unwrap_unchecked!(buffer val)),
            JanetType::CFunction => Self::CFunction(janet_unwrap_unchecked!(cfunc val)),
            JanetType::Fiber => Self::Fiber(janet_unwrap_unchecked!(fiber val)),
            JanetType::Function => Self::Function(janet_unwrap_unchecked!(function val)),
            JanetType::Keyword => Self::Keyword(janet_unwrap_unchecked!(keyword val)),
            JanetType::Nil => Self::Nil,
            JanetType::Number => Self::Number(janet_unwrap_unchecked!(number val)),
            JanetType::Pointer => Self::Pointer(janet_unwrap_unchecked!(pointer val)),
            JanetType::String => Self::String(janet_unwrap_unchecked!(string val)),
            JanetType::Struct => Self::Struct(janet_unwrap_unchecked!(structs val)),
            JanetType::Symbol => Self::Symbol(janet_unwrap_unchecked!(symbol val)),
            JanetType::Table => Self::Table(janet_unwrap_unchecked!(table val)),
            JanetType::Tuple => Self::Tuple(janet_unwrap_unchecked!(tuple val)),
        }
    }
}

impl TaggedJanet<'_> {
    #[inline]
    #[const_fn("1.46")]
    pub const fn kind(&self) -> JanetType {
        match self {
            TaggedJanet::Abstract(_) => JanetType::Abstract,
            TaggedJanet::Array(_) => JanetType::Array,
            TaggedJanet::Boolean(_) => JanetType::Boolean,
            TaggedJanet::Buffer(_) => JanetType::Buffer,
            TaggedJanet::CFunction(_) => JanetType::CFunction,
            TaggedJanet::Fiber(_) => JanetType::Fiber,
            TaggedJanet::Function(_) => JanetType::Function,
            TaggedJanet::Keyword(_) => JanetType::Keyword,
            TaggedJanet::Nil => JanetType::Nil,
            TaggedJanet::Number(_) => JanetType::Number,
            TaggedJanet::Pointer(_) => JanetType::Pointer,
            TaggedJanet::String(_) => JanetType::String,
            TaggedJanet::Struct(_) => JanetType::Struct,
            TaggedJanet::Symbol(_) => JanetType::Symbol,
            TaggedJanet::Table(_) => JanetType::Table,
            TaggedJanet::Tuple(_) => JanetType::Tuple,
        }
    }
}

impl From<TaggedJanet<'_>> for Janet {
    #[inline]
    fn from(val: TaggedJanet) -> Self {
        match val {
            TaggedJanet::Abstract(inner) => inner.into(),
            TaggedJanet::Array(inner) => inner.into(),
            TaggedJanet::Boolean(inner) => inner.into(),
            TaggedJanet::Buffer(inner) => inner.into(),
            TaggedJanet::CFunction(inner) => inner.into(),
            TaggedJanet::Fiber(inner) => inner.into(),
            TaggedJanet::Function(inner) => inner.into(),
            TaggedJanet::Keyword(inner) => inner.into(),
            TaggedJanet::Nil => Janet::nil(),
            TaggedJanet::Number(inner) => inner.into(),
            TaggedJanet::Pointer(inner) => inner.into(),
            TaggedJanet::String(inner) => inner.into(),
            TaggedJanet::Struct(inner) => inner.into(),
            TaggedJanet::Symbol(inner) => inner.into(),
            TaggedJanet::Table(inner) => inner.into(),
            TaggedJanet::Tuple(inner) => inner.into(),
        }
    }
}

/// Representation of all Janet types.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(u32)]
pub enum JanetType {
    Abstract = evil_janet::JanetType_JANET_ABSTRACT,
    Array  = evil_janet::JanetType_JANET_ARRAY,
    Boolean = evil_janet::JanetType_JANET_BOOLEAN,
    Buffer = evil_janet::JanetType_JANET_BUFFER,
    CFunction = evil_janet::JanetType_JANET_CFUNCTION,
    Fiber  = evil_janet::JanetType_JANET_FIBER,
    Function = evil_janet::JanetType_JANET_FUNCTION,
    Keyword = evil_janet::JanetType_JANET_KEYWORD,
    Nil    = evil_janet::JanetType_JANET_NIL,
    Number = evil_janet::JanetType_JANET_NUMBER,
    Pointer = evil_janet::JanetType_JANET_POINTER,
    String = evil_janet::JanetType_JANET_STRING,
    Struct = evil_janet::JanetType_JANET_STRUCT,
    Symbol = evil_janet::JanetType_JANET_SYMBOL,
    Table  = evil_janet::JanetType_JANET_TABLE,
    Tuple  = evil_janet::JanetType_JANET_TUPLE,
}

impl From<CJanetType> for JanetType {
    #[allow(non_upper_case_globals)]
    #[inline]
    fn from(raw: CJanetType) -> Self {
        match raw {
            evil_janet::JanetType_JANET_ABSTRACT => Self::Abstract,
            evil_janet::JanetType_JANET_ARRAY => Self::Array,
            evil_janet::JanetType_JANET_BOOLEAN => Self::Boolean,
            evil_janet::JanetType_JANET_BUFFER => Self::Buffer,
            evil_janet::JanetType_JANET_CFUNCTION => Self::CFunction,
            evil_janet::JanetType_JANET_FIBER => Self::Fiber,
            evil_janet::JanetType_JANET_FUNCTION => Self::Function,
            evil_janet::JanetType_JANET_KEYWORD => Self::Keyword,
            evil_janet::JanetType_JANET_NIL => Self::Nil,
            evil_janet::JanetType_JANET_NUMBER => Self::Number,
            evil_janet::JanetType_JANET_POINTER => Self::Pointer,
            evil_janet::JanetType_JANET_STRING => Self::String,
            evil_janet::JanetType_JANET_STRUCT => Self::Struct,
            evil_janet::JanetType_JANET_SYMBOL => Self::Symbol,
            evil_janet::JanetType_JANET_TABLE => Self::Table,
            evil_janet::JanetType_JANET_TUPLE => Self::Tuple,
            _ => unreachable!(),
        }
    }
}

impl Display for JanetType {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Abstract => Display::fmt("abstract", f),
            Self::Array => Display::fmt("array", f),
            Self::Boolean => Display::fmt("boolean", f),
            Self::Buffer => Display::fmt("buffer", f),
            Self::CFunction => Display::fmt("cfunction", f),
            Self::Fiber => Display::fmt("fiber", f),
            Self::Function => Display::fmt("function", f),
            Self::Keyword => Display::fmt("keyword", f),
            Self::Nil => Display::fmt("nil", f),
            Self::Number => Display::fmt("number", f),
            Self::Pointer => Display::fmt("pointer", f),
            Self::String => Display::fmt("string", f),
            Self::Struct => Display::fmt("struct", f),
            Self::Symbol => Display::fmt("symbol", f),
            Self::Table => Display::fmt("table", f),
            Self::Tuple => Display::fmt("tuple", f),
        }
    }
}

impl From<JanetType> for CJanetType {
    #[inline]
    fn from(val: JanetType) -> Self {
        val as u32
    }
}

/// Signals that can be produced by a [`JanetFunction`] and [`JanetCFunction`]
/// representing that those worked correctly or not.
///
/// `Ok`, `Yield` and `User9` usually represents when it worked, the others usually
/// represents that something went wrong.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(u32)]
pub enum JanetSignal {
    Ok    = evil_janet::JanetSignal_JANET_SIGNAL_OK,
    Error = evil_janet::JanetSignal_JANET_SIGNAL_ERROR,
    Debug = evil_janet::JanetSignal_JANET_SIGNAL_DEBUG,
    Yield = evil_janet::JanetSignal_JANET_SIGNAL_YIELD,
    User0 = evil_janet::JanetSignal_JANET_SIGNAL_USER0,
    User1 = evil_janet::JanetSignal_JANET_SIGNAL_USER1,
    User2 = evil_janet::JanetSignal_JANET_SIGNAL_USER2,
    User3 = evil_janet::JanetSignal_JANET_SIGNAL_USER3,
    User4 = evil_janet::JanetSignal_JANET_SIGNAL_USER4,
    User5 = evil_janet::JanetSignal_JANET_SIGNAL_USER5,
    User6 = evil_janet::JanetSignal_JANET_SIGNAL_USER6,
    User7 = evil_janet::JanetSignal_JANET_SIGNAL_USER7,
    User8 = evil_janet::JanetSignal_JANET_SIGNAL_USER8,
    User9 = evil_janet::JanetSignal_JANET_SIGNAL_USER9,
}

impl From<u32> for JanetSignal {
    fn from(val: u32) -> Self {
        match val {
            evil_janet::JanetSignal_JANET_SIGNAL_OK => Self::Ok,
            evil_janet::JanetSignal_JANET_SIGNAL_ERROR => Self::Error,
            evil_janet::JanetSignal_JANET_SIGNAL_DEBUG => Self::Debug,
            evil_janet::JanetSignal_JANET_SIGNAL_YIELD => Self::Yield,
            evil_janet::JanetSignal_JANET_SIGNAL_USER0 => Self::User0,
            evil_janet::JanetSignal_JANET_SIGNAL_USER1 => Self::User1,
            evil_janet::JanetSignal_JANET_SIGNAL_USER2 => Self::User2,
            evil_janet::JanetSignal_JANET_SIGNAL_USER3 => Self::User3,
            evil_janet::JanetSignal_JANET_SIGNAL_USER4 => Self::User4,
            evil_janet::JanetSignal_JANET_SIGNAL_USER5 => Self::User5,
            evil_janet::JanetSignal_JANET_SIGNAL_USER6 => Self::User6,
            evil_janet::JanetSignal_JANET_SIGNAL_USER7 => Self::User7,
            evil_janet::JanetSignal_JANET_SIGNAL_USER8 => Self::User8,
            evil_janet::JanetSignal_JANET_SIGNAL_USER9 => Self::User9,
            _ => unreachable!(),
        }
    }
}

impl From<JanetSignal> for u32 {
    fn from(val: JanetSignal) -> Self {
        val as u32
    }
}

/// Trait that express the ability of a Janet collection to extend it with another
/// collection.
pub trait JanetExtend<T> {
    fn extend(&mut self, collection: T);
}

macro_rules! impl_string_like {
    ($($ty:ty)+) => {
        $(
            impl From<&[u8]> for $ty {
                #[inline]
                fn from(bytes: &[u8]) -> Self { Self::new(bytes) }
            }

            impl From<alloc::vec::Vec<u8>> for $ty {
                #[inline]
                fn from(vec: Vec<u8>) -> Self {
                    Self::new(vec)
                }
            }

            impl From<&str> for $ty {
                #[inline]
                fn from(rust_str: &str) -> Self { Self::new(rust_str) }
            }

            impl From<alloc::string::String> for $ty {
                #[inline]
                fn from(s: String) -> Self {
                    Self::new(s)
                }
            }

            impl PartialEq for $ty {
                #[inline]
                fn eq(&self, other: &Self) -> bool { unsafe { evil_janet::janet_string_equal(self.raw, other.raw) != 0 } }
            }

            impl Eq for $ty {}

            impl PartialOrd for $ty {
                #[inline]
                fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                    let cmp_res = unsafe { evil_janet::janet_string_compare(self.raw, other.raw) };

                    Some(match cmp_res {
                        0 => Ordering::Equal,
                        _ if cmp_res < 0  => Ordering::Less,
                        _ if cmp_res > 0 => Ordering::Greater,
                        _ => return None,
                    })
                }
            }

            impl Ord for $ty {
                #[inline]
                fn cmp(&self, other: &Self) -> Ordering {
                    match self.partial_cmp(other) {
                        Some(ord) => ord,
                        None => {
                            // Janet seems to ensure that the only values returned as -1, 0 and 1
                            // It could be possible to use unreachable unchecked but I don't think it's
                            // necessary, this branch will probably be optimized out by the compiler.
                            unreachable!()
                        },
                    }
                }
            }
        )+
    };
}

macro_rules! impl_part {
    ($t1:ty, $t2:ty) => {
        impl PartialEq<$t1> for $t2 {
            #[inline]
            fn eq(&self, other: &$t1) -> bool {
                unsafe { evil_janet::janet_string_equal(self.raw, other.raw) != 0 }
            }
        }

        impl PartialEq<$t2> for $t1 {
            #[inline]
            fn eq(&self, other: &$t2) -> bool {
                unsafe { evil_janet::janet_string_equal(self.raw, other.raw) != 0 }
            }
        }

        impl PartialOrd<$t1> for $t2 {
            #[inline]
            fn partial_cmp(&self, other: &$t1) -> Option<Ordering> {
                let cmp_res = unsafe { evil_janet::janet_string_compare(self.raw, other.raw) };

                Some(match cmp_res {
                    0 => Ordering::Equal,
                    _ if cmp_res < 0 => Ordering::Less,
                    _ if cmp_res > 0 => Ordering::Greater,
                    _ => return None,
                })
            }
        }

        impl PartialOrd<$t2> for $t1 {
            #[inline]
            fn partial_cmp(&self, other: &$t2) -> Option<Ordering> {
                let cmp_res = unsafe { evil_janet::janet_string_compare(self.raw, other.raw) };

                Some(match cmp_res {
                    0 => Ordering::Equal,
                    _ if cmp_res < 0 => Ordering::Less,
                    _ if cmp_res > 0 => Ordering::Greater,
                    _ => return None,
                })
            }
        }
    };
}

// Macro to impl PartialEq for Janet String-like types against Rust String-like types.
// For JanetString, JanetSymbol and JanetKeyword it follow the same idea of comparing
// bytes For JanetBuffer where PartialEq means comparison with other Janet Types means if
// the address is the same, it is contra-intuitive, since in this case is byte comparison
// as other String-like types, that is for convenience using Rust types.
macro_rules! string_impl_partial_eq {
    ($lhs:ty, $rhs:ty) => {
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                let other: &[u8] = other.as_ref();
                PartialEq::eq(self.as_bytes(), other)
            }
        }

        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool {
                let this: &[u8] = self.as_ref();
                PartialEq::eq(this, other.as_bytes())
            }
        }
    };
}

// Macro to impl PartialOrd for Janet String-like types against Rust String-like types.
// For JanetString, JanetSymbol and JanetKeyword it follow the same idea of comparing
// bytes For JanetBuffer where PartialOrd means comparison with other Janet Types means if
// the address is the same, it is contra-intuitive, since in this case is byte comparison
// as other String-like types, that is for convenience using Rust types.
macro_rules! string_impl_partial_ord {
    ($lhs:ty, $rhs:ty) => {
        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
            #[inline]
            fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {
                let other: &[u8] = other.as_ref();
                PartialOrd::partial_cmp(self.as_bytes(), other)
            }
        }

        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
            #[inline]
            fn partial_cmp(&self, other: &$lhs) -> Option<Ordering> {
                let this: &[u8] = self.as_ref();
                PartialOrd::partial_cmp(this, other.as_bytes())
            }
        }
    };
}

impl_string_like!(JanetString<'_> JanetKeyword<'_> JanetSymbol<'_>);
impl_part!(JanetString<'_>, JanetKeyword<'_>);
impl_part!(JanetString<'_>, JanetSymbol<'_>);
impl_part!(JanetKeyword<'_>, JanetSymbol<'_>);

string_impl_partial_eq!(JanetString<'_>, Vec<u8>);
string_impl_partial_eq!(JanetString<'_>, [u8]);
string_impl_partial_eq!(JanetString<'_>, &'a [u8]);
string_impl_partial_eq!(JanetString<'_>, String);
string_impl_partial_eq!(JanetString<'_>, str);
string_impl_partial_eq!(JanetString<'_>, &'a str);
string_impl_partial_eq!(JanetString<'_>, bstr::BStr);
string_impl_partial_eq!(JanetString<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetString<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetString<'_>, &'a bstr::BString);

string_impl_partial_ord!(JanetString<'_>, Vec<u8>);
string_impl_partial_ord!(JanetString<'_>, [u8]);
string_impl_partial_ord!(JanetString<'_>, &'a [u8]);
string_impl_partial_ord!(JanetString<'_>, String);
string_impl_partial_ord!(JanetString<'_>, str);
string_impl_partial_ord!(JanetString<'_>, &'a str);
string_impl_partial_ord!(JanetString<'_>, bstr::BStr);
string_impl_partial_ord!(JanetString<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetString<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetString<'_>, &'a bstr::BString);

string_impl_partial_eq!(JanetBuffer<'_>, Vec<u8>);
string_impl_partial_eq!(JanetBuffer<'_>, [u8]);
string_impl_partial_eq!(JanetBuffer<'_>, &'a [u8]);
string_impl_partial_eq!(JanetBuffer<'_>, String);
string_impl_partial_eq!(JanetBuffer<'_>, str);
string_impl_partial_eq!(JanetBuffer<'_>, &'a str);
string_impl_partial_eq!(JanetBuffer<'_>, bstr::BStr);
string_impl_partial_eq!(JanetBuffer<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetBuffer<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetBuffer<'_>, &'a bstr::BString);

string_impl_partial_ord!(JanetBuffer<'_>, Vec<u8>);
string_impl_partial_ord!(JanetBuffer<'_>, [u8]);
string_impl_partial_ord!(JanetBuffer<'_>, &'a [u8]);
string_impl_partial_ord!(JanetBuffer<'_>, String);
string_impl_partial_ord!(JanetBuffer<'_>, str);
string_impl_partial_ord!(JanetBuffer<'_>, &'a str);
string_impl_partial_ord!(JanetBuffer<'_>, bstr::BStr);
string_impl_partial_ord!(JanetBuffer<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetBuffer<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetBuffer<'_>, &'a bstr::BString);

string_impl_partial_eq!(JanetSymbol<'_>, Vec<u8>);
string_impl_partial_eq!(JanetSymbol<'_>, [u8]);
string_impl_partial_eq!(JanetSymbol<'_>, &'a [u8]);
string_impl_partial_eq!(JanetSymbol<'_>, String);
string_impl_partial_eq!(JanetSymbol<'_>, str);
string_impl_partial_eq!(JanetSymbol<'_>, &'a str);
string_impl_partial_eq!(JanetSymbol<'_>, bstr::BStr);
string_impl_partial_eq!(JanetSymbol<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetSymbol<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetSymbol<'_>, &'a bstr::BString);

string_impl_partial_ord!(JanetSymbol<'_>, Vec<u8>);
string_impl_partial_ord!(JanetSymbol<'_>, [u8]);
string_impl_partial_ord!(JanetSymbol<'_>, &'a [u8]);
string_impl_partial_ord!(JanetSymbol<'_>, String);
string_impl_partial_ord!(JanetSymbol<'_>, str);
string_impl_partial_ord!(JanetSymbol<'_>, &'a str);
string_impl_partial_ord!(JanetSymbol<'_>, bstr::BStr);
string_impl_partial_ord!(JanetSymbol<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetSymbol<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetSymbol<'_>, &'a bstr::BString);

string_impl_partial_eq!(JanetKeyword<'_>, Vec<u8>);
string_impl_partial_eq!(JanetKeyword<'_>, [u8]);
string_impl_partial_eq!(JanetKeyword<'_>, &'a [u8]);
string_impl_partial_eq!(JanetKeyword<'_>, String);
string_impl_partial_eq!(JanetKeyword<'_>, str);
string_impl_partial_eq!(JanetKeyword<'_>, &'a str);
string_impl_partial_eq!(JanetKeyword<'_>, bstr::BStr);
string_impl_partial_eq!(JanetKeyword<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetKeyword<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_eq!(JanetKeyword<'_>, &'a bstr::BString);

string_impl_partial_ord!(JanetKeyword<'_>, Vec<u8>);
string_impl_partial_ord!(JanetKeyword<'_>, [u8]);
string_impl_partial_ord!(JanetKeyword<'_>, &'a [u8]);
string_impl_partial_ord!(JanetKeyword<'_>, String);
string_impl_partial_ord!(JanetKeyword<'_>, str);
string_impl_partial_ord!(JanetKeyword<'_>, &'a str);
string_impl_partial_ord!(JanetKeyword<'_>, bstr::BStr);
string_impl_partial_ord!(JanetKeyword<'_>, &'a bstr::BStr);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetKeyword<'_>, bstr::BString);
#[cfg(feature = "std")]
string_impl_partial_ord!(JanetKeyword<'_>, &'a bstr::BString);

#[cfg(all(test, any(feature = "amalgation", feature = "link-system")))]
mod tests {
    use super::*;
    #[cfg(feature = "std")]
    use core::hash::{Hash, Hasher};

    #[cfg_attr(feature = "std", test)]
    #[cfg(feature = "std")]
    fn janet_eq_hash() -> Result<(), crate::client::Error> {
        let _client = crate::client::JanetClient::init()?;

        let mut hasher1 = std::collections::hash_map::DefaultHasher::new();
        let mut hasher2 = std::collections::hash_map::DefaultHasher::new();

        let (j1, j2) = (Janet::from(10), Janet::from(10));
        j1.hash(&mut hasher1);
        j2.hash(&mut hasher2);
        assert_eq!(j1, j2);
        assert_eq!(hasher1.finish(), hasher2.finish());
        assert_eq!(j1 == j2, hasher1.finish() == hasher2.finish());

        let mut hasher1 = std::collections::hash_map::DefaultHasher::new();
        let mut hasher2 = std::collections::hash_map::DefaultHasher::new();

        let (j1, j2) = (Janet::from(10), Janet::from("hey"));
        j1.hash(&mut hasher1);
        j2.hash(&mut hasher2);
        assert_ne!(j1, j2);
        assert_ne!(hasher1.finish(), hasher2.finish());
        assert_eq!(j1 == j2, hasher1.finish() == hasher2.finish());

        Ok(())
    }

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

        unsafe { evil_janet::janet_setdyn("test\0".as_ptr() as *const _, Janet::from(10).into()) };

        assert_eq!(Some(Janet::number(10.0)), Janet::dynamic("test"));

        Ok(())
    }
}