return a Result from StackSource::get_stack with an associated Error

fix #7
This commit is contained in:
edef 2015-04-16 04:14:18 -04:00
parent 42db0ee5b1
commit b8211689fa
4 changed files with 18 additions and 19 deletions

View File

@ -8,7 +8,7 @@ static mut ctx_slot: *mut Context<'static, lwkt::os::Stack> = 0 as *mut Context<
#[bench]
fn swap(b: &mut test::Bencher) {
unsafe {
let stack = lwkt::os::StackSource::get_stack(4 << 20);
let stack = lwkt::os::StackSource::get_stack(4 << 20).unwrap();
let mut ctx = Context::new(stack, move || {
let ctx_ptr = ctx_slot;

View File

@ -7,7 +7,7 @@ static mut ctx_slot: *mut Context<'static, lwkt::os::Stack> = 0 as *mut Context<
fn main() {
unsafe {
let stack = lwkt::os::StackSource::get_stack(4 << 20);
let stack = lwkt::os::StackSource::get_stack(4 << 20).unwrap();
let mut ctx = Context::new(stack, move || {
println!("it's alive!");

View File

@ -17,7 +17,9 @@ pub struct StackSource;
impl stack::StackSource for StackSource {
type Output = Stack;
fn get_stack(size: usize) -> Stack {
type Error = IoError;
fn get_stack(size: usize) -> Result<Stack, IoError> {
Stack::new(size)
}
}
@ -37,7 +39,7 @@ impl stack::Stack for Stack {
}
impl Stack {
fn new(size: usize) -> Stack {
fn new(size: usize) -> Result<Stack, IoError> {
let page_size = sys::page_size();
// round the page size up,
@ -45,25 +47,20 @@ impl Stack {
let len = (size + page_size - 1) & !(page_size - 1);
let stack = unsafe {
let ptr = match sys::map_stack(size) {
None => {
panic!("mmap for stack of size {} failed: {}",
len, IoError::last_os_error())
}
Some(ptr) => ptr
};
let ptr = try!(match sys::map_stack(size) {
None => Err(IoError::last_os_error()),
Some(ptr) => Ok(ptr)
});
Stack { ptr: ptr as *mut u8, len: len }
};
unsafe {
if !sys::protect_stack(stack.ptr) {
panic!("mprotect for guard page of stack {:p} failed: {}",
stack.ptr, IoError::last_os_error());
}
}
try!(unsafe {
if sys::protect_stack(stack.ptr) { Ok(()) }
else { Err(IoError::last_os_error()) }
});
stack
Ok(stack)
}
}

View File

@ -1,4 +1,5 @@
//! Traits for stacks.
use core::prelude::*;
/// A trait for objects that hold ownership of a stack.
pub trait Stack {
@ -15,5 +16,6 @@ pub trait Stack {
/// A trait for objects that provide stacks of arbitrary size.
pub trait StackSource {
type Output: Stack;
fn get_stack(size: usize) -> Self::Output;
type Error = ();
fn get_stack(size: usize) -> Result<Self::Output, Self::Error>;
}