<commit_before>//! Timestamp formatting.

use std::time::{SystemTime, UNIX_EPOCH};

use datetime::{LocalDateTime, TimeZone, DatePiece, TimePiece};
use datetime::fmt::DateFormat;
use locale;
use std::cmp;

/// Every timestamp in exa needs to be rendered by a **time format**.
/// Formatting times is tricky, because how a timestamp is rendered can
/// depend on one or more of the following:
///
/// - The user’s locale, for printing the month name as “Feb”, or as “fév”,
///   or as “2月”;
/// - The current year, because certain formats will be less precise when
///   dealing with dates far in the past;
/// - The formatting style that the user asked for on the command-line.
///
/// Because not all formatting styles need the same data, they all have their
/// own enum variants. It’s not worth looking the locale up if the formatter
/// prints month names as numbers.
///
/// Currently exa does not support *custom* styles, where the user enters a
/// format string in an environment variable or something. Just these four.
#[derive(Debug)]
pub enum TimeFormat {

    /// The **default format** uses the user’s locale to print month names,
    /// and specifies the timestamp down to the minute for recent times, and
    /// day for older times.
    DefaultFormat(DefaultFormat),

    /// Use the **ISO format**, which specifies the timestamp down to the
    /// minute for recent times, and day for older times. It uses a number
    /// for the month so it doesn’t need a locale.
    ISOFormat(ISOFormat),

    /// Use the **long ISO format**, which specifies the timestamp down to the
    /// minute using only numbers, without needing the locale or year.
    LongISO,

    /// Use the **full ISO format**, which specifies the timestamp down to the
    /// millisecond and includes its offset down to the minute. This too uses
    /// only numbers so doesn’t require any special consideration.
    FullISO,
}

// There are two different formatting functions because local and zoned
// timestamps are separate types.

impl TimeFormat {
    pub fn format_local(&self, time: SystemTime) -> String {
        match *self {
            TimeFormat::DefaultFormat(ref fmt) => fmt.format_local(time),
            TimeFormat::ISOFormat(ref iso)     => iso.format_local(time),
            TimeFormat::LongISO                => long_local(time),
            TimeFormat::FullISO                => full_local(time),
        }
    }

    pub fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
        match *self {
            TimeFormat::DefaultFormat(ref fmt) => fmt.format_zoned(time, zone),
            TimeFormat::ISOFormat(ref iso)     => iso.format_zoned(time, zone),
            TimeFormat::LongISO                => long_zoned(time, zone),
            TimeFormat::FullISO                => full_zoned(time, zone),
        }
    }
}

#[derive(Debug, Clone)]
pub struct DefaultFormat {

    /// The year of the current time. This gets used to determine which date
    /// format to use.
    pub current_year: i64,

    /// Localisation rules for formatting timestamps.
    pub locale: locale::Time,

    /// Date format for printing out timestamps that are in the current year.
    pub date_and_time: DateFormat<'static>,

    /// Date format for printing out timestamps that *aren’t*.
    pub date_and_year: DateFormat<'static>,
}

impl DefaultFormat {
    pub fn load() -> DefaultFormat {
        use unicode_width::UnicodeWidthStr;

        let locale = locale::Time::load_user_locale()
                       .unwrap_or_else(|_| locale::Time::english());

        let current_year = LocalDateTime::now().year();

        // Some locales use a three-character wide month name (Jan to Dec);
        // others vary between three to four (1月 to 12月, juil.). We check each month width
        // to detect the longest and set the output format accordingly.
        let mut maximum_month_width = 0;
        for i in 0..11 {
            let current_month_width = UnicodeWidthStr::width(&*locale.short_month_name(i));
            maximum_month_width = cmp::max(maximum_month_width, current_month_width);
        }

        let date_and_time = match maximum_month_width {
            4  => DateFormat::parse("{2>:D} {4<:M} {2>:h}:{02>:m}").unwrap(),
            5  => DateFormat::parse("{2>:D} {5<:M} {2>:h}:{02>:m}").unwrap(),
            _  => DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap(),
        };

        let date_and_year = match maximum_month_width {
            4 => DateFormat::parse("{2>:D} {4<:M} {5>:Y}").unwrap(),
            5 => DateFormat::parse("{2>:D} {5<:M} {5>:Y}").unwrap(),
            _ => DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
        };

        DefaultFormat { current_year, locale, date_and_time, date_and_year }
    }
}

impl DefaultFormat {
    fn is_recent(&self, date: LocalDateTime) -> bool {
        date.year() == self.current_year
    }

    fn month_to_abbrev(month: datetime::Month) -> &'static str {
        match month {
            datetime::Month::January => "Jan",
            datetime::Month::February => "Feb",
            datetime::Month::March => "Mar",
            datetime::Month::April => "Apr",
            datetime::Month::May => "May",
            datetime::Month::June => "Jun",
            datetime::Month::July => "Jul",
            datetime::Month::August => "August",
            datetime::Month::September => "Sep",
            datetime::Month::October => "Oct",
            datetime::Month::November => "Nov",
            datetime::Month::December => "Dec",
        }
    }

    #[allow(trivial_numeric_casts)]
    fn format_local(&self, time: SystemTime) -> String {
        if time == UNIX_EPOCH {
            return "-".to_string();
        }
        let date = LocalDateTime::at(systemtime_epoch(time));

        if self.is_recent(date) {
            format!("{:2} {} {:02}:{:02}",
            date.day(), DefaultFormat::month_to_abbrev(date.month()),
            date.hour(), date.minute())
        }
        else {
            self.date_and_year.format(&date, &self.locale)
        }
    }

    #[allow(trivial_numeric_casts)]
    fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
        if time == UNIX_EPOCH {
            return "-".to_string();
        }

        let date = zone.to_zoned(LocalDateTime::at(systemtime_epoch(time)));

        if self.is_recent(date) {
            format!("{:2} {} {:02}:{:02}",
            date.day(), DefaultFormat::month_to_abbrev(date.month()),
            date.hour(), date.minute())
        }
        else {
            self.date_and_year.format(&date, &self.locale)
        }
    }
}

fn systemtime_epoch(time: SystemTime) -> i64 {
    time
        .duration_since(UNIX_EPOCH)
        .map(|t| t.as_secs() as i64)
        .unwrap_or_else(|e| -(e.duration().as_secs() as i64))
}

fn systemtime_nanos(time: SystemTime) -> u32 {
    time
        .duration_since(UNIX_EPOCH)
        .map(|t| t.subsec_nanos())
        .unwrap_or_else(|e| e.duration().subsec_nanos())
}

#[allow(trivial_numeric_casts)]
fn long_local(time: SystemTime) -> String {
    let date = LocalDateTime::at(systemtime_epoch(time));
    format!("{:04}-{:02}-{:02} {:02}:{:02}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute())
}

#[allow(trivial_numeric_casts)]
fn long_zoned(time: SystemTime, zone: &TimeZone) -> String {
    let date = zone.to_zoned(LocalDateTime::at(systemtime_epoch(time)));
    format!("{:04}-{:02}-{:02} {:02}:{:02}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute())
}

#[allow(trivial_numeric_casts)]
fn full_local(time: SystemTime) -> String {
    let date = LocalDateTime::at(systemtime_epoch(time));
    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute(), date.second(), systemtime_nanos(time))
}

#[allow(trivial_numeric_casts)]
fn full_zoned(time: SystemTime, zone: &TimeZone) -> String {
    use datetime::Offset;

    let local = LocalDateTime::at(systemtime_epoch(time));
    let date = zone.to_zoned(local);
    let offset = Offset::of_seconds(zone.offset(local) as i32).expect("Offset out of range");
    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} {:+03}{:02}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute(), date.second(), systemtime_nanos(time),
            offset.hours(), offset.minutes().abs())
}

#[derive(Debug, Clone)]
pub struct ISOFormat {

    /// The year of the current time. This gets used to determine which date
    /// format to use.
    pub current_year: i64,
}

impl ISOFormat {
    pub fn load() -> ISOFormat {
        let current_year = LocalDateTime::now().year();
        ISOFormat { current_year }
    }
}

impl ISOFormat {
    fn is_recent(&self, date: LocalDateTime) -> bool {
        date.year() == self.current_year
    }

    #[allow(trivial_numeric_casts)]
    fn format_local(&self, time: SystemTime) -> String {
        let date = LocalDateTime::at(systemtime_epoch(time));

        if self.is_recent(date) {
            format!("{:02}-{:02} {:02}:{:02}",
                    date.month() as usize, date.day(),
                    date.hour(), date.minute())
        }
        else {
            format!("{:04}-{:02}-{:02}",
                    date.year(), date.month() as usize, date.day())
        }
    }

    #[allow(trivial_numeric_casts)]
    fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
        let date = zone.to_zoned(LocalDateTime::at(systemtime_epoch(time)));

        if self.is_recent(date) {
            format!("{:02}-{:02} {:02}:{:02}",
                    date.month() as usize, date.day(),
                    date.hour(), date.minute())
        }
        else {
            format!("{:04}-{:02}-{:02}",
                    date.year(), date.month() as usize, date.day())
        }
    }
}
<commit_msg>Correct handling of pre-epoch timestamps<commit_after>//! Timestamp formatting.

use std::time::{SystemTime, UNIX_EPOCH};

use datetime::{LocalDateTime, TimeZone, DatePiece, TimePiece};
use datetime::fmt::DateFormat;
use locale;
use std::cmp;

