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
#![no_std]
//! Minimal safe wrapper around zstd-sys.
//!
//! This crates provides a minimal translation of the [zstd-sys] methods.
//! For a more comfortable high-level library, see the [zstd] crate.
//!
//! [zstd-sys]: http://crates.io/crates/zstd-sys
//! [zstd]: https://crates.io/crates/zstd
//!
//! Most of the functions here map 1-for-1 to a function from
//! [the C zstd library][zstd-c] mentionned in their descriptions.
//! Check the [source documentation][doc] for more information on their
//! behaviour.
//!
//! [doc]: http://facebook.github.io/zstd/zstd_manual.html
//! [zstd-c]: https://facebook.github.io/zstd/
//!
//! Features denoted as experimental in the C library are hidden behind an
//! `experimental` feature.

extern crate libc;
extern crate zstd_sys;

#[cfg(feature = "std")]
extern crate std;

#[cfg(test)]
mod tests;

/// How to compress data.
pub use zstd_sys::ZSTD_strategy as Strategy;

/// Reset directive.
pub use zstd_sys::ZSTD_ResetDirective as ResetDirective;

#[cfg(feature = "std")]
use std::os::raw::{c_char, c_int, c_ulonglong, c_void};

#[cfg(not(feature = "std"))]
use libc::{c_char, c_int, c_ulonglong, c_void};

use core::marker::PhantomData;
use core::ops::Deref;
use core::ops::DerefMut;
use core::str;

// Re-define constants from zstd_sys
pub const VERSION_MAJOR: u32 = zstd_sys::ZSTD_VERSION_MAJOR;
pub const VERSION_MINOR: u32 = zstd_sys::ZSTD_VERSION_MINOR;
pub const VERSION_RELEASE: u32 = zstd_sys::ZSTD_VERSION_RELEASE;
pub const VERSION_NUMBER: u32 = zstd_sys::ZSTD_VERSION_NUMBER;

/// Default compression level.
pub const CLEVEL_DEFAULT: CompressionLevel =
    zstd_sys::ZSTD_CLEVEL_DEFAULT as CompressionLevel;
pub const CONTENTSIZE_UNKNOWN: u64 = zstd_sys::ZSTD_CONTENTSIZE_UNKNOWN as u64;
pub const CONTENTSIZE_ERROR: u64 = zstd_sys::ZSTD_CONTENTSIZE_ERROR as u64;
pub const MAGICNUMBER: u32 = zstd_sys::ZSTD_MAGICNUMBER;
pub const MAGIC_DICTIONARY: u32 = zstd_sys::ZSTD_MAGIC_DICTIONARY;
pub const MAGIC_SKIPPABLE_START: u32 = zstd_sys::ZSTD_MAGIC_SKIPPABLE_START;
pub const BLOCKSIZELOG_MAX: u32 = zstd_sys::ZSTD_BLOCKSIZELOG_MAX;
pub const BLOCKSIZE_MAX: u32 = zstd_sys::ZSTD_BLOCKSIZE_MAX;
#[cfg(feature = "experimental")]
pub const WINDOWLOG_MAX_32: u32 = zstd_sys::ZSTD_WINDOWLOG_MAX_32;
#[cfg(feature = "experimental")]
pub const WINDOWLOG_MAX_64: u32 = zstd_sys::ZSTD_WINDOWLOG_MAX_64;
#[cfg(feature = "experimental")]
pub const WINDOWLOG_MIN: u32 = zstd_sys::ZSTD_WINDOWLOG_MIN;
#[cfg(feature = "experimental")]
pub const HASHLOG_MIN: u32 = zstd_sys::ZSTD_HASHLOG_MIN;
#[cfg(feature = "experimental")]
pub const CHAINLOG_MAX_32: u32 = zstd_sys::ZSTD_CHAINLOG_MAX_32;
#[cfg(feature = "experimental")]
pub const CHAINLOG_MAX_64: u32 = zstd_sys::ZSTD_CHAINLOG_MAX_64;
#[cfg(feature = "experimental")]
pub const CHAINLOG_MIN: u32 = zstd_sys::ZSTD_CHAINLOG_MIN;
#[cfg(feature = "experimental")]
pub const HASHLOG3_MAX: u32 = zstd_sys::ZSTD_HASHLOG3_MAX;
#[cfg(feature = "experimental")]
pub const SEARCHLOG_MIN: u32 = zstd_sys::ZSTD_SEARCHLOG_MIN;
#[cfg(feature = "experimental")]
pub const TARGETLENGTH_MAX: u32 = zstd_sys::ZSTD_TARGETLENGTH_MAX;
#[cfg(feature = "experimental")]
pub const TARGETLENGTH_MIN: u32 = zstd_sys::ZSTD_TARGETLENGTH_MIN;
#[cfg(feature = "experimental")]
pub const LDM_MINMATCH_MAX: u32 = zstd_sys::ZSTD_LDM_MINMATCH_MAX;
#[cfg(feature = "experimental")]
pub const LDM_MINMATCH_MIN: u32 = zstd_sys::ZSTD_LDM_MINMATCH_MIN;
#[cfg(feature = "experimental")]
pub const LDM_BUCKETSIZELOG_MAX: u32 = zstd_sys::ZSTD_LDM_BUCKETSIZELOG_MAX;

/// Represents the compression level used by zstd.
pub type CompressionLevel = i32;

/// Represents a possible error from the zstd library.
pub type ErrorCode = usize;

/// Wrapper result around most zstd functions.
///
/// Either a success code (usually number of bytes written), or an error code.
pub type SafeResult = Result<usize, ErrorCode>;

/// Returns true if code represents error.
fn is_error(code: usize) -> bool {
    unsafe { zstd_sys::ZSTD_isError(code) != 0 }
}

/// Parse the result code
///
/// Returns the number of bytes written if the code represents success,
/// or the error message code otherwise.
fn parse_code(code: usize) -> SafeResult {
    if !is_error(code) {
        Ok(code)
    } else {
        Err(code)
    }
}

fn ptr_void(src: &[u8]) -> *const c_void {
    src.as_ptr() as *const c_void
}

fn ptr_mut_void(dst: &mut [u8]) -> *mut c_void {
    dst.as_mut_ptr() as *mut c_void
}

