blit-ui 0.1.0

an experimental immediate-mode ui library
Documentation
use alloc::vec::Vec;
use core::{
    cell::Cell,
    fmt::{self, Write as _},
    mem::{MaybeUninit, align_of, size_of},
    ops::{Deref, DerefMut},
};

use crate::internal::bump::Bump;

/// reusable storage for temporary slices and formatted text
#[derive(Default)]
pub struct ScratchBuffer {
    pub(crate) bump: Bump,
    used: Cell<usize>,
    peak: Cell<usize>,
    live: Cell<usize>,
}

impl ScratchBuffer {
    /// reserves capacity without initializing elements
    /// pushing past it grows in place while this is the newest guard and spills to the heap otherwise
    pub fn alloc<T: Copy>(&self, capacity: usize) -> Scratch<'_, T> {
        const {
            assert!(
                align_of::<T>() <= Bump::ALIGNMENT,
                "scratch alignment exceeds arena alignment"
            );
        }
        let start = self.used.get().max(self.bump.used());
        let offset = start.next_multiple_of(align_of::<T>());
        let end = size_of::<T>()
            .checked_mul(capacity)
            .and_then(|bytes| offset.checked_add(bytes))
            .filter(|&end| end <= isize::MAX as usize)
            .expect("too much scratch data");
        let live = self.live.get().checked_add(1).expect("too many scratch guards");
        // owned guards never occupy the arena so only borrowed ones advance used
        let inner = if end <= self.bump.capacity() {
            self.used.set(end);
            // safety: this aligned range starts past every live guard and ends within capacity
            ScratchInner::Ref(unsafe { core::slice::from_raw_parts_mut(self.slots(offset, capacity), capacity) })
        } else {
            let mut values = Vec::with_capacity(capacity);
            values.resize_with(capacity, MaybeUninit::uninit);
            ScratchInner::Owned(values)
        };
        self.peak.set(self.peak.get().max(end));
        self.live.set(live);
        Scratch {
            inner,
            len: 0,
            buffer: self,
            start,
            end,
        }
    }

    /// formats arguments into temporary scratch storage
    pub fn fmt(&self, arguments: fmt::Arguments<'_>) -> ScratchStr<'_> {
        if let Some(text) = arguments.as_str() {
            return ScratchStr(ScratchStrInner::Borrowed(text));
        }

        struct Writer<'a, 'b>(&'b mut Scratch<'a, u8>);

        impl fmt::Write for Writer<'_, '_> {
            fn write_str(&mut self, text: &str) -> fmt::Result {
                let bytes = text.as_bytes();
                let new_len = self.0.len + bytes.len();
                self.0.grow(new_len);
                self.0.inner.as_mut_slice()[self.0.len..new_len].write_copy_of_slice(bytes);
                self.0.len = new_len;
                Ok(())
            }
        }

        let mut scratch = self.alloc::<u8>(0);
        let _ = Writer(&mut scratch).write_fmt(arguments);
        // trims growth slack so the next guard starts right after the text
        if let ScratchInner::Ref(values) = &mut scratch.inner
            && self.used.get() == scratch.end
        {
            *values = &mut core::mem::take(values)[..scratch.len];
            scratch.end = scratch.start + scratch.len;
            self.used.set(scratch.end);
        }
        ScratchStr(ScratchStrInner::Scratch(scratch))
    }

    /// borrows text or formats arguments into temporary scratch storage
    pub fn str<'a>(&'a self, source: StrSource<'a>) -> ScratchStr<'a> {
        match source {
            StrSource::Borrowed(text) => ScratchStr(ScratchStrInner::Borrowed(text)),
            StrSource::Formatted(arguments) => self.fmt(arguments),
        }
    }

    /// retains enough storage for the previous peak once no guards are borrowed
    pub fn prepare(&mut self) {
        self.bump.reserve(self.peak.get());
        self.used.set(self.bump.used());
        self.live.set(0);
    }
}

/// a growable temporary buffer exposing only its initialized elements
pub struct Scratch<'a, T: Copy> {
    inner: ScratchInner<'a, T>,
    len: usize,
    buffer: &'a ScratchBuffer,
    start: usize,
    end: usize,
}

impl<T: Copy> Scratch<'_, T> {
    pub fn capacity(&self) -> usize {
        self.inner.as_slice().len()
    }

    pub fn push(&mut self, value: T) {
        self.grow(self.len + 1);
        self.inner.as_mut_slice()[self.len].write(value);
        self.len += 1;
    }

    pub fn resize(&mut self, len: usize, value: T) {
        if len > self.len {
            self.grow(len);
            self.inner.as_mut_slice()[self.len..len].fill(MaybeUninit::new(value));
        }
        self.len = len;
    }

    pub fn pop(&mut self) -> Option<T> {
        let value = *self.last()?;
        self.len -= 1;
        Some(value)
    }

    pub fn clear(&mut self) {
        self.len = 0;
    }
}

impl<T: Copy> Deref for Scratch<'_, T> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        // safety: len only includes initialized elements
        unsafe { self.inner.as_slice()[..self.len].assume_init_ref() }
    }
}

impl<T: Copy> Extend<T> for Scratch<'_, T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for value in iter {
            self.push(value);
        }
    }
}

impl<T: Copy> DerefMut for Scratch<'_, T> {
    fn deref_mut(&mut self) -> &mut [T] {
        // safety: len only includes initialized elements and this borrow is exclusive
        unsafe { self.inner.as_mut_slice()[..self.len].assume_init_mut() }
    }
}

