readcon-db 0.1.2

Mmap-backed CON frame corpus (Heed/LMDB), xxHash exact match, multi-language FFI
Documentation
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
//! C ABI for readcon-db (always linked into cdylib/staticlib).
//!
//! Status codes mirror a small subset of readcon-core style (negative = error).

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::ptr;
use std::sync::{Arc, Mutex};

use crate::corpus::ConCorpus;
use crate::keys::{hash_frame_bytes, ContentHash, FrameKey};
use crate::select::Select;

pub const RKRDB_OK: c_int = 0;
pub const RKRDB_ERR: c_int = -1;
pub const RKRDB_NOT_FOUND: c_int = -2;
pub const RKRDB_NULL: c_int = -3;

struct Handle {
    /// Shared so ingest runs **outside** the handle-table mutex (no app-level writer serialize).
    corpus: Arc<ConCorpus>,
    last_keys: Vec<FrameKey>,
    last_error: String,
}

static HANDLES: Mutex<Vec<Option<Box<Handle>>>> = Mutex::new(Vec::new());

fn push_handle(h: Handle) -> usize {
    let mut g = HANDLES.lock().unwrap();
    for (i, slot) in g.iter_mut().enumerate() {
        if slot.is_none() {
            *slot = Some(Box::new(h));
            return i;
        }
    }
    g.push(Some(Box::new(h)));
    g.len() - 1
}

/// Brief table lock for bookkeeping only — not held across ingest/select CPU or LMDB work.
fn with_handle<F, T>(id: usize, f: F) -> Result<T, c_int>
where
    F: FnOnce(&mut Handle) -> Result<T, c_int>,
{
    let mut g = HANDLES.lock().unwrap();
    let slot = g.get_mut(id).ok_or(RKRDB_NULL)?;
    let h = slot.as_mut().ok_or(RKRDB_NULL)?;
    f(h)
}

fn corpus_arc(id: usize) -> Result<Arc<ConCorpus>, c_int> {
    let g = HANDLES.lock().unwrap();
    let slot = g.get(id).ok_or(RKRDB_NULL)?;
    let h = slot.as_ref().ok_or(RKRDB_NULL)?;
    Ok(Arc::clone(&h.corpus))
}

fn set_err_id(id: usize, e: impl ToString) {
    let mut g = HANDLES.lock().unwrap();
    if let Some(Some(h)) = g.get_mut(id) {
        h.last_error = e.to_string();
    }
}

fn set_err(h: &mut Handle, e: impl ToString) {
    h.last_error = e.to_string();
}

/// Open corpus directory. On success writes opaque handle id to `out_id` (>=0).
/// Returns RKRDB_OK or error code.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_open(path: *const c_char, out_id: *mut usize) -> c_int {
    if path.is_null() || out_id.is_null() {
        return RKRDB_NULL;
    }
    let cpath = unsafe { CStr::from_ptr(path) };
    let path = match cpath.to_str() {
        Ok(s) => s,
        Err(_) => return RKRDB_ERR,
    };
    match ConCorpus::open(path) {
        Ok(corpus) => {
            let id = push_handle(Handle {
                corpus: Arc::new(corpus),
                last_keys: Vec::new(),
                last_error: String::new(),
            });
            unsafe { *out_id = id };
            RKRDB_OK
        }
        Err(_) => RKRDB_ERR,
    }
}

#[no_mangle]
pub unsafe extern "C" fn rkrdb_close(id: usize) -> c_int {
    let mut g = HANDLES.lock().unwrap();
    if let Some(slot) = g.get_mut(id) {
        *slot = None;
        RKRDB_OK
    } else {
        RKRDB_NULL
    }
}

/// Last error message (thread-safe snapshot into caller buffer). Returns bytes written excluding NUL,
/// or -1 if truncated / null.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_last_error(id: usize, buf: *mut c_char, buflen: usize) -> c_int {
    if buf.is_null() || buflen == 0 {
        return RKRDB_NULL;
    }
    with_handle(id, |h| {
        let bytes = h.last_error.as_bytes();
        let n = (buflen - 1).min(bytes.len());
        unsafe {
            ptr::copy_nonoverlapping(bytes.as_ptr(), buf as *mut u8, n);
            *buf.add(n) = 0;
        }
        Ok(n as c_int)
    })
    .unwrap_or(RKRDB_NULL)
}

