Hi everyone,

Introduction

I'm in the process of updating my bump allocation library for the upcoming allocator api stabilization. While being an implementor of Allocator my bump allocator also has helper methods like:

fn alloc<T>(&self, value: T) -> BumpAllocation<T, &Self>; fn alloc_slice_clone<T>(&self, slice: &[T]) -> BumpAllocation<[T], &Self>; fn alloc_fmt(&self, args: fmt::Arguments<'_>) -> BumpAllocation<str, &Self>; 

Often when using a bump allocator you'd be fine if these alloc methods just returned a &mut T. That's what the most popular bump allocation library bumpalo is doing.

However when storing types with a drop implementation or consuming methods you'd rather want a Box<T, A>. Now my thinking was that instead of choosing one or the other I return a meant-to-be temporary type called BumpAllocation<T, A> which has consuming methods to convert to your desired type:

fn into_ref(self) -> &T; fn into_mut(self) -> &mut T; fn into_box(self) -> Box<T, A>; 

Now you might want the Box<T, _> semantics but don't want the box to carry around a reference to the bump allocator. I make that possible with:

fn into_boxu(self) -> BoxU<'a, T>; 

Here BoxU<'a, T> is an alias for Box<T, Unmanaged<'a>> where Unmanaged is a dummy allocator that is zero sized. The only information it carries is the lifetime for the allocation. A BoxU will panic on .clone() or other apis that try to allocate/grow.

So whenever you'd use these alloc apis you'd immediately call one of the into_* methods like:

let boxed: Box<T, _> = bump.alloc(value).into_box(); 

Question

I'm thinking about renaming into_* to as_* since it would read as "allocate as (a) box" which sounds better to me. Though I know as_* is conventionally used to return a reference from a reference (with some exceptions like Duration::as_millis).

In my head as makes more sense than into since I'm only choosing what type I want the allocation to be returned as. It's less about converting one type to another, which into implies to me. In a sense it's a bit like a builder pattern.

But what do you think? Would the naming be better with into_ or as_, or a different api entirely?

1 post - 1 participant

Read full topic