Skip to content

Commit

Permalink
fix(sdk): Return Bytes when using Vec<u8> in params and result
Browse files Browse the repository at this point in the history
Closes #427
  • Loading branch information
shekohex committed Nov 1, 2024
1 parent bdc4ec6 commit d4a6eb8
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions sdk/src/event_listener/tangle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,28 @@ impl_value_to_field_type!(
AccountId32 => Field::AccountId
);

impl<T: ValueIntoFieldType> ValueIntoFieldType for Vec<T> {
impl<T: ValueIntoFieldType + 'static> ValueIntoFieldType for Vec<T> {
fn into_field_type(self) -> Field<AccountId32> {
Field::Array(BoundedVec(
self.into_iter()
.map(ValueIntoFieldType::into_field_type)
.collect(),
))
if core::any::TypeId::of::<T>() == core::any::TypeId::of::<u8>() {
let (ptr, length, capacity) = {
let mut me = core::mem::ManuallyDrop::new(self);
(me.as_mut_ptr() as *mut u8, me.len(), me.capacity())
};
// SAFETY: We are converting a Vec<T> to Vec<u8> only when T is u8.
// This is safe because the memory layout of Vec<u8> is the same as Vec<T> when T is u8.
// We use ManuallyDrop to prevent double-freeing the memory.
// Vec::from_raw_parts takes ownership of the raw parts, ensuring proper deallocation.
#[allow(unsafe_code)]
Field::Bytes(BoundedVec(unsafe {
Vec::from_raw_parts(ptr, length, capacity)
}))
} else {
Field::List(BoundedVec(
self.into_iter()
.map(ValueIntoFieldType::into_field_type)
.collect(),
))
}
}
}

Expand Down

0 comments on commit d4a6eb8

Please sign in to comment.