At present, if you want to statically initialize parameters in code, then you often need Cow<'static,[T]> fields, so that slice types could be created both at runtime via Cow::Owned(vec) and at compile time via Cow::Borrowed(&[..]).
This Cow trick enables shallow clones nicely, but maybe incurs a variant check. I'd hope rustc optimizes away that variant check!
You'd never use &'static Box<[T]> directly, since it incurs an indirection, without any benefits, but..
If you never clone the data, then you might've some big parameters struct containing many slices, so why not use Box<[T]> and create them at compile time?
pub struct Parameters {
foo: Box<[u64]>,
}
static PARAMETERS: &'static Parameters = &Parameters {
foo: unsafe { box_from_static_slice(&[1,2,3,4,5,6]) },
};
pub const unsafe fn box_from_static_slice<T: 'static>(x: &'static [T]) -> Box<[T]> {
unsafe { core::mem::transmute(x) }
}
In this case, rustc complains it "encountered mutable reference or box pointing to read-only memory" under [E0080], with an acknoledgement that "this check might be overzealous".
Should this be allowed? Or should we simply say that Cow<'static,[T]> is idomatic here, and that rustc must optimize away the variant check?
In fact, there maybe an optimization conflict here: Cow<'static,[T]> needs three usize and the variant, while Box<[T]> needs only two usize, so if rustc optimizes agressively for space then it'll treat the NonNull pointer as the variant flag, which then prevents optimizing away the variant check.
Ergo, should we use some ToOwnedBox trait with <[T] as ToOwned>::Owned = Box<[T]> and a corresponding CowBox<'a,T> type, which definitely saves one usize? If so, would rustc optimize away the variant check here?