/// Every timestamp in exa needs to be rendered by a **time format**.
/// Formatting times is tricky, because how a timestamp is rendered can
/// depend on one or more of the following:
///
/// - The user’s locale, for printing the month name as “Feb”, or as “fév”,
///   or as “2月”;
/// - The current year, because certain formats will be less precise when
///   dealing with dates far in the past;
/// - The formatting style that the user asked for on the command-line.
///
/// Because not all formatting styles need the same data, they all have their
/// own enum variants. It’s not worth looking the locale up if the formatter
/// prints month names as numbers.
///
/// Currently exa does not support *custom* styles, where the user enters a
/// format string in an environment variable or something. Just these four.
#[derive(Debug)]
pub enum TimeFormat {

    /// The **default format** uses the user’s locale to print month names,
    /// and specifies the timestamp down to the minute for recent times, and
    /// day for older times.
    DefaultFormat(DefaultFormat),

    /// Use the **ISO format**, which specifies the timestamp down to the
    /// minute for recent times, and day for older times. It uses a number
    /// for the month so it doesn’t need a locale.
    ISOFormat(ISOFormat),

    /// Use the **long ISO format**, which specifies the timestamp down to the
    /// minute using only numbers, without needing the locale or year.
    LongISO,

    /// Use the **full ISO format**, which specifies the timestamp down to the
    /// millisecond and includes its offset down to the minute. This too uses
    /// only numbers so doesn’t require any special consideration.
    FullISO,
}

// There are two different formatting functions because local and zoned
// timestamps are separate types.

impl TimeFormat {
    pub fn format_local(&self, time: SystemTime) -> String {
        match *self {
            TimeFormat::DefaultFormat(ref fmt) => fmt.format_local(time),
            TimeFormat::ISOFormat(ref iso)     => iso.format_local(time),
            TimeFormat::LongISO                => long_local(time),
            TimeFormat::FullISO                => full_local(time),
        }
    }

    pub fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
        match *self {
            TimeFormat::DefaultFormat(ref fmt) => fmt.format_zoned(time, zone),
            TimeFormat::ISOFormat(ref iso)     => iso.format_zoned(time, zone),
            TimeFormat::LongISO                => long_zoned(time, zone),
            TimeFormat::FullISO                => full_zoned(time, zone),
        }
    }
}

#[derive(Debug, Clone)]
pub struct DefaultFormat {

    /// The year of the current time. This gets used to determine which date
    /// format to use.
    pub current_year: i64,

    /// Localisation rules for formatting timestamps.
    pub locale: locale::Time,

    /// Date format for printing out timestamps that are in the current year.
    pub date_and_time: DateFormat<'static>,

    /// Date format for printing out timestamps that *aren’t*.
    pub date_and_year: DateFormat<'static>,
}

impl DefaultFormat {
    pub fn load() -> DefaultFormat {
        use unicode_width::UnicodeWidthStr;

        let locale = locale::Time::load_user_locale()
                       .unwrap_or_else(|_| locale::Time::english());

        let current_year = LocalDateTime::now().year();

        // Some locales use a three-character wide month name (Jan to Dec);
        // others vary between three to four (1月 to 12月, juil.). We check each month width
        // to detect the longest and set the output format accordingly.
        let mut maximum_month_width = 0;
        for i in 0..11 {
            let current_month_width = UnicodeWidthStr::width(&*locale.short_month_name(i));
            maximum_month_width = cmp::max(maximum_month_width, current_month_width);
        }

        let date_and_time = match maximum_month_width {
            4  => DateFormat::parse("{2>:D} {4<:M} {2>:h}:{02>:m}").unwrap(),
            5  => DateFormat::parse("{2>:D} {5<:M} {2>:h}:{02>:m}").unwrap(),
            _  => DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap(),
        };

        let date_and_year = match maximum_month_width {
            4 => DateFormat::parse("{2>:D} {4<:M} {5>:Y}").unwrap(),
            5 => DateFormat::parse("{2>:D} {5<:M} {5>:Y}").unwrap(),
            _ => DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
        };

        DefaultFormat { current_year, locale, date_and_time, date_and_year }
    }
}

impl DefaultFormat {
    fn is_recent(&self, date: LocalDateTime) -> bool {
        date.year() == self.current_year
    }

    fn month_to_abbrev(month: datetime::Month) -> &'static str {
        match month {
            datetime::Month::January => "Jan",
            datetime::Month::February => "Feb",
            datetime::Month::March => "Mar",
            datetime::Month::April => "Apr",
            datetime::Month::May => "May",
            datetime::Month::June => "Jun",
            datetime::Month::July => "Jul",
            datetime::Month::August => "August",
            datetime::Month::September => "Sep",
            datetime::Month::October => "Oct",
            datetime::Month::November => "Nov",
            datetime::Month::December => "Dec",
        }
    }

    #[allow(trivial_numeric_casts)]
    fn format_local(&self, time: SystemTime) -> String {
        if time == UNIX_EPOCH {
            return "-".to_string();
        }
        let date = LocalDateTime::at(systemtime_epoch(time));

        if self.is_recent(date) {
            format!("{:2} {} {:02}:{:02}",
            date.day(), DefaultFormat::month_to_abbrev(date.month()),
            date.hour(), date.minute())
        }
        else {
            self.date_and_year.format(&date, &self.locale)
        }
    }

    #[allow(trivial_numeric_casts)]
    fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
        if time == UNIX_EPOCH {
            return "-".to_string();
        }

        let date = zone.to_zoned(LocalDateTime::at(systemtime_epoch(time)));

        if self.is_recent(date) {
            format!("{:2} {} {:02}:{:02}",
            date.day(), DefaultFormat::month_to_abbrev(date.month()),
            date.hour(), date.minute())
        }
        else {
            self.date_and_year.format(&date, &self.locale)
        }
    }
}

fn systemtime_epoch(time: SystemTime) -> i64 {
    time
        .duration_since(UNIX_EPOCH)
        .map(|t| t.as_secs() as i64)
        .unwrap_or_else(|e| {
            -(e.duration().as_secs() as i64) - e.duration().subsec_nanos().min(1) as i64
        })
}

fn systemtime_nanos(time: SystemTime) -> u32 {
    time
        .duration_since(UNIX_EPOCH)
        .map(|t| t.subsec_nanos())
        .unwrap_or_else(|e| {
            let nanos = e.duration().subsec_nanos();
            if nanos == 0 {
                0
            } else {
                1_000_000_000 - nanos
            }
        })
}

#[allow(trivial_numeric_casts)]
fn long_local(time: SystemTime) -> String {
    let date = LocalDateTime::at(systemtime_epoch(time));
    format!("{:04}-{:02}-{:02} {:02}:{:02}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute())
}

#[allow(trivial_numeric_casts)]
fn long_zoned(time: SystemTime, zone: &TimeZone) -> String {
    let date = zone.to_zoned(LocalDateTime::at(systemtime_epoch(time)));
    format!("{:04}-{:02}-{:02} {:02}:{:02}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute())
}

#[allow(trivial_numeric_casts)]
fn full_local(time: SystemTime) -> String {
    let date = LocalDateTime::at(systemtime_epoch(time));
    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute(), date.second(), systemtime_nanos(time))
}

#[allow(trivial_numeric_casts)]
fn full_zoned(time: SystemTime, zone: &TimeZone) -> String {
    use datetime::Offset;

    let local = LocalDateTime::at(systemtime_epoch(time));
    let date = zone.to_zoned(local);
    let offset = Offset::of_seconds(zone.offset(local) as i32).expect("Offset out of range");
    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} {:+03}{:02}",
            date.year(), date.month() as usize, date.day(),
            date.hour(), date.minute(), date.second(), systemtime_nanos(time),
            offset.hours(), offset.minutes().abs())
}

#[derive(Debug, Clone)]
pub struct ISOFormat {

    /// The year of the current time. This gets used to determine which date
    /// format to use.
    pub current_year: i64,
}

impl ISOFormat {
    pub fn load() -> ISOFormat {
        let current_year = LocalDateTime::now().year();
        ISOFormat { current_year }
    }
}

impl ISOFormat {
    fn is_recent(&self, date: LocalDateTime) -> bool {
        date.year() == self.current_year
    }

    #[allow(trivial_numeric_casts)]
    fn format_local(&self, time: SystemTime) -> String {
        let date = LocalDateTime::at(systemtime_epoch(time));

        if self.is_recent(date) {
            format!("{:02}-{:02} {:02}:{:02}",
                    date.month() as usize, date.day(),
                    date.hour(), date.minute())
        }
        else {
            format!("{:04}-{:02}-{:02}",
                    date.year(), date.month() as usize, date.day())
        }
    }

    #[allow(trivial_numeric_casts)]
    fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
        let date = zone.to_zoned(LocalDateTime::at(systemtime_epoch(time)));

        if self.is_recent(date) {
            format!("{:02}-{:02} {:02}:{:02}",
                    date.month() as usize, date.day(),
                    date.hour(), date.minute())
        }
        else {
            format!("{:04}-{:02}-{:02}",
                    date.year(), date.month() as usize, date.day())
        }
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate objc;

use objc::{Encode, Id, WeakId};
use objc::runtime::{Class, Object};

fn main() {
    // Get a class
    let cls = Class::get("NSObject").unwrap();
    println!("NSObject size: {}", cls.instance_size());

    // Inspect its ivars
    println!("NSObject ivars:");
    for ivar in cls.instance_variables().iter() {
        println!("{}", ivar.name());
    }

    // Allocate an instance
    let obj: Id<Object> = unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        Id::from_retained_ptr(obj)
    };
    println!("NSObject address: {:p}", obj);

    // Access an ivar of the object
    let isa: *const Class = unsafe {
        *obj.get_ivar("isa")
    };
    println!("NSObject isa: {:?}", isa);

    // Inspect a method of the class
    let hash_sel = sel!(hash);
    let hash_method = cls.instance_method(hash_sel).unwrap();
    let hash_return = hash_method.return_type();
    println!("-[NSObject hash] return type: {:?}", hash_return);
    assert!(hash_return == usize::encode());

