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
//! This module provides many Levenshtein distance routines.
//!
//! These distance functions share the same efficient underlying SIMD-accelerated implementation:
//! * `levenshtein_exp` for low number of edits, otherwise `levenshtein`
//! * `rdamerau_exp` for low number of edits, otherwise `rdamerau`
//! * `levenshtein_simd_k`
//! * `levenshtein_simd_k_with_opts`
//!
//! These search functions share the same efficient underlying SIMD-accelerated implementation:
//! * `levenshtein_search`
//! * `levenshtein_search_simd`
//! * `levenshtein_search_simd_with_opts`

use std::*;
use super::*;
use super::jewel::*;

/// A struct holding the edit costs for mismatches, gaps, and possibly transpositions.
///
/// This should be used as a parameter for Levenshtein distance or search routines.
#[derive(Copy, Clone, Debug)]
pub struct EditCosts {
    mismatch_cost: u8,
    gap_cost: u8,
    start_gap_cost: u8,
    transpose_cost: Option<u8>
}

impl EditCosts {
    /// Create a new `EditCosts` struct, checking for whether the specified costs are valid.
    ///
    /// # Arguments
    /// * `mismatch_cost` - cost of a mismatch edit, which must be positive
    /// * `gap_cost` - cost of a gap, which must be positive
    /// * `start_gap_cost` - additional cost of starting a gap, for affine gap costs; this can
    /// be zero for linear gap costs
    /// * `transpose_cost` - cost of a transpose, which must be cheaper than doing the equivalent
    /// operation with mismatches and gaps
    pub fn new(mismatch_cost: u8, gap_cost: u8, start_gap_cost: u8, transpose_cost: Option<u8>) -> Self {
        assert!(mismatch_cost > 0);
        assert!(gap_cost > 0);

        if let Some(cost) = transpose_cost {
            assert!(cost > 0);
            // transpose cost must be cheaper than doing the equivalent with other edits
            assert!((cost >> 1) < mismatch_cost);
            assert!((cost >> 1) < gap_cost);
        }

        Self{
            mismatch_cost: mismatch_cost,
            gap_cost: gap_cost,
            start_gap_cost: start_gap_cost,
            transpose_cost: transpose_cost
        }
    }

    /// For Levenshtein searches, the cost of transpositions must be less than or equal to cost of
    /// gaps.
    ///
    /// This is important for free gaps at the beginning of the needle to be unable to take priority
    /// over transpositions, as it is possible to emulate a transposition with two gaps.
    fn check_search(&self) {
        if let Some(cost) = self.transpose_cost {
            assert!(cost <= self.start_gap_cost + self.gap_cost);
        }
    }
}

/// Costs for Levenshtein distance, where mismatches and gaps both have a cost of 1, and
/// transpositions are not allowed.
pub const LEVENSHTEIN_COSTS: EditCosts = EditCosts{mismatch_cost: 1, gap_cost: 1, start_gap_cost: 0, transpose_cost: None};
/// Costs for restricted Damerau-Levenshtein distance, where mismatches, gaps, and transpositions
/// all have a cost of 1.
pub const RDAMERAU_COSTS: EditCosts = EditCosts{mismatch_cost: 1, gap_cost: 1, start_gap_cost: 0, transpose_cost: Some(1)};

/// Returns the Levenshtein distance between two strings using the naive scalar algorithm.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_naive(b"abc", b"ab");
///
/// assert!(dist == 1);
/// ```
pub fn levenshtein_naive<T: PartialEq>(a: &[T], b: &[T]) -> u32 {
    levenshtein_naive_with_opts(a, b, false, LEVENSHTEIN_COSTS).0
}

/// Returns the Levenshtein distance between two strings using the naive scalar algorithm.
///
/// # Arguments
/// * `a` - first string (&str)
/// * `b` - second string (&str)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenstein_naive_str("abc", "ab");
///
/// assert!(dist == 1);
/// ```
pub fn levenstein_naive_str(a: &str, b: &str) -> u32 {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    levenshtein_naive(&a, &b)
}

/// Returns the Levenshtein distance between two strings and optionally, the edit traceback,
/// using the naive scalar algorithm, with extra options.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
/// * `trace_on` - whether to return the traceback, the sequence of edits between `a` and `b`
/// * `costs` - `EditCosts` struct for the cost of each edit operation
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_naive_with_opts(b"abc", b"ab", true, LEVENSHTEIN_COSTS);
///
/// assert!(dist == (1, Some(vec![Edit{edit: EditType::Match, count: 2},
///                               Edit{edit: EditType::BGap, count: 1}])));
/// ```
#[inline]
pub fn levenshtein_naive_with_opts<T>(a: &[T], b: &[T], trace_on: bool, costs: EditCosts) -> (u32, Option<Vec<Edit>>)
    where T: PartialEq
{
    let swap = a.len() > b.len(); // swap so that a len <= b len
    let a_new = if swap {b} else {a};
    let a_new_len = a_new.len();
    let b_new = if swap {a} else {b};
    let b_new_len = b_new.len();
    let mismatch_cost = costs.mismatch_cost as u32;
    let gap_cost = costs.gap_cost as u32;
    let start_gap_cost = costs.start_gap_cost as u32;
    let transpose_cost = match costs.transpose_cost {
        Some(cost) => cost as u32,
        None => 0
    };
    let allow_transpose = costs.transpose_cost.is_some();

    let len = a_new_len + 1;
    let mut dp0 = vec![0u32; len];
    let mut dp1 = vec![0u32; len]; // in each iteration, dp0 and dp1 are already calculated
    let mut dp2 = vec![0u32; len]; // dp2 the currently calculated column
    let mut a_gap_dp = vec![u32::MAX; len];
    let mut b_gap_dp = vec![u32::MAX; len];
    let mut traceback = if trace_on {vec![0u8; (b_new_len + 1) * len]} else {vec![]};

    for i in 0..len {
        dp1[i] = (i as u32) * gap_cost + if i == 0 {0} else {start_gap_cost};

        if trace_on {
            traceback[0 * len + i] = 2u8;
        }
    }

    for i in 1..(b_new_len + 1) {
        a_gap_dp[0] = (i as u32) * gap_cost + start_gap_cost;
        dp2[0] = (i as u32) * gap_cost + start_gap_cost;

        if trace_on {
            traceback[i * len + 0] = 1u8;
        }

        for j in 1..len {
            let sub = dp1[j - 1] + ((a_new[j - 1] != b_new[i - 1]) as u32) * mismatch_cost;
            a_gap_dp[j] = cmp::min(dp1[j] + start_gap_cost + gap_cost, a_gap_dp[j].saturating_add(gap_cost));
            b_gap_dp[j] = cmp::min(dp2[j - 1] + start_gap_cost + gap_cost, b_gap_dp[j - 1].saturating_add(gap_cost));
            let traceback_idx = i * len + j;

            dp2[j] = a_gap_dp[j];

            if trace_on {
                traceback[traceback_idx] = 1u8;
            }

            if b_gap_dp[j] < dp2[j] {
                dp2[j] = b_gap_dp[j];

                if trace_on {
                    traceback[traceback_idx] = 2u8;
                }
            }

            if sub <= dp2[j] {
                dp2[j] = sub;

                if trace_on {
                    traceback[traceback_idx] = 0u8;
                }
            }

            if allow_transpose && i > 1 && j > 1
                && a_new[j - 1] == b_new[i - 2] && a_new[j - 2] == b_new[i - 1] {
                let transpose = dp0[j - 2] + transpose_cost;

                if transpose <= dp2[j] {
                    dp2[j] = transpose;

                    if trace_on {
                        traceback[traceback_idx] = 3u8;
                    }
                }
            }
        }

        mem::swap(&mut dp0, &mut dp1);
        mem::swap(&mut dp1, &mut dp2);
    }

    if trace_on {
        // estimate an upper bound for the number of Edits
        let mut upper_bound_edits = dp1[a_new_len] / cmp::min(mismatch_cost, gap_cost);

        if allow_transpose {
            upper_bound_edits = cmp::max(upper_bound_edits, (dp1[a_new_len] >> 1) / transpose_cost + 1);
        }

        let mut res: Vec<Edit> = Vec::with_capacity(((upper_bound_edits << 1) + 1) as usize);
        let mut i = b_new_len;
        let mut j = a_new_len;

        while i > 0 || j > 0 {
            let edit = traceback[i * len + j];

            let e = match edit {
                0 => {
                    i -= 1;
                    j -= 1;
                    if a_new[j] == b_new[i] {EditType::Match} else {EditType::Mismatch}
                },
                1 => {
                    i -= 1;
                    if swap {EditType::BGap} else {EditType::AGap}
                },
                2 => {
                    j -= 1;
                    if swap {EditType::AGap} else {EditType::BGap}
                },
                3 => {
                    i -= 2;
                    j -= 2;
                    EditType::Transpose
                },
                _ => unreachable!()
            };

            if res.len() > 0 && res.last().unwrap().edit == e {
                res.last_mut().unwrap().count += 1;
            }else{
                res.push(Edit{edit: e, count: 1});
            }
        }

        res.reverse();
        (dp1[a_new_len], Some(res))
    }else{
        (dp1[a_new_len], None)
    }
}

/// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings, using the
/// naive scalar algorithm.
///
/// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
/// threshold `k`.
/// This should be much faster than `levenshtein_naive` if `k` is small compared to the lengths of
/// `a` and `b`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
/// * `k` - maximum number of edits allowed between `a` and `b`
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_naive_k(b"abc", b"ab", 1);
///
/// assert!(dist.unwrap() == 1);
/// ```
pub fn levenshtein_naive_k(a: &[u8], b: &[u8], k: u32) -> Option<u32> {
    let res = levenshtein_naive_k_with_opts(a, b, k, false, LEVENSHTEIN_COSTS);

    match res {
        Some((edits, _)) => Some(edits),
        None => None
    }
}

/// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings and optionally,
/// the edit traceback, using the naive scalar algorithm, with extra options.
///
/// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
/// threshold `k`.
/// This should be much faster than `levenshtein_naive_with_opts` if `k` is small compared to the lengths of
/// `a` and `b`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
/// * `k` - maximum number of cost allowed between `a` and `b`
/// * `trace_on` - whether to return the traceback, the sequence of edits between `a` and `b`
/// * `costs` - `EditCosts` struct for the cost of each edit operation
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_naive_k_with_opts(b"abc", b"ab", 1, true, LEVENSHTEIN_COSTS);
///
/// assert!(dist.unwrap() == (1, Some(vec![Edit{edit: EditType::Match, count: 2},
///                                        Edit{edit: EditType::BGap, count: 1}])));
/// ```
#[inline]
pub fn levenshtein_naive_k_with_opts<T>(a: &[T], b: &[T], k: u32, trace_on: bool, costs: EditCosts) -> Option<(u32, Option<Vec<Edit>>)>
    where T: PartialEq
{
    let swap = a.len() > b.len(); // swap so that a len <= b len
    let a_new = if swap {b} else {a};
    let a_new_len = a_new.len();
    let b_new = if swap {a} else {b};
    let b_new_len = b_new.len();
    let mismatch_cost = costs.mismatch_cost as u32;
    let gap_cost = costs.gap_cost as u32;
    let start_gap_cost = costs.start_gap_cost as u32;
    let transpose_cost = match costs.transpose_cost {
        Some(cost) => cost as u32,
        None => 0
    };
    let allow_transpose = costs.transpose_cost.is_some();
    // upper bound on the number of edits, in case k is too large
    let max_k = cmp::min((a_new_len as u32) * mismatch_cost,
                         ((a_new_len as u32) << 1) * gap_cost
                         + if a_new_len == 0 {0} else {start_gap_cost
                             + if b_new_len == a_new_len {start_gap_cost} else {0}});
    let max_k = cmp::min(k,
                         max_k + ((b_new_len - a_new_len) as u32) * gap_cost
                         + if b_new_len == a_new_len {0} else {start_gap_cost});
    // farthest we can stray from the main diagonal
    // have to start at least one gap
    let unit_k = (max_k.saturating_sub(start_gap_cost) / gap_cost) as usize;

    if b_new_len - a_new_len > unit_k {
        return None;
    }

    let len = a_new_len + 1;
    let mut lo = 0usize;
    let mut hi = cmp::min(unit_k + 1, b_new_len + 1);
    let mut prev_lo0;
    let mut prev_lo1 = 0; // unused value
    let mut prev_hi;
    let k_len = cmp::min((unit_k << 1) + 1, b_new_len + 1);
    let mut dp0 = vec![0u32; k_len];
    let mut dp1 = vec![0u32; k_len]; // in each iteration, dp0 and dp1 are already calculated
    let mut dp2 = vec![0u32; k_len]; // dp2 the currently calculated row
    let mut a_gap_dp = vec![u32::MAX; k_len];
    let mut b_gap_dp = vec![u32::MAX; k_len];
    let mut traceback = if trace_on {vec![0u8; len * k_len]} else {vec![]};

    for i in 0..(hi - lo) {
        dp1[i] = (i as u32) * gap_cost + if i == 0 {0} else {start_gap_cost};

        if trace_on {
            traceback[0 * k_len + i] = 1u8;
        }
    }

    for i in 1..len {
        // keep track of prev_lo for the offset of previous rows
        prev_lo0 = prev_lo1;
        prev_lo1 = lo;
        prev_hi = hi;
        hi = cmp::min(hi + 1, b_new_len + 1);

        if i > unit_k {
            lo += 1;
        }

        for j in 0..(hi - lo) {
            let idx = lo + j;
            let sub = if idx == 0 {
                u32::MAX
            }else{
                dp1[idx - 1 - prev_lo1] + ((a_new[i - 1] != b_new[idx - 1]) as u32) * mismatch_cost
            };
            a_gap_dp[j] = if j == 0 {
                u32::MAX
            }else{
                cmp::min(dp2[j - 1] + start_gap_cost + gap_cost, a_gap_dp[j - 1].saturating_add(gap_cost))
            };
            b_gap_dp[j] = if idx >= prev_hi {
                u32::MAX
            }else{
                cmp::min(dp1[idx - prev_lo1] + start_gap_cost + gap_cost, b_gap_dp[idx - prev_lo1].saturating_add(gap_cost))
            };

            dp2[j] = sub;

            let traceback_idx = i * k_len + j;

            if trace_on {
                traceback[traceback_idx] = 0u8;
            }

            if a_gap_dp[j] < dp2[j] {
                dp2[j] = a_gap_dp[j];

                if trace_on {
                    traceback[traceback_idx] = 1u8;
                }
            }

            if b_gap_dp[j] < dp2[j] {
                dp2[j] = b_gap_dp[j];

                if trace_on {
                    traceback[traceback_idx] = 2u8;
                }
            }

            if allow_transpose && i > 1 && idx > 1
                && a_new[i - 1] == b_new[idx - 2] && a_new[i - 2] == b_new[idx - 1] {
                let transpose = dp0[idx - prev_lo0 - 2] + transpose_cost;

                if transpose <= dp2[j] {
                    dp2[j] = transpose;

                    if trace_on {
                        traceback[traceback_idx] = 3u8;
                    }
                }
            }
        }

        mem::swap(&mut dp0, &mut dp1);
        mem::swap(&mut dp1, &mut dp2);
    }

    if dp1[hi - lo - 1] > max_k {
        return None;
    }

    if !trace_on {
        return Some((dp1[hi - lo - 1], None));
    }

    // estimate an upper bound for the number of Edits
    let mut upper_bound_edits = dp1[hi - lo - 1] / cmp::min(mismatch_cost, gap_cost);

    if allow_transpose {
        upper_bound_edits = cmp::max(upper_bound_edits, (dp1[hi - lo - 1] >> 1) / transpose_cost + 1);
    }

    let mut res: Vec<Edit> = Vec::with_capacity(((upper_bound_edits << 1) + 1) as usize);
    let mut i = a_new_len;
    let mut j = b_new_len;

    while i > 0 || j > 0 {
        let edit = traceback[i * k_len + (j - (if i > unit_k {i - unit_k} else {0}))];

        let e = match edit {
            0 => {
                i -= 1;
                j -= 1;
                if a_new[i] == b_new[j] {EditType::Match} else {EditType::Mismatch}
            },
            1 => {
                j -= 1;
                if swap {EditType::BGap} else {EditType::AGap}
            },
            2 => {
                i -= 1;
                if swap {EditType::AGap} else {EditType::BGap}
            },
            3 => {
                i -= 2;
                j -= 2;
                EditType::Transpose
            },
            _ => unreachable!()
        };

        if res.len() > 0 && res.last().unwrap().edit == e {
            res.last_mut().unwrap().count += 1;
        }else{
            res.push(Edit{edit: e, count: 1});
        }
    }

    res.reverse();
    Some((dp1[hi - lo - 1], Some(res)))
}

fn translate_str(chars: &mut Vec<char>, s: &str) -> Option<Vec<u8>> {
    s.chars().map(|c| match chars.iter().position(|&d| c == d) {
        Some(i) => Some(i as u8),
        None => {
            let idx = chars.len();
            if idx < 256 {
                chars.push(c);
                Some(idx as u8)
            } else {
                None
            }
        }
    }).collect()
}

/// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two utf8 encoded strings, using
/// SIMD acceleration.
/// # Arguments
/// * `a` - first string (&str)
/// * `b` - second string (&str)
/// * `k` - maximum number of edits allowed between `a` and `b`
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_simd_k_str("abc", "ab", 1);
///
/// assert!(dist.unwrap() == 1);
/// ```
pub fn levenshtein_simd_k_str(a: &str, b: &str, k: u32) -> Option<u32> {
    if a.is_ascii() && b.is_ascii() {
        levenshtein_simd_k(a.as_bytes(), b.as_bytes(), k)
    } else {
        let mut chars = Vec::with_capacity(256);

        let a = translate_str(&mut chars, a)?;
        let b = translate_str(&mut chars, b)?;
        levenshtein_simd_k(&a, &b, k)
    }
}

/// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings, using
/// SIMD acceleration.
///
/// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
/// threshold `k`.
/// This should be much faster than `levenshtein_naive` and `levenshtein_naive_k`.
/// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
/// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
/// `levenshtein_naive_k_with_opts`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
/// * `k` - maximum number of edits allowed between `a` and `b`
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_simd_k(b"abc", b"ab", 1);
///
/// assert!(dist.unwrap() == 1);
/// ```
pub fn levenshtein_simd_k(a: &[u8], b: &[u8], k: u32) -> Option<u32> {
    let res = levenshtein_simd_k_with_opts(a, b, k, false, LEVENSHTEIN_COSTS);

    match res {
        Some((edits, _)) => Some(edits),
        None => None
    }
}

/// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings and optionally,
/// the edit traceback, using SIMD acceleration, with extra options.
///
/// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
/// threshold `k`.
/// This should be much faster than `levenshtein_naive_with_opts` and
/// `levenshtein_naive_k_with_opts`.
/// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
/// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
/// `levenshtein_naive_k_with_opts`.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
/// * `k` - maximum number of cost allowed between `a` and `b`
/// * `trace_on` - whether to return the traceback, the sequence of edits between `a` and `b`
/// * `costs` - `EditCosts` struct for the cost of each edit operation
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let dist = levenshtein_simd_k_with_opts(b"abc", b"ab", 1, true, LEVENSHTEIN_COSTS);
///
/// assert!(dist.unwrap() == (1, Some(vec![Edit{edit: EditType::Match, count: 2},
///                                        Edit{edit: EditType::BGap, count: 1}])));
/// ```
pub fn levenshtein_simd_k_with_opts(a: &[u8], b: &[u8], k: u32, trace_on: bool, costs: EditCosts) -> Option<(u32, Option<Vec<Edit>>)> {
    if a.len() == 0 && b.len() == 0 {
        return if trace_on {Some((0u32, Some(vec![])))} else {Some((0u32, None))};
    }

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        let min_len = cmp::min(a.len(), b.len()) as u32;
        let max_len = cmp::max(a.len(), b.len()) as u32;
        // upper bound on the number of edits, in case k is too large
        let max_k = cmp::min(min_len * (costs.mismatch_cost as u32),
                             (min_len << 1) * (costs.gap_cost as u32)
                             + if min_len == 0 {0} else {costs.start_gap_cost as u32
                                 + if max_len == min_len {costs.start_gap_cost as u32} else {0}});
        let max_k = cmp::min(k,
                             max_k + (max_len - min_len) * (costs.gap_cost as u32)
                             + if max_len == min_len {0} else {costs.start_gap_cost as u32});
        // farthest we can stray from the main diagonal
        // have to start at least one gap
        let unit_k = cmp::min(max_k.saturating_sub(costs.start_gap_cost as u32) / (costs.gap_cost as u32), max_len);

        // note: do not use the MAX value, because it indicates overflow/inaccuracy
        if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
            if cfg!(feature = "jewel-8bit") && unit_k <= (Avx1x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_avx_1x32x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Avx2x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_avx_2x32x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Avx4x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_avx_4x32x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Avx8x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_avx_8x32x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-16bit") && max_k <= ((u16::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_avx_nx16x16(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-32bit") {
                return unsafe {levenshtein_simd_core_avx_nx8x32(a, b, max_k, trace_on, costs)};
            }
        }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
            if cfg!(feature = "jewel-8bit") && unit_k <= (Sse1x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_sse_1x16x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse2x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_sse_2x16x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse4x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_sse_4x16x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse8x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_sse_8x16x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse16x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_sse_16x16x8(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-16bit") && max_k <= ((u16::MAX - 1) as u32) {
                return unsafe {levenshtein_simd_core_sse_nx8x16(a, b, max_k, trace_on, costs)};
            }else if cfg!(feature = "jewel-32bit") {
                return unsafe {levenshtein_simd_core_sse_nx4x32(a, b, max_k, trace_on, costs)};
            }
        }
    }

    levenshtein_naive_k_with_opts(a, b, k, trace_on, costs)
}

