deimos-lang/src/vm/mem.rs
2024-12-01 12:02:52 -06:00

78 lines
3.0 KiB
Rust

use crate::vm::types::{DmImplementation, DmProperty, DmType};
use crate::vm::values::DmValue;
use std::alloc::Layout;
pub struct DmAllocObject<'a> {
pub data: *mut u8,
pub size: usize,
pub layout: Layout,
pub object_type: &'a DmImplementation<'a>,
}
pub unsafe fn get_property_value(dm_property: &DmProperty, dm_property_object: &DmAllocObject) -> DmValue {
let mut data: Vec<u8> = Vec::with_capacity(dm_property.dm_type.size_in_bytes());
for i in dm_property.data_offset..(dm_property.data_offset + dm_property.dm_type.size_in_bytes()) {
data.push(dm_property_object.data.offset(i as isize).read());
}
match dm_property.dm_type {
DmType::Byte => {
DmValue::DmByte(data[0])
}
DmType::Int => {
DmValue::DmInt(i32::from_ne_bytes(data[0..4].try_into().unwrap()))
}
DmType::Long => {
DmValue::DmLong(i64::from_ne_bytes(data[0..8].try_into().unwrap()))
}
DmType::Double => {
DmValue::DmDouble(f64::from_ne_bytes(data[0..8].try_into().unwrap()))
}
DmType::Boolean => {
DmValue::DmBoolean(i32::from_ne_bytes(data[0..4].try_into().unwrap()) != 0)
}
DmType::ObjectPointer(_) => {
DmValue::DmPointer(usize::from_ne_bytes(data[0..8].try_into().unwrap()) as *mut DmAllocObject)
}
DmType::ByteArray(_) => {
DmValue::DmByteArray(data)
}
DmType::IntArray(length) => {
let mut result = Vec::with_capacity(length);
for i in 0..length {
result.push(i32::from_ne_bytes(data[(i * 4)..(i * 4 + 4)].try_into().unwrap()));
}
DmValue::DmIntArray(result)
}
DmType::LongArray(length) => {
let mut result = Vec::with_capacity(length);
for i in 0..length {
result.push(i64::from_ne_bytes(data[i * 8..(i * 8 + 8)].try_into().unwrap()));
}
DmValue::DmLongArray(result)
}
DmType::DoubleArray(length) => {
let mut result = Vec::with_capacity(length);
for i in 0..length {
result.push(f64::from_ne_bytes(data[i * 8..(i * 8 + 8)].try_into().unwrap()));
}
DmValue::DmDoubleArray(result)
}
DmType::BooleanArray(length) => {
let mut result = Vec::with_capacity(length);
for i in 0..length {
result.push(i32::from_ne_bytes(data[(i * 4)..(i * 4 + 4)].try_into().unwrap()) != 0);
}
DmValue::DmBooleanArray(result)
}
DmType::ObjectPointerArray(length, _) => {
let mut result = Vec::with_capacity(length);
for i in 0..length {
result.push(usize::from_ne_bytes(data[(i * 8)..(i * 8 + 8)].try_into().unwrap()) as *mut DmAllocObject);
}
DmValue::DmPointerArray(result)
}
DmType::Unit => {
DmValue::DmUnit
}
}
}