#[no_mangle]
pub unsafe extern "C" fn rkrdb_append_trajectory(
    id: usize,
    traj_id: u64,
    path: *const c_char,
    out_n_frames: *mut u32,
) -> c_int {
    if path.is_null() {
        return RKRDB_NULL;
    }
    let cpath = unsafe { CStr::from_ptr(path) };
    let path = match cpath.to_str() {
        Ok(s) => s,
        Err(_) => return RKRDB_ERR,
    };
    // Prepare+commit on Arc corpus **outside** handle mutex (concurrent writers on distinct handles).
    let corpus = match corpus_arc(id) {
        Ok(c) => c,
        Err(c) => return c,
    };
    match corpus.append_trajectory_path(traj_id, path) {
        Ok(n) => {
            if !out_n_frames.is_null() {
                unsafe { *out_n_frames = n };
            }
            RKRDB_OK
        }
        Err(e) => {
            set_err_id(id, e);
            RKRDB_ERR
        }
    }
}

/// Select by required symbol (optional) and natoms range (use 0, UINT32_MAX for any).
/// Results stored internally; use rkrdb_result_count / rkrdb_result_key.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_select_basic(
    id: usize,
    traj_id: i64,
    symbol: *const c_char,
    natoms_min: u32,
    natoms_max: u32,
    limit: u32,
) -> c_int {
    with_handle(id, |h| {
        let mut sel = Select::new().natoms_range(natoms_min, natoms_max);
        if traj_id >= 0 {
            sel = sel.trajectory(traj_id as u64);
        }
        if !symbol.is_null() {
            let s = unsafe { CStr::from_ptr(symbol) };
            if let Ok(sym) = s.to_str() {
                if !sym.is_empty() {
                    sel = sel.require_symbol(sym);
                }
            }
        }
        if limit > 0 {
            sel = sel.limit(limit as usize);
        }
        match h.corpus.select(&sel) {
            Ok(keys) => {
                h.last_keys = keys;
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Select by exact xxHash3-128 (16 bytes LE).
#[no_mangle]
pub unsafe extern "C" fn rkrdb_select_hash(id: usize, hash16: *const u8) -> c_int {
    if hash16.is_null() {
        return RKRDB_NULL;
    }
    let mut hb = [0u8; 16];
    unsafe { ptr::copy_nonoverlapping(hash16, hb.as_mut_ptr(), 16) };
    with_handle(id, |h| {
        let sel = Select::new().exact_hash(hb);
        match h.corpus.select(&sel) {
            Ok(keys) => {
                h.last_keys = keys;
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Metadata / section filters. Pass `use_energy_range=0` to ignore energy bounds.
/// Flags: bit0=require_forces, bit1=require_velocities, bit2=require_energy.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_select_meta(
    id: usize,
    traj_id: i64,
    symbol: *const c_char,
    natoms_min: u32,
    natoms_max: u32,
    energy_min: f64,
    energy_max: f64,
    use_energy_range: c_int,
    flags: u32,
    limit: u32,
) -> c_int {
    with_handle(id, |h| {
        let mut sel = Select::new().natoms_range(natoms_min, natoms_max);
        if traj_id >= 0 {
            sel = sel.trajectory(traj_id as u64);
        }
        if !symbol.is_null() {
            let s = unsafe { CStr::from_ptr(symbol) };
            if let Ok(sym) = s.to_str() {
                if !sym.is_empty() {
                    sel = sel.require_symbol(sym);
                }
            }
        }
        if use_energy_range != 0 {
            sel = sel.energy_range(energy_min, energy_max);
        }
        if flags & 1 != 0 {
            sel = sel.require_forces();
        }
        if flags & 2 != 0 {
            sel = sel.require_velocities();
        }
        if flags & 4 != 0 {
            sel = sel.require_energy();
        }
        if limit > 0 {
            sel = sel.limit(limit as usize);
        }
        match h.corpus.select(&sel) {
            Ok(keys) => {
                h.last_keys = keys;
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}


/// Rebuild secondary indexes from authoritative frame blobs.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_reindex(id: usize) -> c_int {
    with_handle(id, |h| match h.corpus.reindex() {
        Ok(_) => Ok(RKRDB_OK),
        Err(e) => {
            set_err(h, e);
            Ok(RKRDB_ERR)
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Opt-in cook: derive RCSO into `frames_soa` from CON text in `frames` (CON remains authority).
#[no_mangle]
pub unsafe extern "C" fn rkrdb_cook_frame(id: usize, traj_id: u64, frame_idx: u32) -> c_int {
    with_handle(id, |h| {
        match h.corpus.cook_frame(crate::keys::FrameKey {
            traj_id,
            frame_idx,
        }) {
            Ok(_) => Ok(RKRDB_OK),
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Drop cooked tier only; CON text and indexes unchanged.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_delete_cooked(id: usize, traj_id: u64, frame_idx: u32) -> c_int {
    with_handle(id, |h| {
        match h.corpus.delete_cooked_soa(crate::keys::FrameKey {
            traj_id,
            frame_idx,
        }) {
            Ok(()) => Ok(RKRDB_OK),
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Returns 1 if valid RCSO present, 0 if missing/corrupt, negative on error.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_has_valid_cooked(id: usize, traj_id: u64, frame_idx: u32) -> c_int {
    with_handle(id, |h| {
        match h.corpus.has_valid_cooked_soa(crate::keys::FrameKey {
            traj_id,
            frame_idx,
        }) {
            Ok(true) => Ok(1),
            Ok(false) => Ok(0),
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Prefer cooked positions (no CON parse on hit); else parse CON.
/// Writes `*out_natoms * 3` doubles into `out_xyz` (row-major N×3). `capacity_atoms` is max N.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_get_positions(
    id: usize,
    traj_id: u64,
    frame_idx: u32,
    out_xyz: *mut f64,
    capacity_atoms: u32,
    out_natoms: *mut u32,
) -> c_int {
    if out_xyz.is_null() || out_natoms.is_null() {
        return RKRDB_NULL;
    }
    with_handle(id, |h| {
        match h.corpus.get_positions(crate::keys::FrameKey {
            traj_id,
            frame_idx,
        }) {
            Ok(pos) => {
                let n = pos.len() as u32;
                if n > capacity_atoms {
                    set_err(
                        h,
                        crate::error::Error::Message("positions buffer too small".into()),
                    );
                    return Ok(RKRDB_ERR);
                }
                unsafe {
                    *out_natoms = n;
                    for (i, row) in pos.iter().enumerate() {
                        *out_xyz.add(i * 3) = row[0];
                        *out_xyz.add(i * 3 + 1) = row[1];
                        *out_xyz.add(i * 3 + 2) = row[2];
                    }
                }
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Prefer cooked forces when present; writes N×3 doubles. Sets *out_has_forces 0/1.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_get_forces(
    id: usize,
    traj_id: u64,
    frame_idx: u32,
    out_xyz: *mut f64,
    capacity_atoms: u32,
    out_natoms: *mut u32,
    out_has_forces: *mut u8,
) -> c_int {
    if out_xyz.is_null() || out_natoms.is_null() || out_has_forces.is_null() {
        return RKRDB_NULL;
    }
    with_handle(id, |h| {
        match h.corpus.get_forces(crate::keys::FrameKey {
            traj_id,
            frame_idx,
        }) {
            Ok(None) => {
                unsafe {
                    *out_has_forces = 0;
                    *out_natoms = 0;
                }
                Ok(RKRDB_OK)
            }
            Ok(Some(frc)) => {
                let n = frc.len() as u32;
                if n > capacity_atoms {
                    set_err(
                        h,
                        crate::error::Error::Message("forces buffer too small".into()),
                    );
                    return Ok(RKRDB_ERR);
                }
                unsafe {
                    *out_has_forces = 1;
                    *out_natoms = n;
                    for (i, row) in frc.iter().enumerate() {
                        *out_xyz.add(i * 3) = row[0];
                        *out_xyz.add(i * 3 + 1) = row[1];
                        *out_xyz.add(i * 3 + 2) = row[2];
                    }
                }
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Cook every frame that has CON text (`recook_all`).
#[no_mangle]
pub unsafe extern "C" fn rkrdb_recook_all(id: usize) -> c_int {
    with_handle(id, |h| match h.corpus.recook_all() {
        Ok(_) => Ok(RKRDB_OK),
        Err(e) => {
            set_err(h, e);
            Ok(RKRDB_ERR)
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Canonical composition formula for a stored frame (same as core `index_proj`).
/// Writes into `buf` (NUL-terminated). Returns RKRDB_OK, RKRDB_NOT_FOUND, RKRDB_ERR, or buffer size need as positive? 
/// On success returns RKRDB_OK; if buflen too small returns RKRDB_ERR and sets last_error.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_frame_formula(
    id: usize,
    traj_id: u64,
    frame_idx: u32,
    buf: *mut c_char,
    buflen: usize,
) -> c_int {
    if buf.is_null() || buflen == 0 {
        return RKRDB_NULL;
    }
    with_handle(id, |h| {
        match h.corpus.frame_formula(crate::keys::FrameKey {
            traj_id,
            frame_idx,
        }) {
            Ok(s) => {
                let bytes = s.as_bytes();
                if bytes.len() + 1 > buflen {
                    set_err(h, crate::error::Error::Message("buffer too small".into()));
                    return Ok(RKRDB_ERR);
                }
                unsafe {
                    std::ptr::copy_nonoverlapping(bytes.as_ptr(), buf as *mut u8, bytes.len());
                    *buf.add(bytes.len()) = 0;
                }
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Campaign select: composition formula (NUL-terminated, may be null), optional fmax window.
/// `use_fmax_range` non-zero applies fmax_min/max. Flags: bit0 forces, bit1 velocities, bit2 energy.
/// Element constraints: pass `elem_sym` + `elem_count` + `elem_exact` (1=exact, 0=min) for one pair (null skips).
#[no_mangle]
pub unsafe extern "C" fn rkrdb_select_campaign(
    id: usize,
    traj_id: i64,
    symbol: *const c_char,
    natoms_min: u32,
    natoms_max: u32,
    formula: *const c_char,
    energy_min: f64,
    energy_max: f64,
    use_energy_range: c_int,
    fmax_min: f64,
    fmax_max: f64,
    use_fmax_range: c_int,
    elem_sym: *const c_char,
    elem_count: u32,
    elem_exact: c_int,
    flags: u32,
    limit: u32,
) -> c_int {
    with_handle(id, |h| {
        let mut sel = Select::new().natoms_range(natoms_min, natoms_max);
        if traj_id >= 0 {
            sel = sel.trajectory(traj_id as u64);
        }
        if !symbol.is_null() {
            let s = unsafe { CStr::from_ptr(symbol) };
            if let Ok(sym) = s.to_str() {
                if !sym.is_empty() {
                    sel = sel.require_symbol(sym);
                }
            }
        }
        if !formula.is_null() {
            let s = unsafe { CStr::from_ptr(formula) };
            if let Ok(f) = s.to_str() {
                if !f.is_empty() {
                    sel = sel.exact_composition(f);
                }
            }
        }
        if use_energy_range != 0 {
            sel = sel.energy_range(energy_min, energy_max);
        }
        if use_fmax_range != 0 {
            sel = sel.fmax_range(fmax_min, fmax_max);
        }
        if !elem_sym.is_null() {
            let s = unsafe { CStr::from_ptr(elem_sym) };
            if let Ok(sym) = s.to_str() {
                if !sym.is_empty() {
                    if elem_exact != 0 {
                        sel = sel.element_exact(sym, elem_count);
                    } else {
                        sel = sel.element_min(sym, elem_count);
                    }
                }
            }
        }
        if flags & 1 != 0 {
            sel = sel.require_forces();
        }
        if flags & 2 != 0 {
            sel = sel.require_velocities();
        }
        if flags & 4 != 0 {
            sel = sel.require_energy();
        }
        if limit > 0 {
            sel = sel.limit(limit as usize);
        }
        match h.corpus.select(&sel) {
            Ok(keys) => {
                h.last_keys = keys;
                Ok(RKRDB_OK)
            }
            Err(e) => {
                set_err(h, e);
                Ok(RKRDB_ERR)
            }
        }
    })
    .unwrap_or(RKRDB_NULL)
}

#[no_mangle]
pub unsafe extern "C" fn rkrdb_result_count(id: usize) -> c_int {
    with_handle(id, |h| Ok(h.last_keys.len() as c_int)).unwrap_or(RKRDB_NULL)
}

/// Write traj_id and frame_idx for result index `i` (0-based).
#[no_mangle]
pub unsafe extern "C" fn rkrdb_result_key(
    id: usize,
    i: usize,
    out_traj: *mut u64,
    out_frame: *mut u32,
) -> c_int {
    if out_traj.is_null() || out_frame.is_null() {
        return RKRDB_NULL;
    }
    with_handle(id, |h| {
        let k = match h.last_keys.get(i) {
            Some(k) => *k,
            None => return Ok(RKRDB_NOT_FOUND),
        };
        unsafe {
            *out_traj = k.traj_id;
            *out_frame = k.frame_idx;
        }
        Ok(RKRDB_OK)
    })
    .unwrap_or(RKRDB_NULL)
}

/// Hash frame blob at key; writes 16 LE bytes to out_hash16.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_frame_hash(
    id: usize,
    traj_id: u64,
    frame_idx: u32,
    out_hash16: *mut u8,
) -> c_int {
    if out_hash16.is_null() {
        return RKRDB_NULL;
    }
    let key = FrameKey {
        traj_id,
        frame_idx,
    };
    with_handle(id, |h| match h.corpus.frame_hash(key) {
        Ok(hash) => {
            let b = hash.to_bytes();
            unsafe { ptr::copy_nonoverlapping(b.as_ptr(), out_hash16, 16) };
            Ok(RKRDB_OK)
        }
        Err(e) => {
            set_err(h, e);
            Ok(RKRDB_ERR)
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// Copy frame CON text into buf (NUL-terminated). Returns length excluding NUL, or error code.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_get_frame_text(
    id: usize,
    traj_id: u64,
    frame_idx: u32,
    buf: *mut c_char,
    buflen: usize,
) -> c_int {
    if buf.is_null() || buflen == 0 {
        return RKRDB_NULL;
    }
    let key = FrameKey {
        traj_id,
        frame_idx,
    };
    with_handle(id, |h| match h.corpus.get_frame_text(key) {
        Ok(text) => {
            let bytes = text.as_bytes();
            if bytes.len() + 1 > buflen {
                set_err(h, "buffer too small");
                return Ok(RKRDB_ERR);
            }
            unsafe {
                ptr::copy_nonoverlapping(bytes.as_ptr(), buf as *mut u8, bytes.len());
                *buf.add(bytes.len()) = 0;
            }
            Ok(bytes.len() as c_int)
        }
        Err(e) => {
            set_err(h, e);
            Ok(RKRDB_ERR)
        }
    })
    .unwrap_or(RKRDB_NULL)
}

/// xxHash3-128 of arbitrary bytes (LE 16 bytes) — for clients hashing off-line blobs.
#[no_mangle]
pub unsafe extern "C" fn rkrdb_xxh3_128(data: *const u8, len: usize, out_hash16: *mut u8) -> c_int {
    if data.is_null() || out_hash16.is_null() {
        return RKRDB_NULL;
    }
    let slice = unsafe { std::slice::from_raw_parts(data, len) };
    let h = hash_frame_bytes(slice);
    let b = h.to_bytes();
    unsafe { ptr::copy_nonoverlapping(b.as_ptr(), out_hash16, 16) };
    RKRDB_OK
}

// silence unused CString in some builds
#[allow(dead_code)]
fn _cs(s: &str) -> Result<CString, c_int> {
    CString::new(s).map_err(|_| RKRDB_ERR)
}

// ContentHash used in find path
#[allow(dead_code)]
fn _ch(b: [u8; 16]) -> ContentHash {
    ContentHash(b)
}