zipora 3.1.3

High-performance Rust implementation providing advanced data structures and compression algorithms with memory safety guarantees. Features LRU page cache, sophisticated caching layer, fiber-based concurrency, real-time compression, secure memory pools, SIMD optimizations, and complete C FFI for migration from C++.
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
//! Main C API interface
//!
//! This module provides the primary C-compatible interface for the zipora library,
//! allowing seamless integration with existing C/C++ codebases.

use super::{CResult, types::*};
use crate::blob_store::traits::BlobStore;
use std::cell::RefCell;
#[cfg(test)]
use std::ffi::CStr;
use std::ffi::CString;
use std::os::raw::{c_char, c_int, c_void};
use std::ptr;
use std::sync::Mutex;

// Thread-local storage for error messages
thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = RefCell::new(None);
}

// Global error callback storage
static ERROR_CALLBACK: Mutex<Option<unsafe extern "C" fn(*const c_char)>> = Mutex::new(None);

/// Set the last error message for the current thread
fn set_last_error(msg: &str) {
    LAST_ERROR.with(|error| {
        if let Ok(cstring) = CString::new(msg) {
            // Store a clone for thread-local storage
            *error.borrow_mut() = Some(cstring.clone());

            // Also call the error callback if one is set
            if let Ok(callback_guard) = ERROR_CALLBACK.lock() {
                if let Some(callback) = *callback_guard {
                    // SAFETY: callback function pointer is valid (set via zipora_set_error_callback), called with valid CString pointer
                    unsafe {
                        callback(cstring.as_ptr());
                    }
                }
            }
        }
    });
}

/// Clear the last error message for the current thread (for testing)
#[cfg(test)]
fn clear_last_error() {
    LAST_ERROR.with(|error| {
        *error.borrow_mut() = None;
    });
}

/// Convert CResult to error message
#[allow(dead_code)]
fn cresult_to_error_msg(result: CResult) -> &'static str {
    match result {
        CResult::Success => "Success",
        CResult::InvalidInput => "Invalid input parameter",
        CResult::MemoryError => "Memory allocation error",
        CResult::IoError => "I/O operation failed",
        CResult::InternalError => "Internal library error",
        CResult::UnsupportedOperation => "Unsupported operation",
        CResult::NotFound => "Resource not found",
    }
}

/// Initialize the zipora library
///
/// # Safety
///
/// This function is safe to call multiple times.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zipora_init() -> CResult {
    crate::init();
    CResult::Success
}

/// Get library version string
///
/// # Safety
///
/// The returned string is valid until the next call to this function.
/// The caller should not free the returned pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zipora_version() -> *const c_char {
    use std::sync::OnceLock;
    static VERSION_CSTRING: OnceLock<CString> = OnceLock::new();

    let cstring = VERSION_CSTRING.get_or_init(|| {
        CString::new(crate::VERSION).unwrap_or_else(|_| CString::new("unknown").expect("static string has no NUL bytes"))
    });

    cstring.as_ptr()
}

/// Check if SIMD optimizations are available
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zipora_has_simd() -> c_int {
    if crate::has_simd_support() { 1 } else { 0 }
}

/// Create a new FastVec instance
///
/// # Safety
///
/// The returned pointer must be freed with `fast_vec_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fast_vec_new() -> *mut CFastVec {
    let fast_vec = Box::new(crate::FastVec::<u8>::new());
    Box::into_raw(fast_vec) as *mut CFastVec
}

/// Free a FastVec instance
///
/// # Safety
///
/// The pointer must be a valid CFastVec pointer returned from `fast_vec_new`.
/// The pointer becomes invalid after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fast_vec_free(vec: *mut CFastVec) {
    if !vec.is_null() {
        // SAFETY: pointer is valid (null-checked), created by fast_vec_new via Box::into_raw, not previously freed
        let _vec = unsafe { Box::from_raw(vec as *mut crate::FastVec<u8>) };
        // Automatic cleanup when Box is dropped
    }
}

/// Push a byte to a FastVec
///
/// # Safety
///
/// The vec pointer must be a valid CFastVec pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fast_vec_push(vec: *mut CFastVec, value: u8) -> CResult {
    if vec.is_null() {
        set_last_error("FastVec pointer is null");
        return CResult::InvalidInput;
    }

    // SAFETY: pointer is valid (null-checked at line 132), points to initialized FastVec created by fast_vec_new
    let fast_vec = unsafe { &mut *(vec as *mut crate::FastVec<u8>) };
    match fast_vec.push(value) {
        Ok(_) => CResult::Success,
        Err(e) => {
            set_last_error(&format!("Failed to push to FastVec: {}", e));
            CResult::MemoryError
        }
    }
}

