use crate::HashMap;
use crate::base::{TypeCast, VmAnyType};
use crate::error::{ExecutionError, MemoryError, MemoryOutOfBoundError};
use crate::ext::*;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;
use async_lock::{Mutex, RwLock};
use core::marker::PhantomData;
use core::ops::Deref;
use std::ops::DerefMut;
use cfg_if::cfg_if;
pub type MemoryAllocator<'a> = Arc<Mutex<MemoryAllocation<'a>>>;
#[derive(Debug, Clone)]
pub enum Value<'a> {
Int(i64),
Float(f64),
Bool(bool),
None,
String(Box<str>),
Collection(Arc<RwLock<Vec<ValuePtr<'a>>>>),
Object(Arc<RwLock<HashMap<String, ValuePtr<'a>>>>),
#[doc(hidden)]
_Scope(PhantomData<&'a ()>),
#[doc(hidden)]
MemoryChunk(usize),
Error(ExecutionError),
DPtr(u64, usize),
FnPtrExternal(Box<str>, usize),
Any(Arc<RwLock<dyn VmAnyType>>)
}
impl PartialEq for Value<'_> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Value::Int(a), Value::Int(b)) => a == b,
(Value::Float(a), Value::Float(b)) => a == b,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::None, Value::None) => true,
(Value::String(a), Value::String(b)) => a == b,
(Value::Collection(a), Value::Collection(b)) => Arc::ptr_eq(a, b),
(Value::Object(a), Value::Object(b)) => Arc::ptr_eq(a, b),
(Value::MemoryChunk(a), Value::MemoryChunk(b)) => a == b,
(Value::Error(a), Value::Error(b)) => a == b,
(Value::DPtr(a, c), Value::DPtr(b, d)) => a == b && c == d,
_ => false,
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ValueKind {
Int,
Float,
Bool,
String,
None,
Collection,
Object,
Error,
DPtr,
FnPtrExternal,
#[doc(hidden)]
_Scope,
#[doc(hidden)]
MemoryChunk,
Any,
}
#[derive(Debug, Clone)]
pub enum OwnedValueInternal {
Int(i64),
Float(f64),
Bool(bool),
String(Box<str>),
None,
Collection(Vec<OwnedValue>),
Object(HashMap<String, OwnedValue>),
Error(ExecutionError),
DPtr(u64, usize),
FnPtrExternal(Box<str>, usize),
}
impl PartialEq for OwnedValueInternal {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(OwnedValueInternal::Int(a), OwnedValueInternal::Int(b)) => a == b,
(OwnedValueInternal::Float(a), OwnedValueInternal::Float(b)) => a == b,
(OwnedValueInternal::Bool(a), OwnedValueInternal::Bool(b)) => a == b,
(OwnedValueInternal::None, OwnedValueInternal::None) => true,
(OwnedValueInternal::String(a), OwnedValueInternal::String(b)) => a == b,
(OwnedValueInternal::Collection(a), OwnedValueInternal::Collection(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b))
}
(OwnedValueInternal::Object(a), OwnedValueInternal::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|bv| Arc::ptr_eq(v, bv)))
}
(OwnedValueInternal::Error(a), OwnedValueInternal::Error(b)) => a == b,
(OwnedValueInternal::DPtr(a, c), OwnedValueInternal::DPtr(b, d)) => a == b && c == d,
(OwnedValueInternal::FnPtrExternal(a, c), OwnedValueInternal::FnPtrExternal(b, d)) => {
a == b && c == d
}
_ => false,
}
}
}
impl OwnedValueInternal {
pub fn reset(&mut self) -> () {
*self = OwnedValueInternal::None;
}
}
pub type OwnedValue = Arc<RwLock<OwnedValueInternal>>;
impl Into<ValueKind> for OwnedValue {
fn into(self) -> ValueKind {
match self.read_arc_safe().deref() {
OwnedValueInternal::Int(_) => ValueKind::Int,
OwnedValueInternal::Float(_) => ValueKind::Float,
OwnedValueInternal::Bool(_) => ValueKind::Bool,
OwnedValueInternal::String(_) => ValueKind::String,
OwnedValueInternal::None => ValueKind::None,
OwnedValueInternal::Collection(_) => ValueKind::Collection,
OwnedValueInternal::Object(_) => ValueKind::Object,
OwnedValueInternal::Error(_) => ValueKind::Error,
OwnedValueInternal::DPtr(_, _) => ValueKind::DPtr,
OwnedValueInternal::FnPtrExternal(_, _) => ValueKind::FnPtrExternal,
}
}
}
impl<'a> Into<ValueKind> for &Value<'a> {
fn into(self) -> ValueKind {
match self {
Value::Int(_) => ValueKind::Int,
Value::Float(_) => ValueKind::Float,
Value::Bool(_) => ValueKind::Bool,
Value::String(_) => ValueKind::String,
Value::None => ValueKind::None,
Value::Collection(_) => ValueKind::Collection,
Value::Object(_) => ValueKind::Object,
Value::Error(_) => ValueKind::Error,
Value::DPtr(_, _) => ValueKind::DPtr,
Value::FnPtrExternal(_, _) => ValueKind::FnPtrExternal,
Value::_Scope(_) => ValueKind::_Scope,
Value::MemoryChunk(_) => ValueKind::MemoryChunk,
Value::Any(_) => ValueKind::Any,
}
}
}
#[derive(Debug)]
pub struct ValueInnerPtr<'a> {
pub inner: Value<'a>,
size: usize,
pub(self) alloc: Weak<Mutex<MemoryAllocation<'a>>>,
}
impl<'a> ValueInnerPtr<'a> {
pub fn get_alloc(&self) -> Option<MemoryAllocator<'a>> {
self.alloc.upgrade()
}
}
impl<'a> Deref for ValueInnerPtr<'a> {
type Target = Value<'a>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a> Into<ValueKind> for ValuePtr<'a> {
fn into(self) -> ValueKind {
(&self.read_arc_safe().inner).into()
}
}
impl<'a> ValueInnerPtr<'a> {
pub fn new(inner: Value<'a>, size: usize, alloc: &MemoryAllocator<'a>) -> Self {
Self {
inner,
size,
alloc: Arc::downgrade(alloc),
}
}
pub fn marked_size(&self) -> usize {
self.size
}
}
fn drop_value_iter(root: Value) {
let mut work = Vec::new();
work.push(root);
while let Some(value) = work.pop() {
let children: Option<Vec<ValuePtr>> = match value {
Value::Collection(arc) => Arc::try_unwrap(arc).ok().map(|lock| lock.into_inner()),
Value::Object(arc) => Arc::try_unwrap(arc)
.ok()
.map(|lock| lock.into_inner().into_values().collect()),
_ => None,
};
if let Some(children) = children {
for child in children {
if let Ok(lock) = Arc::try_unwrap(child) {
let mut inner = lock.into_inner();
work.push(core::mem::replace(&mut inner.inner, Value::None));
}
}
}
}
}
impl<'a> Drop for ValueInnerPtr<'a> {
fn drop(&mut self) {
let ptr = self.alloc.upgrade();
if let Some(ptr) = ptr {
if let Some(mut alloc) = ptr.try_lock() {
alloc._internal_dealloc(self.size);
}
}
drop_value_iter(core::mem::replace(&mut self.inner, Value::None));
}
}
pub type ValuePtr<'a> = Arc<RwLock<ValueInnerPtr<'a>>>;
enum OwnedValueConstruction {
List(Vec<usize>),
Dict(HashMap<String, usize>),
None,
}
fn to_owned_init_transform(ptr: &ValuePtr) -> OwnedValue {
Arc::new(RwLock::new(match &ptr.read_arc_safe().inner {
Value::Int(x) => OwnedValueInternal::Int(*x),
Value::Float(x) => OwnedValueInternal::Float(*x),
Value::Bool(x) => OwnedValueInternal::Bool(*x),
Value::None => OwnedValueInternal::None,
Value::String(x) => OwnedValueInternal::String(x.clone()),
Value::Collection(_) => OwnedValueInternal::Collection(Vec::new()),
Value::Object(_) => OwnedValueInternal::Object(HashMap::new()),
Value::_Scope(_) => OwnedValueInternal::None,
Value::MemoryChunk(_) => OwnedValueInternal::None,
Value::Error(e) => OwnedValueInternal::Error(e.clone()),
Value::DPtr(ptr, size) => OwnedValueInternal::DPtr(*ptr, *size),
Value::FnPtrExternal(name, size) => OwnedValueInternal::FnPtrExternal(name.clone(), *size),
Value::Any(_) => OwnedValueInternal::None,
}))
}
fn to_valur_ptr_uninit<'a>(value: &OwnedValue, alloc: &MemoryAllocator<'a>) -> Result<ValuePtr<'a>, MemoryError> {
alloc.alloc(match value.read_arc_safe().deref() {
OwnedValueInternal::Int(x) => Value::Int(*x),
OwnedValueInternal::Float(x) => Value::Float(*x),
OwnedValueInternal::Bool(b) => Value::Bool(*b),
OwnedValueInternal::String(s) => Value::String(s.clone()),
OwnedValueInternal::None => Value::None,
OwnedValueInternal::Collection(_) => Value::Collection(Arc::new(RwLock::new(vec![]))),
OwnedValueInternal::Object(_) => Value::Object(Arc::new(RwLock::new(HashMap::new()))),
OwnedValueInternal::Error(e) => Value::Error(e.clone()),
OwnedValueInternal::DPtr(loc, arg_len) => Value::DPtr(*loc, *arg_len),
OwnedValueInternal::FnPtrExternal(name, arg_len) => Value::FnPtrExternal(name.clone(), *arg_len),
})
}
fn to_empty_collection<'a, 'b>(ptr: &ValuePtr<'a>) -> Value<'b> {
match &ptr.read_arc_safe().inner {
Value::Int(x) => Value::Int(*x),
Value::Float(x) => Value::Float(*x),
Value::Bool(x) => Value::Bool(*x),
Value::None => Value::None,
Value::String(x) => Value::String(x.clone()),
Value::Collection(_) => Value::Collection(Arc::new(RwLock::new(Vec::new()))),
Value::Object(_) => Value::Object(Arc::new(RwLock::new(HashMap::new()))),
Value::_Scope(_x) => Value::_Scope(PhantomData),
Value::MemoryChunk(x) => Value::MemoryChunk(*x),
Value::Error(e) => Value::Error(e.clone()),
Value::DPtr(ptr, size) => Value::DPtr(*ptr, *size),
Value::FnPtrExternal(name, size) => Value::FnPtrExternal(name.clone(), *size),
Value::Any(v) => Value::Any(v.clone()),
}
}
pub fn get_all_owned_value(value: OwnedValue) -> Vec<OwnedValue> {
let mut pending = Vec::new();
let mut list_all = Vec::new();
pending.push(value.clone());
list_all.push(value.clone());
while let Some(value) = pending.pop() {
match value.read_arc_safe().deref() {
OwnedValueInternal::Collection(vec) => {
vec.iter().for_each(|item: &OwnedValue| {
if !list_all.iter().any(|x| Arc::ptr_eq(&item, &x)) {
pending.push(item.clone());
list_all.push(item.clone());
}
});
}
OwnedValueInternal::Object(map) => {
map.values().for_each(|item: &OwnedValue| {
if !list_all.iter().any(|x| Arc::ptr_eq(&item, &x)) {
pending.push(item.clone());
list_all.push(item.clone());
}
});
}
_ => {}
}
}
list_all
}
pub fn deconstruct_owned_value<'a>(value: OwnedValue, alloc: MemoryAllocator<'a>) -> Result<ValuePtr<'a>, MemoryError> {
let all = get_all_owned_value(value);
let mixed: Vec<(OwnedValue, ValuePtr<'a>)> = all
.iter()
.map(
|x| {
let ptr = to_valur_ptr_uninit(x, &alloc)?;
Ok((x.clone(), ptr))
}
).collect::<Result<_, MemoryError>>()?;
let mut immutable: Vec<ValuePtr<'a>> = mixed.iter().map(|x| x.1.clone()).collect::<Vec<_>>();
for (owned, ptr) in mixed.iter() {
let v = owned.read_arc_safe();
let get_idx = |x| all.iter().position(|y| Arc::ptr_eq(x, y));
match v.clone() {
OwnedValueInternal::Collection(c) => {
let idx = c.iter().map(get_idx).collect::<Option<Vec<_>>>().expect("All element should exist in all");
let mut vec = ptr.as_collections().unwrap().write_arc_safe();
idx.into_iter().for_each(|i|
vec.push(immutable.get(i).expect("Index should exist in immutable as it is collected from get_idx").clone())
);
},
OwnedValueInternal::Object(o) => {
let idx_map = o.iter()
.map(|(k, v)| get_idx(v).map(|v| (k.clone(), v)))
.collect::<Option<HashMap<String, usize>>>().expect("All element should exist in all");
let mut map = ptr.as_object().unwrap().write_arc_safe();
idx_map.into_iter().for_each(|(k, i)|
{
let ptr: ValuePtr<'a> = immutable.get(i).expect("Index should exist in immutable as it is collected from get_idx").clone();
map.insert(k, ptr);
()
}
);
},
_ => {}
}
};
return Ok(immutable.swap_remove(0));
}
#[derive(Debug)]
pub struct MemoryAllocation<'a> {
curr: usize,
pub max: usize,
_phantom: PhantomData<&'a ()>,
_obj: Vec<Weak<RwLock<ValueInnerPtr<'a>>>>,
_obj_watermark: usize,
}
impl<'a> MemoryAllocation<'a> {
pub fn new(max: usize) -> MemoryAllocation<'a> {
Self {
curr: 0,
max,
_phantom: Default::default(),
_obj: Vec::new(),
_obj_watermark: 16,
}
}
pub fn check_alloc(&self, size: usize) -> bool {
if size > self.max {
return false;
};
let req_curr = self.max - size;
req_curr >= self.curr
}
pub fn check_alloc_err(&self, size: usize) -> Result<(), MemoryError> {
if self.check_alloc(size) {
return Ok(());
}
Err(MemoryError)
}
pub(self) fn _internal_alloc(&mut self, size: usize) -> Result<(), MemoryError> {
if self.check_alloc(size) {
self.curr += size;
return Ok(());
}
Err(MemoryError)
}
pub(self) fn _internal_dealloc(&mut self, size: usize) -> () {
debug_assert!(
size <= self.curr,
"memory accounting desync: dealloc of {} exceeds tracked {}",
size,
self.curr
);
self.curr = self.curr.saturating_sub(size);
}
pub(self) fn _get_obj_unchecked(&self, idx: usize) -> Weak<RwLock<ValueInnerPtr<'a>>> {
self._obj[idx].clone()
}
pub fn gc_weak(&mut self) -> () {
self._obj.retain(|obj| obj.upgrade().is_some());
}
pub fn obj_count(&self) -> usize {
self._obj.len()
}
pub(self) fn _index_obj(&mut self, obj: &ValuePtr<'a>) -> () {
if self._obj.len() >= self._obj_watermark {
self.gc_weak();
self._obj_watermark = self._obj.len() * 2 + 16;
}
self._obj.push(Arc::downgrade(obj));
}
pub fn curr(&self) -> usize {
self.curr
}
pub fn get_idx_ref(&self, value: &ValuePtr<'a>) -> Result<usize, MemoryOutOfBoundError> {
self._obj
.iter()
.position(|obj| {
if let Some(ptr) = obj.upgrade() {
Arc::ptr_eq(&ptr, value)
} else {
false
}
})
.ok_or(MemoryOutOfBoundError)
}
pub fn get_eq_obj(&self, value: &ValuePtr<'a>) -> Result<ValuePtr<'a>, MemoryOutOfBoundError> {
let idx = self.get_idx_ref(&value)?;
Ok(self._obj.get(idx).ok_or(MemoryOutOfBoundError)?.upgrade().ok_or(MemoryOutOfBoundError)?)
}
fn get_obj_construction(
&self,
value: &ValuePtr<'a>,
) -> Result<OwnedValueConstruction, MemoryOutOfBoundError> {
Ok(match value.read_arc_safe().clone() {
Value::Collection(collect) => OwnedValueConstruction::List(
collect
.read_arc_safe()
.iter()
.map(|item| self.get_idx_ref(item))
.collect::<Result<_, MemoryOutOfBoundError>>()?,
),
Value::Object(obj) => OwnedValueConstruction::Dict(
obj.read_arc_safe()
.iter()
.map(|(k, v)| Ok((k.clone(), self.get_idx_ref(v)?)))
.collect::<Result<_, MemoryOutOfBoundError>>()?,
),
_ => OwnedValueConstruction::None,
})
}
pub fn get_owned(&mut self, value: &ValuePtr<'a>) -> Result<OwnedValue, MemoryOutOfBoundError> {
self.gc_weak();
let idx_self = self.get_idx_ref(value)?;
let mut non_handled: Vec<usize> = Vec::new();
let mut obj_map: HashMap<usize, (OwnedValue, OwnedValueConstruction)> = HashMap::new();
non_handled.push(idx_self);
while let Some(idx_ref) = non_handled.pop() {
let value_idx = self._obj[idx_ref].upgrade().ok_or(MemoryOutOfBoundError)?;
let construction = self.get_obj_construction(&value_idx)?;
match &construction {
OwnedValueConstruction::List(list) => {
list.iter().for_each(|item| {
if !non_handled.contains(item) && !obj_map.contains_key(item) {
non_handled.push(*item);
}
});
}
OwnedValueConstruction::Dict(map) => {
map.values().for_each(|item| {
if !non_handled.contains(item) && !obj_map.contains_key(item) {
non_handled.push(*item);
}
});
}
OwnedValueConstruction::None => {}
};
obj_map.insert(idx_ref, (to_owned_init_transform(&value_idx), construction));
}
let obj_view_map: HashMap<usize, OwnedValue> = obj_map
.iter()
.map(|(k, v)| (*k, Arc::clone(&v.0)))
.collect();
for (_, (ptr, construction)) in obj_map.iter_mut() {
match construction {
OwnedValueConstruction::List(list) => {
if let OwnedValueInternal::Collection(vec) = ptr.write_arc_safe().deref_mut() {
list.iter().for_each(|item| {
vec.push(obj_view_map[item].clone());
})
}
}
OwnedValueConstruction::Dict(map) => {
if let OwnedValueInternal::Object(obj) = ptr.write_arc_safe().deref_mut() {
map.iter_mut().for_each(|(k, v)| {
obj.insert(k.clone(), obj_view_map[v].clone());
});
}
}
_ => {}
}
}
Ok(Arc::clone(&obj_view_map[&idx_self]))
}
pub fn fork<'b>(&mut self) -> (MemoryAllocator<'b>, Vec<ValuePtr<'b>>) {
self.gc_weak();
let mut vec_items: Vec<ValuePtr<'b>> = Vec::new();
let max: usize = self.max.clone();
let inner: MemoryAllocation<'b> = MemoryAllocation::new(max);
let new_alloc: MemoryAllocator<'b> = Arc::new(Mutex::new(inner));
for obj in self._obj.iter() {
let ptr = obj
.upgrade()
.expect("Object should not be dropped inside this scope with gc_weak");
vec_items.push(
new_alloc
.alloc(to_empty_collection(&ptr))
.expect("Allocation should be possible as have been previously allocated"),
);
}
for (idx, obj) in self._obj.iter().enumerate() {
match self
.get_obj_construction(
&obj.upgrade()
.expect("Object should not be dropped inside this scope with gc_weak"),
)
.expect("Memory allocation should be within the allocator")
{
OwnedValueConstruction::List(vec) => vec_items[idx]
.as_collections()
.unwrap()
.write_arc_safe()
.extend(vec.iter().map(|x| vec_items[*x].clone())),
OwnedValueConstruction::Dict(map) => vec_items[idx]
.as_object()
.unwrap()
.write_arc_safe()
.extend(map.iter().map(|(k, v)| (k.clone(), vec_items[*v].clone()))),
OwnedValueConstruction::None => {}
}
}
for obj in vec_items.iter() {
let _ = new_alloc.change_alloc(obj);
}
(new_alloc, vec_items)
}
}
impl Drop for MemoryAllocation<'_> {
fn drop(&mut self) {
self.gc_weak();
self._obj.iter().for_each(|obj| {
if let Some(ptr) = obj.upgrade() {
if let Some(mut inner) = ptr.try_write() {
inner.inner = Value::None;
}
}
});
}
}
pub trait GetSize {
fn get_size(&self) -> usize;
}
pub trait Allocator {
type Input: GetSize;
type Output;
fn alloc(&self, input: Self::Input) -> Result<Self::Output, MemoryError>;
fn change_alloc(&self, data: &Self::Output) -> Result<(), MemoryError>;
fn curr(&self) -> usize;
fn max(&self) -> usize;
}
const NODE_OVERHEAD: usize = 32;
const CONTAINER_OVERHEAD: usize = 32;
impl<'a> GetSize for Value<'a> {
fn get_size(&self) -> usize {
match self {
Value::Int(_i) => 8 + NODE_OVERHEAD,
Value::Float(_f) => 8 + NODE_OVERHEAD,
Value::Bool(_b) => 1 + NODE_OVERHEAD,
Value::Collection(c) => {
c.read_arc_safe().len() * 8 + 16 + NODE_OVERHEAD + CONTAINER_OVERHEAD
}
Value::Object(d) => {
let map = d.read_arc_safe();
map.len() * 8
+ map.keys().map(|k| k.len()).sum::<usize>()
+ 16
+ NODE_OVERHEAD
+ CONTAINER_OVERHEAD
}
Value::String(s) => s.len() + NODE_OVERHEAD,
Value::None => 1 + NODE_OVERHEAD,
Value::_Scope(_) => 1 + NODE_OVERHEAD,
Value::MemoryChunk(size) => *size,
Value::Error(_) => 1024,
Value::DPtr(_, _) => 16 + NODE_OVERHEAD,
Value::FnPtrExternal(f, _) => f.len() + NODE_OVERHEAD,
Value::Any(v) => (move || {
cfg_if! {
if #[cfg(all(feature = "std", not(target_family = "wasm")))] {
v.read_blocking().get_size()
} else {
v.try_read().expect("Deadlock!").get_size()
}
}
})() + NODE_OVERHEAD,
}
}
}
pub trait MemoryAllocatorConstructor<'a> {
fn construct(max: usize) -> MemoryAllocator<'a> {
Arc::new(Mutex::new(MemoryAllocation::new(max)))
}
}
impl<'a> MemoryAllocatorConstructor<'a> for MemoryAllocator<'a> {}
impl<'a> Allocator for MemoryAllocator<'a> {
type Input = Value<'a>;
type Output = Arc<RwLock<ValueInnerPtr<'a>>>;
fn alloc(&self, input: Self::Input) -> Result<Self::Output, MemoryError> {
let size = input.get_size();
self.lock_arc_safe()._internal_alloc(size)?;
let obj = ValueInnerPtr::new(input, size, self);
let ptr = Arc::new(RwLock::new(obj));
self.lock_arc_safe()._index_obj(&ptr);
Ok(ptr)
}
fn change_alloc(&self, data: &Self::Output) -> Result<(), MemoryError> {
let marked_size = data.read_arc_safe().marked_size();
let new_size = data.read_arc_safe().get_size();
if marked_size == new_size {
return Ok(());
}
if marked_size < new_size {
self.lock_arc_safe()
._internal_alloc(new_size - marked_size)?;
} else if marked_size > new_size {
self.lock_arc_safe()
._internal_dealloc(marked_size - new_size);
}
data.write_arc_safe().size = new_size;
Ok(())
}
fn curr(&self) -> usize {
self.lock_arc_safe().curr
}
fn max(&self) -> usize {
self.lock_arc_safe().max
}
}