8000 Think a bit more about TaAlloc · Issue #27 · lrs-lang/lib · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Think a bit more about TaAlloc #27
Open
@mahkoh

Description

@mahkoh

TaAlloc uses the following pool:

/// The memory pool of TaAlloc.
#[derive(Copy)]
pub struct TaPool<'a> {
    pool: *mut *mut [u8],
    _data: PhantomData<&'a ()>,
}

impl<'a> TaPool<'a> {
    /// Creates a new pool from a byte slice.
    ///
    /// [argument, pool]
    /// A reference to the slice that will be used for allocation.
    pub fn new(pool: &'a mut &mut [u8]) -> TaPool<'a> {
        TaPool {
            pool: unsafe { mem::cast(pool) },
            _data: PhantomData,
        }
    }

    // It would be better if the return value here were *mut *mut, but this is a bit more
    // convenient. Just remember that you cannot move a slice into here whose lifetime is
    // shorter than the lifetime of the original slice.
    unsafe fn get(&mut self) -> &mut &mut [u8] {
        mem::cast(self.pool)
    }
}

Note that this pool is copy. This allows us to do things like this:

use std::alloc::{TaPool, TaAlloc};

fn main() {
    let mut buf = &mut [0; 16][..];

    {
        let pool = TaPool::new(&mut buf);

        let mut vec1: Vec<u8, TaAlloc> = Vec::with_pool(pool);
        let mut vec2: Vec<u8, TaAlloc> = Vec::with_pool(pool);

        vec1.push(1);
        vec2.push(2);
        vec1.push(3);
        vec2.push(4);
        vec1.push(5);
        vec2.push(6);

        println!("vec1: {:?}", vec1);
        println!("vec2: {:?}", vec2);
    }

    println!("buf: {:?}", buf);
}

Which prints

vec1: [1, 3, 5]
vec2: [2, 4, 6]
buf: [0, 0]

So, through the pool, 14 bytes were allocated from the buffer. I think this is sound, but someone else might want to take another look.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0