/// Get the length of a FastVec
///
/// # Safety
///
/// The vec pointer must be a valid CFastVec pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fast_vec_len(vec: *const CFastVec) -> usize {
    if vec.is_null() {
        return 0;
    }

    // SAFETY: pointer is valid (null-checked at line 154), points to initialized FastVec
    let fast_vec = unsafe { &*(vec as *const crate::FastVec<u8>) };
    fast_vec.len()
}

/// Get a pointer to the FastVec's data
///
/// # Safety
///
/// The vec pointer must be a valid CFastVec pointer.
/// The returned pointer is valid until the FastVec is modified or freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fast_vec_data(vec: *const CFastVec) -> *const u8 {
    if vec.is_null() {
        return ptr::null();
    }

    // SAFETY: pointer is valid (null-checked at line 170), points to initialized FastVec
    let fast_vec = unsafe { &*(vec as *const crate::FastVec<u8>) };
    fast_vec.as_ptr()
}

/// Create a memory pool
///
/// # Safety
///
/// The returned pointer must be freed with `memory_pool_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn memory_pool_new(chunk_size: usize, max_chunks: usize) -> *mut CMemoryPool {
    let config = crate::memory::PoolConfig::new(chunk_size, max_chunks, 8);
    match crate::memory::MemoryPool::new(config) {
        Ok(pool) => Box::into_raw(Box::new(pool)) as *mut CMemoryPool,
        Err(_) => ptr::null_mut(),
    }
}

/// Free a memory pool
///
/// # Safety
///
/// The pointer must be a valid CMemoryPool pointer returned from `memory_pool_new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn memory_pool_free(pool: *mut CMemoryPool) {
    if !pool.is_null() {
        // SAFETY: pointer is valid (null-checked), created by memory_pool_new via Box::into_raw, not previously freed
        let _pool = unsafe { Box::from_raw(pool as *mut crate::memory::MemoryPool) };
        // Automatic cleanup when Box is dropped
    }
}

/// Allocate memory from a pool
///
/// # Safety
///
/// The pool pointer must be a valid CMemoryPool pointer.
/// The returned pointer must be freed with `memory_pool_deallocate`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn memory_pool_allocate(pool: *mut CMemoryPool) -> *mut c_void {
    if pool.is_null() {
        return ptr::null_mut();
    }

    // SAFETY: pointer is valid (null-checked at line 213), points to initialized MemoryPool
    let memory_pool = unsafe { &*(pool as *const crate::memory::MemoryPool) };
    match memory_pool.allocate() {
        Ok(ptr) => ptr.as_ptr() as *mut c_void,
        Err(_) => ptr::null_mut(),
    }
}

/// Deallocate memory back to a pool
///
/// # Safety
///
/// Both pointers must be valid, and the memory pointer must have been
/// allocated from the specified pool.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn memory_pool_deallocate(
    pool: *mut CMemoryPool,
    ptr: *mut c_void,
) -> CResult {
    if pool.is_null() || ptr.is_null() {
        set_last_error("Memory pool or pointer is null");
        return CResult::InvalidInput;
    }

    // SAFETY: pointer is valid (null-checked at line 235), points to initialized MemoryPool
    let memory_pool = unsafe { &*(pool as *const crate::memory::MemoryPool) };
    let non_null_ptr = match std::ptr::NonNull::new(ptr as *mut u8) {
        Some(p) => p,
        None => {
            set_last_error("Failed to create NonNull pointer from raw pointer");
            return CResult::InvalidInput;
        }
    };

    match memory_pool.deallocate(non_null_ptr) {
        Ok(_) => CResult::Success,
        Err(e) => {
            set_last_error(&format!("Failed to deallocate memory: {}", e));
            CResult::InternalError
        }
    }
}

/// Create a new blob store
///
/// # Safety
///
/// The returned pointer must be freed with `blob_store_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blob_store_new() -> *mut CBlobStore {
    let store = Box::new(crate::blob_store::MemoryBlobStore::new());
    Box::into_raw(store) as *mut CBlobStore
}

