Skip to content

Commit 5391c47

Browse files
committed
Add harp::once!
1 parent a930433 commit 5391c47

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

crates/harp/src/lib.rs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,9 @@ pub(crate) use harp::fixtures::r_task;
7373
pub use harp::object::list_get;
7474
pub use harp::object::list_poke;
7575
pub use harp::object::RObject;
76+
pub use harp::options::*;
7677
pub use harp::session::*;
7778
pub use harp::symbol::RSymbol;
78-
pub use harp::options::*;
7979
pub use harp::weak_ref::RWeakRef;
8080
pub use harp_macros::register;
8181

@@ -258,6 +258,28 @@ macro_rules! push_rds {
258258
};
259259
}
260260

261+
/// Allocate global variable for the R thread with lazy init
262+
///
263+
/// Uses thread_local storage to avoid issues with SEXP being non-Sync.
264+
/// Usage:
265+
///
266+
/// ```
267+
/// harp::once! {
268+
/// static NAME: Type = initialization_expression;
269+
/// }
270+
/// NAME.with(|x| foo(x));
271+
/// ```
272+
///
273+
/// Expands to a thread-local static initialized on first access in the thread.
274+
#[macro_export]
275+
macro_rules! once {
276+
( $( static $name:ident : $ty:ty = $init:expr );* $(;)? ) => {
277+
thread_local! {
278+
$( static $name: $ty = $init; )*
279+
}
280+
};
281+
}
282+
261283
#[cfg(test)]
262284
mod tests {
263285
use libr::*;

crates/harp/src/parser/srcref.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ impl SrcFile {
139139

140140
let inner: RObject = inner.into();
141141

142-
thread_local! {
142+
harp::once! {
143143
static CLASS: RObject = crate::CharacterVector::create(vec!["srcfile", "srcfilecopy"]).into();
144144
}
145145
CLASS.with(|c| inner.set_attribute("class", c.sexp));

0 commit comments

Comments
 (0)