config: unsafe { .get_unchecked() } -> get_or_init()

only 0.13% faster over 1 billion accesses, not worth it
This commit is contained in:
hinto.janai 2023-12-11 20:04:45 -05:00
parent 2853e8ed5f
commit f2f4fe7157
No known key found for this signature in database
GPG key ID: D47CE05FA175A499

View file

@ -5,23 +5,26 @@ use tracing::{error,info,warn,debug,trace};
use disk::Toml; use disk::Toml;
use crate::constants::{ use crate::constants::{
CUPRATE, CUPRATE,
CUPRATE_PORT, DEFAULT_RPC_PORT,
CUPRATE_CONFIG, DEFAULT_CONFIG,
};
use std::{
net::IpAddr,
collections::BTreeSet,
path::PathBuf,
sync::OnceLock,
}; };
use std::net::IpAddr;
use std::collections::BTreeSet;
use std::path::PathBuf;
use once_cell::sync::OnceCell;
//---------------------------------------------------------------------------------------------------- Statics //---------------------------------------------------------------------------------------------------- Statics
static CONFIG: OnceCell<Config> = OnceCell::new(); static CONFIG_CELL: OnceLock<Config> = OnceLock::new();
#[inline(always)] #[inline(always)]
#[allow(non_snake_case)]
/// Acquire our runtime configuration. /// Acquire our runtime configuration.
pub fn config() -> &'static Config { pub fn CONFIG() -> &'static Config {
// SAFETY: // INVARIANT:
// This should always get initialized in the // This should always get initialized in the
// `.builder()` below, by `main()` during init. // `.builder()` below, by `main()` during init.
unsafe { CONFIG.get_unchecked() } CONFIG_CELL.get_or_init(|| unreachable!("CONFIG was not initialized at main()"))
} }
//---------------------------------------------------------------------------------------------------- Constants //---------------------------------------------------------------------------------------------------- Constants
@ -95,16 +98,20 @@ impl Default for ConfigBuilder {
} }
impl ConfigBuilder { impl ConfigBuilder {
/// Initialize the global `CONFIG` that lives for the rest of the program.
///
/// ## Panics
/// This panics if this function is called more than once.
pub fn init( pub fn init(
log_level: Option<tracing::Level>, log_level: Option<tracing::Level>,
cli: Option<Self>, cli: Option<Self>,
) -> &'static Config { ) -> &'static Config {
todo!() // SAFETY: we only set `CONFIG` here.
CONFIG_CELL.set(todo!() /* Self::init_inner() */).unwrap();
CONFIG()
} }
// INVARIANT: must be called once and only once. fn init_inner(self) -> Config {
// Sets `CONFIG`, and returns a ref.
pub fn build_and_set(self) -> &'static Config {
let ConfigBuilder { let ConfigBuilder {
ip, ip,
port, port,
@ -281,9 +288,7 @@ impl ConfigBuilder {
info!("Authorization: {}", AUTH.get().is_some()); info!("Authorization: {}", AUTH.get().is_some());
info!("{DASH} Configuration"); info!("{DASH} Configuration");
// SAFETY: unwrap is okay, we only set `CONFIG` here. c
CONFIG.set(c).unwrap();
config()
} }
// Read from disk, or create a default. // Read from disk, or create a default.