Closed1

RustでMutexGuardから参照みたいなものを取り出す方法

higumachanhigumachan

こんな感じで,MutexGuardをラップするような型を作れば行ける.
Guardを分解するのは無理っぽい

use rerun::time::Timeline;
use rerun::{EntityPath, Session};
use std::ops::{Deref, DerefMut};
use std::sync::{Mutex, MutexGuard};

pub struct ReplaySession {
    frame_index: i64,
    nano_second_per_frame: Option<f64>,
    session: rerun::Session,
}

pub struct GuardedSession(MutexGuard<'static, ReplaySession>);

impl Deref for GuardedSession {
    type Target = Session;

    fn deref(&self) -> &Self::Target {
        &self.0.session
    }
}

impl DerefMut for GuardedSession {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0.session
    }
}

impl ReplaySession {
    fn video_relative_time(&self) -> Option<i64> {
        Some((self.frame_index as f64 * self.nano_second_per_frame?) as i64)
    }
    pub fn set_nano_second_per_frame(&mut self, nano_second_per_frame: Option<f64>) {
        self.nano_second_per_frame = nano_second_per_frame;
    }
}

static REPLAY_SESSION: once_cell::sync::Lazy<Mutex<ReplaySession>> =
    once_cell::sync::Lazy::new(|| {
        let session = rerun::Session::init("debug-session", true);

        Mutex::new(ReplaySession {
            nano_second_per_frame: None,
            frame_index: 0,
            session,
        })
    });

pub fn global_session() -> GuardedSession {
    GuardedSession(REPLAY_SESSION.lock().unwrap())
}

pub fn next_tick() {
    let mut replay = REPLAY_SESSION.lock().unwrap();
    replay.frame_index += 1;
}

pub fn set_global_nano_second_per_frame(nano_second_per_frame: Option<f64>) {
    let mut replay = REPLAY_SESSION.lock().unwrap();
    replay.set_nano_second_per_frame(nano_second_per_frame);
}

pub fn create_sender(name: impl Into<EntityPath>) -> rerun::MsgSender {
    let replay_session = REPLAY_SESSION.lock().unwrap();
    let mut sender = rerun::MsgSender::new(name).with_time(
        Timeline::new_sequence("frame"),
        replay_session.frame_index as i64,
    );

    if let Some(vide_relative_time) = replay_session.video_relative_time() {
        sender = sender.with_time(
            Timeline::new_temporal("video_relative_time"),
            vide_relative_time,
        );
    }

    sender
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it() {}
}
このスクラップは2023/11/30にクローズされました