From 986d624b3a19df757b1ad05576cc0fb1d78dc2d4 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Tue, 20 Aug 2024 12:56:54 +0200 Subject: Share allocations for singletons (#4794) --- crates/typst-utils/src/lib.rs | 3 +++ crates/typst-utils/src/macros.rs | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) (limited to 'crates/typst-utils/src') diff --git a/crates/typst-utils/src/lib.rs b/crates/typst-utils/src/lib.rs index 754fc70d..4d5f8e0c 100644 --- a/crates/typst-utils/src/lib.rs +++ b/crates/typst-utils/src/lib.rs @@ -25,6 +25,9 @@ use std::sync::Arc; use siphasher::sip128::{Hasher128, SipHasher13}; +#[doc(hidden)] +pub use once_cell; + /// Turn a closure into a struct implementing [`Debug`]. pub fn debug(f: F) -> impl Debug where diff --git a/crates/typst-utils/src/macros.rs b/crates/typst-utils/src/macros.rs index dfe0c319..dd60a2e0 100644 --- a/crates/typst-utils/src/macros.rs +++ b/crates/typst-utils/src/macros.rs @@ -1,8 +1,18 @@ +/// Create a lazy initialized, globally unique `'static` reference to a value. +#[macro_export] +macro_rules! singleton { + ($ty:ty, $value:expr) => {{ + static VALUE: $crate::once_cell::sync::Lazy<$ty> = + $crate::once_cell::sync::Lazy::new(|| $value); + &*VALUE + }}; +} + /// Implement the `Sub` trait based on existing `Neg` and `Add` impls. #[macro_export] macro_rules! sub_impl { ($a:ident - $b:ident -> $c:ident) => { - impl std::ops::Sub<$b> for $a { + impl ::core::ops::Sub<$b> for $a { type Output = $c; fn sub(self, other: $b) -> $c { @@ -16,7 +26,7 @@ macro_rules! sub_impl { #[macro_export] macro_rules! assign_impl { ($a:ident += $b:ident) => { - impl std::ops::AddAssign<$b> for $a { + impl ::core::ops::AddAssign<$b> for $a { fn add_assign(&mut self, other: $b) { *self = *self + other; } @@ -24,7 +34,7 @@ macro_rules! assign_impl { }; ($a:ident -= $b:ident) => { - impl std::ops::SubAssign<$b> for $a { + impl ::core::ops::SubAssign<$b> for $a { fn sub_assign(&mut self, other: $b) { *self = *self - other; } @@ -32,7 +42,7 @@ macro_rules! assign_impl { }; ($a:ident *= $b:ident) => { - impl std::ops::MulAssign<$b> for $a { + impl ::core::ops::MulAssign<$b> for $a { fn mul_assign(&mut self, other: $b) { *self = *self * other; } @@ -40,7 +50,7 @@ macro_rules! assign_impl { }; ($a:ident /= $b:ident) => { - impl std::ops::DivAssign<$b> for $a { + impl ::core::ops::DivAssign<$b> for $a { fn div_assign(&mut self, other: $b) { *self = *self / other; } -- cgit v1.2.3