Debian Codegraph @

third_party/rust/litemap/src/databake.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use crate::LiteMap;
6 use databake::*;
7
8 /// Bakes a LiteMap into Rust code for fast runtime construction from data. Use this impl during
9 /// code generation, such as in a `build.rs` script.
10 ///
11 /// For the most efficient bake, bake the [`LiteMap`] with a slice store. Use functions such as
12 /// the following for converting an allocated [`LiteMap`] to a borrowing [`LiteMap`]:
13 ///
14 /// - [`LiteMap::to_borrowed_keys()`]
15 /// - [`LiteMap::to_borrowed_values()`]
16 /// - [`LiteMap::to_borrowed_keys_values()`]
17 /// - [`LiteMap::as_sliced()`]
18 ///
19 /// # Examples
20 ///
21 /// ```
22 /// use databake::*;
23 /// use litemap::LiteMap;
24 ///
25 /// // Construct the LiteMap fully owned and allocated:
26 /// let mut litemap_alloc: LiteMap<usize, String, Vec<_>> = LiteMap::new_vec();
27 /// litemap_alloc.insert(1usize, "one".to_string());
28 /// litemap_alloc.insert(2usize, "two".to_string());
29 /// litemap_alloc.insert(10usize, "ten".to_string());
30 ///
31 /// // Convert to a borrowed type for baking:
32 /// let litemap_str: LiteMap<usize, &str, Vec<_>> =
33 /// litemap_alloc.to_borrowed_values();
34 /// let litemap_slice: LiteMap<usize, &str, &[_]> = litemap_str.as_sliced();
35 ///
36 /// // The bake will now work for const construction:
37 /// let mut ctx = Default::default();
38 /// println!(
39 /// "const FOO: LiteMap<usize, &str, &[(usize, &str)]> = {};",
40 /// litemap_slice.bake(&mut ctx)
41 /// );
42 /// ```
43 impl<K, V, S> Bake for LiteMap<K, V, S>
44 where
45 S: Bake,
46 {
47 fn bake(&self, env: &CrateEnv) -> TokenStream {
48 env.insert("litemap");
49 let store = self.values.bake(env);
50 quote! { litemap::LiteMap::from_sorted_store_unchecked(#store) }
51 }
52 }
53
54 #[test]
55 fn test_baked_map() {
56 // Const construction:
57 test_bake!(
58 LiteMap<usize, &str, &[(usize, &str)]>,
59 const: crate::LiteMap::from_sorted_store_unchecked(
60 &[
61 (1usize, "one"),
62 (2usize, "two"),
63 (10usize, "ten")
64 ]
65 ),
66 litemap
67 );
68 // Non-const construction:
69 test_bake!(
70 LiteMap<usize, String, Vec<(usize, String)>>,
71 crate::LiteMap::from_sorted_store_unchecked(
72 alloc::vec![
73 (1usize, "one".to_owned()),
74 (2usize, "two".to_owned()),
75 (10usize, "ten".to_owned()),
76 ]
77 ),
78 litemap
79 );
80 }