1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
use core::{
    alloc::{AllocErr, AllocInit, AllocRef, Layout, MemoryBlock, ReallocPlacement},
    ptr::NonNull,
};

/// ```rust
/// #![feature(allocator_api)]
///
/// use alloc_compose::Quantizer;
/// use core::mem;
/// use std::alloc::{AllocInit, AllocRef, Global, Layout};
///
/// let mut quantizer = Quantizer {
///     allocator: Global,
///     func: |u| u * 2,
/// };
///
/// let memory = quantizer.alloc(Layout::new::<u32>(), AllocInit::Uninitialized)?;
/// assert!(
///     memory.size >= mem::size_of::<u32>() * 2,
///     "expected: {}, got: {}",
///     mem::size_of::<u32>() * 2,
///     memory.size,
/// );
/// # Ok::<_, core::alloc::AllocErr>(())
/// ```
pub struct Quantizer<A, F> {
    pub allocator: A,
    pub func: F,
}

impl<A, F> Quantizer<A, F>
where
    F: Fn(usize) -> usize,
{
    fn extend_size(&self, size: usize) -> usize {
        let new_size = (self.func)(size);
        debug_assert!(new_size >= size, "Invalid rounding function");
        new_size
    }

    fn extend_layout_unchecked(&self, layout: Layout) -> Layout {
        unsafe {
            Layout::from_size_align_unchecked(self.extend_size(layout.size()), layout.align())
        }
    }

    fn extend_layout(&self, layout: Layout) -> Result<Layout, AllocErr> {
        let size = self.extend_size(layout.size());
        if size > usize::MAX - (layout.align() - 1) {
            return Err(AllocErr);
        }
        unsafe { Ok(Layout::from_size_align_unchecked(size, layout.align())) }
    }
}

unsafe impl<A, F> AllocRef for Quantizer<A, F>
where
    A: AllocRef,
    F: Fn(usize) -> usize,
{
    fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
        let layout = self.extend_layout(layout)?;
        let mut memory = self.allocator.alloc(layout, init)?;
        memory.size = layout.size();
        Ok(memory)
    }

    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
        self.allocator
            .dealloc(ptr, self.extend_layout_unchecked(layout))
    }

    unsafe fn grow(
        &mut self,
        ptr: NonNull<u8>,
        layout: Layout,
        new_size: usize,
        placement: ReallocPlacement,
        init: AllocInit,
    ) -> Result<MemoryBlock, AllocErr> {
        let allocated = self.extend_layout_unchecked(layout);
        let needed =
            self.extend_layout(Layout::from_size_align_unchecked(new_size, layout.align()))?;
        debug_assert!(new_size <= allocated.size());
        debug_assert!(new_size <= needed.size());
        debug_assert!(allocated.size() <= needed.size());
        if allocated.size() == needed.size() {
            return Ok(MemoryBlock {
                ptr,
                size: layout.size(),
            });
        }
        let mut memory = self
            .allocator
            .grow(ptr, layout, needed.size(), placement, init)?;
        memory.size = needed.size();
        Ok(memory)
    }

    unsafe fn shrink(
        &mut self,
        _ptr: NonNull<u8>,
        _layout: Layout,
        _new_size: usize,
        _placement: ReallocPlacement,
    ) -> Result<MemoryBlock, AllocErr> {
        unimplemented!()
    }
}