Skip to main content

tvm_ffi/extra/
cold_init_lazy_lock.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19//! Lazy initialization with an outlined first-access path.
20
21use std::ops::Deref;
22use std::sync::LazyLock;
23
24/// A lazy value that keeps initialization in a separate cold function.
25///
26/// Construct it with an initializer and dereference it to access the value.
27/// Initialization runs once; concurrent callers wait, and an initializer panic
28/// poisons the value, following [`LazyLock`].
29///
30/// # Example
31///
32/// ```
33/// use tvm_ffi::extra::cold_init_lazy_lock::ColdInitLazyLock;
34///
35/// static NAME: ColdInitLazyLock<String> = ColdInitLazyLock::new(|| "ready".into());
36/// assert_eq!(NAME.as_str(), "ready");
37/// ```
38///
39/// # Why avoid inlining initialization?
40///
41/// Inlining initialization can enlarge the caller's stack frame even when the
42/// value is already initialized. We keep initialization in a separate cold
43/// function and inline only the initialized check.
44pub struct ColdInitLazyLock<T, F = fn() -> T> {
45    inner: LazyLock<T, F>,
46}
47
48impl<T, F: FnOnce() -> T> ColdInitLazyLock<T, F> {
49    /// Store `initializer` for execution on the first dereference.
50    ///
51    /// Construction does not execute the initializer or allocate wrapper storage.
52    pub const fn new(initializer: F) -> Self {
53        Self {
54            inner: LazyLock::new(initializer),
55        }
56    }
57}
58
59impl<T, F: FnOnce() -> T> Deref for ColdInitLazyLock<T, F> {
60    type Target = T;
61
62    #[inline(always)]
63    fn deref(&self) -> &T {
64        if let Some(value) = LazyLock::get(&self.inner) {
65            value
66        } else {
67            force_outlined(&self.inner)
68        }
69    }
70}
71
72// Keep the lock's first-access machinery outside initialized callers' frames.
73#[cold]
74#[inline(never)]
75fn force_outlined<T, F: FnOnce() -> T>(lock: &LazyLock<T, F>) -> &T {
76    LazyLock::force(lock)
77}