/// Free a blob store
///
/// # Safety
///
/// The pointer must be a valid CBlobStore pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blob_store_free(store: *mut CBlobStore) {
    if !store.is_null() {
        // SAFETY: pointer is valid (null-checked), created by blob_store_new via Box::into_raw, not previously freed
        let _store = unsafe { Box::from_raw(store as *mut crate::blob_store::MemoryBlobStore) };
        // Automatic cleanup when Box is dropped
    }
}

/// Put data into a blob store
///
/// # Safety
///
/// The store pointer must be valid, and data must point to a valid buffer of the specified size.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blob_store_put(
    store: *mut CBlobStore,
    data: *const u8,
    size: usize,
    record_id: *mut u32,
) -> CResult {
    if store.is_null() || data.is_null() || record_id.is_null() {
        set_last_error("Blob store, data, or record_id pointer is null");
        return CResult::InvalidInput;
    }

    // SAFETY: pointer is valid (null-checked at line 294), points to initialized MemoryBlobStore
    let blob_store = unsafe { &mut *(store as *mut crate::blob_store::MemoryBlobStore) };
    // SAFETY: data pointer is valid (null-checked at line 294), size is provided by caller
    let data_slice = unsafe { std::slice::from_raw_parts(data, size) };

    match blob_store.put(data_slice) {
        Ok(id) => {
            // SAFETY: record_id pointer is valid (null-checked at line 294), points to valid u32
            unsafe {
                *record_id = id;
            }
            CResult::Success
        }
        Err(e) => {
            set_last_error(&format!("Failed to put data in blob store: {}", e));
            CResult::InternalError
        }
    }
}

/// Get data from a blob store
///
/// # Safety
///
/// The store pointer must be valid. The data and size pointers will be set to
/// point to allocated memory that must be freed with `zipora_free_blob_data`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blob_store_get(
    store: *const CBlobStore,
    record_id: u32,
    data: *mut *const u8,
    size: *mut usize,
) -> CResult {
    if store.is_null() || data.is_null() || size.is_null() {
        return CResult::InvalidInput;
    }

    // SAFETY: pointer is valid (null-checked at line 329), points to initialized MemoryBlobStore
    let blob_store = unsafe { &*(store as *const crate::blob_store::MemoryBlobStore) };

    match blob_store.get(record_id) {
        Ok(blob_data) => {
            // Allocate memory for the data that can be properly freed later
            let data_len = blob_data.len();
            // SAFETY: alignment 1 is always valid, size is non-negative usize
            let data_ptr = unsafe {
                std::alloc::alloc(std::alloc::Layout::from_size_align_unchecked(data_len, 1))
            };
            if data_ptr.is_null() {
                return CResult::MemoryError;
            }

            // SAFETY: data_ptr is valid (null-checked at line 344), blob_data is valid slice, non-overlapping
            // Copy the data into the allocated memory
            unsafe {
                std::ptr::copy_nonoverlapping(blob_data.as_ptr(), data_ptr, data_len);
            }

            // SAFETY: data and size pointers are valid (null-checked at line 329), point to valid output parameters
            unsafe {
                *data = data_ptr;
                *size = data_len;
            }
            CResult::Success
        }
        Err(_) => CResult::InvalidInput,
    }
}

/// Create a suffix array from text
///
/// # Safety
///
/// The text pointer must point to a valid buffer of the specified size.
/// The returned pointer must be freed with `suffix_array_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn suffix_array_new(text: *const u8, size: usize) -> *mut CSuffixArray {
    if text.is_null() || size == 0 {
        return ptr::null_mut();
    }

    // SAFETY: pointer is valid (null-checked at line 369), size is non-zero (checked at line 369)
    let text_slice = unsafe { std::slice::from_raw_parts(text, size) };
    match crate::algorithms::SuffixArray::new(text_slice) {
        Ok(sa) => Box::into_raw(Box::new(sa)) as *mut CSuffixArray,
        Err(_) => ptr::null_mut(),
    }
}

/// Free a suffix array
///
/// # Safety
///
/// The pointer must be a valid CSuffixArray pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn suffix_array_free(sa: *mut CSuffixArray) {
    if !sa.is_null() {
        // SAFETY: pointer is valid (null-checked), created by suffix_array_new via Box::into_raw, not previously freed
        let _sa = unsafe { Box::from_raw(sa as *mut crate::algorithms::SuffixArray) };
        // Automatic cleanup when Box is dropped
    }
}

