rust/src/libstd/sys.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Misc low level stuff
2012-03-10 00:04:09 -08:00
#[allow(missing_doc)];
use c_str::ToCStr;
use libc::size_t;
use libc;
use rt::task;
/// Trait for initiating task failure.
pub trait FailWithCause {
/// Fail the current task, taking ownership of `cause`
fn fail_with(cause: Self, file: &'static str, line: uint) -> !;
}
impl FailWithCause for ~str {
fn fail_with(cause: ~str, file: &'static str, line: uint) -> ! {
do cause.with_c_str |msg_buf| {
do file.with_c_str |file_buf| {
task::begin_unwind(msg_buf, file_buf, line as libc::size_t)
}
}
}
}
impl FailWithCause for &'static str {
fn fail_with(cause: &'static str, file: &'static str, line: uint) -> ! {
do cause.with_c_str |msg_buf| {
do file.with_c_str |file_buf| {
task::begin_unwind(msg_buf, file_buf, line as libc::size_t)
}
}
}
}
2012-01-17 17:28:21 -08:00
#[cfg(test)]
mod tests {
use cast;
use sys::*;
2012-01-17 17:28:21 -08:00
2012-08-29 14:04:10 -07:00
#[test]
fn synthesize_closure() {
use unstable::raw::Closure;
unsafe {
let x = 10;
let f: &fn(int) -> int = |y| x + y;
2012-08-29 14:04:10 -07:00
assert_eq!(f(20), 30);
2012-08-29 14:04:10 -07:00
2013-02-15 03:51:28 -05:00
let original_closure: Closure = cast::transmute(f);
2012-08-29 14:04:10 -07:00
let actual_function_pointer = original_closure.code;
let environment = original_closure.env;
2012-08-29 14:04:10 -07:00
let new_closure = Closure {
code: actual_function_pointer,
env: environment
};
2012-08-29 14:04:10 -07:00
let new_f: &fn(int) -> int = cast::transmute(new_closure);
assert_eq!(new_f(20), 30);
}
2012-08-29 14:04:10 -07:00
}
#[test]
#[should_fail]
fn fail_static() { FailWithCause::fail_with("cause", file!(), line!()) }
#[test]
#[should_fail]
fn fail_owned() { FailWithCause::fail_with(~"cause", file!(), line!()) }
2012-01-17 17:28:21 -08:00
}