xref: /linux/rust/pin-init/examples/big_struct_in_place.rs (revision 09808839c7aa6695ceff5cd822c18b0d9550184d)
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 #![cfg_attr(USE_RUSTC_FEATURES, feature(lint_reasons))]
4 #![cfg_attr(USE_RUSTC_FEATURES, feature(raw_ref_op))]
5 
6 use pin_init::*;
7 
8 // Struct with size over 1GiB
9 #[derive(Debug)]
10 #[allow(dead_code)]
11 pub struct BigStruct {
12     buf: [u8; 1024 * 1024 * 1024],
13     a: u64,
14     b: u64,
15     c: u64,
16     d: u64,
17     managed_buf: ManagedBuf,
18 }
19 
20 #[derive(Debug)]
21 pub struct ManagedBuf {
22     buf: [u8; 1024 * 1024],
23 }
24 
25 impl ManagedBuf {
26     pub fn new() -> impl Init<Self> {
27         init!(ManagedBuf { buf <- init_zeroed() })
28     }
29 }
30 
31 fn main() {
32     #[cfg(any(feature = "std", feature = "alloc"))]
33     {
34         // we want to initialize the struct in-place, otherwise we would get a stackoverflow
35         let buf: Box<BigStruct> = Box::init(init!(BigStruct {
36             buf <- init_zeroed(),
37             a: 7,
38             b: 186,
39             c: 7789,
40             d: 34,
41             managed_buf <- ManagedBuf::new(),
42         }))
43         .unwrap();
44         println!("{}", core::mem::size_of_val(&*buf));
45     }
46 }
47