[pbs-devel] [PATCH proxmox 2/2] product-config: use inner mutability for PRODUCT_CONFIG
Shannon Sterz
s.sterz at proxmox.com
Tue Dec 3 14:53:05 CET 2024
On Tue Dec 3, 2024 at 2:48 PM CET, Shannon Sterz wrote:
> with edition 2024 `static mut` references will be disallowed [1]. the
> recommended way to work around this is to use inner mutability, so use a
> `OnceLock` for the `PRODUCT_CONFIG` as that should not change throughout
> the run time of an application.
>
> [1]:
> https://doc.rust-lang.org/nightly/edition-guide/rust-2024/static-mut-references.html
>
> Signed-off-by: Shannon Sterz <s.sterz at proxmox.com>
> ---
> proxmox-product-config/src/init.rs | 33 +++++++++++++++---------------
> 1 file changed, 16 insertions(+), 17 deletions(-)
>
> diff --git a/proxmox-product-config/src/init.rs b/proxmox-product-config/src/init.rs
> index a244559a..291a3b74 100644
> --- a/proxmox-product-config/src/init.rs
> +++ b/proxmox-product-config/src/init.rs
> @@ -1,18 +1,21 @@
> +use std::sync::OnceLock;
> +
> +#[derive(Debug)]
> struct ProxmoxProductConfig {
> api_user: nix::unistd::User,
> priv_user: nix::unistd::User,
> }
>
> -static mut PRODUCT_CONFIG: Option<ProxmoxProductConfig> = None;
> +static PRODUCT_CONFIG: OnceLock<ProxmoxProductConfig> = OnceLock::new();
>
> /// Initialize the global product configuration.
> pub fn init(api_user: nix::unistd::User, priv_user: nix::unistd::User) {
> - unsafe {
> - PRODUCT_CONFIG = Some(ProxmoxProductConfig {
> + PRODUCT_CONFIG
> + .set(ProxmoxProductConfig {
> api_user,
> priv_user,
> - });
> - }
> + })
> + .expect("");
sorry forgot to set a proper message here, will send a v2 in a minute
> }
>
> /// Returns the global api user set with [init].
> @@ -21,12 +24,10 @@ pub fn init(api_user: nix::unistd::User, priv_user: nix::unistd::User) {
> ///
> /// Panics if [init] wasn't called before.
> pub fn get_api_user() -> &'static nix::unistd::User {
> - unsafe {
> - &PRODUCT_CONFIG
> - .as_ref()
> - .expect("ProxmoxProductConfig is not initialized!")
> - .api_user
> - }
> + &PRODUCT_CONFIG
> + .get()
> + .expect("ProxmoxProductConfig is not initialized!")
> + .api_user
> }
>
> // Returns the global privileged user set with [init].
> @@ -35,10 +36,8 @@ pub fn get_api_user() -> &'static nix::unistd::User {
> ///
> /// Panics if [init] wasn't called before.
> pub fn get_priv_user() -> &'static nix::unistd::User {
> - unsafe {
> - &PRODUCT_CONFIG
> - .as_ref()
> - .expect("ProxmoxProductConfig is not initialized!")
> - .priv_user
> - }
> + &PRODUCT_CONFIG
> + .get()
> + .expect("ProxmoxProductConfig is not initialized!")
> + .priv_user
> }
More information about the pbs-devel
mailing list