Skip to content

Commit

Permalink
Merge pull request #1440 from multiversx/remove-maybe-uninit
Browse files Browse the repository at this point in the history
remove maybe uninit
  • Loading branch information
andrei-marinica authored Mar 8, 2024
2 parents 35bff85 + e5b7620 commit 2948999
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
2 changes: 0 additions & 2 deletions framework/base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
#![feature(exhaustive_patterns)]
#![feature(try_trait_v2)]
#![feature(control_flow_enum)]
#![feature(maybe_uninit_uninit_array)]
#![feature(maybe_uninit_array_assume_init)]
#![feature(negative_impls)]
#![feature(generic_const_exprs)]
#![allow(incomplete_features)]
Expand Down
18 changes: 13 additions & 5 deletions framework/base/src/types/managed/wrapped/managed_vec.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::EncodedManagedVecItem;
use crate::{
abi::{TypeAbi, TypeDescriptionContainer, TypeName},
api::{ErrorApiImpl, InvalidSliceError, ManagedTypeApi},
Expand All @@ -12,9 +13,14 @@ use crate::{
},
};
use alloc::vec::Vec;
use core::{borrow::Borrow, cmp::Ordering, fmt::Debug, iter::FromIterator, marker::PhantomData};

use super::EncodedManagedVecItem;
use core::{
borrow::Borrow,
cmp::Ordering,
fmt::Debug,
iter::FromIterator,
marker::PhantomData,
mem::{transmute_copy, ManuallyDrop, MaybeUninit},
};

pub(crate) const INDEX_OUT_OF_RANGE_MSG: &[u8] = b"ManagedVec index out of range";

Expand Down Expand Up @@ -147,12 +153,14 @@ where
return None;
}

let mut result_uninit = core::mem::MaybeUninit::<T::Ref<'_>>::uninit_array();
let mut result_uninit =
unsafe { MaybeUninit::<[MaybeUninit<T::Ref<'_>>; N]>::uninit().assume_init() };

for (index, value) in self.iter().enumerate() {
result_uninit[index].write(value);
}

let result = unsafe { core::mem::MaybeUninit::array_assume_init(result_uninit) };
let result = unsafe { transmute_copy(&ManuallyDrop::new(result_uninit)) };
Some(result)
}

Expand Down
19 changes: 19 additions & 0 deletions framework/scenario/tests/managed_vec_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,25 @@ fn test_into_vec() {
assert_eq!(vec, managed_vec.into_vec());
}

#[test]
fn test_to_array_of_refs() {
let mut vec = ManagedVec::<StaticApi, i32>::new();
for i in 0..10 {
vec.push(i);
}

let refs: Option<[i32; 20]> = vec.to_array_of_refs();
assert!(refs.is_none());

let refs: Option<[i32; 10]> = vec.to_array_of_refs();
assert!(refs.is_some());

let refs = refs.unwrap();
for (i, &item) in refs.iter().enumerate() {
assert_eq!(item, i as i32);
}
}

#[test]
fn test_take_u64() {
let mut vec = Vec::<u64>::new();
Expand Down

0 comments on commit 2948999

Please sign in to comment.