    // Invoke a method on the object
    let hash: usize = unsafe {
        msg_send![obj, hash]
    };
    println!("NSObject hash: {}", hash);

    // Take a weak reference to the object
    let obj = obj.share();
    let weak = WeakId::new(&obj);
    println!("Weak reference is nil? {}", weak.load().is_none());

    println!("Releasing object");
    drop(obj);
    println!("Weak reference is nil? {}", weak.load().is_none());
}
<commit_msg>Replace Id in example.<commit_after>#[macro_use]
extern crate objc;

use objc::Encode;
use objc::runtime::{Class, Object};

/// Wrapper around an `Object` pointer that will release it when dropped.
struct StrongPtr(*mut Object);

impl std::ops::Deref for StrongPtr {
    type Target = Object;

    fn deref(&self) -> &Object {
        unsafe { &*self.0 }
    }
}

impl Drop for StrongPtr {
    fn drop(&mut self) {
        let _: () = unsafe { msg_send![self.0, release] };
    }
}

fn main() {
    // Get a class
    let cls = Class::get("NSObject").unwrap();
    println!("NSObject size: {}", cls.instance_size());

    // Inspect its ivars
    println!("NSObject ivars:");
    for ivar in cls.instance_variables().iter() {
        println!("{}", ivar.name());
    }

    // Allocate an instance
    let obj = unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        StrongPtr(obj)
    };
    println!("NSObject address: {:p}", &*obj);

    // Access an ivar of the object
    let isa: *const Class = unsafe {
        *obj.get_ivar("isa")
    };
    println!("NSObject isa: {:?}", isa);

    // Inspect a method of the class
    let hash_sel = sel!(hash);
    let hash_method = cls.instance_method(hash_sel).unwrap();
    let hash_return = hash_method.return_type();
    println!("-[NSObject hash] return type: {:?}", hash_return);
    assert!(hash_return == usize::encode());

    // Invoke a method on the object
    let hash: usize = unsafe {
        msg_send![obj, hash]
    };
    println!("NSObject hash: {}", hash);
}
<|endoftext|>


<commit_before>#![feature(test)]

extern crate parity_wasm;
extern crate time;

use std::fs;

fn rate(file_name: &'static str, iterations: u64) {
    let file_size = fs::metadata(file_name).expect(&format!("{} to exist", file_name)).len();
	let mut total_ms = 0;

	for _ in 0..iterations {
		let start = time::PreciseTime::now();
		let _module = parity_wasm::deserialize_file(file_name);
		let end = time::PreciseTime::now();

		total_ms += start.to(end).num_milliseconds();
	}

	println!("Rate for {}: {} MB/s", file_name,
		(file_size as f64 * iterations as f64 / (1024*1024) as f64) /  // total work megabytes
		(total_ms as f64 / 1000f64)									   // total seconds
	);
}

fn main() {
	rate("./res/cases/v1/clang.wasm", 10);
	rate("./res/cases/v1/hello.wasm", 100);
	rate("./res/cases/v1/with_names.wasm", 100);
}<commit_msg>add tabs<commit_after>#![feature(test)]

extern crate parity_wasm;
extern crate time;

use std::fs;

fn rate(file_name: &'static str, iterations: u64) {
	let file_size = fs::metadata(file_name).expect(&format!("{} to exist", file_name)).len();
	let mut total_ms = 0;

	for _ in 0..iterations {
		let start = time::PreciseTime::now();
		let _module = parity_wasm::deserialize_file(file_name);
		let end = time::PreciseTime::now();

		total_ms += start.to(end).num_milliseconds();
	}

	println!("Rate for {}: {} MB/s", file_name,
		(file_size as f64 * iterations as f64 / (1024*1024) as f64) /  // total work megabytes
		(total_ms as f64 / 1000f64)									   // total seconds
	);
}

fn main() {
	rate("./res/cases/v1/clang.wasm", 10);
	rate("./res/cases/v1/hello.wasm", 100);
	rate("./res/cases/v1/with_names.wasm", 100);
}<|endoftext|>


<commit_before>use entities::{ EntitiesState, EntityID, ComponentID, NativeComponentType };
use std::collections::{ HashSet, HashMap };
use std::cell::RefCell;
use std::rc::Rc;
use nalgebra::na;
use nalgebra::na::{ Norm, Translation, Vec2 };
use ncollide::geom::geom::Geom;
use nphysics::world::World;
use nphysics::object::{ RigidBody };

pub struct PhysicsSystem {
	world: World,
	bodies: HashMap<EntityID, Rc<RefCell<RigidBody>>>
}

impl PhysicsSystem {
	pub fn new(_: &EntitiesState)
		-> PhysicsSystem
	{
		let mut world = World::new();
		world.set_gravity(Vec2::new(0.0f32, -9.8));

		let shape = ::ncollide::geom::Plane::new(Vec2::new(0.0f32, 1.0));
		let body = Rc::new(RefCell::new(RigidBody::new_static(shape, 0.3, 0.6)));
		world.add_body(body);

		PhysicsSystem {
			world: world,
			bodies: HashMap::new()
		}
	}

	pub fn process(&mut self, state: &mut EntitiesState, elapsed: &u64)
	{
		// getting the list of all entities that have physics activated
		let listOfEntities: HashSet<EntityID> = state.get_components_iter()
            .filter(|c| state.is_component_visible(*c).unwrap())
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "physics", _ => false })
			.filter(|c| match state.get(*c, "activated") { Ok(&::entities::Boolean(ref b)) => *b, _ => false })
			.map(|c| state.get_owner(c).unwrap())
			.collect();

		// removing from the world the elements that have disappeared
		{
			let toRemove: Vec<EntityID> = self.bodies.keys().filter(|e| !listOfEntities.contains(e.clone())).map(|e| e.clone()).collect();
			for e in toRemove.move_iter() {
				//self.bodies.find(&e).		// TODO: remove body from the world
				self.bodies.remove(&e);
			}
		}

		// adding elements that are not yet in the world
		{
			let toCreate: Vec<EntityID> = listOfEntities.iter().filter(|e| !self.bodies.contains_key(e.clone())).map(|e| e.clone()).collect();
			for e in toCreate.move_iter() {
				let shape = ::ncollide::geom::Cuboid::new(Vec2::new(0.5f32, 0.5f32));
				let body = Rc::new(RefCell::new(RigidBody::new_dynamic(shape, 1.0, 0.5, 0.0)));

				// initializing body with current position and movement
				body.borrow_mut().set_translation(PhysicsSystem::get_position(state, &e));
				body.borrow_mut().set_lin_vel(PhysicsSystem::get_movement(state, &e));

				self.bodies.insert(e.clone(), body.clone());
				self.world.add_body(body.clone());
			}
		}

		// setting all positions and movements
		for (entity, body) in self.bodies.iter() {
			let position = PhysicsSystem::get_position(state, entity);
			let movement = PhysicsSystem::get_movement(state, entity);
			let requestedMovement = PhysicsSystem::get_requested_movement(state, entity);

			let mut borrowedBody = body.borrow_mut();
			borrowedBody.set_translation(position);
			borrowedBody.set_lin_vel(movement);

			if requestedMovement != movement {
				let acceleration = na::normalize(&(requestedMovement - movement)) * 5.0f32;
				borrowedBody.set_lin_acc(acceleration);
			}
		}

		// step
		self.world.step((*elapsed as f32) / 1000.0);

		//
		for (entity, body) in self.bodies.iter() {
			PhysicsSystem::set_position(state, entity, &body.borrow().translation());
			PhysicsSystem::set_movement(state, entity, &body.borrow().lin_vel());
		}
	}

	/// returns the position of an entity
	fn get_position(state: &EntitiesState, id: &EntityID)
		-> Vec2<f32>
	{
		state
			.get_components_iter()

			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)

			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "position", _ => false })

			// build a vector from each of the component
			.filter_map(|cmp| match (state.get(cmp, "x"), state.get(cmp, "y"), state.get(cmp, "z")) {
				(Ok(&::entities::Number(ref x)), Ok(&::entities::Number(ref y)), _)
					=> Some(Vec2::new(*x as f32, *y as f32)),
				_ => None
			})

			// add all the elements together
			.fold(Vec2::new(0.0, 0.0), |vec, a| vec + a)
	}

	/// returns the total movement of an entity
	fn get_movement(state: &EntitiesState, id: &EntityID)
		-> Vec2<f32>
	{
		state
			.get_components_iter()

			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)

			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "movement", _ => false })

			// build a vector from each of the component
			.filter_map(|cmp| match (state.get(cmp, "x"), state.get(cmp, "y"), state.get(cmp, "z")) {
				(Ok(&::entities::Number(ref x)), Ok(&::entities::Number(ref y)), _)
					=> Some(Vec2::new(*x as f32, *y as f32)),
				_ => None
			})

			// add all the elements together
			.fold(Vec2::new(0.0, 0.0), |vec, a| vec + a)
	}

	/// returns the total requested movement of an entity
	fn get_requested_movement(state: &EntitiesState, id: &EntityID)
		-> Vec2<f32>
	{
		state
			.get_components_iter()

			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)

			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "requestedMovement", _ => false })

			// build a vector from each of the component
			.filter_map(|cmp| match (state.get(cmp, "x"), state.get(cmp, "y"), state.get(cmp, "z")) {
				(Ok(&::entities::Number(ref x)), Ok(&::entities::Number(ref y)), _)
					=> Some(Vec2::new(*x as f32, *y as f32)),
				_ => None
			})

			// add all the elements together
			.fold(Vec2::new(0.0, 0.0), |vec, a| vec + a)
	}

	/// changes the position of an entity
	/// TODO: this is wrong
	fn set_position(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
	{
		let list: Vec<ComponentID> = state
			.get_components_iter()
			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)
			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "position", _ => false })
			.map(|c| c.clone()).collect();

		for cmp in list.iter()
		{
			state.set(cmp, "x", ::entities::Number(pos.x as f64));
			state.set(cmp, "y", ::entities::Number(pos.y as f64));
		}
	}

	/// changes the movement of an entity
	/// TODO: this is wrong
	fn set_movement(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
	{
		let list: Vec<ComponentID> = state
			.get_components_iter()
			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)
			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "movement", _ => false })
			.map(|c| c.clone()).collect();

		for cmp in list.iter()
		{
			state.set(cmp, "x", ::entities::Number(pos.x as f64));
			state.set(cmp, "y", ::entities::Number(pos.y as f64));
		}
	}
}
<commit_msg>Having no requestedMovement no longer means request (0,0)<commit_after>use entities::{ EntitiesState, EntityID, ComponentID, NativeComponentType };
use std::collections::{ HashSet, HashMap };
use std::cell::RefCell;
use std::rc::Rc;
use nalgebra::na;
use nalgebra::na::{ Norm, Translation, Vec2 };
use ncollide::geom::geom::Geom;
use nphysics::world::World;
use nphysics::object::{ RigidBody };

