Skip to content

Commit

Permalink
fix UB: Rust slice should have NonNull pointer
Browse files Browse the repository at this point in the history
  • Loading branch information
Dushistov committed Apr 20, 2024
1 parent 532f3fc commit 3b0a746
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions couchbase-lite-core-sys/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Code to help deal with C API
use crate::{
C4CollectionSpec, C4String, FLHeapSlice, FLSlice, FLSliceResult, FLSliceResult_Release,
FLString,
C4CollectionSpec, C4String, FLHeapSlice, FLSlice, FLSliceResult, FLSliceResult_New,
FLSliceResult_Release, FLString,
};
use std::{borrow::Cow, os::raw::c_void, ptr, slice, str};

Expand Down Expand Up @@ -47,7 +47,13 @@ impl<'a> From<&'a [u8]> for FLSlice {
impl<'a> From<FLSlice> for &'a [u8] {
#[inline]
fn from(s: FLSlice) -> Self {
unsafe { slice::from_raw_parts(s.buf as *const u8, s.size) }
if s.size != 0 {
unsafe { slice::from_raw_parts(s.buf as *const u8, s.size) }
} else {
// pointer should not be null, even in zero case
// but pointer from FLSlice can be null in zero case, so:
&[]
}
}
}

Expand Down Expand Up @@ -135,3 +141,17 @@ pub const kC4DefaultCollectionSpec: C4CollectionSpec = C4CollectionSpec {
name: kC4DefaultCollectionName,
scope: kC4DefaultScopeID,
};

#[test]
fn test_null_slice_handling() {
let ffi_null_slice = FLSlice {
buf: ptr::null(),
size: 0,
};
let slice: &[u8] = ffi_null_slice.into();
assert!(slice.is_empty());

let ffi_null_slice: FLSliceResult = unsafe { FLSliceResult_New(0) };
let slice: &[u8] = ffi_null_slice.as_bytes();
assert!(slice.is_empty());
}

0 comments on commit 3b0a746

Please sign in to comment.