/// Get the length of a suffix array
///
/// # Safety
///
/// The sa pointer must be a valid CSuffixArray pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn suffix_array_len(sa: *const CSuffixArray) -> usize {
    if sa.is_null() {
        return 0;
    }

    // SAFETY: pointer is valid (null-checked at line 401), points to initialized SuffixArray
    let suffix_array = unsafe { &*(sa as *const crate::algorithms::SuffixArray) };
    suffix_array.text_len()
}

/// Search for a pattern in the suffix array
///
/// # Safety
///
/// All pointers must be valid, and pattern must point to a buffer of the specified size.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn suffix_array_search(
    sa: *const CSuffixArray,
    text: *const u8,
    text_size: usize,
    pattern: *const u8,
    pattern_size: usize,
    start: *mut usize,
    count: *mut usize,
) -> CResult {
    if sa.is_null() || text.is_null() || pattern.is_null() || start.is_null() || count.is_null() {
        return CResult::InvalidInput;
    }

    // SAFETY: pointer is valid (null-checked at line 423), points to initialized SuffixArray
    let suffix_array = unsafe { &*(sa as *const crate::algorithms::SuffixArray) };
    // SAFETY: text pointer is valid (null-checked at line 423), text_size is provided by caller
    let text_slice = unsafe { std::slice::from_raw_parts(text, text_size) };
    // SAFETY: pattern pointer is valid (null-checked at line 423), pattern_size is provided by caller
    let pattern_slice = unsafe { std::slice::from_raw_parts(pattern, pattern_size) };

    let (search_start, search_count) = suffix_array.search(text_slice, pattern_slice);
    // SAFETY: start and count pointers are valid (null-checked at line 423), point to valid output parameters
    unsafe {
        *start = search_start;
        *count = search_count;
    }

    CResult::Success
}

/// Sort an array of 32-bit unsigned integers using radix sort
///
/// # Safety
///
/// The data pointer must point to a valid array of the specified size.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn radix_sort_u32(data: *mut u32, size: usize) -> CResult {
    if data.is_null() || size == 0 {
        return CResult::InvalidInput;
    }

    // SAFETY: pointer is valid (null-checked at line 447), size is non-zero (checked at line 447)
    let data_slice = unsafe { std::slice::from_raw_parts_mut(data, size) };
    let mut sorter = crate::algorithms::RadixSort::new();

    match sorter.sort_u32(data_slice) {
        Ok(_) => CResult::Success,
        Err(_) => CResult::InternalError,
    }
}

/// Get last error message (thread-local)
///
/// # Safety
///
/// The returned string is valid until the next error occurs on this thread.
/// The caller should not free the returned pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zipora_last_error() -> *const c_char {
    LAST_ERROR.with(|error| match error.borrow().as_ref() {
        Some(cstring) => cstring.as_ptr(),
        None => {
            static NO_ERROR_MSG: &[u8] = b"No error information available\0";
            NO_ERROR_MSG.as_ptr() as *const c_char
        }
    })
}

/// Set a custom error callback
///
/// # Safety
///
/// The callback function pointer must be valid for the lifetime of the library usage.
/// The callback will be called from the thread that generates the error.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zipora_set_error_callback(
    callback: Option<unsafe extern "C" fn(*const c_char)>,
) {
    if let Ok(mut callback_guard) = ERROR_CALLBACK.lock() {
        *callback_guard = callback;
    }
}