pub struct PhysicsSystem {
	world: World,
	bodies: HashMap<EntityID, Rc<RefCell<RigidBody>>>
}

impl PhysicsSystem {
	pub fn new(_: &EntitiesState)
		-> PhysicsSystem
	{
		let mut world = World::new();
		world.set_gravity(Vec2::new(0.0f32, -9.8));

		let shape = ::ncollide::geom::Plane::new(Vec2::new(0.0f32, 1.0));
		let body = Rc::new(RefCell::new(RigidBody::new_static(shape, 0.3, 0.6)));
		world.add_body(body);

		PhysicsSystem {
			world: world,
			bodies: HashMap::new()
		}
	}

	pub fn process(&mut self, state: &mut EntitiesState, elapsed: &u64)
	{
		// getting the list of all entities that have physics activated
		let listOfEntities: HashSet<EntityID> = state.get_components_iter()
            .filter(|c| state.is_component_visible(*c).unwrap())
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "physics", _ => false })
			.filter(|c| match state.get(*c, "activated") { Ok(&::entities::Boolean(ref b)) => *b, _ => false })
			.map(|c| state.get_owner(c).unwrap())
			.collect();

		// removing from the world the elements that have disappeared
		{
			let toRemove: Vec<EntityID> = self.bodies.keys().filter(|e| !listOfEntities.contains(e.clone())).map(|e| e.clone()).collect();
			for e in toRemove.move_iter() {
				//self.bodies.find(&e).		// TODO: remove body from the world
				self.bodies.remove(&e);
			}
		}

		// adding elements that are not yet in the world
		{
			let toCreate: Vec<EntityID> = listOfEntities.iter().filter(|e| !self.bodies.contains_key(e.clone())).map(|e| e.clone()).collect();
			for e in toCreate.move_iter() {
				let shape = ::ncollide::geom::Cuboid::new(Vec2::new(0.5f32, 0.5f32));
				let body = Rc::new(RefCell::new(RigidBody::new_dynamic(shape, 1.0, 0.5, 0.0)));

				// initializing body with current position and movement
				body.borrow_mut().set_translation(PhysicsSystem::get_position(state, &e));
				body.borrow_mut().set_lin_vel(PhysicsSystem::get_movement(state, &e));

				self.bodies.insert(e.clone(), body.clone());
				self.world.add_body(body.clone());
			}
		}

		// setting all positions and movements
		for (entity, body) in self.bodies.iter() {
			let position = PhysicsSystem::get_position(state, entity);
			let movement = PhysicsSystem::get_movement(state, entity);
			let requestedMovement = PhysicsSystem::get_requested_movement(state, entity);

			let mut borrowedBody = body.borrow_mut();
			borrowedBody.set_translation(position);
			borrowedBody.set_lin_vel(movement);

			if requestedMovement.is_some() && requestedMovement != Some(movement) {
				let acceleration = na::normalize(&(requestedMovement.unwrap() - movement)) * 5.0f32;
				borrowedBody.set_lin_acc(acceleration);
			}
		}

		// step
		self.world.step((*elapsed as f32) / 1000.0);

		//
		for (entity, body) in self.bodies.iter() {
			PhysicsSystem::set_position(state, entity, &body.borrow().translation());
			PhysicsSystem::set_movement(state, entity, &body.borrow().lin_vel());
		}
	}

	/// returns the position of an entity
	fn get_position(state: &EntitiesState, id: &EntityID)
		-> Vec2<f32>
	{
		state
			.get_components_iter()

			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)

			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "position", _ => false })

			// build a vector from each of the component
			.filter_map(|cmp| match (state.get(cmp, "x"), state.get(cmp, "y"), state.get(cmp, "z")) {
				(Ok(&::entities::Number(ref x)), Ok(&::entities::Number(ref y)), _)
					=> Some(Vec2::new(*x as f32, *y as f32)),
				_ => None
			})

			// add all the elements together
			.fold(Vec2::new(0.0, 0.0), |vec, a| vec + a)
	}

	/// returns the total movement of an entity
	fn get_movement(state: &EntitiesState, id: &EntityID)
		-> Vec2<f32>
	{
		state
			.get_components_iter()

			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)

			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "movement", _ => false })

			// build a vector from each of the component
			.filter_map(|cmp| match (state.get(cmp, "x"), state.get(cmp, "y"), state.get(cmp, "z")) {
				(Ok(&::entities::Number(ref x)), Ok(&::entities::Number(ref y)), _)
					=> Some(Vec2::new(*x as f32, *y as f32)),
				_ => None
			})

			// add all the elements together
			.fold(Vec2::new(0.0, 0.0), |vec, a| vec + a)
	}

	/// returns the total requested movement of an entity
	fn get_requested_movement(state: &EntitiesState, id: &EntityID)
		-> Option<Vec2<f32>>
	{
		state
			.get_components_iter()

			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)

			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "requestedMovement", _ => false })

			// build a vector from each of the component
			.filter_map(|cmp| match (state.get(cmp, "x"), state.get(cmp, "y"), state.get(cmp, "z")) {
				(Ok(&::entities::Number(ref x)), Ok(&::entities::Number(ref y)), _)
					=> Some(Vec2::new(*x as f32, *y as f32)),
				_ => None
			})

			// add all the elements together
			.fold(None, |vec: Option<Vec2<f32>>, a| match vec { None => Some(a), Some(v) => Some(v + a) })
	}

	/// changes the position of an entity
	/// TODO: this is wrong
	fn set_position(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
	{
		let list: Vec<ComponentID> = state
			.get_components_iter()
			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)
			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "position", _ => false })
			.map(|c| c.clone()).collect();

		for cmp in list.iter()
		{
			state.set(cmp, "x", ::entities::Number(pos.x as f64));
			state.set(cmp, "y", ::entities::Number(pos.y as f64));
		}
	}

	/// changes the movement of an entity
	/// TODO: this is wrong
	fn set_movement(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
	{
		let list: Vec<ComponentID> = state
			.get_components_iter()
			// take only the components owned by the entity
			.filter(|c| state.get_owner(*c).unwrap() == *id)
			// take only the "position" components
			.filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "movement", _ => false })
			.map(|c| c.clone()).collect();

		for cmp in list.iter()
		{
			state.set(cmp, "x", ::entities::Number(pos.x as f64));
			state.set(cmp, "y", ::entities::Number(pos.y as f64));
		}
	}
}
<|endoftext|>


<commit_before>extern crate euclid;
#[macro_use]
extern crate glium;
extern crate serde;
extern crate vitral;
extern crate scancode;
extern crate calx_color;
#[macro_use]
extern crate calx_resource;
extern crate calx_grid;
extern crate world;
extern crate display;
extern crate content;

// Make all mods public at the top app level just to make them show up in the rustdoc.

pub mod mapedit_view;

use euclid::{Point2D, Rect, Size2D};
use glium::{DisplayBuild, glutin};
use world::{Location, Terraform, World};
use mapedit_view::View;

pub fn main() {
    // Construct display and Vitral context.
    let display = glutin::WindowBuilder::new()
                      .build_glium()
                      .unwrap();

    let mut backend = display::Backend::new(&display, 640, 360);

    // Initialize game resources.
    content::init_brushes(&display, &mut backend);
    content::init_terrain();

    let mut context = display::Context {
        ui: vitral::Builder::new().build(|img| backend.make_texture(&display, img)),
        backend: backend,
    };

    // Initialize worldstate
    let mut view = View::new(World::new(1));

    for x in -0..8 {
        for y in 0..8 {
            view.world.set_terrain(Location::new(x, y, 0), 3);
        }
    }

    view.world.set_terrain(Location::new(0, -10, 0), 1);
    view.world.set_terrain(Location::new(1, 0, 0), 3);
    view.world.set_terrain(Location::new(2, 0, 0), 5);
    view.world.set_terrain(Location::new(3, 0, 0), 6);
    view.world.set_terrain(Location::new(4, 0, 0), 6);
    view.world.set_terrain(Location::new(3, 2, 0), 7);
    view.world.set_terrain(Location::new(4, 2, 0), 7);

    // Run game.
    loop {
        context.ui.begin_frame();

        let area = Rect::new(Point2D::new(0.0, 0.0), Size2D::new(640.0, 360.0));
        view.draw(&mut context, &area);

        if !context.backend.update(&display, &mut context.ui) {
            return;
        }
    }
}
<commit_msg>Content-crate-less mapedit<commit_after>extern crate euclid;
#[macro_use]
extern crate glium;
extern crate serde;
extern crate vitral;
extern crate scancode;
extern crate calx_color;
#[macro_use]
extern crate calx_resource;
extern crate calx_grid;
extern crate world;
extern crate display;