macro_rules! create_levenshtein_simd_core {
    ($name:ident, $traceback_name:ident, $jewel:ty, $target:literal) => {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        #[target_feature(enable = $target)]
        unsafe fn $name(a_old: &[u8], b_old: &[u8], k: u32, trace_on: bool, costs: EditCosts) -> Option<(u32, Option<Vec<Edit>>)> {
            #[cfg(feature = "debug")]
            {
                println!("Debug: Levenshtein Jewel vector type {} for target {}.", stringify!($jewel), stringify!($target));
            }

            // swap a and b so that a is shorter than b, if applicable
            // makes operations later on slightly easier, since length of a <= length of b
            let swap = a_old.len() > b_old.len();
            let a = if swap {b_old} else {a_old};
            let a_len = a.len();
            let b = if swap {a_old} else {b_old};
            let b_len = b.len();
            let unit_k = cmp::min((k.saturating_sub(costs.start_gap_cost as u32) / (costs.gap_cost as u32)) as usize, b_len);

            if b_len - a_len > unit_k {
                return None;
            }

            // initialized with max values
            // must use saturated additions afterwards to not overflow
            let mut dp1 = <$jewel>::repeating_max((unit_k + 2) as usize);
            let max_len = dp1.upper_bound();
            let mut dp2 = <$jewel>::repeating_max(max_len);
            let mut dp0 = <$jewel>::repeating_max(max_len);
            let mut dp_temp = <$jewel>::repeating_max(max_len);
            // dp0 -> dp_temp -> dp1 -> dp2 -> current diagonal

            // dp for whether to extend gap or start new gap
            let mut a_gap_dp = <$jewel>::repeating_max(max_len);
            let mut b_gap_dp = <$jewel>::repeating_max(max_len);

            // lengths of the (anti) diagonals
            // assumes max_len is even
            let k1 = max_len - 1;
            let k1_div2 = k1 >> 1;
            let k2 = max_len - 2;
            let k2_div2 = k2 >> 1;

            // set dp[0][0] = 0
            dp1.slow_insert(k1_div2, 0);
            // set dp[0][1] = start_gap_cost + gap_cost and dp[1][0] = start_gap_cost + gap_cost
            dp2.slow_insert(k2_div2 - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32);
            dp2.slow_insert(k2_div2, costs.start_gap_cost as u32 + costs.gap_cost as u32);
            b_gap_dp.slow_insert(k2_div2 - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32);
            a_gap_dp.slow_insert(k2_div2, costs.start_gap_cost as u32 + costs.gap_cost as u32);

            // a_k1_window and a_k2_window represent reversed portions of the string a
            // copy in half of k1/k2 number of characters
            // these characters are placed in the second half of b windows
            // since a windows are reversed, the characters are placed in reverse in the first half of b windows
            let mut a_k1_window = <$jewel>::repeating(0, max_len);
            a_k1_window.slow_loadu(k1_div2 - 1, a.as_ptr(), cmp::min(k1_div2, a_len), true);

            let mut b_k1_window = <$jewel>::repeating(0, max_len);
            b_k1_window.slow_loadu(k1_div2 + 1, b.as_ptr(), cmp::min(k1_div2, b_len), false);

            let mut a_k2_window = <$jewel>::repeating(0, max_len);
            a_k2_window.slow_loadu(k2_div2 - 1, a.as_ptr(), cmp::min(k2_div2, a_len), true);

            let mut b_k2_window = <$jewel>::repeating(0, max_len);
            b_k2_window.slow_loadu(k2_div2, b.as_ptr(), cmp::min(k2_div2, b_len), false);

            // used to keep track of the next characters to place in the windows
            let mut k1_idx = k1_div2 - 1;
            let mut k2_idx = k2_div2 - 1;

            let len_diff = b_len - a_len;
            let len = a_len + b_len + 1;
            let len_div2 = (len >> 1) + (len & 1);
            let ends_with_k2 = len & 1 == 0;
            // every diff between the length of a and b results in a shift from the main diagonal
            let final_idx = {
                if ends_with_k2 { // divisible by 2, ends with k2
                    k2_div2 + ((len_diff - 1) >> 1)
                }else{ // not divisible by 2, ends with k1
                    k1_div2 + (len_diff >> 1)
                }
            };

            // 0 = match/mismatch, 1 = a gap, 2 = b gap, 3 = transpose
            let mut traceback_arr = if trace_on {Vec::with_capacity(len + (len & 1))} else {vec![]};

            if trace_on {
                traceback_arr.push(<$jewel>::repeating(0, max_len));
                traceback_arr.push(<$jewel>::repeating(0, max_len));
                traceback_arr.get_unchecked_mut(1).slow_insert(k2_div2 - 1, 2);
                traceback_arr.get_unchecked_mut(1).slow_insert(k2_div2, 1);
            }

            // reusable constant
            let threes = <$jewel>::repeating(3, max_len);

            // used in calculations
            let mut sub = <$jewel>::repeating(0, max_len);
            let mut match_mask0 = <$jewel>::repeating(0, max_len);
            let mut match_mask1 = <$jewel>::repeating(0, max_len);
            let mut a_gap = <$jewel>::repeating(0, max_len);
            let mut b_gap = <$jewel>::repeating(0, max_len);
            let mut transpose = <$jewel>::repeating(0, max_len);

            let mismatch_cost = <$jewel>::repeating(costs.mismatch_cost as u32, max_len);
            let gap_cost = <$jewel>::repeating(costs.gap_cost as u32, max_len);
            let start_gap_cost = <$jewel>::repeating(costs.start_gap_cost as u32 + costs.gap_cost as u32, max_len);
            let transpose_cost = match costs.transpose_cost {
                Some(cost) => <$jewel>::repeating(cost as u32, max_len),
                None => <$jewel>::repeating(0, max_len) // value does not matter
            };
            let allow_transpose = costs.transpose_cost.is_some();

            // example: allow k = 2 edits for two strings of length 3
            //      -b--   
            // | xx */*
            // a  x /*/*
            // |    */*/ x
            // |     */* xx
            //
            // each (anti) diagonal is represented with '*' or '/'
            // '/', use k2 = 2
            // '*', use k1 = 3
            // 'x' represents cells not in the "traditional" dp array
            // these out of bounds dp cells are shown because they represent
            // a horizontal sliding window of length 5 (2 * k + 1)
            //
            // dp2 is one diagonal before current
            // dp1 is two diagonals before current
            // dp0 is four diagonals before current
            // dp0 is useful for transpositions
            // we are trying to calculate the "current" diagonal
            // note that a k1 '*' dp diagonal has its center cell on the main diagonal
            // in general, the diagonals are centered on the main diagonal
            // each diagonal is represented using a Jewel vector
            // each vector goes from bottom-left to top-right
            //
            // the a windows and b windows are queues of a fixed length
            // a is reversed, so that elementwise comparison can be done between a and b
            // this operation obtains the comparison of characters along the (anti) diagonal
            // if transpositions are allowed, then previous match_masks must be saved to calculate
            // a[i - 1] == b[j] and a[i] == b[j - 1]
            // for speed, transpositions are done by directly blending using the mask, without calculating
            // the minimum cost compared to the other edit operations
            //
            // example of moving the windows:
            // a windows: [5 4 3 2 1] -> [6 5 4 3 2] (right shift + insert)
            // b windows: [1 2 3 4 5] -> [2 3 4 5 6] (left shift + insert)
            //
            // initially:
            // a windows: [2 1 0 0 0]
            // b windows: [0 0 0 1 2]
            //
            // note that there will be left over cells not filled in the Jewel vector
            // this is because k1 and k2 are not long enough
            // all of these empty cells should be at the end of the SIMD vectors
            //
            // each iteration of the loop below results in processing both a k1 diagonal and a k2 diagonal
            // this could be done with an alternating state flag but it is unrolled for less branching
            //
            // note: in traditional dp array
            // dp[i][j] -> dp[i + 1][j] is a gap in string b
            // dp[i][j] -> dp[i][j + 1] is a gap in string a

            for _ in 1..len_div2 {
                // move indexes in strings forward
                k1_idx += 1;
                k2_idx += 1;

                // move windows for the strings a and b
                a_k1_window.shift_right_1_mut();

                if k1_idx < a_len {
                    a_k1_window.insert_first(*a.get_unchecked(k1_idx) as u32);
                }

                b_k1_window.shift_left_1_mut();

                if k1_idx < b_len {
                    b_k1_window.insert_last_1(*b.get_unchecked(k1_idx) as u32); // k1 - 1
                }

                a_k2_window.shift_right_1_mut();

                if k2_idx < a_len {
                    a_k2_window.insert_first(*a.get_unchecked(k2_idx) as u32);
                }

                b_k2_window.shift_left_1_mut();

                if k2_idx < b_len {
                    b_k2_window.insert_last_2(*b.get_unchecked(k2_idx) as u32); // k2 - 1
                }

                // (anti) diagonal that matches in the a and b windows
                <$jewel>::cmpeq(&a_k1_window, &b_k1_window, &mut match_mask1);
                <$jewel>::andnot(&match_mask1, &mismatch_cost, &mut sub);
                sub.adds_mut(&dp1);
                // cost of gaps in a
                // start new gap
                <$jewel>::adds(&dp2, &start_gap_cost, &mut a_gap);
                // continue gap
                a_gap_dp.adds_mut(&gap_cost);
                a_gap_dp.min_mut(&a_gap);
                a_gap_dp.shift_right_1_mut();
                a_gap_dp.insert_first_max();
                // cost of gaps in b
                // start new gap
                <$jewel>::adds(&dp2, &start_gap_cost, &mut b_gap);
                // continue gap
                b_gap_dp.adds_mut(&gap_cost);
                b_gap_dp.min_mut(&b_gap);

                if allow_transpose {
                    <$jewel>::shift_right_1(&match_mask0, &mut transpose); // reuse transpose, zeros shifted in
                    transpose.and_mut(&match_mask0);
                    // make sure that current matching locations are excluded
                    <$jewel>::andnot(&match_mask1, &transpose, &mut match_mask0); // reuse match_mask0 to represent transpose mask
                    <$jewel>::adds(&dp0, &transpose_cost, &mut transpose);
                }

                // min of the cost of all three edit operations
                if trace_on {
                    let mut args = <$jewel>::triple_argmin(&sub, &a_gap_dp, &b_gap_dp, &mut dp0);

                    if allow_transpose {
                        // blend using transpose mask
                        dp0.blendv_mut(&transpose, &match_mask0);
                        args.blendv_mut(&threes, &match_mask0);
                        mem::swap(&mut match_mask0, &mut match_mask1);
                    }

                    traceback_arr.push(args);
                }else{
                    <$jewel>::min(&a_gap_dp, &b_gap_dp, &mut dp0);
                    dp0.min_mut(&sub);

                    if allow_transpose {
                        // blend using transpose mask
                        dp0.blendv_mut(&transpose, &match_mask0);
                        mem::swap(&mut match_mask0, &mut match_mask1);
                    }
                }

                mem::swap(&mut dp0, &mut dp_temp);
                mem::swap(&mut dp_temp, &mut dp1);
                mem::swap(&mut dp1, &mut dp2);

                // (anti) diagonal that matches in the a and b windows
                <$jewel>::cmpeq(&a_k2_window, &b_k2_window, &mut match_mask1);
                <$jewel>::andnot(&match_mask1, &mismatch_cost, &mut sub);
                sub.adds_mut(&dp1);
                // cost of gaps in b
                // start new gap
                <$jewel>::adds(&dp2, &start_gap_cost, &mut b_gap);
                // continue gap
                b_gap_dp.adds_mut(&gap_cost);
                b_gap_dp.min_mut(&b_gap);
                b_gap_dp.shift_left_1_mut();
                b_gap_dp.insert_last_max(); // k1, shift in max value
                // cost of gaps in a
                // start new gap
                <$jewel>::adds(&dp2, &start_gap_cost, &mut a_gap);
                a_gap_dp.adds_mut(&gap_cost);
                // continue gap
                a_gap_dp.min_mut(&a_gap);

                if allow_transpose {
                    <$jewel>::shift_left_1(&match_mask0, &mut transpose); // reuse transpose, zeros shifted in
                    transpose.and_mut(&match_mask0);
                    // make sure that current matching locations are excluded
                    <$jewel>::andnot(&match_mask1, &transpose, &mut match_mask0); // reuse match_mask0 to represent transpose mask
                    <$jewel>::adds(&dp0, &transpose_cost, &mut transpose);
                }

                // min of the cost of all three edit operations
                if trace_on {
                    let mut args = <$jewel>::triple_argmin(&sub, &a_gap_dp, &b_gap_dp, &mut dp0);

                    if allow_transpose {
                        // blend using transpose mask
                        dp0.blendv_mut(&transpose, &match_mask0);
                        args.blendv_mut(&threes, &match_mask0);
                        mem::swap(&mut match_mask0, &mut match_mask1);
                    }

                    traceback_arr.push(args);
                }else{
                    <$jewel>::min(&a_gap_dp, &b_gap_dp, &mut dp0);
                    dp0.min_mut(&sub);

                    if allow_transpose {
                        // blend using transpose mask
                        dp0.blendv_mut(&transpose, &match_mask0);
                        mem::swap(&mut match_mask0, &mut match_mask1);
                    }
                }

                mem::swap(&mut dp0, &mut dp_temp);
                mem::swap(&mut dp_temp, &mut dp1);
                mem::swap(&mut dp1, &mut dp2);
            }

            let final_res = if ends_with_k2 {
                dp2.slow_extract(final_idx)
            }else{
                dp1.slow_extract(final_idx)
            };

            if final_res > k {
                return None;
            }

            if !trace_on {
                return Some((final_res, None));
            }

            // upper bound the number of edit operations, to reduce memory allocations for saving the traceback
            let mut upper_bound_edits = final_res / (cmp::min(costs.mismatch_cost, costs.gap_cost) as u32);

            if let Some(cost) = costs.transpose_cost {
                upper_bound_edits = cmp::max(upper_bound_edits, (final_res >> 1) / (cost as u32) + 1);
            }

            Some((final_res, Some($traceback_name(&traceback_arr, upper_bound_edits as usize, final_idx, a, b, swap, ends_with_k2))))
        }

        unsafe fn $traceback_name(arr: &[$jewel], k: usize, mut idx: usize, a: &[u8], b: &[u8], swap: bool, mut is_k2: bool) -> Vec<Edit> {
            // keep track of position in traditional dp array and strings
            let mut i = a.len(); // index in a
            let mut j = b.len(); // index in b

            // last diagonal may overshoot, so ignore it
            let mut arr_idx = arr.len() - 1 - (if is_k2 {0} else {1});
            let mut res: Vec<Edit> = Vec::with_capacity((k << 1) + 1);

            while arr_idx > 0 {
                // each Jewel vector in arr is only visited once, so extract (which is costly) is fine
                let edit = arr.get_unchecked(arr_idx).slow_extract(idx);

                let e = match edit {
                    0 => { // match/mismatch
                        arr_idx -= 2;
                        i -= 1;
                        j -= 1;
                        if *a.get_unchecked(i) == *b.get_unchecked(j) {EditType::Match} else {EditType::Mismatch}
                    },
                    1 => { // a gap
                        arr_idx -= 1;

                        if !is_k2 {
                            idx -= 1;
                        }

                        j -= 1;
                        is_k2 = !is_k2; // must account for alternating k1/k2 diagonals
                        if swap {EditType::BGap} else {EditType::AGap} // account for the swap in the beginning
                    },
                    2 => { // b gap
                        arr_idx -= 1;

                        if is_k2 {
                            idx += 1;
                        }

                        i -= 1;
                        is_k2 = !is_k2;
                        if swap {EditType::AGap} else {EditType::BGap}
                    },
                    3 => { // transpose
                        arr_idx -= 4;
                        i -= 2;
                        j -= 2;
                        EditType::Transpose
                    },
                    _ => unreachable!()
                };

                if res.len() > 0 && res.last().unwrap().edit == e {
                    res.last_mut().unwrap().count += 1;
                }else{
                    res.push(Edit{edit: e, count: 1});
                }
            }

            res.reverse();
            res
        }
    };
}