pub fn version_number() -> u32 {
    unsafe { zstd_sys::ZSTD_versionNumber() as u32 }
}

pub fn version_string() -> &'static str {
    unsafe { c_char_to_str(zstd_sys::ZSTD_versionString()) }
}

/// Returns the minimum (fastest) compression level supported.
pub fn min_c_level() -> CompressionLevel {
    unsafe { zstd_sys::ZSTD_minCLevel() as CompressionLevel }
}

/// Returns the maximum (slowest) compression level supported.
pub fn max_c_level() -> CompressionLevel {
    unsafe { zstd_sys::ZSTD_maxCLevel() as CompressionLevel }
}

/// Wraps the `ZSTD_compress` function.
pub fn compress(
    dst: &mut [u8],
    src: &[u8],
    compression_level: CompressionLevel,
) -> SafeResult {
    let code = unsafe {
        zstd_sys::ZSTD_compress(
            ptr_mut_void(dst),
            dst.len(),
            ptr_void(src),
            src.len(),
            compression_level,
        )
    };
    parse_code(code)
}

/// Wraps the `ZSTD_decompress` function.
pub fn decompress(dst: &mut [u8], src: &[u8]) -> SafeResult {
    let code = unsafe {
        zstd_sys::ZSTD_decompress(
            ptr_mut_void(dst),
            dst.len(),
            ptr_void(src),
            src.len(),
        )
    };
    parse_code(code)
}

/// Wraps the `ZSTD_getDecompressedSize` function.
#[deprecated(note = "Use ZSTD_getFrameContentSize instead")]
pub fn get_decompressed_size(src: &[u8]) -> u64 {
    unsafe {
        zstd_sys::ZSTD_getDecompressedSize(ptr_void(src), src.len()) as u64
    }
}

/// maximum compressed size in worst case single-pass scenario
pub fn compress_bound(src_size: usize) -> usize {
    unsafe { zstd_sys::ZSTD_compressBound(src_size) }
}

pub struct CCtx<'a>(*mut zstd_sys::ZSTD_CCtx, PhantomData<&'a ()>);

impl<'a> Default for CCtx<'a> {
    fn default() -> Self {
        create_cctx()
    }
}

impl CCtx<'static> {
    /// Wrap `ZSTD_createCCtx`
    pub fn create() -> Self {
        CCtx(unsafe { zstd_sys::ZSTD_createCCtx() }, PhantomData)
    }
}

impl<'a> CCtx<'a> {
    /// Wraps the `ZSTD_compressCCtx()` function
    pub fn compress(
        &mut self,
        dst: &mut [u8],
        src: &[u8],
        compression_level: CompressionLevel,
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_compressCCtx(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
                compression_level,
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_compress2()` function.
    pub fn compress2(&mut self, dst: &mut [u8], src: &[u8]) -> SafeResult {
        parse_code(unsafe {
            zstd_sys::ZSTD_compress2(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
            )
        })
    }

    /// Wraps the `ZSTD_compress_usingDict()` function.
    pub fn compress_using_dict(
        &mut self,
        dst: &mut [u8],
        src: &[u8],
        dict: &[u8],
        compression_level: CompressionLevel,
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_compress_usingDict(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
                ptr_void(dict),
                dict.len(),
                compression_level,
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_compress_usingCDict()` function.
    pub fn compress_using_cdict(
        &mut self,
        dst: &mut [u8],
        src: &[u8],
        cdict: &CDict,
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_compress_usingCDict(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
                cdict.0,
            )
        };
        parse_code(code)
    }

    pub fn init(&mut self, compression_level: CompressionLevel) -> usize {
        unsafe { zstd_sys::ZSTD_initCStream(self.0, compression_level) }
    }

    /// Wraps the `ZSTD_initCStream_srcSize()` function.
    #[cfg(feature = "experimental")]
    #[deprecated]
    pub fn init_src_size(
        &mut self,
        compression_level: CompressionLevel,
        pledged_src_size: u64,
    ) -> usize {
        unsafe {
            zstd_sys::ZSTD_initCStream_srcSize(
                self.0,
                compression_level as c_int,
                pledged_src_size as c_ulonglong,
            )
        }
    }

    /// Wraps the `ZSTD_initCStream_usingDict()` function.
    #[cfg(feature = "experimental")]
    #[deprecated]
    pub fn init_using_dict(
        &mut self,
        dict: &[u8],
        compression_level: CompressionLevel,
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_initCStream_usingDict(
                self.0,
                ptr_void(dict),
                dict.len(),
                compression_level,
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_initCStream_usingCDict()` function.
    #[cfg(feature = "experimental")]
    #[deprecated]
    pub fn init_using_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
    where
        'b: 'a, // Dictionary outlives the stream.
    {
        let code =
            unsafe { zstd_sys::ZSTD_initCStream_usingCDict(self.0, cdict.0) };
        parse_code(code)
    }

    pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
        parse_code(unsafe {
            zstd_sys::ZSTD_CCtx_loadDictionary(
                self.0,
                ptr_void(dict),
                dict.len(),
            )
        })
    }

    /// Wraps the `ZSTD_CCtx_refCDict()` function.
    ///
    /// Dictionary must outlive the context.
    pub fn ref_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
    where
        'b: 'a,
    {
        parse_code(unsafe { zstd_sys::ZSTD_CCtx_refCDict(self.0, cdict.0) })
    }

    pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
    where
        'b: 'a,
    {
        parse_code(unsafe {
            zstd_sys::ZSTD_CCtx_refPrefix(
                self.0,
                ptr_void(prefix),
                prefix.len(),
            )
        })
    }

    pub fn compress_stream(
        &mut self,
        output: &mut OutBuffer,
        input: &mut InBuffer,
    ) -> SafeResult {
        let mut output = output.wrap();
        let mut input = input.wrap();
        let code = unsafe {
            zstd_sys::ZSTD_compressStream(
                self.0,
                ptr_mut(&mut output),
                ptr_mut(&mut input),
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_compressStream2()` function.
    pub fn compress_stream2(
        &mut self,
        output: &mut OutBuffer,
        input: &mut InBuffer,
        end_op: zstd_sys::ZSTD_EndDirective,
    ) -> SafeResult {
        let mut output = output.wrap();
        let mut input = input.wrap();
        parse_code(unsafe {
            zstd_sys::ZSTD_compressStream2(
                self.0,
                ptr_mut(&mut output),
                ptr_mut(&mut input),
                end_op,
            )
        })
    }

    /// Wraps the `ZSTD_flushStream()` function.
    pub fn flush_stream(&mut self, output: &mut OutBuffer) -> SafeResult {
        let mut output = output.wrap();
        let code = unsafe {
            zstd_sys::ZSTD_flushStream(self.0, ptr_mut(&mut output))
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_endStream()` function.
    pub fn end_stream(&mut self, output: &mut OutBuffer) -> SafeResult {
        let mut output = output.wrap();
        let code =
            unsafe { zstd_sys::ZSTD_endStream(self.0, ptr_mut(&mut output)) };
        parse_code(code)
    }

    pub fn sizeof(&self) -> usize {
        unsafe { zstd_sys::ZSTD_sizeof_CCtx(self.0) }
    }

    pub fn reset(&mut self, reset: ResetDirective) -> SafeResult {
        parse_code(unsafe { zstd_sys::ZSTD_CCtx_reset(self.0, reset) })
    }

    #[cfg(feature = "experimental")]
    #[deprecated]
    pub fn reset_cstream(&mut self, pledged_src_size: u64) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_resetCStream(
                self.0,
                pledged_src_size as c_ulonglong,
            )
        };
        parse_code(code)
    }

    pub fn set_parameter(&mut self, param: CParameter) -> SafeResult {
        // TODO: Until bindgen properly generates a binding for this, we'll need to do it here.
        #[cfg(feature = "experimental")]
        use zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam2 as ZSTD_c_format;
        #[cfg(feature = "experimental")]
        use zstd_sys::ZSTD_format_e;

        use zstd_sys::ZSTD_cParameter::*;
        use CParameter::*;

        let (param, value) = match param {
            #[cfg(feature = "experimental")]
            Format(FrameFormat::One) => {
                (ZSTD_c_format, ZSTD_format_e::ZSTD_f_zstd1 as c_int)
            }
            #[cfg(feature = "experimental")]
            Format(FrameFormat::Magicless) => (
                ZSTD_c_format,
                ZSTD_format_e::ZSTD_f_zstd1_magicless as c_int,
            ),
            CompressionLevel(level) => (ZSTD_c_compressionLevel, level),
            WindowLog(value) => (ZSTD_c_windowLog, value as c_int),
            HashLog(value) => (ZSTD_c_hashLog, value as c_int),
            ChainLog(value) => (ZSTD_c_chainLog, value as c_int),
            SearchLog(value) => (ZSTD_c_searchLog, value as c_int),
            MinMatch(value) => (ZSTD_c_minMatch, value as c_int),
            TargetLength(value) => (ZSTD_c_targetLength, value as c_int),
            Strategy(strategy) => (ZSTD_c_strategy, strategy as c_int),
            EnableLongDistanceMatching(flag) => {
                (ZSTD_c_enableLongDistanceMatching, flag as c_int)
            }
            LdmHashLog(value) => (ZSTD_c_ldmHashLog, value as c_int),
            LdmMinMatch(value) => (ZSTD_c_ldmMinMatch, value as c_int),
            LdmBucketSizeLog(value) => {
                (ZSTD_c_ldmBucketSizeLog, value as c_int)
            }
            LdmHashRateLog(value) => (ZSTD_c_ldmHashRateLog, value as c_int),
            ContentSizeFlag(flag) => (ZSTD_c_contentSizeFlag, flag as c_int),
            ChecksumFlag(flag) => (ZSTD_c_checksumFlag, flag as c_int),
            DictIdFlag(flag) => (ZSTD_c_dictIDFlag, flag as c_int),

            NbWorkers(value) => (ZSTD_c_nbWorkers, value as c_int),

            JobSize(value) => (ZSTD_c_jobSize, value as c_int),

            OverlapSizeLog(value) => (ZSTD_c_overlapLog, value as c_int),
        };

        parse_code(unsafe {
            zstd_sys::ZSTD_CCtx_setParameter(self.0, param, value)
        })
    }

    pub fn set_pledged_src_size(
        &mut self,
        pledged_src_size: u64,
    ) -> SafeResult {
        parse_code(unsafe {
            zstd_sys::ZSTD_CCtx_setPledgedSrcSize(
                self.0,
                pledged_src_size as c_ulonglong,
            )
        })
    }

    /// Wraps the `ZSTD_getBlockSize()` function.
    #[cfg(feature = "experimental")]
    pub fn get_block_size(&self) -> usize {
        unsafe { zstd_sys::ZSTD_getBlockSize(self.0) }
    }

    /// Wraps the `ZSTD_compressBlock()` function.
    #[cfg(feature = "experimental")]
    pub fn compress_block(
        &mut self,
        dst: &mut [u8],
        src: &[u8],
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_compressBlock(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
            )
        };
        parse_code(code)
    }
}

pub fn create_cctx<'a>() -> CCtx<'a> {
    CCtx::create()
}

impl<'a> Drop for CCtx<'a> {
    fn drop(&mut self) {
        unsafe {
            zstd_sys::ZSTD_freeCCtx(self.0);
        }
    }
}

unsafe impl<'a> Send for CCtx<'a> {}
// CCtx can't be shared across threads, so it does not implement Sync.

unsafe fn c_char_to_str(text: *const c_char) -> &'static str {
    #[cfg(not(feature = "std"))]
    {
        // To be safe, we need to compute right now its length
        let len = libc::strlen(text);

        // Cast it to a slice
        let slice = core::slice::from_raw_parts(text as *mut u8, len);
        // And hope it's still text.
        str::from_utf8(slice).expect("bad error message from zstd")
    }

    #[cfg(feature = "std")]
    {
        std::ffi::CStr::from_ptr(text)
            .to_str()
            .expect("bad error message from zstd")
    }
}

pub fn get_error_name(code: usize) -> &'static str {
    unsafe {
        let name = zstd_sys::ZSTD_getErrorName(code);
        c_char_to_str(name)
    }
}

/// Wraps the `ZSTD_compressCCtx()` function
pub fn compress_cctx(
    ctx: &mut CCtx,
    dst: &mut [u8],
    src: &[u8],
    compression_level: CompressionLevel,
) -> SafeResult {
    ctx.compress(dst, src, compression_level)
}

/// Wraps the `ZSTD_compress2()` function.
pub fn compress2(ctx: &mut CCtx, dst: &mut [u8], src: &[u8]) -> SafeResult {
    ctx.compress2(dst, src)
}

/// A Decompression Context.
///
/// The lifetime references the potential dictionary used for this context.
///
/// If no dictionary was used, it will most likely be `'static`.
///
/// Same as `DStream`.
pub struct DCtx<'a>(*mut zstd_sys::ZSTD_DCtx, PhantomData<&'a ()>);

impl Default for DCtx<'_> {
    fn default() -> Self {
        create_dctx()
    }
}

impl DCtx<'static> {
    pub fn create() -> Self {
        DCtx(unsafe { zstd_sys::ZSTD_createDCtx() }, PhantomData)
    }
}

impl<'a> DCtx<'a> {
    /// Wraps the `ZSTD_decompressDCtx()` function.
    pub fn decompress(&mut self, dst: &mut [u8], src: &[u8]) -> SafeResult {
        parse_code(unsafe {
            zstd_sys::ZSTD_decompressDCtx(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
            )
        })
    }

    pub fn decompress_using_dict(
        &mut self,
        dst: &mut [u8],
        src: &[u8],
        dict: &[u8],
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_decompress_usingDict(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
                ptr_void(dict),
                dict.len(),
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_decompress_usingDDict()` function.
    pub fn decompress_using_ddict(
        &mut self,
        dst: &mut [u8],
        src: &[u8],
        ddict: &DDict,
    ) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_decompress_usingDDict(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
                ddict.0,
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_initCStream()` function.
    ///
    /// Initializes an existing `DStream` for decompression.
    pub fn init(&mut self) -> usize {
        unsafe { zstd_sys::ZSTD_initDStream(self.0) }
    }

    /// Wraps the `ZSTD_initDStream_usingDict()` function.
    #[cfg(feature = "experimental")]
    #[deprecated]
    pub fn init_using_dict(&mut self, dict: &[u8]) -> SafeResult {
        let code = unsafe {
            zstd_sys::ZSTD_initDStream_usingDict(
                self.0,
                ptr_void(dict),
                dict.len(),
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_initDStream_usingDDict()` function.
    #[cfg(feature = "experimental")]
    #[deprecated]
    pub fn init_using_ddict<'b>(&mut self, ddict: &DDict<'b>) -> SafeResult
    where
        'b: 'a,
    {
        let code =
            unsafe { zstd_sys::ZSTD_initDStream_usingDDict(self.0, ddict.0) };
        parse_code(code)
    }

    /// Wraps the `ZSTD_resetDStream()` function.
    #[cfg(feature = "experimental")]
    pub fn reset(&mut self) -> SafeResult {
        let code = unsafe { zstd_sys::ZSTD_resetDStream(self.0) };
        parse_code(code)
    }

    pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
        parse_code(unsafe {
            zstd_sys::ZSTD_DCtx_loadDictionary(
                self.0,
                ptr_void(dict),
                dict.len(),
            )
        })
    }

    pub fn ref_ddict<'b>(&mut self, ddict: &DDict<'b>) -> SafeResult
    where
        'b: 'a,
    {
        parse_code(unsafe { zstd_sys::ZSTD_DCtx_refDDict(self.0, ddict.0) })
    }

    pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
    where
        'b: 'a,
    {
        parse_code(unsafe {
            zstd_sys::ZSTD_DCtx_refPrefix(
                self.0,
                ptr_void(prefix),
                prefix.len(),
            )
        })
    }

    pub fn set_parameter(&mut self, param: DParameter) -> SafeResult {
        #[cfg(feature = "experimental")]
        use zstd_sys::ZSTD_dParameter::ZSTD_d_experimentalParam1 as ZSTD_d_format;
        #[cfg(feature = "experimental")]
        use zstd_sys::ZSTD_format_e;

        use zstd_sys::ZSTD_dParameter::*;
        use DParameter::*;

        let (param, value) = match param {
            #[cfg(feature = "experimental")]
            Format(FrameFormat::One) => {
                (ZSTD_d_format, ZSTD_format_e::ZSTD_f_zstd1 as c_int)
            }
            #[cfg(feature = "experimental")]
            Format(FrameFormat::Magicless) => (
                ZSTD_d_format,
                ZSTD_format_e::ZSTD_f_zstd1_magicless as c_int,
            ),

            WindowLogMax(value) => (ZSTD_d_windowLogMax, value as c_int),
        };

        parse_code(unsafe {
            zstd_sys::ZSTD_DCtx_setParameter(self.0, param, value)
        })
    }

    /// Wraps the `ZSTD_decompressStream()` function.
    pub fn decompress_stream(
        &mut self,
        output: &mut OutBuffer,
        input: &mut InBuffer,
    ) -> SafeResult {
        let mut output = output.wrap();
        let mut input = input.wrap();
        let code = unsafe {
            zstd_sys::ZSTD_decompressStream(
                self.0,
                ptr_mut(&mut output),
                ptr_mut(&mut input),
            )
        };
        parse_code(code)
    }

    /// Wraps the `ZSTD_DStreamInSize()` function.
    ///
    /// Returns a hint for the recommended size of the input buffer for decompression.
    pub fn in_size() -> usize {
        unsafe { zstd_sys::ZSTD_DStreamInSize() }
    }

    /// Wraps the `ZSTD_DStreamOutSize()` function.
    ///
    /// Returns a hint for the recommended size of the output buffer for decompression.
    pub fn out_size() -> usize {
        unsafe { zstd_sys::ZSTD_DStreamOutSize() }
    }

    /// Wraps the `ZSTD_sizeof_DCtx()` function.
    pub fn sizeof(&self) -> usize {
        unsafe { zstd_sys::ZSTD_sizeof_DCtx(self.0) }
    }

    /// Wraps the `ZSTD_decompressBlock()` function.
    #[cfg(feature = "experimental")]
    pub fn decompress_block(&mut self, dst: &mut [u8], src: &[u8]) -> usize {
        unsafe {
            zstd_sys::ZSTD_decompressBlock(
                self.0,
                ptr_mut_void(dst),
                dst.len(),
                ptr_void(src),
                src.len(),
            )
        }
    }

    /// Wraps the `ZSTD_insertBlock()` function.
    #[cfg(feature = "experimental")]
    pub fn insert_block(&mut self, block: &[u8]) -> usize {
        unsafe {
            zstd_sys::ZSTD_insertBlock(self.0, ptr_void(block), block.len())
        }
    }
}

/// Prepares a new decompression context without dictionary.
pub fn create_dctx() -> DCtx<'static> {
    DCtx::create()
}

impl Drop for DCtx<'_> {
    fn drop(&mut self) {
        unsafe {
            zstd_sys::ZSTD_freeDCtx(self.0);
        }
    }
}

unsafe impl Send for DCtx<'_> {}
// DCtx can't be shared across threads, so it does not implement Sync.

/// Wraps the `ZSTD_decompressDCtx()` function.
pub fn decompress_dctx(
    ctx: &mut DCtx,
    dst: &mut [u8],
    src: &[u8],
) -> SafeResult {
    ctx.decompress(dst, src)
}

/// Wraps the `ZSTD_compress_usingDict()` function.
pub fn compress_using_dict(
    ctx: &mut CCtx,
    dst: &mut [u8],
    src: &[u8],
    dict: &[u8],
    compression_level: CompressionLevel,
) -> SafeResult {
    ctx.compress_using_dict(dst, src, dict, compression_level)
}

/// Wraps the `ZSTD_decompress_usingDict()` function.
pub fn decompress_using_dict(
    dctx: &mut DCtx,
    dst: &mut [u8],
    src: &[u8],
    dict: &[u8],
) -> SafeResult {
    dctx.decompress_using_dict(dst, src, dict)
}

/// Compression dictionary.
pub struct CDict<'a>(*mut zstd_sys::ZSTD_CDict, PhantomData<&'a ()>);

impl CDict<'static> {
    pub fn create(
        dict_buffer: &[u8],
        compression_level: CompressionLevel,
    ) -> Self {
        CDict(
            unsafe {
                zstd_sys::ZSTD_createCDict(
                    ptr_void(dict_buffer),
                    dict_buffer.len(),
                    compression_level,
                )
            },
            PhantomData,
        )
    }
}

impl<'a> CDict<'a> {
    #[cfg(feature = "experimental")]
    pub fn create_by_reference(
        dict_buffer: &'a [u8],
        compression_level: CompressionLevel,
    ) -> Self {
        CDict(
            unsafe {
                zstd_sys::ZSTD_createCDict_byReference(
                    ptr_void(dict_buffer),
                    dict_buffer.len(),
                    compression_level,
                )
            },
            PhantomData,
        )
    }
    pub fn sizeof(&self) -> usize {
        unsafe { zstd_sys::ZSTD_sizeof_CDict(self.0) }
    }
}

/// Wraps the `ZSTD_createCDict()` function.
pub fn create_cdict(
    dict_buffer: &[u8],
    compression_level: CompressionLevel,
) -> CDict<'static> {
    CDict::create(dict_buffer, compression_level)
}

impl<'a> Drop for CDict<'a> {
    fn drop(&mut self) {
        unsafe {
            zstd_sys::ZSTD_freeCDict(self.0);
        }
    }
}

unsafe impl<'a> Send for CDict<'a> {}
unsafe impl<'a> Sync for CDict<'a> {}

/// Wraps the `ZSTD_compress_usingCDict()` function.
pub fn compress_using_cdict(
    cctx: &mut CCtx,
    dst: &mut [u8],
    src: &[u8],
    cdict: &CDict,
) -> SafeResult {
    cctx.compress_using_cdict(dst, src, cdict)
}

pub struct DDict<'a>(*mut zstd_sys::ZSTD_DDict, PhantomData<&'a ()>);

impl DDict<'static> {
    pub fn create(dict_buffer: &[u8]) -> Self {
        DDict(
            unsafe {
                zstd_sys::ZSTD_createDDict(
                    ptr_void(dict_buffer),
                    dict_buffer.len(),
                )
            },
            PhantomData,
        )
    }
}

impl<'a> DDict<'a> {
    pub fn sizeof(&self) -> usize {
        unsafe { zstd_sys::ZSTD_sizeof_DDict(self.0) }
    }

    /// Wraps the `ZSTD_createDDict_byReference()` function.
    ///
    /// The dictionary will keep referencing `dict_buffer`.
    #[cfg(feature = "experimental")]
    pub fn create_by_reference(dict_buffer: &'a [u8]) -> Self {
        DDict(
            unsafe {
                zstd_sys::ZSTD_createDDict_byReference(
                    ptr_void(dict_buffer),
                    dict_buffer.len(),
                )
            },
            PhantomData,
        )
    }

    pub fn get_dict_id(&self) -> u32 {
        unsafe { zstd_sys::ZSTD_getDictID_fromDDict(self.0) as u32 }
    }
}

/// Wraps the `ZSTD_createDDict()` function.
///
/// It copies the dictionary internally, so the resulting `DDict` is `'static`.
pub fn create_ddict(dict_buffer: &[u8]) -> DDict<'static> {
    DDict::create(dict_buffer)
}

impl<'a> Drop for DDict<'a> {
    fn drop(&mut self) {
        unsafe {
            zstd_sys::ZSTD_freeDDict(self.0);
        }
    }
}

unsafe impl<'a> Send for DDict<'a> {}
unsafe impl<'a> Sync for DDict<'a> {}

/// Wraps the `ZSTD_decompress_usingDDict()` function.
pub fn decompress_using_ddict(
    dctx: &mut DCtx,
    dst: &mut [u8],
    src: &[u8],
    ddict: &DDict,
) -> SafeResult {
    dctx.decompress_using_ddict(dst, src, ddict)
}

/// Compression stream.
///
/// Same as `CCtx`.
pub type CStream<'a> = CCtx<'a>;

// CStream can't be shared across threads, so it does not implement Sync.

/// Allocates a new `CStream`.
pub fn create_cstream<'a>() -> CStream<'a> {
    CCtx(unsafe { zstd_sys::ZSTD_createCStream() }, PhantomData)
}

/// Prepares an existing `CStream` for compression at the given level.
pub fn init_cstream(
    zcs: &mut CStream,
    compression_level: CompressionLevel,
) -> usize {
    zcs.init(compression_level)
}

#[derive(Debug)]
/// Wrapper around an input buffer.
///
/// Bytes will be read starting at `src[pos]`.
///
/// `pos` will be updated after reading.
pub struct InBuffer<'a> {
    pub src: &'a [u8],
    pub pos: usize,
}

#[derive(Debug)]
/// Wrapper around an output buffer.
///
/// Bytes will be written starting at `dst[pos]`.
///
/// `pos` will be updated after writing.
pub struct OutBuffer<'a> {
    pub dst: &'a mut [u8],
    pub pos: usize,
}

/// Convenience method to get a mut pointer from a mut ref.
fn ptr_mut<B>(ptr_void: &mut B) -> *mut B {
    ptr_void as *mut B
}

/// Interface between a C-level ZSTD_outBuffer and a rust-level `OutBuffer`.
///
/// Will update the parent buffer from the C buffer on drop.
struct OutBufferWrapper<'a, 'b: 'a> {
    buf: zstd_sys::ZSTD_outBuffer,
    parent: &'a mut OutBuffer<'b>,
}

impl<'a, 'b: 'a> Deref for OutBufferWrapper<'a, 'b> {
    type Target = zstd_sys::ZSTD_outBuffer;

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

impl<'a, 'b: 'a> DerefMut for OutBufferWrapper<'a, 'b> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.buf
    }
}

impl<'a> OutBuffer<'a> {
    /// Returns a new `OutBuffer` around the given slice.
    ///
    /// Starts with `pos = 0`.
    pub fn around(dst: &'a mut [u8]) -> Self {
        OutBuffer { dst, pos: 0 }
    }

    fn wrap<'b>(&'b mut self) -> OutBufferWrapper<'b, 'a> {
        OutBufferWrapper {
            buf: zstd_sys::ZSTD_outBuffer {
                dst: ptr_mut_void(self.dst),
                size: self.dst.len(),
                pos: self.pos,
            },
            parent: self,
        }
    }

    /// Returns the part of this buffer that was written to.
    pub fn as_slice<'b>(&'b self) -> &'a [u8]
    where
        'b: 'a,
    {
        let pos = self.pos;
        &self.dst[..pos]
    }
}

impl<'a, 'b> Drop for OutBufferWrapper<'a, 'b> {
    fn drop(&mut self) {
        self.parent.pos = self.buf.pos;
    }
}

struct InBufferWrapper<'a, 'b: 'a> {
    buf: zstd_sys::ZSTD_inBuffer,
    parent: &'a mut InBuffer<'b>,
}