// Make all mods public at the top app level just to make them show up in the rustdoc.

pub mod mapedit_view;

use euclid::{Point2D, Rect, Size2D};
use glium::{DisplayBuild, glutin};
use world::{Location, Terraform, World};
use mapedit_view::View;

pub fn main() {
    // Construct display and Vitral context.
    let display = glutin::WindowBuilder::new()
                      .build_glium()
                      .unwrap();

    let mut backend = display::Backend::new(&display, 640, 360);

    // Initialize game resources.
    ::display::init::brushes(&display, &mut backend);
    ::world::init::terrain();

    let mut context = display::Context {
        ui: vitral::Builder::new().build(|img| backend.make_texture(&display, img)),
        backend: backend,
    };

    // Initialize worldstate
    let mut view = View::new(World::new(1));

    for x in -0..8 {
        for y in 0..8 {
            view.world.set_terrain(Location::new(x, y, 0), 3);
        }
    }

    view.world.set_terrain(Location::new(0, -10, 0), 1);
    view.world.set_terrain(Location::new(1, 0, 0), 3);
    view.world.set_terrain(Location::new(2, 0, 0), 5);
    view.world.set_terrain(Location::new(3, 0, 0), 6);
    view.world.set_terrain(Location::new(4, 0, 0), 6);
    view.world.set_terrain(Location::new(3, 2, 0), 7);
    view.world.set_terrain(Location::new(4, 2, 0), 7);

    // Run game.
    loop {
        context.ui.begin_frame();

        let area = Rect::new(Point2D::new(0.0, 0.0), Size2D::new(640.0, 360.0));
        view.draw(&mut context, &area);

        if !context.backend.update(&display, &mut context.ui) {
            return;
        }
    }
}
<|endoftext|>


<commit_before>extern crate tiny_http;

/**!

A web server that redirects every request to a PHP script.

Usage: php-cgi <php-script-path>

*/

use std::os;

fn handle(rq: tiny_http::Request, script: &str) {
    use std::io::process::{Command, ExitStatus, ExitSignal, Ignored};
    use std::io::util;

    let mut php = Command::new("php-cgi")
        .arg(script)
        //.stdin(Ignored)
        //.extra_io(Ignored)
        .env("AUTH_TYPE", "")
        .env("CONTENT_LENGTH", format!("{}", rq.get_body_length().unwrap_or(0)))
        .env("CONTENT_TYPE", "")
        .env("GATEWAY_INTERFACE", "CGI/1.1")
        .env("PATH_INFO", "")
        .env("PATH_TRANSLATED", "")
        .env("QUERY_STRING", format!("{}", rq.get_url()))
        .env("REMOTE_ADDR", format!("{}", rq.get_remote_addr().ip))
        .env("REMOTE_HOST", "")
        .env("REMOTE_IDENT", "")
        .env("REMOTE_USER", "")
        .env("REQUEST_METHOD", format!("{}", rq.get_method()))
        .env("SCRIPT_NAME", script)
        .env("SERVER_NAME", "tiny-http php-cgi example")
        .env("SERVER_PORT", format!("{}", rq.get_remote_addr().port))
        .env("SERVER_PROTOCOL", "HTTP/1.1")
        .env("SERVER_SOFTWARE", "tiny-http php-cgi example")
        .output()
        .unwrap();

    // note: this is not a good implementation
    // cgi returns the status code in the headers ; also many headers will be missing
    //  in the response
    match php.status {
        status if status.success() => {
            let mut writer = rq.into_writer();
            let mut writer: &mut Writer = writer;

            (write!(writer, "HTTP/1.1 200 OK\r\n")).unwrap();
            (write!(writer, "{}", php.output.into_ascii().into_string())).unwrap();

            writer.flush().unwrap();
        },
        _ => {
            println!("Error in script execution: {}", php.error.clone().into_ascii().into_string());
        }
    }
}

fn main() {
    use std::sync::Arc;

    let php_script = {
        let args = os::args();
        if args.len() < 2 { println!("Usage: php-cgi <php-script-path>"); return }
        args[1].to_string()
    };

    let server = Arc::new(tiny_http::ServerBuilder::new().with_port(9975).build().unwrap());
    println!("Now listening on port 9975");

    for _ in range(0, os::num_cpus()) {
        let server = server.clone();
        let php_script = php_script.clone();

        spawn(proc() {
            for rq in server.incoming_requests() {
                handle(rq, php_script.as_slice());
            }
        })
    }
}
<commit_msg>Track Rust master<commit_after>extern crate tiny_http;

/**!

A web server that redirects every request to a PHP script.

Usage: php-cgi <php-script-path>

*/

use std::os;

fn handle(rq: tiny_http::Request, script: &str) {
    use std::io::process::{Command, ExitStatus, ExitSignal, Ignored};
    use std::io::util;

    let mut php = Command::new("php-cgi")
        .arg(script)
        //.stdin(Ignored)
        //.extra_io(Ignored)
        .env("AUTH_TYPE", "")
        .env("CONTENT_LENGTH", format!("{}", rq.get_body_length().unwrap_or(0)))
        .env("CONTENT_TYPE", "")
        .env("GATEWAY_INTERFACE", "CGI/1.1")
        .env("PATH_INFO", "")
        .env("PATH_TRANSLATED", "")
        .env("QUERY_STRING", format!("{}", rq.get_url()))
        .env("REMOTE_ADDR", format!("{}", rq.get_remote_addr().ip))
        .env("REMOTE_HOST", "")
        .env("REMOTE_IDENT", "")
        .env("REMOTE_USER", "")
        .env("REQUEST_METHOD", format!("{}", rq.get_method()))
        .env("SCRIPT_NAME", script)
        .env("SERVER_NAME", "tiny-http php-cgi example")
        .env("SERVER_PORT", format!("{}", rq.get_remote_addr().port))
        .env("SERVER_PROTOCOL", "HTTP/1.1")
        .env("SERVER_SOFTWARE", "tiny-http php-cgi example")
        .output()
        .unwrap();

    // note: this is not a good implementation
    // cgi returns the status code in the headers ; also many headers will be missing
    //  in the response
    match php.status {
        status if status.success() => {
            let mut writer = rq.into_writer();
            let mut writer: &mut Writer = &mut *writer;

            (write!(writer, "HTTP/1.1 200 OK\r\n")).unwrap();
            (write!(writer, "{}", php.output.into_ascii().into_string())).unwrap();

            writer.flush().unwrap();
        },
        _ => {
            println!("Error in script execution: {}", php.error.clone().into_ascii().into_string());
        }
    }
}

fn main() {
    use std::sync::Arc;

    let php_script = {
        let args = os::args();
        if args.len() < 2 { println!("Usage: php-cgi <php-script-path>"); return }
        args[1].to_string()
    };

    let server = Arc::new(tiny_http::ServerBuilder::new().with_port(9975).build().unwrap());
    println!("Now listening on port 9975");

    for _ in range(0, os::num_cpus()) {
        let server = server.clone();
        let php_script = php_script.clone();

        spawn(proc() {
            for rq in server.incoming_requests() {
                handle(rq, php_script.as_slice());
            }
        })
    }
}
<|endoftext|>


<commit_before>extern crate stdweb;

use std::rc::Rc;

use stdweb::unstable::TryInto;
use stdweb::web::{
    IParentNode,
    IEventTarget,
    INode,
    HtmlElement,
    document,
    WebSocket,
};

use stdweb::web::event::{
    IEvent,
    IKeyboardEvent,
    IMessageEvent,
    KeyPressEvent,
    SocketOpenEvent,
    SocketCloseEvent,
    SocketErrorEvent,
    SocketMessageEvent,
};

use stdweb::web::html_element::InputElement;

// Shamelessly stolen from webplatform's TodoMVC example.
macro_rules! enclose {
    ( ($( $x:ident ),*) $y:expr ) => {
        {
            $(let $x = $x.clone();)*
            $y
        }
    };
}

fn main() {
    stdweb::initialize();

    let output_div: HtmlElement = document().query_selector( ".output" ).unwrap().unwrap().try_into().unwrap();
    let output_msg = Rc::new(move |msg: &str| {
        let elem = document().create_element("p").unwrap();
        elem.set_text_content(msg);
        if let Some(child) = output_div.first_child() {
            output_div.insert_before(&elem, &child);
        } else {
            output_div.append_child(&elem);
        }
    });

    output_msg("> Connecting...");

    let ws = WebSocket::new("wss://echo.websocket.org").unwrap();

    ws.add_event_listener( enclose!( (output_msg) move |_: SocketOpenEvent| {
        output_msg("> Opened connection");
    }));

    ws.add_event_listener( enclose!( (output_msg) move |_: SocketErrorEvent| {
        output_msg("> Connection Errored");
    }));

    ws.add_event_listener( enclose!( (output_msg) move |event: SocketCloseEvent| {
        output_msg(&format!("> Connection Closed: {}", event.reason()));
    }));

    ws.add_event_listener( enclose!( (output_msg) move |event: SocketMessageEvent| {
        output_msg(&event.data().into_text().unwrap());
    }));

    let text_entry: InputElement = document().query_selector( ".form input" ).unwrap().unwrap().try_into().unwrap();
    text_entry.add_event_listener( enclose!( (text_entry) move |event: KeyPressEvent| {
        if event.key() == "Enter" {
            event.prevent_default();

            let text: String = text_entry.value().try_into().unwrap();
            if text.is_empty() == false {
                text_entry.set_value("");
                ws.send_text(&text);
            }
        }
    }));

    stdweb::event_loop();
}
<commit_msg>fix compile error in echo example<commit_after>extern crate stdweb;

use std::rc::Rc;

