Fortune for rsh's current commit: Half curse − 半凶specialisation
parent
4877a843bd
commit
226901861a
@ -0,0 +1,38 @@
|
|||||||
|
//! Extensions
|
||||||
|
use super::*;
|
||||||
|
use std::mem::{self, MaybeUninit};
|
||||||
|
use std::iter;
|
||||||
|
|
||||||
|
/// Max size of memory allowed to be allocated on the stack.
|
||||||
|
pub const STACK_MEM_ALLOC_MAX: usize = 4096;
|
||||||
|
|
||||||
|
pub fn vec_uninit<T>(sz: usize) -> Vec<MaybeUninit<T>>
|
||||||
|
{
|
||||||
|
let mut mem: Vec<T> = Vec::with_capacity(sz);
|
||||||
|
unsafe {
|
||||||
|
mem.set_len(sz);
|
||||||
|
mem::transmute(mem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allocate a local buffer initialised with `init`.
|
||||||
|
pub fn alloc_local_with<T, U>(sz: usize, init: impl FnMut() -> T, within: impl FnOnce(&mut [T]) -> U) -> U
|
||||||
|
{
|
||||||
|
if sz > STACK_MEM_ALLOC_MAX {
|
||||||
|
let mut memory: Vec<T> = iter::repeat_with(init).take(sz).collect();
|
||||||
|
within(&mut memory[..])
|
||||||
|
} else {
|
||||||
|
stackalloc::stackalloc_with(sz, init, within)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allocate a local buffer initialised with `init`.
|
||||||
|
pub fn alloc_local<T: Clone, U>(sz: usize, init: T, within: impl FnOnce(&mut [T]) -> U) -> U
|
||||||
|
{
|
||||||
|
if sz > STACK_MEM_ALLOC_MAX {
|
||||||
|
let mut memory: Vec<T> = iter::repeat(init).take(sz).collect();
|
||||||
|
within(&mut memory[..])
|
||||||
|
} else {
|
||||||
|
stackalloc::stackalloc(sz, init, within)
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue