querent_synapse/cross/
clrepr.rs

1use crate::cross::clrepr_python::PythonRef;
2use std::collections::{
3	hash_map::{IntoIter, Iter, Keys},
4	HashMap,
5};
6
7#[derive(Clone)]
8pub struct CLReprObject(pub(crate) HashMap<String, CLRepr>);
9
10impl CLReprObject {
11	pub fn new() -> Self {
12		Self(HashMap::new())
13	}
14
15	pub fn get(&self, key: &str) -> Option<&CLRepr> {
16		self.0.get(key)
17	}
18
19	pub fn insert(&mut self, key: String, value: CLRepr) -> Option<CLRepr> {
20		self.0.insert(key, value)
21	}
22
23	pub fn into_iter(self) -> IntoIter<String, CLRepr> {
24		self.0.into_iter()
25	}
26
27	pub fn iter(&self) -> Iter<String, CLRepr> {
28		self.0.iter()
29	}
30
31	pub fn keys(&self) -> Keys<'_, String, CLRepr> {
32		self.0.keys()
33	}
34}
35
36impl std::fmt::Debug for CLReprObject {
37	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38		std::fmt::Debug::fmt(&self.0, f)
39	}
40}
41
42impl std::fmt::Display for CLReprObject {
43	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44		std::fmt::Debug::fmt(&self.0, f)
45	}
46}
47
48#[derive(Debug)]
49pub enum CLReprKind {
50	String,
51	Bool,
52	Float,
53	Int,
54	Tuple,
55	Array,
56	Object,
57	JsFunction,
58	PythonRef,
59	Null,
60}
61
62#[derive(Debug, Clone)]
63pub enum StringType {
64	Normal,
65	#[allow(unused)]
66	Safe,
67}
68
69/// Cross language representation is abstraction to transfer values between
70/// JavaScript and Python across Rust. Converting between two different languages requires
71/// to use Context which is available on the call (one for python and one for js), which result as
72/// blocking.
73#[derive(Debug, Clone)]
74pub enum CLRepr {
75	String(String, StringType),
76	Bool(bool),
77	Float(f64),
78	Int(i64),
79	#[allow(dead_code)]
80	Tuple(Vec<CLRepr>),
81	Array(Vec<CLRepr>),
82	Object(CLReprObject),
83	PythonRef(PythonRef),
84	Null,
85}
86
87impl std::fmt::Display for CLRepr {
88	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89		std::fmt::Display::fmt(&self, f)
90	}
91}
92
93impl CLRepr {
94	pub fn is_null(&self) -> bool {
95		matches!(self, CLRepr::Null)
96	}
97
98	pub fn downcast_to_object(self) -> CLReprObject {
99		match self {
100			CLRepr::Object(obj) => obj,
101			_ => panic!("downcast_to_object rejected, actual: {:?}", self.kind()),
102		}
103	}
104
105	#[allow(unused)]
106	pub fn kind(&self) -> CLReprKind {
107		match self {
108			CLRepr::String(_, _) => CLReprKind::String,
109			CLRepr::Bool(_) => CLReprKind::Bool,
110			CLRepr::Float(_) => CLReprKind::Float,
111			CLRepr::Int(_) => CLReprKind::Int,
112			CLRepr::Tuple(_) => CLReprKind::Tuple,
113			CLRepr::Array(_) => CLReprKind::Array,
114			CLRepr::Object(_) => CLReprKind::Object,
115			CLRepr::PythonRef(_) => CLReprKind::PythonRef,
116			CLRepr::Null => CLReprKind::Null,
117		}
118	}
119}