#memory-allocator #memory #malloc #read-memory #madvise

alloc-madvise

用于创建大块对齐内存的内存分配器

3 个版本 (破坏性更新)

0.4.0 2024年6月19日
0.3.0 2023年1月19日
0.2.0 2023年1月19日

#165内存管理

Download history 100/week @ 2024-06-15 12/week @ 2024-06-22

每月 140 次下载

EUPL-1.2

26KB
514

对齐分配器

用于以最佳方式创建大块对齐内存的内存分配器。此库旨在独立使用或通过 FFI 与原始用例(.NET P/Invoke)一起使用。

fn main() {
    const TWO_MEGABYTES: usize = 2 * 1024 * 1024;
    const SIZE: usize = TWO_MEGABYTES * 2;

    // Allocate 4 MiB of aligned, zeroed-out, sequential read memory.
    // The memory will be automatically freed when it leaves scope.
    let memory = Memory::allocate(SIZE, true, true)
        .expect("allocation failed");

    assert_ne!(memory.address, std::ptr::null_mut());
    assert_eq!((memory.address as usize) % TWO_MEGABYTES, 0);

    // Get a reference to a mutable slice.
    let data: &mut [f32] = memory.as_mut();
    data[0] = 1.234;
    data[1] = 5.678;

    // Get a reference to an immutable slice.
    let reference: &[f32] = memory.as_ref();
    assert_eq!(reference[0], 1.234);
    assert_eq!(reference[1], 5.678);
    assert_eq!(reference[2], 0.0);
    assert_eq!(reference.len(), memory.len() / std::mem::size_of::<f32>());
}

构建

cargo build --release

为了创建更小的库,运行例如:

strip target/release/liballoc_madvise.so

请注意,未来的 Cargo 版本将具有剥离调试符号的选项。

C/C++ FFI

对于 FFI,库以 dylib 和 staticlib 两种形式构建。构建 crate 将自动生成包含声明的头文件

#include <cstdarg>
#include <cstdint>
#include <cstdlib>
#include <ostream>
#include <new>

namespace ffi {

/// Information about the allocated memory.
struct Memory {
  /// The allocation status: 0 if valid.
  uint32_t status;
  /// Allocation flags. Used internally when calling free.
  uint32_t flags;
  /// The number of allocated bytes. Used internally when calling free.
  uint32_t num_bytes;
  /// The address of the allocated memory.
  void *address;
};

extern "C" {

/// Gets a version reference in order to identify the library version.
const char *version();

/// Allocates memory of the specified number of bytes.
///
/// The optimal alignment will be determined by the number of bytes provided.
/// If the amount of bytes is a multiple of 2MB, Huge/Large Page support is enabled.
Memory allocate_block(uint32_t num_bytes, bool sequential, bool clear);

/// Frees memory of the specified number of bytes.
///
/// The memory instance is required to be created by `allocate`.
void free_block(Memory memory);

} // extern "C"

} // namespace ffi

依赖项

~0–1MB
~10K SLoC