// create a version of the functions for each Jewel vector
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_avx_1x32x8, traceback_avx_1x32x8, Avx1x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_avx_2x32x8, traceback_avx_2x32x8, Avx2x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_avx_4x32x8, traceback_avx_4x32x8, Avx4x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_avx_8x32x8, traceback_avx_8x32x8, Avx8x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_avx_nx16x16, traceback_avx_nx16x16, AvxNx16x16, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_avx_nx8x32, traceback_avx_nx8x32, AvxNx8x32, "avx2");

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_1x16x8, traceback_sse_1x16x8, Sse1x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_2x16x8, traceback_sse_2x16x8, Sse2x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_4x16x8, traceback_sse_4x16x8, Sse4x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_8x16x8, traceback_sse_8x16x8, Sse8x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_16x16x8, traceback_sse_16x16x8, Sse16x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_nx8x16, traceback_sse_nx8x16, SseNx8x16, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_simd_core!(levenshtein_simd_core_sse_nx4x32, traceback_sse_nx4x32, SseNx4x32, "sse4.1");

/// Returns the Levenshtein distance between two strings using SIMD acceleration.
///
/// Note that `levenshtein_exp` may be much faster if the number of edits between the two strings
/// is expected to be small.
/// Internally, this will call `levenshtein_simd_k`.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let dist = levenshtein(b"abc", b"ab");
///
/// assert!(dist == 1);
/// ```
pub fn levenshtein(a: &[u8], b: &[u8]) -> u32 {
    levenshtein_simd_k(a, b, u32::MAX).unwrap()
}

/// Returns the restricted Damerau-Levenshtein distance between two strings using SIMD acceleration.
///
/// Note that `rdamerau_exp` may be much faster if the number of edits between the two strings
/// is expected to be small.
/// Internally, this will call `levenshtein_simd_k_with_opts`.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let dist = rdamerau(b"abc", b"acb");
///
/// assert!(dist == 1);
/// ```
pub fn rdamerau(a: &[u8], b: &[u8]) -> u32 {
    levenshtein_simd_k_with_opts(a, b, u32::MAX, false, RDAMERAU_COSTS).unwrap().0
}

/// Returns the Levenshtein distance between two strings using exponential search and SIMD
/// acceleration.
///
/// This may be much more efficient than `levenshtein` if the number of edits between `a` and `b`
/// is expected to be small.
/// Internally, this will call `levenshtein_simd_k` with values of `k` determined through
/// exponential search.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let dist = levenshtein_exp(b"abc", b"ab");
///
/// assert!(dist == 1);
/// ```
pub fn levenshtein_exp(a: &[u8], b: &[u8]) -> u32 {
    let mut k = 30;
    let mut res = levenshtein_simd_k(a, b, k);

    // exponential search
    while res.is_none() {
        k <<= 1;
        res = levenshtein_simd_k(a, b, k);
    }

    // should not panic
    res.unwrap()
}

