How to allocate a large structure in a heap baked `Arc<T>` without stack overflow in Rust?

91 views Asked by At

I have a large structure.

The size of arrays is known at compile time and I will not use multiple Vec<_> for that.

This current initialization code trigger a stack overflow in unoptimized builds:

use std::sync::atomic::AtomicUsize;
use std::sync::Arc;

#[derive(Debug)]
pub struct OuterStruct {
    pub big_array_0: [u32; 108],

    pub big_array_1: std::sync::Mutex<[Option<String>; 65536]>,

    pub big_array_2: [AtomicUsize; 65536],
}

fn main() {
    let manager = Arc::new(OuterStruct {
        big_array_0: [0; 108], // Doesn't explode my stack

        big_array_1: std::sync::Mutex::new(std::array::from_fn(|_| None)),

        big_array_2: std::array::from_fn(|_| 0.into()),
    });
}

So how do I allocate this structure in it's own Arc<OuterStruct> baked heap allocation without triggering a stack overflow ?

I am using latest stable Rust, prefer avoiding unsafe code and I have #![deny(invalid_value)] so some std::mem::MaybeUninit based solutions will error (these would cause warnings anyway).

0

There are 0 answers