2025-09-03 05:04:56 +09:00
|
|
|
/*!
|
|
|
|
|
* Host Handle Registry (global)
|
|
|
|
|
*
|
|
|
|
|
* 目的:
|
|
|
|
|
* - C ABI(TLV)でユーザー/内蔵Boxを渡すためのホスト管理ハンドルを提供。
|
|
|
|
|
* - u64ハンドルID → Arc<dyn NyashBox> をグローバルに保持し、VM/PluginHost/JITから参照可能にする。
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
use once_cell::sync::OnceCell;
|
|
|
|
|
use std::collections::HashMap;
|
2025-09-17 07:43:07 +09:00
|
|
|
use std::sync::{
|
|
|
|
|
atomic::{AtomicU64, Ordering},
|
|
|
|
|
Arc, RwLock,
|
|
|
|
|
};
|
2025-09-03 05:04:56 +09:00
|
|
|
|
|
|
|
|
use crate::box_trait::NyashBox;
|
|
|
|
|
|
|
|
|
|
struct Registry {
|
|
|
|
|
next: AtomicU64,
|
|
|
|
|
map: RwLock<HashMap<u64, Arc<dyn NyashBox>>>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Registry {
|
2025-09-17 07:43:07 +09:00
|
|
|
fn new() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
next: AtomicU64::new(1),
|
|
|
|
|
map: RwLock::new(HashMap::new()),
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-09-03 05:04:56 +09:00
|
|
|
fn alloc(&self, obj: Arc<dyn NyashBox>) -> u64 {
|
|
|
|
|
let h = self.next.fetch_add(1, Ordering::Relaxed);
|
2025-09-17 07:43:07 +09:00
|
|
|
if let Ok(mut m) = self.map.write() {
|
|
|
|
|
m.insert(h, obj);
|
|
|
|
|
}
|
2025-09-03 05:04:56 +09:00
|
|
|
h
|
|
|
|
|
}
|
|
|
|
|
fn get(&self, h: u64) -> Option<Arc<dyn NyashBox>> {
|
|
|
|
|
self.map.read().ok().and_then(|m| m.get(&h).cloned())
|
|
|
|
|
}
|
|
|
|
|
#[allow(dead_code)]
|
2025-09-17 07:43:07 +09:00
|
|
|
fn drop_handle(&self, h: u64) {
|
|
|
|
|
if let Ok(mut m) = self.map.write() {
|
|
|
|
|
m.remove(&h);
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-09-03 05:04:56 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static REG: OnceCell<Registry> = OnceCell::new();
|
2025-09-17 07:43:07 +09:00
|
|
|
fn reg() -> &'static Registry {
|
|
|
|
|
REG.get_or_init(Registry::new)
|
|
|
|
|
}
|
2025-09-03 05:04:56 +09:00
|
|
|
|
|
|
|
|
/// Box<dyn NyashBox> → HostHandle (u64)
|
2025-09-17 07:43:07 +09:00
|
|
|
pub fn to_handle_box(bx: Box<dyn NyashBox>) -> u64 {
|
|
|
|
|
reg().alloc(Arc::from(bx))
|
|
|
|
|
}
|
2025-09-03 05:04:56 +09:00
|
|
|
/// Arc<dyn NyashBox> → HostHandle (u64)
|
2025-09-17 07:43:07 +09:00
|
|
|
pub fn to_handle_arc(arc: Arc<dyn NyashBox>) -> u64 {
|
|
|
|
|
reg().alloc(arc)
|
|
|
|
|
}
|
2025-09-03 05:04:56 +09:00
|
|
|
/// HostHandle(u64) → Arc<dyn NyashBox>
|
2025-09-17 07:43:07 +09:00
|
|
|
pub fn get(h: u64) -> Option<Arc<dyn NyashBox>> {
|
|
|
|
|
reg().get(h)
|
|
|
|
|
}
|