/// Returns the restricted Damerau-Levenshtein distance between two strings using exponential
/// search and SIMD acceleration.
///
/// This may be much more efficient than `rdamerau` if the number of edits between `a` and `b`
/// is expected to be small.
/// Internally, this will call `levenshtein_simd_k_with_opts` with values of `k` determined through
/// exponential search.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
///
/// # Arguments
/// * `a` - first string (slice)
/// * `b` - second string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let dist = rdamerau_exp(b"abc", b"acb");
///
/// assert!(dist == 1);
/// ```
pub fn rdamerau_exp(a: &[u8], b: &[u8]) -> u32 {
    let mut k = 30;
    let mut res = levenshtein_simd_k_with_opts(a, b, k, false, RDAMERAU_COSTS);

    // exponential search
    while res.is_none() {
        k <<= 1;
        res = levenshtein_simd_k_with_opts(a, b, k, false, RDAMERAU_COSTS);
    }

    // should not panic
    res.unwrap().0
}

/// Returns an iterator over the best `Match`s by searching through the text `haystack` for the
/// pattern `needle` using the naive algorithm.
///
/// The best matches are the matches with the lowest Levenshtein distance.
/// If multiple best matches end at the same position or fully overlap, then the longest match is chosen.
/// If `needle` is empty, then no `Match`es are returned.
/// Each returned `Match` requires at least half or more bytes of the `needle` to match
/// somewhere in the `haystack`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let matches: Vec<Match> = levenshtein_search_naive(b"abc", b"  abd").collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn levenshtein_search_naive<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
    levenshtein_search_naive_with_opts(needle, haystack, ((needle.len() as u32) >> 1) + ((needle.len() as u32) & 1), SearchType::Best, LEVENSHTEIN_COSTS, false)
}

/// Returns an iterator over `Match`s by searching through the text `haystack` for the
/// pattern `needle` using the naive algorithm, with extra options.
///
/// Note that overlapping matches may be returned.
/// If multiple matches end at the same position, then the longest match is chosen.
/// If `needle` is empty and `anchored` is false, then no `Match`es are returned.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
/// * `k` - maximum cost threshold for a match to be returned
/// * `search_type` - indicates whether to return all matches (within a cost of `k`), or the best matches with
/// the lowest cost (additionally, only the longest matches are retained for matches that fully overlap)
/// * `costs` - `EditCosts` struct for the cost of each edit operation
/// * `anchored` - whether the `needle` should be anchored to the start of the `haystack` string,
/// causing any shifts to cost gap edits
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let matches: Vec<Match> = levenshtein_search_naive_with_opts(b"abc", b"  acb", 1, SearchType::All, RDAMERAU_COSTS, false).collect();
///
/// // note: it is possible to end the match at two different positions
/// assert!(matches == vec![Match{start: 2, end: 4, k: 1}, Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn levenshtein_search_naive_with_opts<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType, costs: EditCosts, anchored: bool) -> Box<dyn Iterator<Item = Match> + 'a> {
    let needle_len = needle.len();
    let haystack_len = haystack.len();

    if needle_len == 0 {
        // special case when anchored is true: return possible matches
        if anchored {
            return match search_type {
                SearchType::All => {
                    let mut i = 0;
                    let mut cost = costs.start_gap_cost as u32;
                    let mut start = true;

                    Box::new(iter::from_fn(move || {
                        if start {
                            start = false;
                            return Some(Match{start: 0, end: 0, k: 0});
                        }

                        if i < haystack_len {
                            i += 1;
                            cost += costs.gap_cost as u32;

                            if cost <= k {
                                return Some(Match{start: 0, end: i, k: cost});
                            }
                        }

                        None
                    }))
                },
                SearchType::Best => Box::new(iter::once(Match{start: 0, end: 0, k: 0}))
            };
        }else{
            return Box::new(iter::empty());
        }
    }

    // enforce another constraint on the costs
    costs.check_search();

    let len = needle_len + 1;
    let iter_len = if anchored {
        // start_gap_cost must be incurred at least once
        cmp::min(haystack_len, needle_len.saturating_add(
                (k.saturating_sub(costs.start_gap_cost as u32) as usize) / (costs.gap_cost as usize)))
    }else{
        haystack_len
    };

    let mut dp0 = vec![0u32; len];
    let mut dp1 = vec![0u32; len];
    let mut dp2 = vec![0u32; len];
    let mut needle_gap_dp = vec![u32::MAX; len];
    let mut haystack_gap_dp = vec![u32::MAX; len];
    let mut length0 = vec![0usize; len];
    let mut length1 = vec![0usize; len];
    let mut length2 = vec![0usize; len];
    let mut needle_gap_length = vec![0usize; len];
    let mut haystack_gap_length = vec![0usize; len];
    let mut curr_k = k;
    let mismatch_cost = costs.mismatch_cost as u32;
    let gap_cost = costs.gap_cost as u32;
    let start_gap_cost = costs.start_gap_cost as u32;
    let transpose_cost = match costs.transpose_cost {
        Some(cost) => cost as u32,
        None => 0
    };
    let allow_transpose = costs.transpose_cost.is_some();
    let mut first = true;
    let mut i = 0;

    let res = iter::from_fn(move || {
        if first {
            first = false;

            for j in 0..len {
                dp1[j] = (j as u32) * gap_cost + if j == 0 {0} else {start_gap_cost};
            }

            if dp1[len - 1] <= curr_k {
                if search_type == SearchType::Best {
                    curr_k = dp1[len - 1];
                }

                return Some((Match{start: 0, end: 0, k: dp1[len - 1]}, curr_k));
            }
        }

        while i < iter_len {
            needle_gap_dp[0] = if anchored {(i as u32 + 1) * gap_cost + start_gap_cost} else {0};
            dp2[0] = if anchored {(i as u32 + 1) * gap_cost + start_gap_cost} else {0};
            needle_gap_length[0] = 0;
            length2[0] = 0;

            for j in 1..len {
                let sub = dp1[j - 1] + ((needle[j - 1] != haystack[i]) as u32) * mismatch_cost;

                let new_gap = dp1[j] + start_gap_cost + gap_cost;
                let cont_gap = needle_gap_dp[j].saturating_add(gap_cost);
                if new_gap < cont_gap {
                    needle_gap_dp[j] = new_gap;
                    needle_gap_length[j] = length1[j] + 1;
                }else if new_gap > cont_gap {
                    needle_gap_dp[j] = cont_gap;
                    needle_gap_length[j] += 1;
                }else{
                    needle_gap_dp[j] = cont_gap;
                    needle_gap_length[j] = cmp::max(length1[j], needle_gap_length[j]) + 1;
                }

                let new_gap = dp2[j - 1] + start_gap_cost + gap_cost;
                let cont_gap = haystack_gap_dp[j - 1].saturating_add(gap_cost);
                if new_gap < cont_gap {
                    haystack_gap_dp[j] = new_gap;
                    haystack_gap_length[j] = length2[j - 1];
                }else if new_gap > cont_gap {
                    haystack_gap_dp[j] = cont_gap;
                    haystack_gap_length[j] = haystack_gap_length[j - 1];
                }else{
                    haystack_gap_dp[j] = cont_gap;
                    haystack_gap_length[j] = cmp::max(length2[j - 1], haystack_gap_length[j - 1]);
                }

                dp2[j] = needle_gap_dp[j];
                length2[j] = needle_gap_length[j];

                if (haystack_gap_dp[j] < dp2[j]) || (haystack_gap_dp[j] == dp2[j] && length2[j - 1] > length2[j]) {
                    dp2[j] = haystack_gap_dp[j];
                    length2[j] = haystack_gap_length[j];
                }

                if (sub < dp2[j]) || (sub == dp2[j] && (length1[j - 1] + 1) > length2[j]) {
                    dp2[j] = sub;
                    length2[j] = length1[j - 1] + 1;
                }

                if allow_transpose && i > 0 && j > 1
                    && needle[j - 1] == haystack[i - 1] && needle[j - 2] == haystack[i] {
                        let transpose = dp0[j - 2] + transpose_cost;

                        if transpose <= dp2[j] {
                            dp2[j] = transpose;
                            length2[j] = length0[j - 2] + 2;
                        }
                    }
            }

            let final_res = dp2[len - 1];
            let final_length = length2[len - 1];

            mem::swap(&mut dp0, &mut dp1);
            mem::swap(&mut dp1, &mut dp2);
            mem::swap(&mut length0, &mut length1);
            mem::swap(&mut length1, &mut length2);

            i += 1;

            if final_res <= curr_k {
                match search_type {
                    SearchType::Best => curr_k = final_res,
                    _ => ()
                }

                return Some((Match{start: i - final_length, end: i, k: final_res}, curr_k));
            }
        }

        None
    });

    if search_type == SearchType::Best {
        // estimate the number of Matches
        let mut res_vec = Vec::with_capacity(iter_len / needle_len);

        for m in res {
            match res_vec.len() {
                0 => res_vec.push(m.0),
                _ => {
                    let last = res_vec.last_mut().unwrap();

                    // replace previous if fully overlapping
                    if m.0.start <= last.start {
                        *last = m.0;
                    }else{
                        res_vec.push(m.0);
                    }
                }
            }

            curr_k = m.1;
        }

        return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
    }

    Box::new(res.map(|m| m.0))
}