use stdweb::unstable::TryInto;
use stdweb::web::{
    IParentNode,
    IEventTarget,
    INode,
    HtmlElement,
    document,
    WebSocket,
};

use stdweb::web::event::{
    IEvent,
    IKeyboardEvent,
    IMessageEvent,
    KeyPressEvent,
    SocketOpenEvent,
    SocketCloseEvent,
    SocketErrorEvent,
    SocketMessageEvent,
};

use stdweb::web::html_element::InputElement;

// Shamelessly stolen from webplatform's TodoMVC example.
macro_rules! enclose {
    ( ($( $x:ident ),*) $y:expr ) => {
        {
            $(let $x = $x.clone();)*
            $y
        }
    };
}

fn main() {
    stdweb::initialize();

    let output_div: HtmlElement = document().query_selector( ".output" ).unwrap().unwrap().try_into().unwrap();
    let output_msg = Rc::new(move |msg: &str| {
        let elem = document().create_element("p").unwrap();
        elem.set_text_content(msg);
        if let Some(child) = output_div.first_child() {
            output_div.insert_before(&elem, &child);
        } else {
            output_div.append_child(&elem);
        }
    });

    output_msg("> Connecting...");

    let ws = WebSocket::new("wss://echo.websocket.org").unwrap();

    ws.add_event_listener( enclose!( (output_msg) move |_: SocketOpenEvent| {
        output_msg("> Opened connection");
    }));

    ws.add_event_listener( enclose!( (output_msg) move |_: SocketErrorEvent| {
        output_msg("> Connection Errored");
    }));

    ws.add_event_listener( enclose!( (output_msg) move |event: SocketCloseEvent| {
        output_msg(&format!("> Connection Closed: {}", event.reason()));
    }));

    ws.add_event_listener( enclose!( (output_msg) move |event: SocketMessageEvent| {
        output_msg(&event.data().into_text().unwrap());
    }));

    let text_entry: InputElement = document().query_selector( ".form input" ).unwrap().unwrap().try_into().unwrap();
    text_entry.add_event_listener( enclose!( (text_entry) move |event: KeyPressEvent| {
        if event.key() == "Enter" {
            event.prevent_default();

            let text: String = text_entry.raw_value();
            if text.is_empty() == false {
                text_entry.set_raw_value("");
                ws.send_text(&text);
            }
        }
    }));

    stdweb::event_loop();
}
<|endoftext|>


<commit_before>use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process;

const PREVIEW_LEN: usize = 50;

#[derive(Debug, PartialEq)]
struct Match {
    offset: usize,
    key: u8,
    preview: String,
}

fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    if args.len() < 2 {
        eprintln!("usage: roxor <file> <crib>");
        process::exit(1);
    }

    let path = Path::new(&args[0]);
    let crib = args[1].as_bytes();

    if crib.len() < 2 {
        eprintln!("error: crib too short");
        process::exit(1);
    }

    let mut file = match File::open(&path) {
        Err(why) => {
            eprintln!("error: failed to open {}: {}", path.display(), why);
            process::exit(1);
        }
        Ok(file) => file,
    };

    let mut ciphertext: Vec<u8> = Vec::new();
    file.read_to_end(&mut ciphertext).unwrap();

    if ciphertext.len() < crib.len() {
        eprintln!("error: ciphertext too short");
        process::exit(1);
    }

    for m in attack_cipher(&ciphertext[..], crib) {
        println!("Found text at 0x{:x} (XOR key 0x{:02x})", m.offset, m.key);
        println!("  preview: {}", m.preview);
    }
}

fn attack_cipher(ciphertext: &[u8], crib: &[u8]) -> Vec<Match> {
    let mut matches: Vec<Match> = Vec::new();
    for (i, x) in ciphertext.iter().enumerate() {
        let mut old_key = x ^ crib[0];
        let mut j = 1;
        while j < crib.len() && (i + j) < ciphertext.len() {
            let key = ciphertext[i + j] ^ crib[j];
            if key != old_key {
                break;
            }
            old_key = key;
            j += 1;
            if j == crib.len() {
                let preview: String = ciphertext[i..]
                    .iter()
                    .take(PREVIEW_LEN)
                    .map(|x| x ^ key)
                    .map(|x| if x >= 32 && x <= 126 { x as char } else { '.' })
                    .collect();
                matches.push(Match {
                    offset: i,
                    key,
                    preview,
                });
            }
        }
    }
    matches
}

#[cfg(test)]
mod tests {
    use super::{attack_cipher, Match};

    struct Test {
        ciphertext: &'static [u8],
        crib: &'static [u8],
        matches: Vec<Match>,
    }

    #[test]
    fn test_attack_cipher() {
        let tests = vec![
            Test {
                ciphertext: &[],
                crib: &[],
                matches: vec![],
            },
            Test {
                ciphertext: b"haystack",
                crib: b"needle",
                matches: vec![],
            },
            Test {
                ciphertext: b"needle in haystack",
                crib: b"needle",
                matches: vec![
                    Match { offset: 0, key: 0, preview: "needle in haystack".to_string() },
                ],
            },
            Test {
                ciphertext: b"a needle, another needle",
                crib: b"needle",
                matches: vec![
                    Match { offset: 2, key: 0, preview: "needle, another needle".to_string() },
                    Match { offset: 18, key: 0, preview: "needle".to_string() },
                ],
            },
            Test {
                ciphertext: b"\x23\x62\x2c\x27\x27\x26\x2e\x27\x6e\x62\x23\x2c\x2d\x36\x2a\x27\x30\x62\x2c\x27\x27\x26\x2e\x27",
                crib: b"needle",
                matches: vec![
                    Match { offset: 2, key: 0x42, preview: "needle, another needle".to_string() },
                    Match { offset: 18, key: 0x42, preview: "needle".to_string() },
                ],
            },
        ];

        for t in tests.iter() {
            assert_eq!(t.matches, attack_cipher(t.ciphertext, t.crib));
        }
    }
}
<commit_msg>assert_eq!(got, want)<commit_after>use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process;

const PREVIEW_LEN: usize = 50;

#[derive(Debug, PartialEq)]
struct Match {
    offset: usize,
    key: u8,
    preview: String,
}

fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    if args.len() < 2 {
        eprintln!("usage: roxor <file> <crib>");
        process::exit(1);
    }

    let path = Path::new(&args[0]);
    let crib = args[1].as_bytes();

    if crib.len() < 2 {
        eprintln!("error: crib too short");
        process::exit(1);
    }

    let mut file = match File::open(&path) {
        Err(why) => {
            eprintln!("error: failed to open {}: {}", path.display(), why);
            process::exit(1);
        }
        Ok(file) => file,
    };

    let mut ciphertext: Vec<u8> = Vec::new();
    file.read_to_end(&mut ciphertext).unwrap();

    if ciphertext.len() < crib.len() {
        eprintln!("error: ciphertext too short");
        process::exit(1);
    }

    for m in attack_cipher(&ciphertext[..], crib) {
        println!("Found text at 0x{:x} (XOR key 0x{:02x})", m.offset, m.key);
        println!("  preview: {}", m.preview);
    }
}

fn attack_cipher(ciphertext: &[u8], crib: &[u8]) -> Vec<Match> {
    let mut matches: Vec<Match> = Vec::new();
    for (i, x) in ciphertext.iter().enumerate() {
        let mut old_key = x ^ crib[0];
        let mut j = 1;
        while j < crib.len() && (i + j) < ciphertext.len() {
            let key = ciphertext[i + j] ^ crib[j];
            if key != old_key {
                break;
            }
            old_key = key;
            j += 1;
            if j == crib.len() {
                let preview: String = ciphertext[i..]
                    .iter()
                    .take(PREVIEW_LEN)
                    .map(|x| x ^ key)
                    .map(|x| if x >= 32 && x <= 126 { x as char } else { '.' })
                    .collect();
                matches.push(Match {
                    offset: i,
                    key,
                    preview,
                });
            }
        }
    }
    matches
}

#[cfg(test)]
mod tests {
    use super::{attack_cipher, Match};

    struct Test {
        ciphertext: &'static [u8],
        crib: &'static [u8],
        matches: Vec<Match>,
    }

    #[test]
    fn test_attack_cipher() {
        let tests = vec![
            Test {
                ciphertext: &[],
                crib: &[],
                matches: vec![],
            },
            Test {
                ciphertext: b"haystack",
                crib: b"needle",
                matches: vec![],
            },
            Test {
                ciphertext: b"needle in haystack",
                crib: b"needle",
                matches: vec![
                    Match { offset: 0, key: 0, preview: "needle in haystack".to_string() },
                ],
            },
            Test {
                ciphertext: b"a needle, another needle",
                crib: b"needle",
                matches: vec![
                    Match { offset: 2, key: 0, preview: "needle, another needle".to_string() },
                    Match { offset: 18, key: 0, preview: "needle".to_string() },
                ],
            },
            Test {
                ciphertext: b"\x23\x62\x2c\x27\x27\x26\x2e\x27\x6e\x62\x23\x2c\x2d\x36\x2a\x27\x30\x62\x2c\x27\x27\x26\x2e\x27",
                crib: b"needle",
                matches: vec![
                    Match { offset: 2, key: 0x42, preview: "needle, another needle".to_string() },
                    Match { offset: 18, key: 0x42, preview: "needle".to_string() },
                ],
            },
        ];

        for t in tests.iter() {
            assert_eq!(attack_cipher(t.ciphertext, t.crib), t.matches);
        }
    }
}
<|endoftext|>


<commit_before>import libc::c_double;
import azure::*;
import azure::bindgen::*;
import azure::cairo;
import azure::cairo::bindgen::*;