impl<'a, 'b: 'a> Deref for InBufferWrapper<'a, 'b> {
    type Target = zstd_sys::ZSTD_inBuffer;

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

impl<'a, 'b: 'a> DerefMut for InBufferWrapper<'a, 'b> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.buf
    }
}

impl<'a> InBuffer<'a> {
    /// Returns a new `InBuffer` around the given slice.
    ///
    /// Starts with `pos = 0`.
    pub fn around(src: &'a [u8]) -> Self {
        InBuffer { src, pos: 0 }
    }

    fn wrap<'b>(&'b mut self) -> InBufferWrapper<'b, 'a> {
        InBufferWrapper {
            buf: zstd_sys::ZSTD_inBuffer {
                src: ptr_void(self.src),
                size: self.src.len(),
                pos: self.pos,
            },
            parent: self,
        }
    }
}

impl<'a, 'b> Drop for InBufferWrapper<'a, 'b> {
    fn drop(&mut self) {
        self.parent.pos = self.buf.pos;
    }
}

/// Wraps the `ZSTD_compressStream()` function.
pub fn compress_stream(
    zcs: &mut CStream,
    output: &mut OutBuffer,
    input: &mut InBuffer,
) -> SafeResult {
    zcs.compress_stream(output, input)
}

pub fn compress_stream2(
    cctx: &mut CCtx,
    output: &mut OutBuffer,
    input: &mut InBuffer,
    end_op: zstd_sys::ZSTD_EndDirective,
) -> SafeResult {
    cctx.compress_stream2(output, input, end_op)
}

/// Wraps the `ZSTD_flushStream()` function.
pub fn flush_stream(zcs: &mut CStream, output: &mut OutBuffer) -> SafeResult {
    zcs.flush_stream(output)
}

/// Wraps the `ZSTD_endStream()` function.
pub fn end_stream(zcs: &mut CStream, output: &mut OutBuffer) -> SafeResult {
    zcs.end_stream(output)
}

/// Wraps `ZSTD_CStreamInSize()`
pub fn cstream_in_size() -> usize {
    unsafe { zstd_sys::ZSTD_CStreamInSize() }
}

/// Wraps `ZSTD_CStreamOutSize()`
pub fn cstream_out_size() -> usize {
    unsafe { zstd_sys::ZSTD_CStreamOutSize() }
}

/// A Decompression stream.
///
/// Same as `DCtx`.
pub type DStream<'a> = DCtx<'a>;

pub fn create_dstream() -> DStream<'static> {
    DStream::create()
}

/// Wraps the `ZSTD_initCStream()` function.
///
/// Initializes an existing `DStream` for decompression.
pub fn init_dstream(zds: &mut DStream) -> usize {
    zds.init()
}

/// Wraps the `ZSTD_decompressStream()` function.
pub fn decompress_stream(
    zds: &mut DStream,
    output: &mut OutBuffer,
    input: &mut InBuffer,
) -> SafeResult {
    zds.decompress_stream(output, input)
}

