use std::alloc;
use std::alloc::Layout;
use std::mem;
use std::ops::Deref;
use std::ptr;

struct Inner<T: ?Sized> {
    start: usize,
    len: usize,
    buf: T,
}

pub struct Static<T, const N: usize> {
    inner: Inner<[T; N]>,
}

pub struct Dynamic<T> {
    inner: Box<Inner<[T]>>,
}

#[repr(transparent)]
pub struct Ref<T> {
    inner: Inner<[T]>,
}

impl<T, const N: usize> Deref for Static<T, N> {
    type Target = Ref<T>;

    fn deref(&self) -> &Self::Target {
        let inner: &Inner<[T]> = &self.inner;
        unsafe { mem::transmute::<&Inner<[T]>, &Ref<T>>(inner) }
    }
}

impl<T> Dynamic<T> {
    #[inline]
    fn layout_for(capacity: usize) -> Layout {
        Layout::new::<Inner<()>>()
            .extend(Layout::array::<T>(capacity).expect("..."))
            .expect("...")
            .0
    }

    #[inline]
    fn ptr_to_inner(ptr: *mut u8, capacity: usize) -> *mut Inner<[T]> {
        assert!(!ptr.is_null());
        ptr::slice_from_raw_parts_mut(ptr.cast::<T>(), capacity) as *mut Inner<[T]>
    }

    pub fn new(capacity: usize) -> Self {
        let layout = Self::layout_for(capacity);
        let inner = unsafe {
            let ptr = Self::ptr_to_inner(alloc::alloc(layout), capacity);
            ptr::addr_of_mut!((*ptr).start).write(0);
            ptr::addr_of_mut!((*ptr).len).write(0);
            Box::from_raw(ptr)
        };
        Self { inner }
    }

    pub fn capacity(&self) -> usize {
        self.inner.buf.len()
    }

    pub fn grow(&mut self, new_capacity: usize) {
        assert!(new_capacity >= self.capacity());
        let layout = Self::layout_for(self.capacity());
        let new_layout = Self::layout_for(new_capacity);
        unsafe {
            let ptr = Box::into_raw(ptr::addr_of_mut!(self.inner).read()) as *mut u8;
            let new_ptr =
                Self::ptr_to_inner(alloc::realloc(ptr, layout, new_layout.size()), new_capacity);
            let inner = Box::from_raw(new_ptr);
            ptr::addr_of_mut!(self.inner).write(inner);
        }
    }
}

impl<T> Deref for Dynamic<T> {
    type Target = Ref<T>;

    fn deref(&self) -> &Self::Target {
        let inner: &Inner<[T]> = &self.inner;
        unsafe { mem::transmute::<&Inner<[T]>, &Ref<T>>(inner) }
    }
}

impl<T> Ref<T> {
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn size() {
        // `Dynamic` should have the same size as a fat pointer
        assert_eq!(size_of::<Dynamic<i32>>(), size_of::<*mut [i32]>());
        assert_eq!(size_of::<Dynamic<i32>>(), size_of::<Box<[i32]>>());
        assert_eq!(size_of::<Dynamic<i32>>(), size_of::<[usize; 2]>());
    }

    #[test]
    fn capacity() {
        let mut b = Dynamic::<i32>::new(10);
        assert_eq!(b.capacity(), 10);

        b.grow(20);
        assert_eq!(b.capacity(), 20);
    }

    #[test]
    fn deref() {
        let b = Dynamic::<i32>::new(0);
        assert_eq!(b.len(), 0);
    }
}