// A function for spawning into the platform's main thread
fn on_osmain<T: send>(f: fn~(comm::port<T>)) -> comm::chan<T> {
    let builder = task::builder();
    let opts = {
        sched: some({
            mode: task::osmain,
            native_stack_size: none
        })
        with task::get_opts(builder)
    };
    task::set_opts(builder, opts);
    ret task::run_listener(builder, f);
}

// Messages to the platform event handler task
enum osmain_msg {
    om_get_draw_target(comm::chan<AzDrawTargetRef>),
    om_add_key_handler(comm::chan<()>),
    om_draw(comm::chan<()>),
    om_exit
}

enum draw_msg {
    dm_draw,
    dm_exit(comm::chan<()>)
}

fn main() {
    // The platform event handler thread
    let osmain_ch = on_osmain::<osmain_msg> {|po|
        let mut key_handlers = [];

        sdl::init([
            sdl::init_video
        ]);
        let screen = sdl::video::set_video_mode(
            800, 600, 32,
            [sdl::video::swsurface],
            [sdl::video::doublebuf]);
        assert !screen.is_null();
        let sdl_surf = sdl::video::create_rgb_surface(
            [sdl::video::swsurface],
            800, 600, 32,
            0x00FF0000u32,
            0x0000FF00u32,
            0x000000FFu32,
            0x00000000u32
            );
        assert !sdl_surf.is_null();
        sdl::video::lock_surface(sdl_surf);
        let cairo_surf = unsafe {
            cairo_image_surface_create_for_data(
                unsafe::reinterpret_cast((*sdl_surf).pixels),
                cairo::CAIRO_FORMAT_RGB24,
                (*sdl_surf).w,
                (*sdl_surf).h,
                (*sdl_surf).pitch as libc::c_int
            )
        };
        assert !cairo_surf.is_null();
        let azure_target = AzCreateDrawTargetForCairoSurface(cairo_surf);
        assert !azure_target.is_null();

        loop {
            sdl::event::poll_event {|event|
                alt event {
                  sdl::event::keydown_event(_) {
                    key_handlers.iter {|key_ch|
                        comm::send(key_ch, ())
                    }
                  }
                  _ { }
                }
            }

            // Handle messages
            if comm::peek(po) {
                alt check comm::recv(po) {
                  om_add_key_handler(key_ch) {
                    key_handlers += [key_ch];
                  }
                  om_get_draw_target(response_ch) {
                    comm::send(response_ch, azure_target);
                  }
                  om_draw(response_ch) {
                    sdl::video::unlock_surface(sdl_surf);
                    sdl::video::blit_surface(sdl_surf, ptr::null(),
                                             screen, ptr::null());
                    sdl::video::lock_surface(sdl_surf);
                    sdl::video::flip(screen);
                    comm::send(response_ch, ());
                  }
                  exit { break; }
                }
            }
        }
        AzReleaseDrawTarget(azure_target);
        cairo_surface_destroy(cairo_surf);
        sdl::video::unlock_surface(sdl_surf);
        sdl::quit();
    };

    // The drawing task
    let draw_ch = task::spawn_listener {|po|
        let draw_target_po = comm::port();
        comm::send(osmain_ch, om_get_draw_target(comm::chan(draw_target_po)));
        let draw_target = comm::recv(draw_target_po);

        let red_color = {
            r: 1f as azure::AzFloat,
            g: 0f as azure::AzFloat,
            b: 0f as azure::AzFloat,
            a: 0.8f as azure::AzFloat
        };
        let red_pattern = AzCreateColorPattern(ptr::addr_of(red_color));

        let green_color = {
            r: 0f as azure::AzFloat,
            g: 1f as azure::AzFloat,
            b: 0f as azure::AzFloat,
            a: 0.8f as azure::AzFloat
        };
        let green_pattern = AzCreateColorPattern(ptr::addr_of(green_color));

        let mut exit_confirm_ch = none;
        loop {
            alt comm::recv::<draw_msg>(po) {
              dm_draw {
                let red_rect = {
                    x: 100f as azure::AzFloat,
                    y: 100f as azure::AzFloat,
                    width: 200f as azure::AzFloat,
                    height: 200f as azure::AzFloat
                };
                AzDrawTargetFillRect(
                    draw_target,
                    ptr::addr_of(red_rect),
                    unsafe { unsafe::reinterpret_cast(red_pattern) }
                );
                let green_rect = {
                    x: 200f as azure::AzFloat,
                    y: 200f as azure::AzFloat,
                    width: 200f as azure::AzFloat,
                    height: 200f as azure::AzFloat
                };
                AzDrawTargetFillRect(
                    draw_target,
                    ptr::addr_of(green_rect),
                    unsafe { unsafe::reinterpret_cast(green_pattern) }
                );
                let draw_po = comm::port();
                comm::send(osmain_ch, om_draw(comm::chan(draw_po)));
                comm::recv(draw_po);
              }
              dm_exit(response_ch) {
                exit_confirm_ch = some(response_ch);
                break;
              }
            }
        }

        AzReleaseColorPattern(red_pattern);
        AzReleaseColorPattern(green_pattern);

        assert exit_confirm_ch.is_some();
        comm::send(exit_confirm_ch.get(), ());
    };

    // The keyboard handler
    task::spawn {||
        let key_po = comm::port();
        comm::send(osmain_ch, om_add_key_handler(comm::chan(key_po)));
        loop {
            alt comm::recv(key_po) {
              _ {
                let draw_exit_confirm_po = comm::port();
                comm::send(draw_ch, dm_exit(comm::chan(draw_exit_confirm_po)));
                comm::recv(draw_exit_confirm_po);
                comm::send(osmain_ch, om_exit);
                break;
              }
            }
        }
    }

    comm::send(draw_ch, dm_draw);
}<commit_msg>Do some animation<commit_after>import libc::c_double;
import azure::*;
import azure::bindgen::*;
import azure::cairo;
import azure::cairo::bindgen::*;

// FIXME: Busy wait hack
fn sleep() {
    iter::repeat(100000u) {||
        task::yield();
    }
}

// A function for spawning into the platform's main thread
fn on_osmain<T: send>(f: fn~(comm::port<T>)) -> comm::chan<T> {
    let builder = task::builder();
    let opts = {
        sched: some({
            mode: task::osmain,
            native_stack_size: none
        })
        with task::get_opts(builder)
    };
    task::set_opts(builder, opts);
    ret task::run_listener(builder, f);
}

// Messages to the platform event handler task
enum osmain_msg {
    om_get_draw_target(comm::chan<AzDrawTargetRef>),
    om_add_key_handler(comm::chan<()>),
    om_draw(comm::chan<()>),
    om_exit
}

enum draw_msg {
    dm_draw(model),
    dm_exit(comm::chan<()>)
}

type model = {
    x1: int, y1: int, w1: int, h1: int,
    x2: int, y2: int, w2: int, h2: int
};