/// Wraps the `ZSTD_DStreamInSize()` function.
///
/// Returns a hint for the recommended size of the input buffer for decompression.
pub fn dstream_in_size() -> usize {
    DStream::in_size()
}

/// Wraps the `ZSTD_DStreamOutSize()` function.
///
/// Returns a hint for the recommended size of the output buffer for decompression.
pub fn dstream_out_size() -> usize {
    DStream::out_size()
}

/// Wraps the `ZSTD_findFrameCompressedSize()` function.
///
/// `src` should contain at least an entire frame.
pub fn find_frame_compressed_size(src: &[u8]) -> SafeResult {
    let code = unsafe {
        zstd_sys::ZSTD_findFrameCompressedSize(ptr_void(src), src.len())
    };
    parse_code(code)
}

/// Wraps the `ZSTD_getFrameContentSize()` function.
///
/// `src` should contain at least a frame header.
pub fn get_frame_content_size(src: &[u8]) -> u64 {
    unsafe { zstd_sys::ZSTD_getFrameContentSize(ptr_void(src), src.len()) }
}

/// Wraps the `ZSTD_findDecompressedSize()` function.
///
/// `src` should be exactly a sequence of ZSTD frames.
#[cfg(feature = "experimental")]
pub fn find_decompressed_size(src: &[u8]) -> u64 {
    unsafe { zstd_sys::ZSTD_findDecompressedSize(ptr_void(src), src.len()) }
}

