Skip to content

Commit

Permalink
feat(schema): remove need for user crate to depend on parking_lot
Browse files Browse the repository at this point in the history
  • Loading branch information
nelson137 committed Nov 19, 2024
1 parent add30b6 commit b1aa6d0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
16 changes: 5 additions & 11 deletions framework_crates/bones_schema/macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,17 +282,16 @@ pub fn derive_has_schema(input: TokenStream) -> TokenStream {

let register_schema = if input.generic_params().is_some() {
quote! {
static S: OnceLock<RwLock<HashMap<TypeId, &'static #schema_mod::Schema>>> = OnceLock::new();
let schema = {
S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.read()
.get(&TypeId::of::<Self>())
.copied()
};
schema.unwrap_or_else(|| {
let schema = compute_schema();

S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.write()
.insert(TypeId::of::<Self>(), schema);

Expand Down Expand Up @@ -395,27 +394,22 @@ pub fn derive_has_schema(input: TokenStream) -> TokenStream {
quote! {
unsafe impl<#impl_bounds> #schema_mod::HasSchema for #name<#struct_params> {
fn schema() -> &'static #schema_mod::Schema {
use ::std::sync::OnceLock;
use ::std::any::TypeId;
use bones_utils::HashMap;
use parking_lot::RwLock;
static S: OnceLock<RwLock<HashMap<TypeId, &'static #schema_mod::Schema>>> = OnceLock::new();
use ::std::{any::TypeId, sync::OnceLock};
let schema = {
S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.read()
.get(&TypeId::of::<Self>())
.copied()
};
schema.unwrap_or_else(|| {
let schema = #schema_register;

S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.write()
.insert(TypeId::of::<Self>(), schema);

schema
})

}
}
}
Expand Down
13 changes: 11 additions & 2 deletions framework_crates/bones_schema/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@

use std::{
alloc::Layout,
sync::atomic::{AtomicU32, Ordering::SeqCst},
any::TypeId,
sync::{
atomic::{AtomicU32, Ordering::SeqCst},
LazyLock,
},
};

use append_only_vec::AppendOnlyVec;
use bones_utils::Deref;
use bones_utils::{Deref, HashMap};
use parking_lot::RwLock;

use crate::prelude::*;

Expand Down Expand Up @@ -143,6 +148,10 @@ pub static SCHEMA_REGISTRY: SchemaRegistry = SchemaRegistry {
schemas: AppendOnlyVec::new(),
};

#[doc(hidden)]
pub static GENERIC_SCHEMA_CACHE: LazyLock<RwLock<HashMap<TypeId, &'static Schema>>> =
LazyLock::new(Default::default);

#[cfg(test)]
mod test {
use bones_utils::default;
Expand Down

0 comments on commit b1aa6d0

Please sign in to comment.