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