Skip to main content

managed_exprs/
managed.rs

1use std::{collections::HashMap, sync::Mutex};
2
3use once_cell::sync::Lazy;
4
5use wolfram_library_link::{
6    self as wll,
7    expr::{expr, Expr, ExprKind},
8    managed::{Id, ManagedExpressionEvent},
9};
10
11wll::generate_loader![load_managed_exprs_functions];
12
13/// Storage for all instances of [`MyObject`] associated with managed expressions
14/// created using `CreateManagedLibraryExpression`.
15static INSTANCES: Lazy<Mutex<HashMap<Id, MyObject>>> =
16    Lazy::new(|| Mutex::new(HashMap::new()));
17
18#[derive(Clone)]
19struct MyObject {
20    value: String,
21}
22
23#[wll::init]
24fn init() {
25    // Register `manage_instance()` as the handler for managed expressions created using:
26    //
27    //     CreateManagedLibraryExpression["my_object", _]
28    wll::managed::register_library_expression_manager("my_object", manage_instance);
29}
30
31fn manage_instance(action: ManagedExpressionEvent) {
32    let mut instances = INSTANCES.lock().unwrap();
33
34    match action {
35        ManagedExpressionEvent::Create(id) => {
36            // Insert a new MyObject instance with some default values.
37            instances.insert(
38                id,
39                MyObject {
40                    value: String::from("default"),
41                },
42            );
43        },
44        ManagedExpressionEvent::Drop(id) => {
45            if let Some(obj) = instances.remove(&id) {
46                drop(obj);
47            }
48        },
49    }
50}
51
52/// Set the `MyObject.value` field for the specified instance ID.
53#[wll::export(wstp)]
54fn set_instance_value(args: Vec<Expr>) {
55    assert!(args.len() == 2, "set_instance_value: expected 2 arguments");
56
57    let id: u32 = unwrap_id_arg(&args[0]);
58    let value: String = match args[1].kind() {
59        ExprKind::String(str) => str.clone(),
60        _ => panic!("expected 2nd argument to be a String, got: {}", args[1]),
61    };
62
63    let mut instances = INSTANCES.lock().unwrap();
64
65    let instance: &mut MyObject =
66        instances.get_mut(&id).expect("instance does not exist");
67
68    instance.value = value;
69}
70
71/// Get the fields of the `MyObject` instance for the specified instance ID.
72#[wll::export(wstp)]
73fn get_instance_data(args: Vec<Expr>) -> Expr {
74    assert!(args.len() == 1, "get_instance_data: expected 1 argument");
75
76    let id: u32 = unwrap_id_arg(&args[0]);
77
78    let MyObject { value } = {
79        let instances = INSTANCES.lock().unwrap();
80
81        instances
82            .get(&id)
83            .cloned()
84            .expect("instance does not exist")
85    };
86
87    expr!({ "Value" -> value })
88}
89
90fn unwrap_id_arg(arg: &Expr) -> u32 {
91    match arg.kind() {
92        ExprKind::Integer(int) => u32::try_from(*int).expect("id overflows u32"),
93        _ => panic!("expected Integer instance ID argument, got: {}", arg),
94    }
95}