-
Notifications
You must be signed in to change notification settings - Fork 155
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Do not allocate input singleton data for non-singleton inputs
- Loading branch information
Showing
4 changed files
with
78 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
use crossbeam::atomic::AtomicCell; | ||
use parking_lot::Mutex; | ||
|
||
use crate::{id::FromId, Id}; | ||
|
||
mod sealed { | ||
pub trait Sealed {} | ||
} | ||
|
||
pub trait SingletonChoice: sealed::Sealed + Default { | ||
fn with_lock(&self, cb: impl FnOnce() -> Id) -> Id; | ||
fn index(&self) -> Option<Id>; | ||
} | ||
|
||
pub struct Singleton { | ||
index: AtomicCell<Option<Id>>, | ||
lock: Mutex<()>, | ||
} | ||
impl sealed::Sealed for Singleton {} | ||
impl SingletonChoice for Singleton { | ||
fn with_lock(&self, cb: impl FnOnce() -> Id) -> Id { | ||
let _guard = self.lock.lock(); | ||
if self.index.load().is_some() { | ||
panic!("singleton struct may not be duplicated"); | ||
} | ||
let id = cb(); | ||
self.index.store(Some(id)); | ||
drop(_guard); | ||
id | ||
} | ||
|
||
fn index(&self) -> Option<Id> { | ||
self.index.load().map(FromId::from_id) | ||
} | ||
} | ||
|
||
impl Default for Singleton { | ||
fn default() -> Self { | ||
Self { | ||
index: AtomicCell::new(None), | ||
lock: Default::default(), | ||
} | ||
} | ||
} | ||
#[derive(Default)] | ||
pub struct NoSingleton; | ||
impl sealed::Sealed for NoSingleton {} | ||
impl SingletonChoice for NoSingleton { | ||
fn with_lock(&self, cb: impl FnOnce() -> Id) -> Id { | ||
cb() | ||
} | ||
fn index(&self) -> Option<Id> { | ||
None | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters