Debian Codegraph @

debian/rust-vendor/ctor/examples/ctor-advanced.rs

raw
1 //! Constructors beyond `ctor-basic` / `ctor-example`: anonymous `#[ctor]`, priorities, nested modules,
2 //! inherent `#[ctor]` methods on generic `impl`s, and ctors under a module-level `const`.
3 use ctor::ctor;
4 use libc_print::*;
5 use std::collections::HashMap;
6
7 /// A global hashmap (allocation before main).
8 #[ctor(unsafe)]
9 pub static SHOWCASE_GLOBAL: HashMap<u32, &'static str> = {
10 let mut m = HashMap::new();
11 _ = m.insert(0, "foo");
12 _ = m.insert(1, "bar");
13 _ = m.insert(2, "baz");
14 libc_println!("SHOWCASE_GLOBAL");
15 m
16 };
17
18 /// Anonymous ctor (#1 of 2 with the same Rust name).
19 #[ctor(unsafe, anonymous)]
20 fn anonymous_ctor() {
21 libc_println!("ctor_anonymous (#1)");
22 let _f = anonymous_ctor;
23 }
24
25 /// Anonymous ctor (#2 of 2 with the same Rust name).
26 #[ctor(unsafe, anonymous)]
27 fn anonymous_ctor() {
28 libc_println!("ctor_anonymous (#2)");
29 }
30
31 const _: () = {
32 /// Anonymous ctor inside a `const` scope (#3).
33 #[ctor(unsafe)]
34 fn anonymous_ctor() {
35 libc_println!("ctor_anonymous (#3)");
36 let _f = anonymous_ctor;
37 }
38 };
39
40 /// Regular `#[ctor]` function.
41 #[ctor(unsafe)]
42 fn ctor() {
43 libc_println!("ctor");
44 }
45
46 /// Priority 1 `#[ctor]` function.
47 #[ctor(unsafe, priority = 1)]
48 fn ctor_priority_one() {
49 libc_println!("ctor_priority_one");
50 }
51
52 /// A nested module with a `static` item.
53 pub mod module {
54 use ctor::*;
55 use libc_print::*;
56
57 /// A `static` item in a nested module.
58 #[ctor(unsafe)]
59 pub(crate) static STATIC_CTOR: u8 = {
60 libc_println!("module::STATIC_CTOR");
61 42
62 };
63 }
64
65 /// A generic `impl` with a `#[ctor]` method.
66 #[derive(Default)]
67 struct Foo<T> {
68 _t: ::std::marker::PhantomData<T>,
69 }
70
71 impl<T: Default> Foo<T> {
72 /// Drop the default value of the generic type.
73 fn generic(self) {
74 drop(T::default());
75 }
76
77 /// A `#[ctor]` method in a generic `impl`.
78 #[ctor(unsafe)]
79 fn ctor() {
80 libc_println!("Foo::ctor");
81 }
82 }
83
84 fn main() {
85 libc_println!("main!");
86 libc_println!("SHOWCASE_GLOBAL = {:?}", *SHOWCASE_GLOBAL);
87 libc_println!("module::STATIC_CTOR = {:?}", *module::STATIC_CTOR);
88
89 // Only one ctor call runs across monomorphizations; generics are unavailable in ctor bodies.
90 Foo::<u32>::default().generic();
91 Foo::<u64>::default().generic();
92 }