use std::sync::Arc;
pub struct Expose<M, T> {
name: &'static str,
get: Arc<dyn Fn(&M) -> T + Send + Sync>,
}
impl<M: 'static, T: 'static> Expose<M, T> {
pub fn new(name: &'static str, get: impl Fn(&M) -> T + Send + Sync + 'static) -> Self {
Self {
name,
get: Arc::new(get),
}
}
pub(crate) fn into_parts(self) -> (&'static str, Arc<dyn Fn(&M) -> T + Send + Sync>) {
(self.name, self.get)
}
}
impl<M, T> std::fmt::Debug for Expose<M, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Expose").field("name", &self.name).finish()
}
}
#[doc(hidden)]
#[must_use]
pub fn __expose_name(path: &'static str) -> &'static str {
fn is_ident_byte(byte: u8) -> bool {
byte == b'_' || byte.is_ascii_alphanumeric()
}
let bytes = path.as_bytes();
let mut end = bytes.len();
while end > 0 && !is_ident_byte(bytes[end - 1]) {
end -= 1;
}
let mut start = end;
while start > 0 && is_ident_byte(bytes[start - 1]) {
start -= 1;
}
&path[start..end]
}
#[macro_export]
macro_rules! expose {
($first:ident $(:: $rest:ident)+ as $name:literal) => {
$crate::Expose::new(
$name,
|__model: &$first| __model $(. $rest)+ .clone(),
)
};
($first:ident $(:: $rest:ident)+) => {
$crate::Expose::new(
$crate::__expose_name(concat!(
stringify!($first)
$(, "::", stringify!($rest))*
)),
|__model: &$first| __model $(. $rest)+ .clone(),
)
};
}