/// Returns an iterator over the best `Match`s by searching through the text `haystack` for the
/// pattern `needle` using SIMD acceleration.
///
/// The best matches are the matches with the lowest Levenshtein distance.
/// If multiple best matches end at the same position or fully overlap, then the longest match is chosen.
/// If `needle` is empty, then no `Match`es are returned.
/// Each returned `Match` requires at least half or more bytes of the `needle` to match
/// somewhere in the `haystack`.
/// This should be much faster than `levenshtein_search_naive`.
/// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
/// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
/// `levenshtein_search_naive_with_opts`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let matches: Vec<Match> = levenshtein_search_simd(b"abc", b"  abd").collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn levenshtein_search_simd<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
    levenshtein_search_simd_with_opts(needle, haystack, ((needle.len() >> 1) as u32) + ((needle.len() as u32) & 1), SearchType::Best, LEVENSHTEIN_COSTS, false)
}

/// Returns an iterator over `Match`s by searching through the text `haystack` for the
/// pattern `needle` using SIMD acceleration, with extra options.
///
/// Note that overlapping matches may be returned.
/// If multiple matches end at the same position, then the longest match is chosen.
/// If `needle` is empty and `anchored` is false, then no `Match`es are returned.
/// This should be much faster than `levenshtein_search_naive_with_opts`.
/// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
/// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
/// `levenshtein_search_naive_with_opts`.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
/// * `k` - maximum cost threshold for a match to be returned
/// * `search_type` - indicates whether to return all matches (within a cost of `k`), or the best matches with
/// the lowest cost (additionally, only the longest matches are retained for matches that fully overlap)
/// * `costs` - `EditCosts` struct for the cost of each edit operation
/// * `anchored` - whether the `needle` should be anchored to the start of the `haystack` string,
/// causing any shifts to cost gap edits
///
/// # Example
/// ```
/// # use triple_accel::*;
/// # use triple_accel::levenshtein::*;
/// let matches: Vec<Match> = levenshtein_search_simd_with_opts(b"abc", b"  acb", 1, SearchType::All, RDAMERAU_COSTS, false).collect();
///
/// // note: it is possible to end the match at two different positions
/// assert!(matches == vec![Match{start: 2, end: 4, k: 1}, Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn levenshtein_search_simd_with_opts<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType, costs: EditCosts, anchored: bool) -> Box<dyn Iterator<Item = Match> + 'a> {
    if needle.len() == 0 {
        // special case when anchored is true: return possible matches
        if anchored {
            return match search_type {
                SearchType::All => {
                    let mut i = 0;
                    let mut cost = costs.start_gap_cost as u32;
                    let mut start = true;

                    Box::new(iter::from_fn(move || {
                        if start {
                            start = false;
                            return Some(Match{start: 0, end: 0, k: 0});
                        }

                        if i < haystack.len() {
                            i += 1;
                            cost += costs.gap_cost as u32;

                            if cost <= k {
                                return Some(Match{start: 0, end: i, k: cost});
                            }
                        }

                        None
                    }))
                },
                SearchType::Best => Box::new(iter::once(Match{start: 0, end: 0, k: 0}))
            };
        }else{
            return Box::new(iter::empty());
        }
    }

    costs.check_search();

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        let unit_k = k.saturating_sub(costs.start_gap_cost as u32) / (costs.gap_cost as u32);
        // either the length of the match or the number of edits may exceed the maximum
        // available int size; additionally, MAX value is used to indicate overflow
        let upper_bound = cmp::max((needle.len() as u32).saturating_add(unit_k), k.saturating_add(1));

        if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
            if cfg!(feature = "jewel-8bit") && needle.len() <= Avx1x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_avx_1x32x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Avx2x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_avx_2x32x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Avx4x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_avx_4x32x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Avx8x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_avx_8x32x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-16bit") && upper_bound <= u16::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_avx_nx16x16(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-32bit") {
                return unsafe {levenshtein_search_simd_core_avx_nx8x32(needle, haystack, k, search_type, costs, anchored)};
            }
        }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
            if cfg!(feature = "jewel-8bit") && needle.len() <= Sse1x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_sse_1x16x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse2x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_sse_2x16x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse4x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_sse_4x16x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse8x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_sse_8x16x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse16x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_sse_16x16x8(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-16bit") && upper_bound <= u16::MAX as u32 {
                return unsafe {levenshtein_search_simd_core_sse_nx8x16(needle, haystack, k, search_type, costs, anchored)};
            }else if cfg!(feature = "jewel-32bit") {
                return unsafe {levenshtein_search_simd_core_sse_nx4x32(needle, haystack, k, search_type, costs, anchored)};
            }
        }
    }

    levenshtein_search_naive_with_opts(needle, haystack, k, search_type, costs, anchored)
}