/// Free blob data returned by blob_store_get
///
/// # Safety
///
/// The data pointer must be a pointer returned by `blob_store_get`.
/// The size must match the size returned by `blob_store_get`.
/// The pointer becomes invalid after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zipora_free_blob_data(data: *mut u8, size: usize) {
    if !data.is_null() && size > 0 {
        // SAFETY: alignment 1 is always valid, size matches allocation from blob_store_get
        // data pointer was allocated by blob_store_get via std::alloc::alloc with same layout
        unsafe {
            let layout = std::alloc::Layout::from_size_align_unchecked(size, 1);
            std::alloc::dealloc(data, layout);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ptr;

    #[test]
    fn test_version_api() {
        // SAFETY: test calls C API functions with valid parameters, CStr::from_ptr receives valid static string pointer
        unsafe {
            let version_ptr = zipora_version();
            assert!(!version_ptr.is_null());

            let version_cstr = CStr::from_ptr(version_ptr);
            let version_str = version_cstr.to_str().unwrap();
            assert!(!version_str.is_empty());
        }
    }

    #[test]
    fn test_fast_vec_api() {
        // SAFETY: test calls C API functions with valid parameters, slice created from valid pointer returned by fast_vec_data
        unsafe {
            let vec = fast_vec_new();
            assert!(!vec.is_null());

            assert_eq!(fast_vec_len(vec), 0);

            assert_eq!(fast_vec_push(vec, 42), CResult::Success);
            assert_eq!(fast_vec_push(vec, 84), CResult::Success);

            assert_eq!(fast_vec_len(vec), 2);

            let data_ptr = fast_vec_data(vec);
            assert!(!data_ptr.is_null());

            let data_slice = std::slice::from_raw_parts(data_ptr, 2);
            assert_eq!(data_slice, &[42, 84]);

            fast_vec_free(vec);
        }
    }

    #[test]
    fn test_memory_pool_api() {
        // SAFETY: test calls C API functions with valid parameters, allocated pointers are deallocated before pool is freed
        unsafe {
            let pool = memory_pool_new(1024, 10);
            assert!(!pool.is_null());

            let ptr1 = memory_pool_allocate(pool);
            assert!(!ptr1.is_null());

            let ptr2 = memory_pool_allocate(pool);
            assert!(!ptr2.is_null());
            assert_ne!(ptr1, ptr2);

            assert_eq!(memory_pool_deallocate(pool, ptr1), CResult::Success);
            assert_eq!(memory_pool_deallocate(pool, ptr2), CResult::Success);

            memory_pool_free(pool);
        }
    }

    #[test]
    fn test_blob_store_api() {
        // SAFETY: test calls C API functions with valid parameters, slice created from valid pointer, blob data freed before store
        unsafe {
            let store = blob_store_new();
            assert!(!store.is_null());

            let test_data = b"Hello, world!";
            let mut record_id: u32 = 0;

            let result = blob_store_put(store, test_data.as_ptr(), test_data.len(), &mut record_id);
            assert_eq!(result, CResult::Success);

            let mut data_ptr: *const u8 = ptr::null();
            let mut size: usize = 0;

            let result = blob_store_get(store, record_id, &mut data_ptr, &mut size);
            assert_eq!(result, CResult::Success);
            assert!(!data_ptr.is_null());
            assert_eq!(size, test_data.len());

            // Verify the data content
            let retrieved_data = std::slice::from_raw_parts(data_ptr, size);
            assert_eq!(retrieved_data, test_data);

            // Free the blob data
            zipora_free_blob_data(data_ptr as *mut u8, size);

            blob_store_free(store);
        }
    }

    #[test]
    fn test_radix_sort_api() {
        // SAFETY: test calls C API function with valid pointer to mutable array and correct length
        unsafe {
            let mut data = [5u32, 2, 8, 1, 9, 3, 7, 4, 6];
            let result = radix_sort_u32(data.as_mut_ptr(), data.len());

            assert_eq!(result, CResult::Success);
            assert_eq!(data, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
        }
    }

    #[test]
    fn test_init_and_simd() {
        // SAFETY: test calls C API functions with no parameters, both are safe operations
        unsafe {
            assert_eq!(zipora_init(), CResult::Success);

            let has_simd = zipora_has_simd();
            // Should not panic, return 0 or 1
            assert!(has_simd == 0 || has_simd == 1);
        }
    }

    #[test]
    fn test_error_handling() {
        // SAFETY: test calls C API functions, CStr::from_ptr receives valid static/thread-local string pointers
        unsafe {
            // Test initial state - no error
            let error_ptr = zipora_last_error();
            assert!(!error_ptr.is_null());
            let error_msg = CStr::from_ptr(error_ptr).to_str().unwrap();
            assert_eq!(error_msg, "No error information available");

            // Test setting an error message directly
            set_last_error("Test error message");

            // Check that error message was set
            let error_ptr = zipora_last_error();
            assert!(!error_ptr.is_null());
            let error_msg = CStr::from_ptr(error_ptr).to_str().unwrap();
            assert_eq!(error_msg, "Test error message");
        }
    }

    #[test]
    fn test_error_callback() {
        use std::sync::Mutex;
        use std::sync::atomic::{AtomicBool, Ordering};

        static CALLBACK_CALLED: AtomicBool = AtomicBool::new(false);
        static CALLBACK_MESSAGE: Mutex<Option<String>> = Mutex::new(None);

        unsafe extern "C" fn test_callback(msg: *const c_char) {
            CALLBACK_CALLED.store(true, Ordering::SeqCst);
            // SAFETY: msg pointer is valid, passed from set_last_error via CString::as_ptr
            let c_str = unsafe { CStr::from_ptr(msg) };
            if let Ok(str_slice) = c_str.to_str() {
                if let Ok(mut callback_msg) = CALLBACK_MESSAGE.lock() {
                    *callback_msg = Some(str_slice.to_string());
                }
            }
        }

        // SAFETY: test calls C API functions with valid callback function pointer
        unsafe {
            // Clear any previous error state
            clear_last_error();

            // Set the error callback
            zipora_set_error_callback(Some(test_callback));

            // Reset callback state
            CALLBACK_CALLED.store(false, Ordering::SeqCst);
            if let Ok(mut callback_msg) = CALLBACK_MESSAGE.lock() {
                *callback_msg = None;
            }

            // Trigger an error by setting one directly
            set_last_error("Test callback message");

            // Check that callback was called
            assert!(CALLBACK_CALLED.load(Ordering::SeqCst));
            if let Ok(callback_msg) = CALLBACK_MESSAGE.lock() {
                assert!(callback_msg.is_some());
                assert_eq!(callback_msg.as_ref().unwrap(), "Test callback message");
            }

            // Clear the callback
            zipora_set_error_callback(None);

            // Reset state and trigger another error
            CALLBACK_CALLED.store(false, Ordering::SeqCst);
            if let Ok(mut callback_msg) = CALLBACK_MESSAGE.lock() {
                *callback_msg = None;
            }

            set_last_error("Another test message");

            // Callback should not have been called this time
            assert!(!CALLBACK_CALLED.load(Ordering::SeqCst));
            if let Ok(callback_msg) = CALLBACK_MESSAGE.lock() {
                assert!(callback_msg.is_none());
            }
        }
    }

    #[test]
    fn test_thread_local_errors() {
        use std::sync::{Arc, Mutex};
        use std::thread;

        let results = Arc::new(Mutex::new(Vec::new()));
        let mut handles = Vec::new();

        // Create multiple threads that each generate different errors
        for i in 0..3 {
            let results_clone = Arc::clone(&results);
            let handle = thread::spawn(move || {
                // SAFETY: test calls C API functions from spawned thread, CStr::from_ptr receives valid thread-local pointer
                unsafe {
                    // Each thread sets a different error message
                    let error_msg = match i {
                        0 => "Thread 0 error",
                        1 => "Thread 1 error",
                        2 => "Thread 2 error",
                        _ => "Unknown thread error",
                    };

                    set_last_error(error_msg);

                    // Get the error message from this thread
                    let error_ptr = zipora_last_error();
                    let retrieved_msg = if !error_ptr.is_null() {
                        CStr::from_ptr(error_ptr)
                            .to_str()
                            .unwrap_or("Invalid UTF-8")
                            .to_string()
                    } else {
                        "Null pointer".to_string()
                    };

                    // Store the result
                    let mut results_guard = results_clone.lock().unwrap_or_else(|e| e.into_inner());
                    results_guard.push((i, retrieved_msg));
                }
            });
            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // Check that each thread got its own error message
        let results_guard = results.lock().unwrap_or_else(|e| e.into_inner());
        assert_eq!(results_guard.len(), 3);

        // Check that we got the expected error messages (order may vary due to threading)
        let mut found_thread0 = false;
        let mut found_thread1 = false;
        let mut found_thread2 = false;

        for (thread_id, error_msg) in results_guard.iter() {
            match *thread_id {
                0 => {
                    assert_eq!(error_msg, "Thread 0 error");
                    found_thread0 = true;
                }
                1 => {
                    assert_eq!(error_msg, "Thread 1 error");
                    found_thread1 = true;
                }
                2 => {
                    assert_eq!(error_msg, "Thread 2 error");
                    found_thread2 = true;
                }
                _ => {}
            }
        }

        assert!(found_thread0 && found_thread1 && found_thread2);
    }
}