Skip to content

Commit

Permalink
m
Browse files Browse the repository at this point in the history
  • Loading branch information
ajewellamz committed Jan 21, 2025
1 parent 6be36b6 commit 82aefc7
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 74 deletions.
7 changes: 2 additions & 5 deletions DynamoDbEncryption/runtimes/rust/examples/basic_async.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::future::Future;
use aws_db_esdk::key_store::types::KeyStoreConfig;
use aws_db_esdk::key_store::types::KmsConfiguration;
use aws_db_esdk::material_providers::types::MaterialProvidersConfig;
use aws_db_esdk::key_store::client as keystore_client;
use aws_db_esdk::material_providers::client;

fn is_send<T: Future + Send>(_f: T) {}

fn example() {
pub async fn example() {
let future = async move {
let kms_key_id =
"random key stuff"
Expand Down Expand Up @@ -44,5 +41,5 @@ fn example() {
.unwrap();
};

is_send(future);
future.await;
}
2 changes: 1 addition & 1 deletion DynamoDbEncryption/runtimes/rust/examples/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ pub mod multi_get_put_example;
pub mod searchableencryption;
pub mod test_utils;

#[cfg(feature = "async-fixed")]
pub mod basic_async;

use std::convert::From;
Expand Down Expand Up @@ -50,6 +49,7 @@ impl<T: std::fmt::Debug> From<T> for BoxError {

#[tokio::main]
pub async fn main() -> Result<(), BoxError2> {
basic_async::example().await;
basic_get_put_example::put_item_get_item().await?;
itemencryptor::item_encrypt_decrypt::encrypt_decrypt().await?;
get_encrypted_data_key_description::get_encrypted_data_key_description().await?;
Expand Down
132 changes: 66 additions & 66 deletions releases/rust/db_esdk/dafny_runtime_rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ pub use mem::MaybeUninit;
use num::{bigint::ParseBigIntError, Integer, Num, One, Signed};
pub use once_cell::unsync::Lazy;
use std::{
any::Any,
borrow::Borrow,
boxed::Box,
clone::Clone,
Expand Down Expand Up @@ -41,6 +40,15 @@ pub use num::ToPrimitive;
pub use num::Zero;
pub use std::convert::Into;

pub use ::std::any::Any;
pub use ::std::marker::Send;
pub use ::std::marker::Sync;

#[cfg(not(feature = "sync"))]
pub type DynAny = dyn Any;
#[cfg(feature = "sync")]
pub type DynAny = dyn Any + Send + Sync;

#[cfg(not(feature = "sync"))]
pub use ::std::cell::UnsafeCell;

Expand Down Expand Up @@ -812,10 +820,10 @@ where
#[cfg(feature = "sync")]
let into_boxed_borrowed = into_boxed;
#[cfg(feature = "sync")]
let guard = into_boxed_borrowed.lock().unwrap();
let mut guard = into_boxed_borrowed.lock().unwrap();
#[cfg(feature = "sync")]
let borrowed: Option<&Rc<Vec<T>>> = guard.as_ref();

#[cfg(not(feature = "sync"))]
let into_boxed = boxed.as_ref().clone();
#[cfg(not(feature = "sync"))]
Expand All @@ -828,19 +836,38 @@ where
// Let's create an array of size length and fill it up recursively
// We don't materialize nested arrays because most of the time they are forgotten
let mut array: Vec<T> = Vec::with_capacity(*length);
Sequence::<T>::append_recursive(&mut array, self);
Sequence::<T>::append_recursive_safe(&mut array, &borrowed, left, right);
let result = Rc::new(array);
let mutable_left: *mut Sequence<T> = left.get();
let mutable_right: *mut Sequence<T> = right.get();
// safety: Once the array is computed, left and right won't ever be read again.
unsafe { *mutable_left = seq!() };
unsafe { *mutable_right = seq!() };
Self::write_cache(boxed, result.clone());
#[cfg(not(feature = "sync"))]
let mut guard = boxed.borrow_mut();
*guard = Some(result.clone());
result
}
}
}

pub fn append_recursive_safe(
array: &mut Vec<T>,
borrowed: &Option<&Rc<Vec<T>>>,
left: &Rc<UnsafeCell<Sequence<T>>>,
right: &Rc<UnsafeCell<Sequence<T>>>,
) {
if let Some(values) = borrowed.as_ref() {
for value in values.iter() {
array.push(value.clone());
}
return;
}
// safety: When a concat is initialized, the left and right are well defined
Sequence::<T>::append_recursive(array, unsafe { &mut *left.get() });
Sequence::<T>::append_recursive(array, unsafe { &mut *right.get() });
}

pub fn append_recursive(array: &mut Vec<T>, this: &Sequence<T>) {
match this {
Sequence::ArraySequence { values, .. } =>
Expand All @@ -863,7 +890,7 @@ where
let guard = into_boxed_borrowed.lock().unwrap();
#[cfg(feature = "sync")]
let borrowed: Option<&Rc<Vec<T>>> = guard.as_ref();

#[cfg(not(feature = "sync"))]
let into_boxed = boxed.as_ref().clone();
#[cfg(not(feature = "sync"))]
Expand Down Expand Up @@ -940,28 +967,6 @@ where
}
}

#[cfg(feature = "sync")]
impl<T> Sequence<T>
where
T: DafnyType,
{
fn write_cache(boxed: &Rc<RefCell<Option<Rc<Vec<T>>>>>, array: Rc<Vec<T>>) {
let mut cache = boxed.lock().unwrap();
*cache = Some(array.clone());
}
}

#[cfg(not(feature = "sync"))]
impl<T> Sequence<T>
where
T: DafnyType,
{
fn write_cache(boxed: &Rc<RefCell<Option<Rc<Vec<T>>>>>, array: Rc<Vec<T>>) {
let mut cache = boxed.borrow_mut();
*cache = Some(array.clone());
}
}

pub struct SequenceIter<T: Clone> {
array: Rc<Vec<T>>,
index: SizeT,
Expand Down Expand Up @@ -2178,7 +2183,7 @@ impl DafnyPrint for () {
}
}

#[derive(Clone)]
#[derive(Clone, Copy)]
pub struct DafnyCharUTF16(pub u16);
pub type DafnyStringUTF16 = Sequence<DafnyCharUTF16>;

Expand Down Expand Up @@ -2254,7 +2259,7 @@ impl Sub<DafnyCharUTF16> for DafnyCharUTF16 {
}
}

#[derive(Clone)]
#[derive(Clone, Copy)]
pub struct DafnyChar(pub char);
pub type DafnyString = Sequence<DafnyChar>;

Expand Down Expand Up @@ -3200,18 +3205,19 @@ macro_rules! is_object {
#[macro_export]
macro_rules! cast_any {
($raw:expr) => {
$crate::Upcast::<dyn ::std::any::Any>::upcast($crate::read!($raw))
$crate::Upcast::<$crate::DynAny>::upcast($crate::read!($raw))
};
}
// cast_any_object is meant to be used on references only, to convert any references (classes or traits)*
// to an Any reference trait
#[macro_export]
macro_rules! cast_any_object {
($obj:expr) => {
$crate::UpcastObject::<dyn ::std::any::Any>::upcast($crate::md!($obj))
$crate::UpcastObject::<$crate::DynAny>::upcast($crate::md!($obj))
};
}


// When initializing an uninitialized field for the first time,
// we ensure we don't drop the previous content
// This is problematic if the same field is overwritten multiple times
Expand Down Expand Up @@ -3354,12 +3360,12 @@ impl<T: ?Sized> Ptr<T> {
}
}

impl<T: ?Sized + 'static + Upcast<dyn Any>> Ptr<T> {
impl<T: ?Sized + 'static + Upcast<DynAny>> Ptr<T> {
pub fn is_instance_of<U: 'static>(self) -> bool {
if self.is_null() {
false
} else {
read!(Upcast::<dyn Any>::upcast(read!(self)))
read!(Upcast::<DynAny>::upcast(read!(self)))
.downcast_ref::<U>()
.is_some()
}
Expand Down Expand Up @@ -3490,10 +3496,10 @@ impl<T: ?Sized> Object<T> {
self.0.is_none()
}
}
impl<T: ?Sized + 'static + UpcastObject<dyn Any>> Object<T> {
impl<T: ?Sized + 'static + UpcastObject<DynAny>> Object<T> {
pub fn is_instance_of<U: 'static>(self) -> bool {
// safety: Dafny won't call this function unless it can guarantee the object is still allocated
rd!(UpcastObject::<dyn Any>::upcast(rd!(self)))
rd!(UpcastObject::<DynAny>::upcast(rd!(self)))
.downcast_ref::<U>()
.is_some()
}
Expand All @@ -3517,14 +3523,14 @@ impl<T: ?Sized> Default for Object<T> {
}
}