fn main() {
    // The platform event handler thread
    let osmain_ch = on_osmain::<osmain_msg> {|po|
        let mut key_handlers = [];

        sdl::init([
            sdl::init_video
        ]);
        let screen = sdl::video::set_video_mode(
            800, 600, 32,
            [sdl::video::swsurface],
            [sdl::video::doublebuf]);
        assert !screen.is_null();
        let sdl_surf = sdl::video::create_rgb_surface(
            [sdl::video::swsurface],
            800, 600, 32,
            0x00FF0000u32,
            0x0000FF00u32,
            0x000000FFu32,
            0x00000000u32
            );
        assert !sdl_surf.is_null();
        sdl::video::lock_surface(sdl_surf);
        let cairo_surf = unsafe {
            cairo_image_surface_create_for_data(
                unsafe::reinterpret_cast((*sdl_surf).pixels),
                cairo::CAIRO_FORMAT_RGB24,
                (*sdl_surf).w,
                (*sdl_surf).h,
                (*sdl_surf).pitch as libc::c_int
            )
        };
        assert !cairo_surf.is_null();
        let azure_target = AzCreateDrawTargetForCairoSurface(cairo_surf);
        assert !azure_target.is_null();

        loop {
            sdl::event::poll_event {|event|
                alt event {
                  sdl::event::keydown_event(_) {
                    key_handlers.iter {|key_ch|
                        comm::send(key_ch, ())
                    }
                  }
                  _ { }
                }
            }

            // Handle messages
            if comm::peek(po) {
                alt check comm::recv(po) {
                  om_add_key_handler(key_ch) {
                    key_handlers += [key_ch];
                  }
                  om_get_draw_target(response_ch) {
                    comm::send(response_ch, azure_target);
                  }
                  om_draw(response_ch) {
                    sdl::video::unlock_surface(sdl_surf);
                    sdl::video::blit_surface(sdl_surf, ptr::null(),
                                             screen, ptr::null());
                    sdl::video::lock_surface(sdl_surf);
                    sdl::video::flip(screen);
                    comm::send(response_ch, ());
                  }
                  exit { break; }
                }
            }
        }
        AzReleaseDrawTarget(azure_target);
        cairo_surface_destroy(cairo_surf);
        sdl::video::unlock_surface(sdl_surf);
        sdl::quit();
    };

    // The drawing task
    let draw_ch = task::spawn_listener {|po|
        let draw_target_po = comm::port();
        comm::send(osmain_ch, om_get_draw_target(comm::chan(draw_target_po)));
        let draw_target = comm::recv(draw_target_po);

        let black_color = {
            r: 0f as azure::AzFloat,
            g: 0f as azure::AzFloat,
            b: 0f as azure::AzFloat,
            a: 1f as azure::AzFloat
        };
        let black_pattern = AzCreateColorPattern(ptr::addr_of(black_color));

        let red_color = {
            r: 1f as azure::AzFloat,
            g: 0f as azure::AzFloat,
            b: 0f as azure::AzFloat,
            a: 0.5f as azure::AzFloat
        };
        let red_pattern = AzCreateColorPattern(ptr::addr_of(red_color));

        let green_color = {
            r: 0f as azure::AzFloat,
            g: 1f as azure::AzFloat,
            b: 0f as azure::AzFloat,
            a: 0.5f as azure::AzFloat
        };
        let green_pattern = AzCreateColorPattern(ptr::addr_of(green_color));

        let mut exit_confirm_ch = none;
        loop {
            alt comm::recv::<draw_msg>(po) {
              dm_draw(model) {
                let black_rect = {
                    x: 0 as azure::AzFloat,
                    y: 0 as azure::AzFloat,
                    width: 800 as azure::AzFloat,
                    height: 600 as azure::AzFloat,
                };
                AzDrawTargetFillRect(
                    draw_target,
                    ptr::addr_of(black_rect),
                    unsafe { unsafe::reinterpret_cast(black_pattern) }
                );

                let red_rect = {
                    x: model.x1 as azure::AzFloat,
                    y: model.y1 as azure::AzFloat,
                    width: model.w1 as azure::AzFloat,
                    height: model.h1 as azure::AzFloat
                };
                AzDrawTargetFillRect(
                    draw_target,
                    ptr::addr_of(red_rect),
                    unsafe { unsafe::reinterpret_cast(red_pattern) }
                );
                let green_rect = {
                    x: model.x2 as azure::AzFloat,
                    y: model.y2 as azure::AzFloat,
                    width: model.w2 as azure::AzFloat,
                    height: model.h2 as azure::AzFloat
                };
                AzDrawTargetFillRect(
                    draw_target,
                    ptr::addr_of(green_rect),
                    unsafe { unsafe::reinterpret_cast(green_pattern) }
                );
                let draw_po = comm::port();
                comm::send(osmain_ch, om_draw(comm::chan(draw_po)));
                comm::recv(draw_po);
              }
              dm_exit(response_ch) {
                exit_confirm_ch = some(response_ch);
                break;
              }
            }
        }

        AzReleaseColorPattern(red_pattern);
        AzReleaseColorPattern(green_pattern);

        assert exit_confirm_ch.is_some();
        comm::send(exit_confirm_ch.get(), ());
    };

    // The model
    let model_ch = task::spawn_listener {|po|
        let mut x1 = 100;
        let mut y1 = 100;
        let mut w1 = 200;
        let mut h1 = 200;
        let mut x2 = 200;
        let mut y2 = 200;
        let mut w2 = 300;
        let mut h2 = 300;

        while !comm::peek(po) {
            let model = {
                x1: x1, y1: y1, w1: w1, h1: h1,
                x2: x2, y2: y2, w2: w2, h2: h2
            };
            comm::send(draw_ch, dm_draw(model));

            sleep();

            x1 += 1;
            y1 += 1;
            x2 -= 1;
            y2 -= 1;
            if x1 > 800 { x1 = 0 }
            if y1 > 600 { y1 = 0 }
            if x2 < 0 { x2 = 800 }
            if y2 < 0 { y2 = 600 }
        }
    };

    // The keyboard handler
    task::spawn {||
        let key_po = comm::port();
        comm::send(osmain_ch, om_add_key_handler(comm::chan(key_po)));
        loop {
            alt comm::recv(key_po) {
              _ {
                comm::send(model_ch, ());
                let draw_exit_confirm_po = comm::port();
                comm::send(draw_ch, dm_exit(comm::chan(draw_exit_confirm_po)));
                comm::recv(draw_exit_confirm_po);
                comm::send(osmain_ch, om_exit);
                break;
              }
            }
        }
    }
}<|endoftext|>


<commit_before>use rustc_middle::mir;

use crate::*;
use helpers::check_arg_count;

#[derive(Debug, Copy, Clone)]
pub enum Dlsym {
    GetEntropy,
}

impl Dlsym {
    // Returns an error for unsupported symbols, and None if this symbol
    // should become a NULL pointer (pretend it does not exist).
    pub fn from_str(name: &[u8], target_os: &str) -> InterpResult<'static, Option<Dlsym>> {
        use self::Dlsym::*;
        let name = String::from_utf8_lossy(name);
        Ok(match target_os {
            "linux" | "macos" => match &*name {
                "getentropy" => Some(GetEntropy),
                "__pthread_get_minstack" => None,
                _ => throw_unsup_format!("unsupported dlsym: {}", name),
            }
            "windows" => match &*name {
                "SetThreadStackGuarantee" => None,
                "AcquireSRWLockExclusive" => None,
                _ => throw_unsup_format!("unsupported dlsym: {}", name),
            }
            os => bug!("dlsym not implemented for target_os {}", os),
        })
    }
}

impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
    fn call_dlsym(
        &mut self,
        dlsym: Dlsym,
        args: &[OpTy<'tcx, Tag>],
        ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
    ) -> InterpResult<'tcx> {
        use self::Dlsym::*;

        let this = self.eval_context_mut();
        let (dest, ret) = ret.expect("we don't support any diverging dlsym");

        match dlsym {
            GetEntropy => {
                let &[ptr, len] = check_arg_count(args)?;
                let ptr = this.read_scalar(ptr)?.not_undef()?;
                let len = this.read_scalar(len)?.to_machine_usize(this)?;
                this.gen_random(ptr, len)?;
                this.write_null(dest)?;
            }
        }

        this.dump_place(*dest);
        this.go_to_block(ret);
        Ok(())
    }
}
<commit_msg>disentangle macos and linux dlsyms<commit_after>use rustc_middle::mir;

use crate::*;
use helpers::check_arg_count;

#[derive(Debug, Copy, Clone)]
pub enum Dlsym {
    GetEntropy,
}

impl Dlsym {
    // Returns an error for unsupported symbols, and None if this symbol
    // should become a NULL pointer (pretend it does not exist).
    pub fn from_str(name: &[u8], target_os: &str) -> InterpResult<'static, Option<Dlsym>> {
        use self::Dlsym::*;
        let name = String::from_utf8_lossy(name);
        Ok(match target_os {
            "linux" => match &*name {
                "__pthread_get_minstack" => None,
                _ => throw_unsup_format!("unsupported Linux dlsym: {}", name),
            }
            "macos" => match &*name {
                "getentropy" => Some(GetEntropy),
                _ => throw_unsup_format!("unsupported macOS dlsym: {}", name),
            }
            "windows" => match &*name {
                "SetThreadStackGuarantee" => None,
                "AcquireSRWLockExclusive" => None,
                _ => throw_unsup_format!("unsupported Windows dlsym: {}", name),
            }
            os => bug!("dlsym not implemented for target_os {}", os),
        })
    }
}

impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
    fn call_dlsym(
        &mut self,
        dlsym: Dlsym,
        args: &[OpTy<'tcx, Tag>],
        ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
    ) -> InterpResult<'tcx> {
        use self::Dlsym::*;

        let this = self.eval_context_mut();
        let (dest, ret) = ret.expect("we don't support any diverging dlsym");

        match dlsym {
            GetEntropy => {
                let &[ptr, len] = check_arg_count(args)?;
                let ptr = this.read_scalar(ptr)?.not_undef()?;
                let len = this.read_scalar(len)?.to_machine_usize(this)?;
                this.gen_random(ptr, len)?;
                this.write_null(dest)?;
            }
        }

        this.dump_place(*dest);
        this.go_to_block(ret);
        Ok(())
    }
}
<|endoftext|>


<commit_before>// Copyright 2022 The ChromiumOS Authors.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::{event_details_proto::RecordDetails, MetricEventType, MetricsClientDestructor};
use base::Tube;

/// This interface exists to be used and re-implemented by downstream forks. Updates shouldn't be
/// done without ensuring they won't cause breakages in dependent codebases.
pub fn initialize(_: Tube) {}
#[cfg(test)]
pub fn force_initialize(_: Tube) {}
pub fn get_destructor() -> MetricsClientDestructor {
    MetricsClientDestructor::new(|| {})
}
pub fn set_auth_token(_: &str) {}
pub fn set_graphics_api(_: &str) {}
pub fn set_package_name(_: &str) {}
pub fn merge_session_invariants(_: &[u8]) {}
pub fn log_descriptor(_: MetricEventType, _: i64) {}
pub fn log_event(_: MetricEventType) {}
pub fn log_metric(_: MetricEventType, _: i64) {}
pub fn log_histogram_metric(_: MetricEventType, _: i64) {}
pub fn log_high_frequency_descriptor_event(_: MetricEventType, _: i64, _: i64) {}
pub fn log_event_with_details(_: MetricEventType, _: &RecordDetails) {}
<commit_msg>metrics: add is_initialized() stub<commit_after>// Copyright 2022 The ChromiumOS Authors.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::{event_details_proto::RecordDetails, MetricEventType, MetricsClientDestructor};
use base::Tube;

/// This interface exists to be used and re-implemented by downstream forks. Updates shouldn't be
/// done without ensuring they won't cause breakages in dependent codebases.
pub fn initialize(_: Tube) {}
#[cfg(test)]
pub fn force_initialize(_: Tube) {}
pub fn get_destructor() -> MetricsClientDestructor {
    MetricsClientDestructor::new(|| {})
}
pub fn is_initialized() -> bool {
    false
}
pub fn set_auth_token(_: &str) {}
pub fn set_graphics_api(_: &str) {}
pub fn set_package_name(_: &str) {}
pub fn merge_session_invariants(_: &[u8]) {}
pub fn log_descriptor(_: MetricEventType, _: i64) {}
pub fn log_event(_: MetricEventType) {}
pub fn log_metric(_: MetricEventType, _: i64) {}
pub fn log_histogram_metric(_: MetricEventType, _: i64) {}
pub fn log_high_frequency_descriptor_event(_: MetricEventType, _: i64, _: i64) {}
pub fn log_event_with_details(_: MetricEventType, _: &RecordDetails) {}
<|endoftext|>