Skip to content

Commit

Permalink
Fix #5165
Browse files Browse the repository at this point in the history
  • Loading branch information
ethe committed Oct 7, 2024
1 parent d74bf7c commit 86b9a0b
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions bindings/c/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,32 @@ use opendal::Buffer;
#[repr(C)]
pub struct opendal_bytes {
/// Pointing to the byte array on heap
pub data: *const u8,
pub data: *mut u8,
/// The length of the byte array
pub len: usize,
/// The capacity of the byte array
pub capacity: usize,
}

impl opendal_bytes {
/// Construct a [`opendal_bytes`] from the Rust [`Vec`] of bytes
pub(crate) fn new(buf: Buffer) -> Self {
let vec = buf.to_vec();
let data = vec.as_ptr();
let len = vec.len();
std::mem::forget(vec);
Self { data, len }
let buf = std::mem::ManuallyDrop::new(vec);
let data = buf.as_mut_ptr();
let len = buf.len();
let capa = buf.capacity();
Self {
data,
len,
capacity,
}
}

/// \brief Frees the heap memory used by the opendal_bytes
#[no_mangle]
pub unsafe extern "C" fn opendal_bytes_free(ptr: *mut opendal_bytes) {
if !ptr.is_null() {
let data_mut = (*ptr).data as *mut u8;
drop(Vec::from_raw_parts(data_mut, (*ptr).len, (*ptr).len));
drop(Box::from_raw(ptr));
let _ = Vec::from_raw_parts((*ptr).data, (*ptr).len, (*ptr).capacity);
}
}
}
Expand Down

0 comments on commit 86b9a0b

Please sign in to comment.