Skip to main content

runmat_core/
value_metadata.rs

1use runmat_builtins::{LogicalArray, NumericDType, Value};
2
3/// MATLAB-style class name for a runtime value.
4pub fn matlab_class_name(value: &Value) -> String {
5    match value {
6        Value::Num(_) | Value::Tensor(_) | Value::ComplexTensor(_) | Value::Complex(_, _) => {
7            "double".to_string()
8        }
9        Value::Int(iv) => iv.class_name().to_string(),
10        Value::Bool(_) | Value::LogicalArray(_) => "logical".to_string(),
11        Value::String(_) | Value::StringArray(_) => "string".to_string(),
12        Value::CharArray(_) => "char".to_string(),
13        Value::Cell(_) => "cell".to_string(),
14        Value::Struct(_) => "struct".to_string(),
15        Value::GpuTensor(_) => "gpuArray".to_string(),
16        Value::FunctionHandle(_) | Value::Closure(_) => "function_handle".to_string(),
17        Value::HandleObject(handle) => {
18            if handle.class_name.is_empty() {
19                "handle".to_string()
20            } else {
21                handle.class_name.clone()
22            }
23        }
24        Value::Listener(_) => "event.listener".to_string(),
25        // Internal destructuring helper; shouldn't surface in user-facing values,
26        // but handle it defensively for completeness.
27        Value::OutputList(_) => "OutputList".to_string(),
28        Value::Object(obj) => obj.class_name.clone(),
29        Value::ClassRef(_) => "meta.class".to_string(),
30        Value::MException(_) => "MException".to_string(),
31    }
32}
33
34/// Returns the MATLAB-style shape for the provided value when applicable.
35pub fn value_shape(value: &Value) -> Option<Vec<usize>> {
36    match value {
37        Value::Num(_) | Value::Int(_) | Value::Bool(_) | Value::Complex(_, _) => Some(vec![1, 1]),
38        Value::LogicalArray(arr) => Some(arr.shape.clone()),
39        Value::StringArray(sa) => Some(sa.shape.clone()),
40        Value::String(s) => Some(vec![1, s.chars().count()]),
41        Value::CharArray(ca) => Some(vec![ca.rows, ca.cols]),
42        Value::Tensor(t) => Some(t.shape.clone()),
43        Value::ComplexTensor(t) => Some(t.shape.clone()),
44        Value::Cell(ca) => Some(ca.shape.clone()),
45        Value::GpuTensor(handle) => Some(handle.shape.clone()),
46        Value::Object(obj) if obj.is_class("datetime") => match obj.properties.get("__serial") {
47            Some(Value::Tensor(tensor)) => Some(tensor.shape.clone()),
48            Some(Value::Num(_)) => Some(vec![1, 1]),
49            _ => None,
50        },
51        _ => None,
52    }
53}
54
55/// Returns a MATLAB dtype label for numeric values when available.
56pub fn numeric_dtype_label(value: &Value) -> Option<&'static str> {
57    match value {
58        Value::Num(_) | Value::Complex(_, _) => Some("double"),
59        Value::Tensor(t) => Some(match t.dtype {
60            NumericDType::F32 => "single",
61            NumericDType::F64 => "double",
62        }),
63        Value::LogicalArray(_) => Some("logical"),
64        Value::Int(iv) => Some(iv.class_name()),
65        _ => None,
66    }
67}
68
69/// Rough estimate of the in-memory footprint for the provided value, in bytes.
70pub fn approximate_size_bytes(value: &Value) -> Option<u64> {
71    Some(match value {
72        Value::Num(_) | Value::Int(_) | Value::Complex(_, _) => 8,
73        Value::Bool(_) => 1,
74        Value::LogicalArray(arr) => arr.data.len() as u64,
75        Value::Tensor(t) => (t.data.len() * 8) as u64,
76        Value::ComplexTensor(t) => (t.data.len() * 16) as u64,
77        Value::String(s) => s.len() as u64,
78        Value::StringArray(sa) => sa.data.iter().map(|s| s.len() as u64).sum(),
79        Value::CharArray(ca) => (ca.rows * ca.cols) as u64,
80        _ => return None,
81    })
82}
83
84/// Produce a numeric preview (up to `limit` elements) for scalars and dense arrays.
85pub fn preview_numeric_values(value: &Value, limit: usize) -> Option<(Vec<f64>, bool)> {
86    match value {
87        Value::Num(n) => Some((vec![*n], false)),
88        Value::Int(iv) => Some((vec![iv.to_f64()], false)),
89        Value::Bool(flag) => Some((vec![if *flag { 1.0 } else { 0.0 }], false)),
90        Value::Tensor(t) => Some(preview_f64_slice(&t.data, limit)),
91        Value::LogicalArray(arr) => Some(preview_logical_slice(arr, limit)),
92        Value::StringArray(_) | Value::String(_) | Value::CharArray(_) => None,
93        Value::ComplexTensor(_) | Value::Complex(_, _) => None,
94        Value::Cell(_)
95        | Value::Struct(_)
96        | Value::Object(_)
97        | Value::HandleObject(_)
98        | Value::Listener(_)
99        | Value::OutputList(_)
100        | Value::FunctionHandle(_)
101        | Value::Closure(_)
102        | Value::ClassRef(_)
103        | Value::MException(_)
104        | Value::GpuTensor(_) => None,
105    }
106}
107
108fn preview_f64_slice(data: &[f64], limit: usize) -> (Vec<f64>, bool) {
109    if data.len() > limit {
110        (data[..limit].to_vec(), true)
111    } else {
112        (data.to_vec(), false)
113    }
114}
115
116fn preview_logical_slice(arr: &LogicalArray, limit: usize) -> (Vec<f64>, bool) {
117    let truncated = arr.data.len() > limit;
118    let mut preview = Vec::with_capacity(arr.data.len().min(limit));
119    for value in arr.data.iter().take(limit) {
120        preview.push(if *value == 0 { 0.0 } else { 1.0 });
121    }
122    (preview, truncated)
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use runmat_builtins::{ObjectInstance, Tensor};
129
130    #[test]
131    fn datetime_object_shape_comes_from_internal_serial_tensor() {
132        let mut object = ObjectInstance::new("datetime".to_string());
133        object.properties.insert(
134            "__serial".to_string(),
135            Value::Tensor(Tensor::new(vec![739351.0, 739352.0], vec![2, 1]).expect("tensor")),
136        );
137
138        assert_eq!(value_shape(&Value::Object(object)), Some(vec![2, 1]));
139    }
140}