libfringe/src/stack/owned_stack.rs

41 lines
1.3 KiB
Rust
Raw Normal View History

2016-08-19 21:58:45 +08:00
// This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// See the LICENSE file included in this distribution.
extern crate alloc;
use core::slice;
use self::alloc::heap;
2016-08-19 21:58:45 +08:00
use self::alloc::boxed::Box;
use stack::Stack;
2016-08-19 21:58:45 +08:00
/// OwnedStack holds a non-guarded, heap-allocated stack.
#[derive(Debug)]
2016-08-19 21:58:45 +08:00
pub struct OwnedStack(Box<[u8]>);
impl OwnedStack {
/// Allocates a new stack with exactly `size` accessible bytes and alignment appropriate
/// for the current platform using the default Rust allocator.
2016-08-19 21:58:45 +08:00
pub fn new(size: usize) -> OwnedStack {
unsafe {
let aligned_size = size & !(::STACK_ALIGNMENT - 1);
let ptr = heap::allocate(aligned_size, ::STACK_ALIGNMENT);
OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, aligned_size)))
}
2016-08-19 21:58:45 +08:00
}
}
unsafe impl Stack for OwnedStack {
2016-08-19 21:58:45 +08:00
#[inline(always)]
fn base(&self) -> *mut u8 {
// The slice cannot wrap around the address space, so the conversion from usize
// to isize will not wrap either.
let len = self.0.len() as isize;
2016-08-19 21:58:45 +08:00
unsafe { self.limit().offset(len) }
}
#[inline(always)]
fn limit(&self) -> *mut u8 {
self.0.as_ptr() as *mut u8
}
}