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+ 
125use  crc32fast:: Hasher ; 
226use  std:: os:: raw:: c_char; 
327use  std:: slice; 
428
29+ /// Opaque type for C for use in FFI 
530#[ repr( C ) ]  
631pub  struct  HasherHandle ( * mut  Hasher ) ; 
732
33+ /// Creates a new Hasher to compute CRC32 checksums 
834#[ no_mangle]  
935pub  extern  "C"  fn  hasher_new ( )  -> * mut  HasherHandle  { 
1036    let  hasher = Box :: new ( Hasher :: new ( ) ) ; 
1137    let  handle = Box :: new ( HasherHandle ( Box :: into_raw ( hasher) ) ) ; 
1238    Box :: into_raw ( handle) 
1339} 
1440
41+ /// Writes data to the Hasher 
42+ /// 
1543/// # Safety 
1644/// 
1745/// Uses unsafe method calls 
@@ -26,6 +54,8 @@ pub unsafe extern "C" fn hasher_write(handle: *mut HasherHandle, data: *const c_
2654    hasher. update ( bytes) ; 
2755} 
2856
57+ /// Calculates the CRC32 checksum for data that's been written to the Hasher 
58+ /// 
2959/// # Safety 
3060/// 
3161/// Uses unsafe method calls 
@@ -40,6 +70,7 @@ pub unsafe extern "C" fn hasher_finalize(handle: *mut HasherHandle) -> u32 {
4070    hasher. finalize ( ) 
4171} 
4272
73+ /// Helper method to just calculate a CRC32 checksum directly for a string 
4374#[ no_mangle]  
4475pub  extern  "C"  fn  crc32_hash ( data :  * const  c_char ,  len :  usize )  -> u32  { 
4576    if  data. is_null ( )  { 
0 commit comments