impl<T: ?Sized + UpcastObject<dyn Any>> Debug for Object<T> {
impl<T: ?Sized + UpcastObject<DynAny>> Debug for Object<T> {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
self.fmt_print(f, false)
}
}
impl<T: ?Sized + UpcastObject<dyn Any>> DafnyPrint for Object<T> {
impl<T: ?Sized + UpcastObject<DynAny>> DafnyPrint for Object<T> {
fn fmt_print(&self, f: &mut Formatter<'_>, _in_seq: bool) -> std::fmt::Result {
let obj_any = UpcastObject::<dyn Any>::upcast(self.as_ref());
let obj_any = UpcastObject::<DynAny>::upcast(self.as_ref());
let option_string = obj_any.as_ref().downcast_ref::<String>();
match option_string {
Some(s) => write!(f, "{}", s),
Expand All @@ -3538,11 +3544,10 @@ impl<T: DafnyType> DafnyPrint for Object<[T]> {
write!(f, "<object>")
}
}

impl UpcastObject<dyn Any> for String {
fn upcast(&self) -> Object<dyn Any> {
impl UpcastObject<DynAny> for String {
fn upcast(&self) -> Object<DynAny> {
// SAFETY: RC was just created
unsafe { Object::from_rc(Rc::new(self.clone()) as Rc<dyn Any>) }
unsafe { Object::from_rc(Rc::new(self.clone()) as Rc<DynAny>) }
}
}

Expand Down Expand Up @@ -3630,9 +3635,18 @@ pub fn allocate_object<T>() -> Object<T> {
}

pub struct AllocationTracker {
allocations: Vec<Weak<dyn Any>>,
allocations: Vec<Weak<DynAny>>,
}

#[cfg(feature = "sync")]
pub fn allocate_object_track<T: 'static + Sync + Send>(allocation_tracker: &mut AllocationTracker) -> Object<T> {
let res = allocate_object::<T>();
allocation_tracker
.allocations
.push(Rc::<UnsafeCell<T>>::downgrade(&res.0.clone().unwrap()));
res
}
#[cfg(not(feature = "sync"))]
pub fn allocate_object_track<T: 'static>(allocation_tracker: &mut AllocationTracker) -> Object<T> {
let res = allocate_object::<T>();
allocation_tracker
Expand Down Expand Up @@ -3778,31 +3792,17 @@ macro_rules! refcount {
}

pub mod object {
use std::any::Any;

#[cfg(not(feature = "sync"))]
pub fn downcast<T: 'static>(_self: crate::Object<dyn Any>) -> crate::Object<T> {
unsafe {
crate::Object(Some(crate::rcmut::downcast::<T>(_self.0.unwrap()).unwrap()))
// Use unwrap_unchecked?
}
}
use crate::{Any, DynAny};

#[cfg(feature = "sync")]
pub fn downcast<T: 'static + Send + Sync>(
_self: crate::Object<dyn Any + Send + Sync>,
) -> crate::Object<T> {
unsafe {
crate::Object(Some(crate::rcmut::downcast::<T>(_self.0.unwrap()).unwrap()))
// Use unwrap_unchecked?
}
pub fn downcast<T: 'static>(_self: crate::Object<DynAny>) -> crate::Object<T> {
super::cast_object!(_self, T)
}

pub fn new<T>(val: T) -> crate::Object<T> {
crate::Object(Some(crate::rcmut::new(val)))
}
#[inline]
pub fn is<T: 'static + ::std::any::Any>(_self: crate::Object<dyn Any>) -> bool {
pub fn is<T: 'static + Any>(_self: crate::Object<DynAny>) -> bool {
is_object!(_self, T)
}
}
Expand Down Expand Up @@ -3875,16 +3875,16 @@ pub mod rcmut {

#[cfg(feature = "sync")]
pub unsafe fn downcast<T: 'static + Send + Sync>(
this: RcMut<dyn ::std::any::Any + Send + Sync>,
this: RcMut<crate::DynAny>,
) -> Option<RcMut<T>> {
let t: Rc<dyn ::std::any::Any + Send + Sync> = to_rc(this);
let t: Rc<crate::DynAny> = to_rc(this);
let t: Rc<T> = Rc::downcast::<T>(t).ok()?;
mem::transmute(t)
}

#[cfg(not(feature = "sync"))]
pub unsafe fn downcast<T: 'static>(this: RcMut<dyn ::std::any::Any>) -> Option<RcMut<T>> {
let t: Rc<dyn ::std::any::Any> = to_rc(this);
pub unsafe fn downcast<T: 'static>(this: RcMut<crate::DynAny>) -> Option<RcMut<T>> {
let t: Rc<crate::DynAny> = to_rc(this);
let t: Rc<T> = Rc::downcast::<T>(t).ok()?;
mem::transmute(t)
}
Expand Down
15 changes: 15 additions & 0 deletions releases/rust/db_esdk/dafny_runtime_rust/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ mod tests {
assert_eq!(*length, 6);
assert_eq!(unsafe { &*left.get() }.cardinality_usize(), 3);
// Test that boxed is None
#[cfg(not(feature = "sync"))]
assert!(boxed.as_ref().clone().borrow().as_ref().is_none());
#[cfg(feature = "sync")]
assert!(boxed.as_ref().clone().borrow().lock().unwrap().as_ref().is_none());
}
_ => panic!("This should never happen"),
}
Expand Down Expand Up @@ -1022,6 +1025,18 @@ mod tests {
assert_eq!(gtsgt._as_Datatype(), x);
assert_eq!(gtsgt._as_Datatype(), x);
}

#[test]
fn test_chars_copy() {
let c = DafnyChar('a');
let c2 = c;
let c3 = c;
assert_eq!(c3, c2);
let c = DafnyCharUTF16(213);
let c2 = c;
let c3 = c;
assert_eq!(c3, c2);
}
/*impl GeneralTrait for Rc<ADatatype> {
fn _clone(&self) -> Box<dyn GeneralTrait> {
Box::new(self.as_ref().clone())
Expand Down
2 changes: 1 addition & 1 deletion submodules/MaterialProviders
2 changes: 1 addition & 1 deletion submodules/smithy-dafny

0 comments on commit 82aefc7

Please sign in to comment.