naga/back/spv/recyclable.rs
1/*!
2Reusing collections' previous allocations.
3*/
4
5use alloc::vec::Vec;
6
7/// A value that can be reset to its initial state, retaining its current allocations.
8///
9/// Naga attempts to lower the cost of SPIR-V generation by allowing clients to
10/// reuse the same `Writer` for multiple Module translations. Reusing a `Writer`
11/// means that the `Vec`s, `HashMap`s, and other heap-allocated structures the
12/// `Writer` uses internally begin the translation with heap-allocated buffers
13/// ready to use.
14///
15/// But this approach introduces the risk of `Writer` state leaking from one
16/// module to the next. When a developer adds fields to `Writer` or its internal
17/// types, they must remember to reset their contents between modules.
18///
19/// One trick to ensure that every field has been accounted for is to use Rust's
20/// struct literal syntax to construct a new, reset value. If a developer adds a
21/// field, but neglects to update the reset code, the compiler will complain
22/// that a field is missing from the literal. This trait's `recycle` method
23/// takes `self` by value, and returns `Self` by value, encouraging the use of
24/// struct literal expressions in its implementation.
25pub trait Recyclable {
26 /// Clear `self`, retaining its current memory allocations.
27 ///
28 /// Shrink the buffer if it's currently much larger than was actually used.
29 /// This prevents a module with exceptionally large allocations from causing
30 /// the `Writer` to retain more memory than it needs indefinitely.
31 fn recycle(self) -> Self;
32}
33
34// Stock values for various collections.
35
36impl<T> Recyclable for Vec<T> {
37 fn recycle(mut self) -> Self {
38 self.clear();
39 self
40 }
41}
42
43impl<K, V, S: Clone> Recyclable for hashbrown::HashMap<K, V, S> {
44 fn recycle(mut self) -> Self {
45 self.clear();
46 self
47 }
48}
49
50impl<K, S: Clone> Recyclable for hashbrown::HashSet<K, S> {
51 fn recycle(mut self) -> Self {
52 self.clear();
53 self
54 }
55}
56
57impl<K, S: Clone> Recyclable for indexmap::IndexSet<K, S> {
58 fn recycle(mut self) -> Self {
59 self.clear();
60 self
61 }
62}
63
64impl<K: Ord, V> Recyclable for alloc::collections::BTreeMap<K, V> {
65 fn recycle(mut self) -> Self {
66 self.clear();
67 self
68 }
69}
70
71impl<K, V> Recyclable for crate::arena::HandleVec<K, V> {
72 fn recycle(mut self) -> Self {
73 self.clear();
74 self
75 }
76}