rust_css_parser/bindings/
mod.rs1pub mod api;
14pub mod value;
15
16use crate::ast::arena::AstArena;
17use crate::host::{Host, HostError, HostValue};
18use std::cell::RefCell;
19use std::rc::Rc;
20use value::Val;
21
22thread_local! {
23 pub static EXCHANGE: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(1 << 16));
25 static ARENAS: RefCell<Vec<Option<Rc<AstArena>>>> = const { RefCell::new(Vec::new()) };
27 static HOST_CALL: RefCell<Option<fn(&[u8]) -> Vec<u8>>> = const { RefCell::new(None) };
29}
30
31pub fn write_exchange(bytes: &[u8]) {
34 EXCHANGE.with(|e| {
35 let mut buffer = e.borrow_mut();
36 if buffer.len() < bytes.len() {
37 buffer.resize(bytes.len(), 0);
38 }
39 buffer[..bytes.len()].copy_from_slice(bytes);
40 });
41}
42
43thread_local! {
44 static OUTPUTS: RefCell<Vec<Option<Vec<u8>>>> = const { RefCell::new(Vec::new()) };
46}
47
48pub fn give_output(mut bytes: Vec<u8>) -> Val {
51 let len = bytes.len() as u32;
52 bytes.resize(bytes.capacity(), 0);
54 OUTPUTS.with(|o| {
55 let mut outputs = o.borrow_mut();
56 let entry = Some(bytes);
57 let id = match outputs.iter().position(|x| x.is_none()) {
58 Some(i) => {
59 outputs[i] = entry;
60 i + 1
61 }
62 None => {
63 outputs.push(entry);
64 outputs.len()
65 }
66 };
67 Val::Output(id as u32, len)
68 })
69}
70
71pub fn take_output(id: u32) -> Option<Vec<u8>> {
73 OUTPUTS.with(|o| o.borrow_mut().get_mut((id as usize).wrapping_sub(1)).and_then(|x| x.take()))
74}
75
76pub fn set_host_call(f: fn(&[u8]) -> Vec<u8>) {
78 HOST_CALL.with(|h| *h.borrow_mut() = Some(f));
79}
80
81pub fn arena_handle(arena: &Rc<AstArena>) -> u32 {
83 ARENAS.with(|a| {
84 let mut arenas = a.borrow_mut();
85 if let Some(index) = arenas.iter().position(|x| x.as_ref().is_some_and(|x| Rc::ptr_eq(x, arena))) {
86 return index as u32 + 1;
87 }
88 if let Some(index) = arenas.iter().position(|x| x.is_none()) {
89 arenas[index] = Some(arena.clone());
90 return index as u32 + 1;
91 }
92 arenas.push(Some(arena.clone()));
93 arenas.len() as u32
94 })
95}
96
97pub fn arena_of(handle: u32) -> Result<Rc<AstArena>, HostError> {
99 ARENAS.with(|a| a.borrow().get((handle as usize).wrapping_sub(1)).cloned().flatten()).ok_or_else(|| HostError(format!("invalid arena handle {}", handle)))
100}
101
102pub fn free_arena(handle: u32) {
104 ARENAS.with(|a| {
105 if let Some(slot) = a.borrow_mut().get_mut((handle as usize).wrapping_sub(1)) {
106 *slot = None;
107 }
108 });
109}
110
111pub fn call_js(callback: u32, arena: Option<&Rc<AstArena>>, args: Vec<Val>) -> Result<Val, HostError> {
113 let mut request = Vec::with_capacity(64);
114 let mut list = vec![Val::Num(callback as f64), arena.map_or(Val::Undefined, |a| Val::Arena(arena_handle(a)))];
115 list.extend(args);
116 Val::Array(list).encode(&mut request);
117 let f = HOST_CALL.with(|h| *h.borrow()).ok_or_else(|| HostError("no javascript host".into()))?;
118 let response = f(&request);
119 match Val::decode(&response, &mut 0) {
120 Val::Error(message) => Err(HostError(message.to_string())),
121 value => Ok(value),
122 }
123}
124
125pub struct JsHost;
127
128impl Host for JsHost {
129 fn call(&self, callback: u32, arena: Option<&Rc<AstArena>>, args: Vec<HostValue>) -> Result<HostValue, HostError> {
130 let handle = arena.map_or(0, arena_handle);
131 let args = args.iter().map(|a| Val::from_host(a, handle)).collect();
132 call_js(callback, arena, args).map(|v| v.to_host())
133 }
134
135 fn arena(&self, handle: u32) -> Option<Rc<AstArena>> {
136 arena_of(handle).ok()
137 }
138}
139
140pub fn call(length: usize) -> usize {
143 let request = EXCHANGE.with(|e| {
144 let buffer = e.borrow();
145 Val::decode(&buffer[..length.min(buffer.len())], &mut 0)
146 });
147 let (method, args) = match request {
148 Val::Array(mut items) if !items.is_empty() => {
149 let method = items.remove(0);
150 (method.as_str().unwrap_or("").to_string(), items)
151 }
152 _ => (String::new(), Vec::new()),
153 };
154 let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| api::dispatch(&method, args))) {
155 Ok(Ok(value)) => value,
156 Ok(Err(error)) => Val::Error(Rc::from(error.0.as_str())),
157 Err(panic) => {
158 let message = panic.downcast_ref::<String>().cloned().or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default();
159 Val::Error(Rc::from(format!("internal error in {}: {}", method, message).as_str()))
160 }
161 };
162 let mut out = Vec::with_capacity(256);
163 result.encode(&mut out);
164 write_exchange(&out);
165 out.len()
166}