/// Wraps the `ZSTD_sizeofCCtx()` function.
pub fn sizeof_cctx(cctx: &CCtx) -> usize {
    cctx.sizeof()
}

/// Wraps the `ZSTD_sizeof_DCtx()` function.
pub fn sizeof_dctx(dctx: &DCtx) -> usize {
    dctx.sizeof()
}

/// Wraps the `ZSTD_sizeof_CStream()` function.
pub fn sizeof_cstream(zcs: &CStream) -> usize {
    zcs.sizeof()
}

/// Wraps the `ZSTD_sizeof_DStream()` function.
pub fn sizeof_dstream(zds: &DStream) -> usize {
    zds.sizeof()
}

/// Wraps the `ZSTD_sizeof_CDict()` function.
pub fn sizeof_cdict(cdict: &CDict) -> usize {
    cdict.sizeof()
}

/// Wraps the `ZSTD_sizeof_DDict()` function.
pub fn sizeof_ddict(ddict: &DDict) -> usize {
    ddict.sizeof()
}

/// Wraps the `ZSTD_createCDict_byReference()` function.
///
/// The dictionary will keep referencing `dict_buffer`.
#[cfg(feature = "experimental")]
pub fn create_cdict_by_reference<'a>(
    dict_buffer: &'a [u8],
    compression_level: CompressionLevel,
) -> CDict<'a> {
    CDict::create_by_reference(dict_buffer, compression_level)
}

/// Wraps the `ZSTD_isFrame()` function.
#[cfg(feature = "experimental")]
pub fn is_frame(buffer: &[u8]) -> u32 {
    unsafe { zstd_sys::ZSTD_isFrame(ptr_void(buffer), buffer.len()) as u32 }
}

/// Wraps the `ZSTD_createDDict_byReference()` function.
///
/// The dictionary will keep referencing `dict_buffer`.
#[cfg(feature = "experimental")]
pub fn create_ddict_by_reference(dict_buffer: &[u8]) -> DDict {
    DDict::create_by_reference(dict_buffer)
}

/// Wraps the `ZSTD_getDictID_fromDict()` function.
pub fn get_dict_id_from_dict(dict: &[u8]) -> u32 {
    unsafe {
        zstd_sys::ZSTD_getDictID_fromDict(ptr_void(dict), dict.len()) as u32
    }
}

/// Wraps the `ZSTD_getDictID_fromDDict()` function.
pub fn get_dict_id_from_ddict(ddict: &DDict) -> u32 {
    ddict.get_dict_id()
}

/// Wraps the `ZSTD_getDictID_fromFrame()` function.
pub fn get_dict_id_from_frame(src: &[u8]) -> u32 {
    unsafe {
        zstd_sys::ZSTD_getDictID_fromFrame(ptr_void(src), src.len()) as u32
    }
}

/// Wraps the `ZSTD_initCStream_srcSize()` function.
#[cfg(feacctxture = "experimental")]
#[deprecated]
#[allow(deprecated)]
pub fn init_cstream_src_size(
    zcs: &mut CStream,
    compression_level: CompressionLevel,
    pledged_src_size: u64,
) -> usize {
    zcs.init_src_size(compression_level, pledged_src_size)
}

/// Wraps the `ZSTD_initCStream_usingDict()` function.
#[cfg(feature = "experimental")]
#[deprecated]
#[allow(deprecated)]
pub fn init_cstream_using_dict(
    zcs: &mut CStream,
    dict: &[u8],
    compression_level: CompressionLevel,
) -> SafeResult {
    zcs.init_using_dict(dict, compression_level)
}

/// Wraps the `ZSTD_initCStream_usingCDict()` function.
#[cfg(feature = "experimental")]
#[deprecated]
#[allow(deprecated)]
pub fn init_cstream_using_cdict<'a, 'b>(
    zcs: &mut CStream<'a>,
    cdict: &CDict<'b>,
) -> SafeResult
where
    'b: 'a, // Dictionary outlives the stream.
{
    zcs.init_using_cdict(cdict)
}

/// Wraps the `ZSTD_CCtx_loadDictionary()` function.
pub fn cctx_load_dictionary(cctx: &mut CCtx, dict: &[u8]) -> SafeResult {
    cctx.load_dictionary(dict)
}

/// Wraps the `ZSTD_CCtx_refCDict()` function.
///
/// Dictionary must outlive the context.
pub fn cctx_ref_cdict<'a, 'b>(
    cctx: &mut CCtx<'a>,
    cdict: &CDict<'b>,
) -> SafeResult
where
    'b: 'a,
{
    cctx.ref_cdict(cdict)
}

/// Wraps the `ZSTD_CCtx_refPrefix()` function.
///
/// Dictionary must outlive the prefix.
pub fn cctx_ref_prefix<'a, 'b>(
    cctx: &mut CCtx<'a>,
    prefix: &'b [u8],
) -> SafeResult
where
    'b: 'a,
{
    cctx.ref_prefix(prefix)
}

/// Wraps the `ZSTD_DCtx_loadDictionary()` function.
pub fn dctx_load_dictionary(dctx: &mut DCtx<'_>, dict: &[u8]) -> SafeResult {
    dctx.load_dictionary(dict)
}

/// Wraps the `ZSTD_DCtx_refDDict()` function.
pub fn dctx_ref_ddict<'a, 'b>(
    dctx: &mut DCtx<'a>,
    ddict: &'b DDict<'b>,
) -> SafeResult
where
    'b: 'a,
{
    dctx.ref_ddict(ddict)
}

/// Wraps the `ZSTD_DCtx_refPrefix()` function.
pub fn dctx_ref_prefix<'a, 'b>(
    dctx: &mut DCtx<'a>,
    prefix: &'b [u8],
) -> SafeResult
where
    'b: 'a,
{
    dctx.ref_prefix(prefix)
}

/// Wraps the `ZSTD_CCtx_reset()` function.
pub fn cctx_reset(cctx: &mut CCtx, reset: ResetDirective) -> SafeResult {
    cctx.reset(reset)
}

/// Wraps the `ZSTD_DCtx_reset()` function.
pub fn dctx_reset(dctx: &mut DCtx, reset: ResetDirective) -> SafeResult {
    parse_code(unsafe { zstd_sys::ZSTD_DCtx_reset(dctx.0, reset) })
}

/// Wraps the `ZSTD_resetCStream()` function.
#[cfg(feature = "experimental")]
#[deprecated]
#[allow(deprecated)]
pub fn reset_cstream(zcs: &mut CStream, pledged_src_size: u64) -> SafeResult {
    zcs.reset_cstream(pledged_src_size)
}

/// Wraps the `ZSTD_initDStream_usingDict()` function.
#[cfg(feature = "experimental")]
#[deprecated]
#[allow(deprecated)]
pub fn init_dstream_using_dict(zds: &mut DStream, dict: &[u8]) -> SafeResult {
    zds.init_using_dict(dict)
}

/// Wraps the `ZSTD_initDStream_usingDDict()` function.
#[cfg(feature = "experimental")]
#[deprecated]
#[allow(deprecated)]
pub fn init_dstream_using_ddict<'a, 'b>(
    zds: &mut DStream<'a>,
    ddict: &DDict<'b>,
) -> SafeResult
where
    'b: 'a,
{
    zds.init_using_ddict(ddict)
}

/// Wraps the `ZSTD_resetDStream()` function.
#[cfg(feature = "experimental")]
pub fn reset_dstream(zds: &mut DStream) -> SafeResult {
    zds.reset()
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum FrameFormat {
    /// Regular zstd format.
    One,

    /// Skip the 4 bytes identifying the content as zstd-compressed data.
    Magicless,
}

/// A compression parameter.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CParameter {
    #[cfg(feature = "experimental")]
    Format(FrameFormat),

    CompressionLevel(CompressionLevel),

    WindowLog(u32),

    HashLog(u32),

    ChainLog(u32),

    SearchLog(u32),

    MinMatch(u32),

    TargetLength(u32),

    Strategy(Strategy),

    EnableLongDistanceMatching(bool),

    LdmHashLog(u32),

    LdmMinMatch(u32),

    LdmBucketSizeLog(u32),

    LdmHashRateLog(u32),

    ContentSizeFlag(bool),

    ChecksumFlag(bool),

    DictIdFlag(bool),

    NbWorkers(u32),

    JobSize(u32),

    OverlapSizeLog(u32),
}

/// A decompression parameter.
pub enum DParameter {
    WindowLogMax(u32),

    /// See `FrameFormat`.
    #[cfg(feature = "experimental")]
    Format(FrameFormat),
}

/// Wraps the `ZSTD_DCtx_setParameter()` function.
pub fn dctx_set_parameter(dctx: &mut DCtx, param: DParameter) -> SafeResult {
    dctx.set_parameter(param)
}

/// Wraps the `ZSTD_CCtx_setParameter()` function.
pub fn cctx_set_parameter(cctx: &mut CCtx, param: CParameter) -> SafeResult {
    cctx.set_parameter(param)
}

/// Wraps the `ZSTD_CCtx_setPledgedSrcSize()` function.
pub fn cctx_set_pledged_src_size(
    cctx: &mut CCtx,
    pledged_src_size: u64,
) -> SafeResult {
    cctx.set_pledged_src_size(pledged_src_size)
}

/// Wraps thge `ZDICT_trainFromBuffer()` function.
pub fn train_from_buffer(
    dict_buffer: &mut [u8],
    samples_buffer: &[u8],
    samples_sizes: &[usize],
) -> SafeResult {
    assert_eq!(samples_buffer.len(), samples_sizes.iter().sum());
    parse_code(unsafe {
        zstd_sys::ZDICT_trainFromBuffer(
            ptr_mut_void(dict_buffer),
            dict_buffer.len(),
            ptr_void(samples_buffer),
            samples_sizes.as_ptr(),
            samples_sizes.len() as u32,
        )
    })
}

/// Wraps the `ZSTD_getDictID_fromDict()` function.
pub fn get_dict_id(dict_buffer: &[u8]) -> Option<u32> {
    let id = unsafe {
        zstd_sys::ZDICT_getDictID(ptr_void(dict_buffer), dict_buffer.len())
    };
    if id > 0 {
        Some(id)
    } else {
        None
    }
}

/// Wraps the `ZSTD_getBlockSize()` function.
#[cfg(feature = "experimental")]
pub fn get_block_size(cctx: &CCtx) -> usize {
    unsafe { zstd_sys::ZSTD_getBlockSize(cctx.0) }
}

/// Wraps the `ZSTD_compressBlock()` function.
#[cfg(feature = "experimental")]
pub fn compress_block(
    cctx: &mut CCtx,
    dst: &mut [u8],
    src: &[u8],
) -> SafeResult {
    cctx.compress_block(dst, src)
}

/// Wraps the `ZSTD_decompressBlock()` function.
#[cfg(feature = "experimental")]
pub fn decompress_block(dctx: &mut DCtx, dst: &mut [u8], src: &[u8]) -> usize {
    dctx.decompress_block(dst, src)
}

/// Wraps the `ZSTD_insertBlock()` function.
#[cfg(feature = "experimental")]
pub fn insert_block(dctx: &mut DCtx, block: &[u8]) -> usize {
    dctx.insert_block(block)
}