impl<T: Copy> Drop for Scratch<'_, T> {
    fn drop(&mut self) {
        let live = self.buffer.live.get() - 1;
        self.buffer.live.set(live);
        // gaps from guards dropped out of order remain until the last guard drops
        if live == 0 {
            self.buffer.used.set(self.buffer.bump.used());
        } else if matches!(self.inner, ScratchInner::Ref(_)) && self.buffer.used.get() == self.end {
            self.buffer.used.set(self.start);
        }
    }
}

/// temporary text borrowed directly or formatted into a [`ScratchBuffer`]
pub struct ScratchStr<'a>(ScratchStrInner<'a>);

impl Deref for ScratchStr<'_> {
    type Target = str;

    fn deref(&self) -> &str {
        match &self.0 {
            ScratchStrInner::Borrowed(text) => text,
            // safety: fmt only writes valid utf-8 slices into the backing scratch buffer
            ScratchStrInner::Scratch(scratch) => unsafe { core::str::from_utf8_unchecked(scratch) },
        }
    }
}

impl AsRef<str> for ScratchStr<'_> {
    fn as_ref(&self) -> &str {
        self
    }
}

/// text from borrowed strings or formatting arguments
#[derive(Clone, Copy, Debug)]
pub enum StrSource<'a> {
    Borrowed(&'a str),
    Formatted(fmt::Arguments<'a>),
}

impl Default for StrSource<'_> {
    fn default() -> Self {
        Self::Borrowed("")
    }
}

impl fmt::Display for StrSource<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Borrowed(text) => f.write_str(text),
            Self::Formatted(arguments) => f.write_fmt(*arguments),
        }
    }
}

impl<'a, T: AsRef<str> + ?Sized> From<&'a T> for StrSource<'a> {
    fn from(text: &'a T) -> Self {
        Self::Borrowed(T::as_ref(text))
    }
}

impl<'a, T: AsRef<str> + ?Sized> From<&'a mut T> for StrSource<'a> {
    fn from(text: &'a mut T) -> Self {
        Self::Borrowed(T::as_ref(text))
    }
}

impl<'a> From<fmt::Arguments<'a>> for StrSource<'a> {
    fn from(arguments: fmt::Arguments<'a>) -> Self {
        match arguments.as_str() {
            Some(text) => Self::Borrowed(text),
            None => Self::Formatted(arguments),
        }
    }
}

//
// internals
//

impl ScratchBuffer {
    /// start of `len` elements at `offset`, dangling when no storage is touched
    fn slots<T>(&self, offset: usize, len: usize) -> *mut MaybeUninit<T> {
        if len == 0 || size_of::<T>() == 0 {
            core::ptr::NonNull::dangling().as_ptr()
        } else {
            self.bump.as_ptr().wrapping_add(offset).cast()
        }
    }
}

impl<T: Copy> Scratch<'_, T> {
    /// ensures capacity for `len` elements
    #[inline]
    fn grow(&mut self, len: usize) {
        // kept out of line so pushes stay small since growth is rare once prepare reserves the peak
        #[cold]
        #[inline(never)]
        fn reallocate<T: Copy>(scratch: &mut Scratch<'_, T>, len: usize) {
            let capacity = scratch.capacity();
            // doubling bounds the spills of one guard to a few allocations
            let target = len.max(capacity.saturating_mul(2));
            let buffer = scratch.buffer;
            let offset = scratch.end - capacity * size_of::<T>();
            let end = size_of::<T>()
                .checked_mul(target)
                .and_then(|bytes| offset.checked_add(bytes))
                .filter(|&end| end <= isize::MAX as usize)
                .expect("too much scratch data");
            // the next prepare reserves this so later frames fit in place
            buffer.peak.set(buffer.peak.get().max(end));
            match &mut scratch.inner {
                ScratchInner::Ref(values) => {
                    let newest = buffer.used.get() == scratch.end;
                    if newest && end <= buffer.bump.capacity() {
                        // safety: as the newest guard nothing else borrows this aligned range up to capacity
                        *values = unsafe { core::slice::from_raw_parts_mut(buffer.slots(offset, target), target) };
                        buffer.used.set(end);
                    } else {
                        let mut owned = Vec::with_capacity(target);
                        owned.extend_from_slice(&values[..scratch.len]);
                        owned.resize(target, MaybeUninit::uninit());
                        if newest {
                            buffer.used.set(scratch.start);
                        }
                        scratch.inner = ScratchInner::Owned(owned);
                    }
                }
                ScratchInner::Owned(values) => values.resize(target, MaybeUninit::uninit()),
            }
            scratch.end = end;
        }

        if len > self.capacity() {
            reallocate(self, len);
        }
    }
}

enum ScratchInner<'a, T> {
    Ref(&'a mut [MaybeUninit<T>]),
    Owned(Vec<MaybeUninit<T>>),
}

impl<T> ScratchInner<'_, T> {
    fn as_slice(&self) -> &[MaybeUninit<T>] {
        match self {
            Self::Ref(values) => values,
            Self::Owned(values) => values,
        }
    }

    fn as_mut_slice(&mut self) -> &mut [MaybeUninit<T>] {
        match self {
            Self::Ref(values) => values,
            Self::Owned(values) => values,
        }
    }
}

enum ScratchStrInner<'a> {
    Borrowed(&'a str),
    Scratch(Scratch<'a, u8>),
}