1
0

feat: update cdylib

This commit is contained in:
2026-05-15 16:00:54 +08:00
parent 5c182bb4d3
commit 684a24fcf8
5 changed files with 202 additions and 20 deletions

View File

@@ -25,34 +25,40 @@ pub struct ObjectPool<T> {
}
impl<T> ObjectPool<T> {
/// Create a new [ObjectPool].
pub fn new() -> Self {
Self {
objs: SlotMap::new(),
}
}
/// Convert [slotmap] crate's [DefaultKey] to our [Token].
fn key_to_token(key: &DefaultKey) -> Token {
key.data().as_ffi()
}
/// Convert our [Token] to [slotmap] crate's [DefaultKey].
fn token_to_key(token: Token) -> DefaultKey {
DefaultKey::from(KeyData::from_ffi(token))
}
/// Put given object into the pool and return its token.
///
/// The ownership of given object is transferred to the pool.
pub fn allocate(&mut self, value: T) -> Result<Token, Error> {
let key = self.objs.insert(value);
Ok(Self::key_to_token(&key))
}
/// Free the object in the pool corresponding to the given token.
pub fn free(&mut self, token: Token) -> Result<(), Error> {
let _ = self.pop(token)?;
Ok(())
}
pub fn clear(&mut self) -> () {
self.objs.clear();
}
/// Remove the object from the pool corresponding to the given token and return it.
///
/// The ownership of the object is transferred to the caller.
pub fn pop(&mut self, token: Token) -> Result<T, Error> {
match self.objs.remove(Self::token_to_key(token)) {
Some(obj) => Ok(obj),
@@ -60,12 +66,19 @@ impl<T> ObjectPool<T> {
}
}
/// Clear all objects in the pool.
pub fn clear(&mut self) -> () {
self.objs.clear();
}
/// Get a reference to the object in the pool corresponding to the given token.
pub fn get(&self, token: Token) -> Result<&T, Error> {
self.objs
.get(Self::token_to_key(token))
.ok_or(Error::NoSuchToken)
}
/// Get a mutable reference to the object in the pool corresponding to the given token.
pub fn get_mut(&mut self, token: Token) -> Result<&mut T, Error> {
self.objs
.get_mut(Self::token_to_key(token))