wslplugins_rs/wsl_context.rs
1//! # WSL Context Management
2//!
3//! This module provides a global context for interacting with the WSL plugin API. It ensures
4//! that a single instance of `WSLContext` is initialized and accessible globally during the
5//! plugin's lifecycle.
6
7use crate::api::ApiV1;
8use std::sync::OnceLock;
9
10/// A static instance of `WSLContext` initialized once during the program's lifecycle.
11static CURRENT_CONTEXT: OnceLock<WSLContext> = OnceLock::new();
12
13/// A global context for the WSL plugin API.
14///
15/// The `WSLContext` contains the API interface (`ApiV1`) and ensures safe, global access
16/// throughout the plugin's lifecycle.
17#[derive(Debug)]
18pub struct WSLContext {
19 /// The API interface used for interacting with the WSL plugin API.
20 pub api: &'static ApiV1,
21}
22
23impl WSLContext {
24 /// Retrieves the current `WSLContext` instance, if it has been initialized.
25 ///
26 /// # Returns
27 /// - `Some(&'static WSLContext)`: If the context has been initialized.
28 /// - `None`: If the context has not yet been initialized.
29 ///
30 /// # Example
31 /// ```rust
32 /// use wslplugins_rs::WSLContext;
33 ///
34 /// if let Some(context) = WSLContext::get_current() {
35 /// // Use the context
36 /// } else {
37 /// eprintln!("WSL context is not initialized.");
38 /// }
39 /// ```
40 #[inline]
41 pub fn get_current() -> Option<&'static Self> {
42 CURRENT_CONTEXT.get()
43 }
44 #[expect(clippy::expect_used)]
45 /// Retrieves the current `WSLContext` instance or panics if it is not initialized.
46 ///
47 /// # Panics
48 /// This function will panic if the context has not been initialized.
49 ///
50 /// # Returns
51 /// A reference to the current `WSLContext`.
52 #[must_use]
53 #[inline]
54 pub fn get_current_or_panic() -> &'static Self {
55 Self::get_current().expect("WSL context is not initialised.")
56 }
57
58 /// Initializes the global `WSLContext` with the provided `ApiV1` instance.
59 ///
60 /// # Arguments
61 /// - `api`: The [`ApiV1`] instance to associate with the context.
62 ///
63 /// # Returns
64 /// - `Some(&'static WSLContext)`: If the context was successfully initialized.
65 /// - `None`: If the context has already been initialized.
66 #[inline]
67 pub fn init(api: &'static ApiV1) -> Option<&'static Self> {
68 CURRENT_CONTEXT.set(Self { api }).ok()?;
69 CURRENT_CONTEXT.get()
70 }
71}