1
+ // Copyright 2024 Don MacAskill. Licensed under MIT.
2
+
3
+ //! `crc32fast-lib`
4
+ //! ===============
5
+ //!
6
+ //! Fast, SIMD-accelerated
7
+ //! [CRC-32/ISO-HDLC](https://reveng.sourceforge.io/crc-catalogue/all.htm#crc.cat.crc-32-iso-hdlc)
8
+ //! (aka `crc32`) checksum computation in Rust exposed as a C-compatible shared library.
9
+ //!
10
+ //! Results in a dramatic performance improvement. For example, when
11
+ //! [using it via FFI in PHP](https://github.com/awesomized/crc-fast-php), it's >10X faster than
12
+ //! PHP's native [crc32](https://www.php.net/crc32) implementation.
13
+ //!
14
+ //! ## Usage
15
+ //!
16
+ //! ### PHP example
17
+ //!
18
+ //! ```php
19
+ //! $hasher = $ffi->hasher_new();
20
+ //! $ffi->hasher_write($hasher, 'hello world!', 12);
21
+ //! $checksum = $ffi->hasher_finalize($hasher); // 0x03b4c26d
22
+ //! ```
23
+ //!
24
+
1
25
use crc32fast:: Hasher ;
2
26
use std:: os:: raw:: c_char;
3
27
use std:: slice;
4
28
29
+ /// Opaque type for C for use in FFI
5
30
#[ repr( C ) ]
6
31
pub struct HasherHandle ( * mut Hasher ) ;
7
32
33
+ /// Creates a new Hasher to compute CRC32 checksums
8
34
#[ no_mangle]
9
35
pub extern "C" fn hasher_new ( ) -> * mut HasherHandle {
10
36
let hasher = Box :: new ( Hasher :: new ( ) ) ;
11
37
let handle = Box :: new ( HasherHandle ( Box :: into_raw ( hasher) ) ) ;
12
38
Box :: into_raw ( handle)
13
39
}
14
40
41
+ /// Writes data to the Hasher
42
+ ///
15
43
/// # Safety
16
44
///
17
45
/// Uses unsafe method calls
@@ -26,6 +54,8 @@ pub unsafe extern "C" fn hasher_write(handle: *mut HasherHandle, data: *const c_
26
54
hasher. update ( bytes) ;
27
55
}
28
56
57
+ /// Calculates the CRC32 checksum for data that's been written to the Hasher
58
+ ///
29
59
/// # Safety
30
60
///
31
61
/// Uses unsafe method calls
@@ -40,6 +70,7 @@ pub unsafe extern "C" fn hasher_finalize(handle: *mut HasherHandle) -> u32 {
40
70
hasher. finalize ( )
41
71
}
42
72
73
+ /// Helper method to just calculate a CRC32 checksum directly for a string
43
74
#[ no_mangle]
44
75
pub extern "C" fn crc32_hash ( data : * const c_char , len : usize ) -> u32 {
45
76
if data. is_null ( ) {
0 commit comments