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, ExprKind, Symbol},
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(id, MyObject {
38                value: String::from("default"),
39            });
40        },
41        ManagedExpressionEvent::Drop(id) => {
42            if let Some(obj) = instances.remove(&id) {
43                drop(obj);
44            }
45        },
46    }
47}
48
49/// Set the `MyObject.value` field for the specified instance ID.
50#[wll::export(wstp)]
51fn set_instance_value(args: Vec<Expr>) {
52    assert!(args.len() == 2, "set_instance_value: expected 2 arguments");
53
54    let id: u32 = unwrap_id_arg(&args[0]);
55    let value: String = match args[1].kind() {
56        ExprKind::String(str) => str.clone(),
57        _ => panic!("expected 2nd argument to be a String, got: {}", args[1]),
58    };
59
60    let mut instances = INSTANCES.lock().unwrap();
61
62    let instance: &mut MyObject =
63        instances.get_mut(&id).expect("instance does not exist");
64
65    instance.value = value;
66}
67
68/// Get the fields of the `MyObject` instance for the specified instance ID.
69#[wll::export(wstp)]
70fn get_instance_data(args: Vec<Expr>) -> Expr {
71    assert!(args.len() == 1, "get_instance_data: expected 1 argument");
72
73    let id: u32 = unwrap_id_arg(&args[0]);
74
75    let MyObject { value } = {
76        let instances = INSTANCES.lock().unwrap();
77
78        instances
79            .get(&id)
80            .cloned()
81            .expect("instance does not exist")
82    };
83
84    Expr::normal(Symbol::new("System`Association"), vec![Expr::normal(
85        Symbol::new("System`Rule"),
86        vec![Expr::string("Value"), Expr::string(value)],
87    )])
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}