macro_rules! create_levenshtein_search_simd_core {
    ($name:ident, $jewel:ty, $target:literal) => {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        #[target_feature(enable = $target)]
        unsafe fn $name<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType, costs: EditCosts, anchored: bool) -> Box<dyn Iterator<Item = Match> + 'a> {
            #[cfg(feature = "debug")]
            {
                println!("Debug: Levenshtein search Jewel vector type {} for target {}.", stringify!($jewel), stringify!($target));
            }

            let needle_len = needle.len();
            let haystack_len = haystack.len();
            let mut dp0 = <$jewel>::repeating_max(needle_len);
            let mut dp_temp = <$jewel>::repeating_max(needle_len);
            let mut dp1 = <$jewel>::repeating_max(needle_len);
            let mut dp2 = <$jewel>::repeating_max(needle_len);
            let mut needle_gap_dp = <$jewel>::repeating_max(needle_len);
            let mut haystack_gap_dp = <$jewel>::repeating_max(needle_len);
            dp2.slow_insert(dp2.upper_bound() - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32); // last cell
            haystack_gap_dp.slow_insert(dp2.upper_bound() - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32);

            // save length instead of start idx due to int size constraints
            let mut length0 = <$jewel>::repeating(0, needle_len);
            let mut length_temp = <$jewel>::repeating(0, needle_len);
            let mut length1 = <$jewel>::repeating(0, needle_len);
            let mut length2 = <$jewel>::repeating(0, needle_len);
            let mut needle_gap_length = <$jewel>::repeating(0, needle_len);
            let mut haystack_gap_length = <$jewel>::repeating(0, needle_len);

            let ones = <$jewel>::repeating(1, needle_len);
            let twos = <$jewel>::repeating(2, needle_len);

            // the suffix of haystack can be ignored if needle must be anchored
            let len = if anchored {
                needle_len + cmp::min(haystack_len, needle_len.saturating_add(
                        (k.saturating_sub(costs.start_gap_cost as u32) as usize) / (costs.gap_cost as usize)))
            }else{
                needle_len + haystack_len
            };

            let final_idx = dp1.upper_bound() - needle_len;

            // load needle characters into needle_window in reversed order
            let mut needle_window = <$jewel>::repeating(0, needle_len);
            needle_window.slow_loadu(needle_window.upper_bound() - 1, needle.as_ptr(), needle_len, true);

            let mut haystack_window = <$jewel>::repeating(0, needle_len);
            let mut haystack_idx = 0usize;
            let mut curr_k = k;

            // used in calculations
            let mut match_mask0 = <$jewel>::repeating(0, needle_len);
            let mut match_mask1 = <$jewel>::repeating(0, needle_len);
            let mut match_mask_cost = <$jewel>::repeating(0, needle_len);
            let mut sub = <$jewel>::repeating(0, needle_len);
            let mut sub_length = <$jewel>::repeating(0, needle_len);
            let mut needle_gap = <$jewel>::repeating(0, needle_len);
            let mut haystack_gap = <$jewel>::repeating(0, needle_len);
            let mut transpose = <$jewel>::repeating(0, needle_len);
            let mut transpose_length = <$jewel>::repeating(0, needle_len);

            let mismatch_cost = <$jewel>::repeating(costs.mismatch_cost as u32, needle_len);
            let gap_cost = <$jewel>::repeating(costs.gap_cost as u32, needle_len);
            let start_gap_cost = <$jewel>::repeating(costs.start_gap_cost as u32, needle_len);
            let transpose_cost = match costs.transpose_cost {
                Some(cost) => <$jewel>::repeating(cost as u32, needle_len),
                None => <$jewel>::repeating(0, needle_len)
            };
            let allow_transpose = costs.transpose_cost.is_some();

            //       ..i...
            //       --h---
            // |     //////xxxx
            // |    x//////xxx
            // n   xx//////xx
            // |  xxx//////x
            // | xxxx//////
            //
            // 'n' = needle, 'h' = haystack
            // each (anti) diagonal is denoted using '/' and 'x'
            // 'x' marks cells that are not in the traditional dp array
            // every (anti) diagonal is calculated simultaneously using Jewel vectors
            // note: each vector goes from bottom-left to top-right, ending at the first row in the
            // DP matrix
            // similar to levenshtein_simd_k, but without alternating anti-diagonals
            // note that the first row, which should be all zeros for searching, is not saved in the
            // Jewel vectors, for space concerns
            // therefore, starting at i = 1 does not include the first diagonal that only contains
            // a zero from the initial row of zeros
            // when left shift are required, then zeros must be shifted in
            // if anchored = true, then the number of gaps times the gap cost plus the starting gap
            // cost must be shifted in
            // for speed, transpositions are done by directly blending using the mask, without calculating
            // the minimum cost compared to the other edit operations

            let mut i = 1;

            let res = iter::from_fn(move || {
                while i < len {
                    // shift the haystack window
                    haystack_window.shift_left_1_mut();

                    if haystack_idx < haystack_len {
                        haystack_window.insert_last_0(*haystack.get_unchecked(haystack_idx) as u32);
                        haystack_idx += 1;
                    }

                    <$jewel>::cmpeq(&needle_window, &haystack_window, &mut match_mask1);
                    <$jewel>::andnot(&match_mask1, &mismatch_cost, &mut match_mask_cost);

                    // match/mismatch
                    <$jewel>::shift_left_1(&dp1, &mut sub);

                    if anchored && i > 1 {
                        // dp1 is 2 diagonals behind the current i
                        // must be capped at k to prevent overflow when inserting
                        sub.insert_last_0(cmp::min((i as u32 - 1) * (costs.gap_cost as u32) + costs.start_gap_cost as u32, k + 1));
                    }

                    sub.adds_mut(&match_mask_cost);

                    <$jewel>::shift_left_1(&length1, &mut sub_length); // zeros are shifted in
                    sub_length.add_mut(&ones);

                    // gap in needle
                    <$jewel>::adds(&dp2, &start_gap_cost, &mut needle_gap);
                    <$jewel>::double_min_length(&needle_gap, &mut needle_gap_dp, &length2, &mut needle_gap_length);
                    needle_gap_dp.adds_mut(&gap_cost);
                    needle_gap_length.add_mut(&ones);

                    // gap in haystack
                    <$jewel>::adds(&dp2, &start_gap_cost, &mut haystack_gap);
                    <$jewel>::double_min_length(&haystack_gap, &mut haystack_gap_dp, &length2, &mut haystack_gap_length);
                    haystack_gap_dp.shift_left_1_mut(); // zeros are shifted in

                    if anchored {
                        // dp2 is one diagonal behind the current i
                        haystack_gap_dp.insert_last_0(cmp::min((i as u32) * (costs.gap_cost as u32) + costs.start_gap_cost as u32, k + 1));
                    }else{
                        haystack_gap_dp.insert_last_0(costs.start_gap_cost as u32);
                    }

                    haystack_gap_dp.adds_mut(&gap_cost);
                    haystack_gap_length.shift_left_1_mut(); // zeros are shifted in

                    if allow_transpose {
                        <$jewel>::shift_left_1(&match_mask0, &mut transpose); // reuse transpose, shift in zeros
                        transpose.and_mut(&match_mask0);
                        // ensure that current matches are excluded
                        <$jewel>::andnot(&match_mask1, &transpose, &mut match_mask0); // reuse match_mask0 to represent transpose mask
                        dp0.shift_left_2_mut();

                        if anchored && i > 3 {
                            // dp0 is four diagonals behind the current i
                            dp0.insert_last_1(cmp::min((i as u32 - 3) * (costs.gap_cost as u32) + costs.start_gap_cost as u32, k + 1));
                        }

                        length0.shift_left_2_mut();
                        <$jewel>::adds(&dp0, &transpose_cost, &mut transpose);
                        <$jewel>::add(&length0, &twos, &mut transpose_length);
                    }

                    <$jewel>::triple_min_length(&sub, &needle_gap_dp, &haystack_gap_dp, &sub_length,
                                                &needle_gap_length, &haystack_gap_length, &mut dp0, &mut length0);

                    if allow_transpose {
                        // blend using transpose mask
                        dp0.blendv_mut(&transpose, &match_mask0);
                        length0.blendv_mut(&transpose_length, &match_mask0);
                        mem::swap(&mut match_mask0, &mut match_mask1);
                    }

                    mem::swap(&mut dp0, &mut dp_temp);
                    mem::swap(&mut dp_temp, &mut dp1);
                    mem::swap(&mut dp1, &mut dp2);
                    mem::swap(&mut length0, &mut length_temp);
                    mem::swap(&mut length_temp, &mut length1);
                    mem::swap(&mut length1, &mut length2);

                    i += 1;

                    if i >= needle_len {
                        let final_res = dp2.slow_extract(final_idx);
                        let final_length = length2.slow_extract(final_idx) as usize;

                        if final_res <= curr_k {
                            let end_idx = i - needle_len;

                            match search_type {
                                // if we want the best, then we can shrink the k threshold
                                SearchType::Best => curr_k = final_res,
                                _ => ()
                            }

                            return Some((Match{start: end_idx - final_length, end: end_idx, k: final_res}, curr_k));
                        }
                    }
                }

                None
            });

            if search_type == SearchType::Best {
                // estimate the number of Matches
                let mut res_vec = Vec::with_capacity((len - needle_len) / needle_len);

                for m in res {
                    match res_vec.len() {
                        0 => res_vec.push(m.0),
                        _ => {
                            let last = res_vec.last_mut().unwrap();

                            // replace previous if fully overlapping
                            if m.0.start <= last.start {
                                *last = m.0;
                            }else{
                                res_vec.push(m.0);
                            }
                        }
                    }

                    curr_k = m.1;
                }

                // only retain matches with the lowest k
                return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
            }

            Box::new(res.map(|m| m.0))
        }
    };
}

// duplicate functions for each Jewel vector type
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_1x32x8, Avx1x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_2x32x8, Avx2x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_4x32x8, Avx4x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_8x32x8, Avx8x32x8, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_nx16x16, AvxNx16x16, "avx2");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_nx8x32, AvxNx8x32, "avx2");

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_1x16x8, Sse1x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_2x16x8, Sse2x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_4x16x8, Sse4x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_8x16x8, Sse8x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_16x16x8, Sse16x16x8, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_nx8x16, SseNx8x16, "sse4.1");
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_nx4x32, SseNx4x32, "sse4.1");

/// Returns an iterator over best `Match`s by searching through the text `haystack` for the
/// pattern `needle` using SIMD acceleration.
///
/// The best matches are the matches with the lowest Levenshtein distance.
/// If multiple best matches end at the same position or fully overlap, then the longest match is chosen.
/// If `needle` is empty, then no `Match`es are returned.
/// Each returned `Match` requires at least half or more bytes of the `needle` to match
/// somewhere in the `haystack`.
/// Internally, this will call `levenshtein_search_simd`.
/// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
///
/// # Arguments
/// * `needle` - pattern string (slice)
/// * `haystack` - text string (slice)
///
/// # Example
/// ```
/// # use triple_accel::*;
/// let matches: Vec<Match> = levenshtein_search(b"abc", b"  abd").collect();
///
/// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
/// ```
pub fn levenshtein_search<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
    levenshtein_search_simd(needle, haystack)
}