+/livesplit-wrapper

git clone https://git.julia.blue/+/livesplit-wrapper

P1n3appl3deploy: 9b9f353f3b0e319547cabc5dcadc542d5ab54386b0170e4

gh-pages
21.7 KiB254 linesraw
1<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="Overview"><meta name="keywords" content="rust, rustlang, rust-lang, once_cell"><title>once_cell - Rust</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceSerif4-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../FiraSans-Regular.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../FiraSans-Medium.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceCodePro-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceSerif4-Bold.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceCodePro-Semibold.ttf.woff2"><link rel="stylesheet" href="../normalize.css"><link rel="stylesheet" href="../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" href="../ayu.css" disabled><link rel="stylesheet" href="../dark.css" disabled><link rel="stylesheet" href="../light.css" id="themeStyle"><script id="default-settings" ></script><script src="../storage.js"></script><script defer src="../crates.js"></script><script defer src="../main.js"></script><noscript><link rel="stylesheet" href="../noscript.css"></noscript><link rel="alternate icon" type="image/png" href="../favicon-16x16.png"><link rel="alternate icon" type="image/png" href="../favicon-32x32.png"><link rel="icon" type="image/svg+xml" href="../favicon.svg"></head><body class="rustdoc mod crate"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="mobile-topbar"><button class="sidebar-menu-toggle">&#9776;</button><a class="sidebar-logo" href="../once_cell/index.html"><div class="logo-container"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></div></a><h2 class="location"></h2></nav><nav class="sidebar"><a class="sidebar-logo" href="../once_cell/index.html"><div class="logo-container"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></div></a><h2 class="location"><a href="#">Crate once_cell</a></h2><div class="sidebar-elems"><div class="block"><ul><li class="version">Version 1.15.0</li><li><a id="all-types" href="all.html">All Items</a></li></ul></div><section><div class="block"><ul><li><a href="#modules">Modules</a></li></ul></div></section></div></nav><main><div class="width-limiter"><div class="sub-container"><a class="sub-logo-container" href="../once_cell/index.html"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></a><nav class="sub"><form class="search-form"><div class="search-container"><span></span><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><div id="help-button" title="help" tabindex="-1"><button type="button">?</button></div><div id="settings-menu" tabindex="-1"><a href="../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../wheel.svg"></a></div></div></form></nav></div><section id="main-content" class="content"><div class="main-heading"><h1 class="fqn"><span class="in-band">Crate <a class="mod" href="#">once_cell</a><button id="copy-path" onclick="copy_path(this)" title="Copy item path to clipboard"><img src="../clipboard.svg" width="19" height="18" alt="Copy item path"></button></span></h1><span class="out-of-band"><a class="srclink" href="../src/once_cell/lib.rs.html#1-1368">source</a> · <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class="inner">&#x2212;</span>]</a></span></div><details class="rustdoc-toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><h2 id="overview"><a href="#overview">Overview</a></h2>
2<p><code>once_cell</code> provides two new cell-like types, <a href="unsync/struct.OnceCell.html"><code>unsync::OnceCell</code></a> and <a href="sync/struct.OnceCell.html"><code>sync::OnceCell</code></a>. A <code>OnceCell</code>
3might store arbitrary non-<code>Copy</code> types, can be assigned to at most once and provides direct access
4to the stored contents. The core API looks <em>roughly</em> like this (and there’s much more inside, read on!):</p>
5
6<div class="example-wrap ignore"><div class='tooltip'>ⓘ</div><pre class="rust rust-example-rendered"><code><span class="kw">impl</span>&lt;T&gt; OnceCell&lt;T&gt; {
7    <span class="kw">const fn </span>new() -&gt; OnceCell&lt;T&gt; { ... }
8    <span class="kw">fn </span>set(<span class="kw-2">&amp;</span><span class="self">self</span>, value: T) -&gt; <span class="prelude-ty">Result</span>&lt;(), T&gt; { ... }
9    <span class="kw">fn </span>get(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; <span class="prelude-ty">Option</span>&lt;<span class="kw-2">&amp;</span>T&gt; { ... }
10}</code></pre></div>
11<p>Note that, like with <a href="https://doc.rust-lang.org/std/cell/struct.RefCell.html"><code>RefCell</code></a> and <a href="https://doc.rust-lang.org/std/sync/struct.Mutex.html"><code>Mutex</code></a>, the <code>set</code> method requires only a shared reference.
12Because of the single assignment restriction <code>get</code> can return a <code>&amp;T</code> instead of <code>Ref&lt;T&gt;</code>
13or <code>MutexGuard&lt;T&gt;</code>.</p>
14<p>The <code>sync</code> flavor is thread-safe (that is, implements the <a href="https://doc.rust-lang.org/std/marker/trait.Sync.html"><code>Sync</code></a> trait), while the <code>unsync</code> one is not.</p>
15<h2 id="recipes"><a href="#recipes">Recipes</a></h2>
16<p><code>OnceCell</code> might be useful for a variety of patterns.</p>
17<h3 id="safe-initialization-of-global-data"><a href="#safe-initialization-of-global-data">Safe Initialization of Global Data</a></h3>
18<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>std::{env, io};
19
20<span class="kw">use </span>once_cell::sync::OnceCell;
21
22<span class="attribute">#[derive(Debug)]
23</span><span class="kw">pub struct </span>Logger {
24    <span class="comment">// ...
25</span>}
26<span class="kw">static </span>INSTANCE: OnceCell&lt;Logger&gt; = OnceCell::new();
27
28<span class="kw">impl </span>Logger {
29    <span class="kw">pub fn </span>global() -&gt; <span class="kw-2">&amp;</span><span class="lifetime">&#39;static </span>Logger {
30        INSTANCE.get().expect(<span class="string">&quot;logger is not initialized&quot;</span>)
31    }
32
33    <span class="kw">fn </span>from_cli(args: env::Args) -&gt; <span class="prelude-ty">Result</span>&lt;Logger, std::io::Error&gt; {
34       <span class="comment">// ...
35    </span>}
36}
37
38<span class="kw">fn </span>main() {
39    <span class="kw">let </span>logger = Logger::from_cli(env::args()).unwrap();
40    INSTANCE.set(logger).unwrap();
41    <span class="comment">// use `Logger::global()` from now on
42</span>}</code></pre></div>
43<h3 id="lazy-initialized-global-data"><a href="#lazy-initialized-global-data">Lazy Initialized Global Data</a></h3>
44<p>This is essentially the <code>lazy_static!</code> macro, but without a macro.</p>
45
46<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>std::{sync::Mutex, collections::HashMap};
47
48<span class="kw">use </span>once_cell::sync::OnceCell;
49
50<span class="kw">fn </span>global_data() -&gt; <span class="kw-2">&amp;</span><span class="lifetime">&#39;static </span>Mutex&lt;HashMap&lt;i32, String&gt;&gt; {
51    <span class="kw">static </span>INSTANCE: OnceCell&lt;Mutex&lt;HashMap&lt;i32, String&gt;&gt;&gt; = OnceCell::new();
52    INSTANCE.get_or_init(|| {
53        <span class="kw">let </span><span class="kw-2">mut </span>m = HashMap::new();
54        m.insert(<span class="number">13</span>, <span class="string">&quot;Spica&quot;</span>.to_string());
55        m.insert(<span class="number">74</span>, <span class="string">&quot;Hoyten&quot;</span>.to_string());
56        Mutex::new(m)
57    })
58}</code></pre></div>
59<p>There are also the <a href="sync/struct.Lazy.html"><code>sync::Lazy</code></a> and <a href="unsync/struct.Lazy.html"><code>unsync::Lazy</code></a> convenience types to streamline this pattern:</p>
60
61<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>std::{sync::Mutex, collections::HashMap};
62<span class="kw">use </span>once_cell::sync::Lazy;
63
64<span class="kw">static </span>GLOBAL_DATA: Lazy&lt;Mutex&lt;HashMap&lt;i32, String&gt;&gt;&gt; = Lazy::new(|| {
65    <span class="kw">let </span><span class="kw-2">mut </span>m = HashMap::new();
66    m.insert(<span class="number">13</span>, <span class="string">&quot;Spica&quot;</span>.to_string());
67    m.insert(<span class="number">74</span>, <span class="string">&quot;Hoyten&quot;</span>.to_string());
68    Mutex::new(m)
69});
70
71<span class="kw">fn </span>main() {
72    <span class="macro">println!</span>(<span class="string">&quot;{:?}&quot;</span>, GLOBAL_DATA.lock().unwrap());
73}</code></pre></div>
74<p>Note that the variable that holds <code>Lazy</code> is declared as <code>static</code>, <em>not</em>
75<code>const</code>. This is important: using <code>const</code> instead compiles, but works wrong.</p>
76<h3 id="general-purpose-lazy-evaluation"><a href="#general-purpose-lazy-evaluation">General purpose lazy evaluation</a></h3>
77<p>Unlike <code>lazy_static!</code>, <code>Lazy</code> works with local variables.</p>
78
79<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>once_cell::unsync::Lazy;
80
81<span class="kw">fn </span>main() {
82    <span class="kw">let </span>ctx = <span class="macro">vec!</span>[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
83    <span class="kw">let </span>thunk = Lazy::new(|| {
84        ctx.iter().sum::&lt;i32&gt;()
85    });
86    <span class="macro">assert_eq!</span>(<span class="kw-2">*</span>thunk, <span class="number">6</span>);
87}</code></pre></div>
88<p>If you need a lazy field in a struct, you probably should use <code>OnceCell</code>
89directly, because that will allow you to access <code>self</code> during initialization.</p>
90
91<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>std::{fs, path::PathBuf};
92
93<span class="kw">use </span>once_cell::unsync::OnceCell;
94
95<span class="kw">struct </span>Ctx {
96    config_path: PathBuf,
97    config: OnceCell&lt;String&gt;,
98}
99
100<span class="kw">impl </span>Ctx {
101    <span class="kw">pub fn </span>get_config(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; <span class="prelude-ty">Result</span>&lt;<span class="kw-2">&amp;</span>str, std::io::Error&gt; {
102        <span class="kw">let </span>cfg = <span class="self">self</span>.config.get_or_try_init(|| {
103            fs::read_to_string(<span class="kw-2">&amp;</span><span class="self">self</span>.config_path)
104        })<span class="question-mark">?</span>;
105        <span class="prelude-val">Ok</span>(cfg.as_str())
106    }
107}</code></pre></div>
108<h3 id="lazily-compiled-regex"><a href="#lazily-compiled-regex">Lazily Compiled Regex</a></h3>
109<p>This is a <code>regex!</code> macro which takes a string literal and returns an
110<em>expression</em> that evaluates to a <code>&amp;'static Regex</code>:</p>
111
112<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="macro">macro_rules! </span>regex {
113    (<span class="macro-nonterminal">$re</span>:literal $(,)<span class="question-mark">?</span>) =&gt; {{
114        <span class="kw">static </span>RE: once_cell::sync::OnceCell&lt;regex::Regex&gt; = once_cell::sync::OnceCell::new();
115        RE.get_or_init(|| regex::Regex::new(<span class="macro-nonterminal">$re</span>).unwrap())
116    }};
117}</code></pre></div>
118<p>This macro can be useful to avoid the “compile regex on every loop iteration” problem.</p>
119<h3 id="runtime-include_bytes"><a href="#runtime-include_bytes">Runtime <code>include_bytes!</code></a></h3>
120<p>The <code>include_bytes</code> macro is useful to include test resources, but it slows
121down test compilation a lot. An alternative is to load the resources at
122runtime:</p>
123
124<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>std::path::Path;
125
126<span class="kw">use </span>once_cell::sync::OnceCell;
127
128<span class="kw">pub struct </span>TestResource {
129    path: <span class="kw-2">&amp;</span><span class="lifetime">&#39;static </span>str,
130    cell: OnceCell&lt;Vec&lt;u8&gt;&gt;,
131}
132
133<span class="kw">impl </span>TestResource {
134    <span class="kw">pub const fn </span>new(path: <span class="kw-2">&amp;</span><span class="lifetime">&#39;static </span>str) -&gt; TestResource {
135        TestResource { path, cell: OnceCell::new() }
136    }
137    <span class="kw">pub fn </span>bytes(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; <span class="kw-2">&amp;</span>[u8] {
138        <span class="self">self</span>.cell.get_or_init(|| {
139            <span class="kw">let </span>dir = std::env::var(<span class="string">&quot;CARGO_MANIFEST_DIR&quot;</span>).unwrap();
140            <span class="kw">let </span>path = Path::new(dir.as_str()).join(<span class="self">self</span>.path);
141            std::fs::read(<span class="kw-2">&amp;</span>path).unwrap_or_else(|_err| {
142                <span class="macro">panic!</span>(<span class="string">&quot;failed to load test resource: {}&quot;</span>, path.display())
143            })
144        }).as_slice()
145    }
146}
147
148<span class="kw">static </span>TEST_IMAGE: TestResource = TestResource::new(<span class="string">&quot;test_data/lena.png&quot;</span>);
149
150<span class="attribute">#[test]
151</span><span class="kw">fn </span>test_sobel_filter() {
152    <span class="kw">let </span>rgb: <span class="kw-2">&amp;</span>[u8] = TEST_IMAGE.bytes();
153    <span class="comment">// ...
154</span>}</code></pre></div>
155<h3 id="lateinit"><a href="#lateinit"><code>lateinit</code></a></h3>
156<p><code>LateInit</code> type for delayed initialization. It is reminiscent of Kotlin’s
157<code>lateinit</code> keyword and allows construction of cyclic data structures:</p>
158
159<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>once_cell::sync::OnceCell;
160
161<span class="attribute">#[derive(Debug)]
162</span><span class="kw">pub struct </span>LateInit&lt;T&gt; { cell: OnceCell&lt;T&gt; }
163
164<span class="kw">impl</span>&lt;T&gt; LateInit&lt;T&gt; {
165    <span class="kw">pub fn </span>init(<span class="kw-2">&amp;</span><span class="self">self</span>, value: T) {
166        <span class="macro">assert!</span>(<span class="self">self</span>.cell.set(value).is_ok())
167    }
168}
169
170<span class="kw">impl</span>&lt;T&gt; Default <span class="kw">for </span>LateInit&lt;T&gt; {
171    <span class="kw">fn </span>default() -&gt; <span class="self">Self </span>{ LateInit { cell: OnceCell::default() } }
172}
173
174<span class="kw">impl</span>&lt;T&gt; std::ops::Deref <span class="kw">for </span>LateInit&lt;T&gt; {
175    <span class="kw">type </span>Target = T;
176    <span class="kw">fn </span>deref(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; <span class="kw-2">&amp;</span>T {
177        <span class="self">self</span>.cell.get().unwrap()
178    }
179}
180
181<span class="attribute">#[derive(Default, Debug)]
182</span><span class="kw">struct </span>A&lt;<span class="lifetime">&#39;a</span>&gt; {
183    b: LateInit&lt;<span class="kw-2">&amp;</span><span class="lifetime">&#39;a </span>B&lt;<span class="lifetime">&#39;a</span>&gt;&gt;,
184}
185
186<span class="attribute">#[derive(Default, Debug)]
187</span><span class="kw">struct </span>B&lt;<span class="lifetime">&#39;a</span>&gt; {
188    a: LateInit&lt;<span class="kw-2">&amp;</span><span class="lifetime">&#39;a </span>A&lt;<span class="lifetime">&#39;a</span>&gt;&gt;
189}
190
191<span class="kw">fn </span>build_cycle() {
192    <span class="kw">let </span>a = A::default();
193    <span class="kw">let </span>b = B::default();
194    a.b.init(<span class="kw-2">&amp;</span>b);
195    b.a.init(<span class="kw-2">&amp;</span>a);
196    <span class="macro">println!</span>(<span class="string">&quot;{:?}&quot;</span>, a.b.a.b.a);
197}</code></pre></div>
198<h2 id="comparison-with-std"><a href="#comparison-with-std">Comparison with std</a></h2><div><table><thead><tr><th><code>!Sync</code> types</th><th>Access Mode</th><th>Drawbacks</th></tr></thead><tbody>
199<tr><td><code>Cell&lt;T&gt;</code></td><td><code>T</code></td><td>requires <code>T: Copy</code> for <code>get</code></td></tr>
200<tr><td><code>RefCell&lt;T&gt;</code></td><td><code>RefMut&lt;T&gt;</code> / <code>Ref&lt;T&gt;</code></td><td>may panic at runtime</td></tr>
201<tr><td><code>unsync::OnceCell&lt;T&gt;</code></td><td><code>&amp;T</code></td><td>assignable only once</td></tr>
202</tbody></table>
203</div><div><table><thead><tr><th><code>Sync</code> types</th><th>Access Mode</th><th>Drawbacks</th></tr></thead><tbody>
204<tr><td><code>AtomicT</code></td><td><code>T</code></td><td>works only with certain <code>Copy</code> types</td></tr>
205<tr><td><code>Mutex&lt;T&gt;</code></td><td><code>MutexGuard&lt;T&gt;</code></td><td>may deadlock at runtime, may block the thread</td></tr>
206<tr><td><code>sync::OnceCell&lt;T&gt;</code></td><td><code>&amp;T</code></td><td>assignable only once, may block the thread</td></tr>
207</tbody></table>
208</div>
209<p>Technically, calling <code>get_or_init</code> will also cause a panic or a deadlock if it recursively calls
210itself. However, because the assignment can happen only once, such cases should be more rare than
211equivalents with <code>RefCell</code> and <code>Mutex</code>.</p>
212<h2 id="minimum-supported-rustc-version"><a href="#minimum-supported-rustc-version">Minimum Supported <code>rustc</code> Version</a></h2>
213<p>This crate’s minimum supported <code>rustc</code> version is <code>1.56.0</code>.</p>
214<p>If only the <code>std</code> feature is enabled, MSRV will be updated conservatively.
215When using other features, like <code>parking_lot</code>, MSRV might be updated more frequently, up to the latest stable.
216In both cases, increasing MSRV is <em>not</em> considered a semver-breaking change.</p>
217<h2 id="implementation-details"><a href="#implementation-details">Implementation details</a></h2>
218<p>The implementation is based on the <a href="https://github.com/rust-lang-nursery/lazy-static.rs/"><code>lazy_static</code></a>
219and <a href="https://github.com/indiv0/lazycell/"><code>lazy_cell</code></a> crates and <a href="https://doc.rust-lang.org/std/sync/struct.Once.html"><code>std::sync::Once</code></a>. In some sense,
220<code>once_cell</code> just streamlines and unifies those APIs.</p>
221<p>To implement a sync flavor of <code>OnceCell</code>, this crates uses either a custom
222re-implementation of <code>std::sync::Once</code> or <code>parking_lot::Mutex</code>. This is
223controlled by the <code>parking_lot</code> feature (disabled by default). Performance
224is the same for both cases, but the <code>parking_lot</code> based <code>OnceCell&lt;T&gt;</code> is
225smaller by up to 16 bytes.</p>
226<p>This crate uses <code>unsafe</code>.</p>
227<h2 id="faq"><a href="#faq">F.A.Q.</a></h2>
228<p><strong>Should I use lazy_static or once_cell?</strong></p>
229<p>To the first approximation, <code>once_cell</code> is both more flexible and more convenient than <code>lazy_static</code>
230and should be preferred.</p>
231<p>Unlike <code>once_cell</code>, <code>lazy_static</code> supports spinlock-based implementation of blocking which works with
232<code>#![no_std]</code>.</p>
233<p><code>lazy_static</code> has received significantly more real world testing, but <code>once_cell</code> is also a widely
234used crate.</p>
235<p><strong>Should I use the sync or unsync flavor?</strong></p>
236<p>Because Rust compiler checks thread safety for you, it’s impossible to accidentally use <code>unsync</code> where
237<code>sync</code> is required. So, use <code>unsync</code> in single-threaded code and <code>sync</code> in multi-threaded. It’s easy
238to switch between the two if code becomes multi-threaded later.</p>
239<p>At the moment, <code>unsync</code> has an additional benefit that reentrant initialization causes a panic, which
240might be easier to debug than a deadlock.</p>
241<p><strong>Does this crate support async?</strong></p>
242<p>No, but you can use <a href="https://crates.io/crates/async_once_cell"><code>async_once_cell</code></a> instead.</p>
243<h2 id="related-crates"><a href="#related-crates">Related crates</a></h2>
244<ul>
245<li><a href="https://github.com/niklasf/double-checked-cell">double-checked-cell</a></li>
246<li><a href="https://crates.io/crates/lazy-init">lazy-init</a></li>
247<li><a href="https://crates.io/crates/lazycell">lazycell</a></li>
248<li><a href="https://crates.io/crates/mitochondria">mitochondria</a></li>
249<li><a href="https://crates.io/crates/lazy_static">lazy_static</a></li>
250<li><a href="https://crates.io/crates/async_once_cell">async_once_cell</a></li>
251</ul>
252<p>Most of this crate’s functionality is available in <code>std</code> in nightly Rust.
253See the <a href="https://github.com/rust-lang/rust/issues/74465">tracking issue</a>.</p>
254</div></details><h2 id="modules" class="small-section-header"><a href="#modules">Modules</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="mod" href="race/index.html" title="once_cell::race mod">race</a></div><div class="item-right docblock-short">Thread-safe, non-blocking, “first one wins” flavor of <code>OnceCell</code>.</div></div><div class="item-row"><div class="item-left module-item"><a class="mod" href="sync/index.html" title="once_cell::sync mod">sync</a></div><div class="item-right docblock-short">Thread-safe, blocking version of <code>OnceCell</code>.</div></div><div class="item-row"><div class="item-left module-item"><a class="mod" href="unsync/index.html" title="once_cell::unsync mod">unsync</a></div><div class="item-right docblock-short">Single-threaded version of <code>OnceCell</code>.</div></div></div></section></div></main><div id="rustdoc-vars" data-root-path="../" data-current-crate="once_cell" data-themes="ayu,dark,light" data-resource-suffix="" data-rustdoc-version="1.66.0-nightly (4a1467723 2022-09-23)" ></div></body></html>