Skip to main content

diskann_quantization/alloc/
traits.rs

1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6use std::ptr::NonNull;
7
8use thiserror::Error;
9
10/// Indicate that an allocation error has occurred.
11///
12/// This type is limited in what it can contain because additional context
13/// inevitably requires more memory allocation, which is what we're trying to avoid.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
15#[error("unknown allocation error")]
16pub struct AllocatorError;
17
18/// A dynamic memory allocator for use with [`crate::alloc::Poly`].
19///
20/// # Safety
21///
22/// Implementations must ensure that if `allocate` succeeds, the returned slice has a length
23/// of at least `layout.size()` bytes and an alignment of at least `layout.align()`. If this
24/// cannot be satisfied, then an error **must** be returned.
25pub unsafe trait AllocatorCore {
26    /// Allocate space for at least `layout.size()` bytes aligned to at least
27    /// `layout.align()`. Returns an error if the requested size or alignment is not
28    /// possible with this allocator.
29    fn allocate(&self, layout: std::alloc::Layout) -> Result<NonNull<[u8]>, AllocatorError>;
30
31    /// Deallocation companion to `allocate`.
32    ///
33    /// # Safety
34    ///
35    /// The caller must ensure that
36    ///
37    /// 1. `ptr` is "currently allocated" from the allocator.
38    ///    See: <https://doc.rust-lang.org/std/alloc/trait.Allocator.html#currently-allocated-memory>
39    /// 2. `ptr` has the same base pointer as the slice-pointer returned from [`Self::allocate`].
40    /// 3. `layout` is the same layout that was passed to [`Self::allocate`] for this pointer.
41    unsafe fn deallocate(&self, ptr: NonNull<[u8]>, layout: std::alloc::Layout);
42}
43
44/// A dynamic memory allocator for use with [`crate::alloc::Poly`].
45///
46/// Users should implement [`AllocatorCore`] instead and use the blanket implementation for
47/// the full cloneable allocator.
48pub trait Allocator: AllocatorCore + Clone {}
49
50impl<T> Allocator for T where T: AllocatorCore + Clone {}