]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/common/alloc.rs
Auto merge of #107443 - cjgillot:generator-less-query, r=compiler-errors
[rust.git] / library / std / src / sys / common / alloc.rs
1 use crate::alloc::{GlobalAlloc, Layout, System};
2 use crate::cmp;
3 use crate::ptr;
4
5 // The minimum alignment guaranteed by the architecture. This value is used to
6 // add fast paths for low alignment values.
7 #[cfg(any(
8     target_arch = "x86",
9     target_arch = "arm",
10     target_arch = "m68k",
11     target_arch = "mips",
12     target_arch = "powerpc",
13     target_arch = "powerpc64",
14     target_arch = "sparc",
15     target_arch = "asmjs",
16     target_arch = "wasm32",
17     target_arch = "hexagon",
18     all(target_arch = "riscv32", not(target_os = "espidf")),
19     all(target_arch = "xtensa", not(target_os = "espidf")),
20 ))]
21 pub const MIN_ALIGN: usize = 8;
22 #[cfg(any(
23     target_arch = "x86_64",
24     target_arch = "aarch64",
25     target_arch = "mips64",
26     target_arch = "s390x",
27     target_arch = "sparc64",
28     target_arch = "riscv64",
29     target_arch = "wasm64",
30 ))]
31 pub const MIN_ALIGN: usize = 16;
32 // The allocator on the esp-idf platform guarantees 4 byte alignment.
33 #[cfg(any(
34     all(target_arch = "riscv32", target_os = "espidf"),
35     all(target_arch = "xtensa", target_os = "espidf"),
36 ))]
37 pub const MIN_ALIGN: usize = 4;
38
39 pub unsafe fn realloc_fallback(
40     alloc: &System,
41     ptr: *mut u8,
42     old_layout: Layout,
43     new_size: usize,
44 ) -> *mut u8 {
45     // Docs for GlobalAlloc::realloc require this to be valid:
46     let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
47
48     let new_ptr = GlobalAlloc::alloc(alloc, new_layout);
49     if !new_ptr.is_null() {
50         let size = cmp::min(old_layout.size(), new_size);
51         ptr::copy_nonoverlapping(ptr, new_ptr, size);
52         GlobalAlloc::dealloc(alloc, ptr, old_layout);
53     }
54     new_ptr
55 }