<commit_before>// no-reformat

#[doc = "

    A demonstration module

    Contains documentation in various forms that rustdoc understands,
    for testing purposes. It doesn't surve any functional
    purpose. This here, for instance, is just some filler text.

    FIXME (1654): It would be nice if we could run some automated
    tests on this file

"];

#[doc = "The base price of a muffin on a non-holiday"]
const price_of_a_muffin: float = 70f;

type waitress = {
    hair_color: str
};

#[doc = "The type of things that produce omnomnom"]
enum omnomnomy {
    #[doc = "Delicious sugar cookies"]
    cookie,
    #[doc = "It's pizza"]
    pizza_pie([uint])
}

fn take_my_order_please(
    _waitress: waitress,
    _order: [omnomnomy]
) -> uint {

    #[doc(
        desc = "OMG would you take my order already?",
        args(_waitress = "The waitress that you want to bother",
             _order = "The order vector. It should be filled with food."),
        return = "The price of the order, including tax",
        failure = "This function is full of fail"
    )];

    fail;
}

mod fortress_of_solitude {
    #[doc(
        brief = "Superman's vacation home",
        desc = "

        The fortress of solitude is located in the Arctic and it is
        cold. What you may not know about the fortress of solitude
        though is that it contains two separate bowling alleys. One of
        them features bumper-bowling and is kind of lame.

        Really, it's pretty cool.

    ")];

}

mod blade_runner {
    #[doc(
        brief = "Blade Runner is probably the best movie ever",
        desc = "I like that in the world of Blade Runner it is always
                raining, and that it's always night time. And Aliens
                was also a really good movie.

                Alien 3 was crap though."
    )];
}

#[doc(
    brief = "Bored",
    desc = "

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec
    molestie nisl. Duis massa risus, pharetra a scelerisque a,
    molestie eu velit. Donec mattis ligula at ante imperdiet ut
    dapibus mauris malesuada. Sed gravida nisi a metus elementum sit
    amet hendrerit dolor bibendum. Aenean sit amet neque massa, sed
    tempus tortor. Sed ut lobortis enim. Proin a mauris quis nunc
    fermentum ultrices eget a erat. Mauris in lectus vitae metus
    sodales auctor. Morbi nunc quam, ultricies at venenatis non,
    pellentesque ac dui.

    Quisque vitae est id eros placerat laoreet sit amet eu
    nisi. Curabitur suscipit neque porttitor est euismod
    lacinia. Curabitur non quam vitae ipsum adipiscing
    condimentum. Mauris ut ante eget metus sollicitudin
    blandit. Aliquam erat volutpat. Morbi sed nisl mauris. Nulla
    facilisi. Phasellus at mollis ipsum. Maecenas sed convallis
    sapien. Nullam in ligula turpis. Pellentesque a neque augue. Sed
    eget ante feugiat tortor congue auctor ac quis ante. Proin
    condimentum lacinia tincidunt.

")]
resource bored(bored: bool) {
    log(error, bored);
}

#[doc(
    brief = "The Shunned House",
    desc = "

From even the greatest of horrors irony is seldom absent. Sometimes it
enters directly into the composition of the events, while sometimes it
relates only to their fortuitous position among persons and
places. The latter sort is splendidly exemplified by a case in the
ancient city of Providence, where in the late forties Edgar Allan Poe
used to sojourn often during his unsuccessful wooing of the gifted
poetess, Mrs.  Whitman. Poe generally stopped at the Mansion House in
Benefit Street--the renamed Golden Ball Inn whose roof has sheltered
Washington, Jefferson, and Lafayette--and his favorite walk led
northward along the same street to Mrs. Whitman's home and the
neighboring hillside churchyard of St. John's, whose hidden expanse of
Eighteenth Century gravestones had for him a peculiar fascination.

")]
iface the_shunned_house {
    #[doc(
        desc = "

    Now the irony is this. In this walk, so many times repeated, the
    world's greatest master of the terrible and the bizarre was
    obliged to pass a particular house on the eastern side of the
    street; a dingy, antiquated structure perched on the abruptly
    rising side hill, with a great unkempt yard dating from a time
    when the region was partly open country. It does not appear that
    he ever wrote or spoke of it, nor is there any evidence that he
    even noticed it. And yet that house, to the two persons in
    possession of certain information, equals or outranks in horror
    the wildest fantasy of the genius who so often passed it
    unknowingly, and stands starkly leering as a symbol of all that is
    unutterably hideous.

    ",
        args(
            a =
            "A yard dating from a time when the region was partly
             open country"
    ))]
    fn dingy_house(unkempt_yard: int);

    #[doc(
        desc = "

    The house was--and for that matter still is--of a kind to attract
    the attention of the curious. Originally a farm or semi-farm
    building, it followed the average New England colonial lines of
    the middle Eighteenth Century--the prosperous peaked-roof sort,
    with two stories and dormerless attic, and with the Georgian
    doorway and interior panelling dictated by the progress of taste
    at that time. It faced south, with one gable end buried to the
    lower windows in the eastward rising hill, and the other exposed
    to the foundations toward the street. Its construction, over a
    century and a half ago, had followed the grading and straightening
    of the road in that especial vicinity; for Benefit Street--at
    first called Back Street--was laid out as a lane winding amongst
    the graveyards of the first settlers, and straightened only when
    the removal of the bodies to the North Burial Ground made it
    decently possible to cut through the old family plots.

    ",
        return = "A dingy house with an unkempt yard",
        failure = "Will fail if bodies are removed from premises"
    )]
    fn construct() -> bool;
}<commit_msg>rustdoc: Add impl docs to demo mod<commit_after>// no-reformat

#[doc = "

    A demonstration module

    Contains documentation in various forms that rustdoc understands,
    for testing purposes. It doesn't surve any functional
    purpose. This here, for instance, is just some filler text.

    FIXME (1654): It would be nice if we could run some automated
    tests on this file

"];

#[doc = "The base price of a muffin on a non-holiday"]
const price_of_a_muffin: float = 70f;

type waitress = {
    hair_color: str
};

#[doc = "The type of things that produce omnomnom"]
enum omnomnomy {
    #[doc = "Delicious sugar cookies"]
    cookie,
    #[doc = "It's pizza"]
    pizza_pie([uint])
}

fn take_my_order_please(
    _waitress: waitress,
    _order: [omnomnomy]
) -> uint {

    #[doc(
        desc = "OMG would you take my order already?",
        args(_waitress = "The waitress that you want to bother",
             _order = "The order vector. It should be filled with food."),
        return = "The price of the order, including tax",
        failure = "This function is full of fail"
    )];

    fail;
}

mod fortress_of_solitude {
    #[doc(
        brief = "Superman's vacation home",
        desc = "

        The fortress of solitude is located in the Arctic and it is
        cold. What you may not know about the fortress of solitude
        though is that it contains two separate bowling alleys. One of
        them features bumper-bowling and is kind of lame.

        Really, it's pretty cool.

    ")];

}

mod blade_runner {
    #[doc(
        brief = "Blade Runner is probably the best movie ever",
        desc = "I like that in the world of Blade Runner it is always
                raining, and that it's always night time. And Aliens
                was also a really good movie.

                Alien 3 was crap though."
    )];
}

#[doc(
    brief = "Bored",
    desc = "

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec
    molestie nisl. Duis massa risus, pharetra a scelerisque a,
    molestie eu velit. Donec mattis ligula at ante imperdiet ut
    dapibus mauris malesuada. Sed gravida nisi a metus elementum sit
    amet hendrerit dolor bibendum. Aenean sit amet neque massa, sed
    tempus tortor. Sed ut lobortis enim. Proin a mauris quis nunc
    fermentum ultrices eget a erat. Mauris in lectus vitae metus
    sodales auctor. Morbi nunc quam, ultricies at venenatis non,
    pellentesque ac dui.

    Quisque vitae est id eros placerat laoreet sit amet eu
    nisi. Curabitur suscipit neque porttitor est euismod
    lacinia. Curabitur non quam vitae ipsum adipiscing
    condimentum. Mauris ut ante eget metus sollicitudin
    blandit. Aliquam erat volutpat. Morbi sed nisl mauris. Nulla
    facilisi. Phasellus at mollis ipsum. Maecenas sed convallis
    sapien. Nullam in ligula turpis. Pellentesque a neque augue. Sed
    eget ante feugiat tortor congue auctor ac quis ante. Proin
    condimentum lacinia tincidunt.

")]
resource bored(bored: bool) {
    log(error, bored);
}

#[doc(
    brief = "The Shunned House",
    desc = "

From even the greatest of horrors irony is seldom absent. Sometimes it
enters directly into the composition of the events, while sometimes it
relates only to their fortuitous position among persons and
places. The latter sort is splendidly exemplified by a case in the
ancient city of Providence, where in the late forties Edgar Allan Poe
used to sojourn often during his unsuccessful wooing of the gifted
poetess, Mrs.  Whitman. Poe generally stopped at the Mansion House in
Benefit Street--the renamed Golden Ball Inn whose roof has sheltered
Washington, Jefferson, and Lafayette--and his favorite walk led
northward along the same street to Mrs. Whitman's home and the
neighboring hillside churchyard of St. John's, whose hidden expanse of
Eighteenth Century gravestones had for him a peculiar fascination.

")]
iface the_shunned_house {
    #[doc(
        desc = "

    Now the irony is this. In this walk, so many times repeated, the
    world's greatest master of the terrible and the bizarre was
    obliged to pass a particular house on the eastern side of the
    street; a dingy, antiquated structure perched on the abruptly
    rising side hill, with a great unkempt yard dating from a time
    when the region was partly open country. It does not appear that
    he ever wrote or spoke of it, nor is there any evidence that he
    even noticed it. And yet that house, to the two persons in
    possession of certain information, equals or outranks in horror
    the wildest fantasy of the genius who so often passed it
    unknowingly, and stands starkly leering as a symbol of all that is
    unutterably hideous.

    ",
        args(
            a =
            "A yard dating from a time when the region was partly
             open country"
    ))]
    fn dingy_house(unkempt_yard: int);

    #[doc(
        desc = "

    The house was--and for that matter still is--of a kind to attract
    the attention of the curious. Originally a farm or semi-farm
    building, it followed the average New England colonial lines of
    the middle Eighteenth Century--the prosperous peaked-roof sort,
    with two stories and dormerless attic, and with the Georgian
    doorway and interior panelling dictated by the progress of taste
    at that time. It faced south, with one gable end buried to the
    lower windows in the eastward rising hill, and the other exposed
    to the foundations toward the street. Its construction, over a
    century and a half ago, had followed the grading and straightening
    of the road in that especial vicinity; for Benefit Street--at
    first called Back Street--was laid out as a lane winding amongst
    the graveyards of the first settlers, and straightened only when
    the removal of the bodies to the North Burial Ground made it
    decently possible to cut through the old family plots.

    ",
        return = "A dingy house with an unkempt yard",
        failure = "Will fail if bodies are removed from premises"
    )]
    fn construct() -> bool;
}

#[doc = "Whatever"]
impl of the_shunned_house for omnomnomy {
    #[doc(args(_unkempt_yard = "Whatever"))]
    fn dingy_house(_unkempt_yard: int) {
    }

    fn construct() -> bool {
        fail;
    }
}<|endoftext|>


<commit_before><commit_msg>compile-fail test for new unresolved import error<commit_after>// Copyright 2013 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.

use foo::bar; //~ ERROR unresolved import. maybe a missing
              //~^ ERROR failed to resolve import
<|endoftext|>


<commit_before><commit_msg>Add regression test for lint deprecation<commit_after>// Copyright 2014 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.

// Check that lint deprecation works

#[deny(unused_variable)] //~ warning: lint unused_variable has been renamed to unused_variables
pub fn main() {
    let x = 0u8; //~ error: unused variable:
}
<|endoftext|>


<commit_before>
use std;
import std::vec::*;

fn main() {
    let v = empty[int]();
    v += [4, 2];
    assert (reversed(v) == [2, 4]);
}<commit_msg>Convert run-pass/import-glob-crate to ivecs<commit_after>
use std;
import std::ivec::*;

fn main() {
    let v = init_elt(0, 0u);
    v += ~[4, 2];
    assert (reversed(v) == ~[2, 4]);
}<|endoftext|>


<commit_before><commit_msg>Fix to_rule test<commit_after><|endoftext|>


<commit_before><commit_msg>implement hofstadter q sequence<commit_after>#[cfg(not(test))]
fn main() {
	let q_array: Vec<uint> = hofstadter_q_wrapper(1000);
	for i in range(1u, 1+q_array.len()) {
		println!("H({}) = {}", i, q_array[i-1]);
	}
}

// Fill up the array A from indices 0 to maxval-1 (inclusive)
// where A[i] is equal to the Hofstadter Q sequence indexed at i+1
fn hofstadter_q_wrapper(maxval: uint) -> Vec<uint> {
	let mut memoize_vec: Vec<uint> = Vec::from_fn(maxval, |_| 0u);
	// Initialize the first two elements of the array
	*memoize_vec.get_mut(0) = 1;
	*memoize_vec.get_mut(1) = 1;
	// Fill up the array
	for n in range(1u, 1+maxval) {
		hofstadter_q(n, &mut memoize_vec);
	}
	// Return the array
	memoize_vec
}

// Returns the n-th element (counting starts from 1) of the Hofstadter Q sequence
fn hofstadter_q(n: uint, memoize_vec: &mut Vec<uint>) -> uint {
	if (*memoize_vec)[n-1] > 0u {
		(*memoize_vec)[n-1]
	} else {
		// Make the required recursive calls...
		let rec_call_1: uint = hofstadter_q(n - 1, memoize_vec);
		let rec_call_2: uint = hofstadter_q(n - 2, memoize_vec);
		let rec_call_3: uint = hofstadter_q(n - rec_call_1, memoize_vec);
		let rec_call_4: uint = hofstadter_q(n - rec_call_2, memoize_vec);
		// ...update the memoization vector...
		let new_val: uint = rec_call_3 + rec_call_4;
		*memoize_vec.get_mut(n-1) = new_val;
		// ...and return the result
		new_val
	}
}

#[test]
fn test_result() {
	let q_array: Vec<uint> = hofstadter_q_wrapper(1000);
	assert_eq!(q_array[0], 1);
	assert_eq!(q_array[1], 1);
	assert_eq!(q_array[2], 2);
	assert_eq!(q_array[3], 3);
	assert_eq!(q_array[4], 3);
	assert_eq!(q_array[5], 4);
	assert_eq!(q_array[6], 5);
	assert_eq!(q_array[7], 5);
	assert_eq!(q_array[8], 6);
	assert_eq!(q_array[9], 6);
	assert_eq!(q_array[999], 502);
}<|endoftext|>


<commit_before><commit_msg>Update windows check<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #60627 - matklad:test, r=estebank<commit_after>// compile-pass
use std::marker::PhantomData;

struct Meta<A> {
    value: i32,
    type_: PhantomData<A>
}

trait MetaTrait {
    fn get_value(&self) -> i32;
}

impl<A> MetaTrait for Meta<A> {
    fn get_value(&self) -> i32 { self.value }
}

trait Bar {
    fn get_const(&self) -> &dyn MetaTrait;
}

struct Foo<A> {
    _value: A
}

impl<A: 'static> Foo<A> {
    const CONST: &'static dyn MetaTrait = &Meta::<Self> {
        value: 10,
        type_: PhantomData
    };
}

impl<A: 'static> Bar for Foo<A> {
    fn get_const(&self) -> &dyn MetaTrait { Self::CONST }
}

fn main() {
    let foo = Foo::<i32> { _value: 10 };
    let bar: &dyn Bar = &foo;
    println!("const {}", bar.get_const().get_value());
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue-66768<commit_after>// Regression test for #66768.
// check-pass
#![allow(dead_code)]
//-^ "dead code" is needed to reproduce the issue.

use std::marker::PhantomData;
use std::ops::{Add, Mul};

fn problematic_function<Space>(material_surface_element: Edge2dElement)
where
    DefaultAllocator: FiniteElementAllocator<DimU1, Space>,
{
    let _: Point2<f64> = material_surface_element.map_reference_coords().into();
}

impl<T> ArrayLength<T> for UTerm {
    type ArrayType = ();
}
impl<T, N: ArrayLength<T>> ArrayLength<T> for UInt<N, B0> {
    type ArrayType = GenericArrayImplEven<T, N>;
}
impl<T, N: ArrayLength<T>> ArrayLength<T> for UInt<N, B1> {
    type ArrayType = GenericArrayImplOdd<T, N>;
}
impl<U> Add<U> for UTerm {
    type Output = U;
    fn add(self, _: U) -> Self::Output {
        unimplemented!()
    }
}
impl<Ul, Ur> Add<UInt<Ur, B1>> for UInt<Ul, B0>
where
    Ul: Add<Ur>,
{
    type Output = UInt<Sum<Ul, Ur>, B1>;
    fn add(self, _: UInt<Ur, B1>) -> Self::Output {
        unimplemented!()
    }
}
impl<U> Mul<U> for UTerm {
    type Output = UTerm;
    fn mul(self, _: U) -> Self {
        unimplemented!()
    }
}
impl<Ul, B, Ur> Mul<UInt<Ur, B>> for UInt<Ul, B0>
where
    Ul: Mul<UInt<Ur, B>>,
{
    type Output = UInt<Prod<Ul, UInt<Ur, B>>, B0>;
    fn mul(self, _: UInt<Ur, B>) -> Self::Output {
        unimplemented!()
    }
}
impl<Ul, B, Ur> Mul<UInt<Ur, B>> for UInt<Ul, B1>
where
    Ul: Mul<UInt<Ur, B>>,
    UInt<Prod<Ul, UInt<Ur, B>>, B0>: Add<UInt<Ur, B>>,
{
    type Output = Sum<UInt<Prod<Ul, UInt<Ur, B>>, B0>, UInt<Ur, B>>;
    fn mul(self, _: UInt<Ur, B>) -> Self::Output {
        unimplemented!()
    }
}
impl<N, R, C> Allocator<N, R, C> for DefaultAllocator
where
    R: DimName,
    C: DimName,
    R::Value: Mul<C::Value>,
    Prod<R::Value, C::Value>: ArrayLength<N>,
{
    type Buffer = ArrayStorage<N, R, C>;
    fn allocate_uninitialized(_: R, _: C) -> Self::Buffer {
        unimplemented!()
    }
    fn allocate_from_iterator<I>(_: R, _: C, _: I) -> Self::Buffer {
        unimplemented!()
    }
}
impl<N, C> Allocator<N, Dynamic, C> for DefaultAllocator {
    type Buffer = VecStorage<N, Dynamic, C>;
    fn allocate_uninitialized(_: Dynamic, _: C) -> Self::Buffer {
        unimplemented!()
    }
    fn allocate_from_iterator<I>(_: Dynamic, _: C, _: I) -> Self::Buffer {
        unimplemented!()
    }
}
impl DimName for DimU1 {
    type Value = U1;
    fn name() -> Self {
        unimplemented!()
    }
}
impl DimName for DimU2 {
    type Value = U2;
    fn name() -> Self {
        unimplemented!()
    }
}
impl<N, D> From<VectorN<N, D>> for Point<N, D>
where
    DefaultAllocator: Allocator<N, D>,
{
    fn from(_: VectorN<N, D>) -> Self {
        unimplemented!()
    }
}
impl<GeometryDim, NodalDim> FiniteElementAllocator<GeometryDim, NodalDim> for DefaultAllocator where
    DefaultAllocator: Allocator<f64, GeometryDim> + Allocator<f64, NodalDim>
{
}
impl ReferenceFiniteElement for Edge2dElement {
    type NodalDim = DimU1;
}
impl FiniteElement<DimU2> for Edge2dElement {
    fn map_reference_coords(&self) -> Vector2<f64> {
        unimplemented!()
    }
}

type Owned<N, R, C> = <DefaultAllocator as Allocator<N, R, C>>::Buffer;
type MatrixMN<N, R, C> = Matrix<N, R, C, Owned<N, R, C>>;
type VectorN<N, D> = MatrixMN<N, D, DimU1>;
type Vector2<N> = VectorN<N, DimU2>;
type Point2<N> = Point<N, DimU2>;
type U1 = UInt<UTerm, B1>;
type U2 = UInt<UInt<UTerm, B1>, B0>;
type Sum<A, B> = <A as Add<B>>::Output;
type Prod<A, B> = <A as Mul<B>>::Output;

struct GenericArray<T, U: ArrayLength<T>> {
    _data: U::ArrayType,
}
struct GenericArrayImplEven<T, U> {
    _parent2: U,
    _marker: T,
}
struct GenericArrayImplOdd<T, U> {
    _parent2: U,
    _data: T,
}
struct B0;
struct B1;
struct UTerm;
struct UInt<U, B> {
    _marker: PhantomData<(U, B)>,
}
struct DefaultAllocator;
struct Dynamic;
struct DimU1;
struct DimU2;
struct Matrix<N, R, C, S> {
    _data: S,
    _phantoms: PhantomData<(N, R, C)>,
}
struct ArrayStorage<N, R, C>
where
    R: DimName,
    C: DimName,
    R::Value: Mul<C::Value>,
    Prod<R::Value, C::Value>: ArrayLength<N>,
{
    _data: GenericArray<N, Prod<R::Value, C::Value>>,
}
struct VecStorage<N, R, C> {
    _data: N,
    _nrows: R,
    _ncols: C,
}
struct Point<N, D>
where
    DefaultAllocator: Allocator<N, D>,
{
    _coords: VectorN<N, D>,
}
struct Edge2dElement;

trait ArrayLength<T> {
    type ArrayType;
}
trait Allocator<Scalar, R, C = DimU1> {
    type Buffer;
    fn allocate_uninitialized(nrows: R, ncols: C) -> Self::Buffer;
    fn allocate_from_iterator<I>(nrows: R, ncols: C, iter: I) -> Self::Buffer;
}
trait DimName {
    type Value;
    fn name() -> Self;
}
trait FiniteElementAllocator<GeometryDim, NodalDim>:
    Allocator<f64, GeometryDim> + Allocator<f64, NodalDim>
{
}
trait ReferenceFiniteElement {
    type NodalDim;
}
trait FiniteElement<GeometryDim>: ReferenceFiniteElement
where
    DefaultAllocator: FiniteElementAllocator<GeometryDim, Self::NodalDim>,
{
    fn map_reference_coords(&self) -> VectorN<f64, GeometryDim>;
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>handshake base encoded<commit_after>extern crate "rust-crypto" as rust_crypto;
extern crate serialize;

use rust_crypto::sha1::Sha1;
use rust_crypto::digest::Digest;
use serialize::base64::{ToBase64, STANDARD};

fn main () {
    let from_server = b"dGhlIHNhbXBsZSBub25jZQ==";
    let guid = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    let mut sha = Sha1::new();

    sha.input(from_server);
    sha.input(guid);
    let mut out = [0u8, ..20];
    sha.result(out.as_mut_slice());

    println!("{} {}", sha.result_str(), out.to_base64(STANDARD));
}
<|endoftext|>


<commit_before><commit_msg>Adding source code.<commit_after><|endoftext|>


<commit_before><commit_msg>Add lints<commit_after><|endoftext|>


<commit_before>// Copyright 2012-2013 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.

//! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not have finalizers (i.e. they do not
//! contain owned boxes or implement `Drop`), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the `Clone` trait and calling
//! the `clone` method.
//!
//! Basic usage example:
//!
//! ```
//! let s = String::new(); // String type implements Clone
//! let copy = s.clone(); // so we can clone it
//! ```
//!
//! To easily implement the Clone trait, you can also use
//! `#[derive(Clone)]`. Example:
//!
//! ```
//! #[derive(Clone)] // we add the Clone trait to Morpheus struct
//! struct Morpheus {
//!    blue_pill: f32,
//!    red_pill: i64,
//! }
//!
//! fn main() {
//!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
//!    let copy = f.clone(); // and now we can clone it!
//! }
//! ```

#![stable(feature = "rust1", since = "1.0.0")]

use marker::Sized;

/// A common trait for cloning an object.
///
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
/// implementation of `clone()` calls `clone()` on each field.
///
/// Types that are `Copy` should have a trivial implementation of `Clone`. More formally:
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
/// must not rely on it to ensure memory safety.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Clone : Sized {
    /// Returns a copy of the value.
    ///
    /// # Examples
    ///
    /// ```
    /// let hello = "Hello"; // &str implements Clone
    ///
    /// assert_eq!("Hello", hello.clone());
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn clone(&self) -> Self;

    /// Performs copy-assignment from `source`.
    ///
    /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
    /// but can be overridden to reuse the resources of `a` to avoid unnecessary
    /// allocations.
    #[inline(always)]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn clone_from(&mut self, source: &Self) {
        *self = source.clone()
    }
}

// FIXME(aburka): this method is used solely by #[derive] to
// assert that every component of a type implements Clone.
//
// This should never be called by user code.
#[doc(hidden)]
#[inline(always)]
#[unstable(feature = "derive_clone_copy",
           reason = "deriving hack, should not be public",
           issue = "0")]
pub fn assert_receiver_is_clone<T: Clone + ?Sized>(_: &T) {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Clone for &'a T {
    /// Returns a shallow copy of the reference.
    #[inline]
    fn clone(&self) -> &'a T { *self }
}

macro_rules! clone_impl {
    ($t:ty) => {
        #[stable(feature = "rust1", since = "1.0.0")]
        impl Clone for $t {
            /// Returns a deep copy of the value.
            #[inline]
            fn clone(&self) -> $t { *self }
        }
    }
}

clone_impl! { isize }
clone_impl! { i8 }
clone_impl! { i16 }
clone_impl! { i32 }
clone_impl! { i64 }

clone_impl! { usize }
clone_impl! { u8 }
clone_impl! { u16 }
clone_impl! { u32 }
clone_impl! { u64 }

clone_impl! { f32 }
clone_impl! { f64 }

clone_impl! { () }
clone_impl! { bool }
clone_impl! { char }
<commit_msg>Add more detail to `Clone`'s documentation<commit_after>// Copyright 2012-2013 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.

//! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not have finalizers (i.e. they do not
//! contain owned boxes or implement `Drop`), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the `Clone` trait and calling
//! the `clone` method.
//!
//! Basic usage example:
//!
//! ```
//! let s = String::new(); // String type implements Clone
//! let copy = s.clone(); // so we can clone it
//! ```
//!
//! To easily implement the Clone trait, you can also use
//! `#[derive(Clone)]`. Example:
//!
//! ```
//! #[derive(Clone)] // we add the Clone trait to Morpheus struct
//! struct Morpheus {
//!    blue_pill: f32,
//!    red_pill: i64,
//! }
//!
//! fn main() {
//!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
//!    let copy = f.clone(); // and now we can clone it!
//! }
//! ```

#![stable(feature = "rust1", since = "1.0.0")]

use marker::Sized;

/// A common trait for cloning an object. Differs from `Copy` in that you can
/// define `Clone` to run arbitrary code, while you are not allowed to override
/// the implementation of `Copy` that only does a `memcpy`.
///
/// Since `Clone` is more general than `Copy`, you can automatically make anything
/// `Copy` be `Clone` as well.
///
/// ## Derivable
///
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
/// implementation of `clone()` calls `clone()` on each field.
///
/// ## How can I implement `Clone`?
///
/// Types that are `Copy` should have a trivial implementation of `Clone`. More formally:
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
/// must not rely on it to ensure memory safety.
///
/// An example is an array holding more than 32 of a type that is `Clone`; the standard library
/// only implements `Clone` up until arrays of size 32. In this case, the implementation of
/// `Clone` cannot be `derive`d, but can be implemented as:
///
/// ```
/// #[derive(Copy)]
/// struct Stats {
///    frequencies: [i32; 100],
/// }
///
/// impl Clone for Stats {
///     fn clone(&self) -> Self { *self }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Clone : Sized {
    /// Returns a copy of the value.
    ///
    /// # Examples
    ///
    /// ```
    /// let hello = "Hello"; // &str implements Clone
    ///
    /// assert_eq!("Hello", hello.clone());
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn clone(&self) -> Self;

    /// Performs copy-assignment from `source`.
    ///
    /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
    /// but can be overridden to reuse the resources of `a` to avoid unnecessary
    /// allocations.
    #[inline(always)]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn clone_from(&mut self, source: &Self) {
        *self = source.clone()
    }
}

// FIXME(aburka): this method is used solely by #[derive] to
// assert that every component of a type implements Clone.
//
// This should never be called by user code.
#[doc(hidden)]
#[inline(always)]
#[unstable(feature = "derive_clone_copy",
           reason = "deriving hack, should not be public",
           issue = "0")]
pub fn assert_receiver_is_clone<T: Clone + ?Sized>(_: &T) {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Clone for &'a T {
    /// Returns a shallow copy of the reference.
    #[inline]
    fn clone(&self) -> &'a T { *self }
}

macro_rules! clone_impl {
    ($t:ty) => {
        #[stable(feature = "rust1", since = "1.0.0")]
        impl Clone for $t {
            /// Returns a deep copy of the value.
            #[inline]
            fn clone(&self) -> $t { *self }
        }
    }
}

clone_impl! { isize }
clone_impl! { i8 }
clone_impl! { i16 }
clone_impl! { i32 }
clone_impl! { i64 }

clone_impl! { usize }
clone_impl! { u8 }
clone_impl! { u16 }
clone_impl! { u32 }
clone_impl! { u64 }

clone_impl! { f32 }
clone_impl! { f64 }

clone_impl! { () }
clone_impl! { bool }
clone_impl! { char }
<|endoftext|>


<commit_before><commit_msg>added Video object<commit_after>use objects::PhotoSize;

/// Represents a video file
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Video{
    pub file_id: String,
    pub width: i64,
    pub heigh: i64,
    pub duration: i64,
    pub thump: Option<PhotoSize>,
    pub mime_type: Option<String>,
    pub file_size: Option<i64>,
}<|endoftext|>


<commit_before><commit_msg>cleaned up comments a bit<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::DocumentBinding;
use dom::bindings::utils::{DOMString, WrapperCache, ErrorResult, null_string, str};
use dom::bindings::utils::{BindingObject, CacheableWrapper, rust_box, DerivedWrapper};
use dom::bindings::utils::{is_valid_element_name, InvalidCharacter, Traceable};
use dom::element::{Element};
use dom::element::{HTMLHtmlElementTypeId, HTMLHeadElementTypeId, HTMLTitleElementTypeId};
use dom::event::Event;
use dom::htmlcollection::HTMLCollection;
use dom::htmldocument::HTMLDocument;
use dom::htmlelement::HTMLElement;
use dom::htmlhtmlelement::HTMLHtmlElement;
use dom::node::{AbstractNode, ScriptView, Node, ElementNodeTypeId};
use dom::text::Text;
use dom::window::Window;
use dom::windowproxy::WindowProxy;
use dom::htmltitleelement::HTMLTitleElement;
use html::hubbub_html_parser::build_element_from_tag;
use js::jsapi::{JSObject, JSContext, JSVal};
use js::jsapi::{JSTRACE_OBJECT, JSTracer, JS_CallTracer};
use js::glue::RUST_OBJECT_TO_JSVAL;
use servo_util::tree::TreeNodeRef;

use std::cast;
use std::ptr;
use std::str::eq_slice;
use std::libc;
use std::ascii::StrAsciiExt;

pub trait WrappableDocument {
    fn init_wrapper(@mut self, cx: *JSContext);
}

#[deriving(Eq)]
pub struct AbstractDocument {
    document: *Document
}

impl AbstractDocument {
    pub fn as_abstract<T: WrappableDocument>(cx: *JSContext, doc: @mut T) -> AbstractDocument {
        doc.init_wrapper(cx);
        AbstractDocument {
            document: unsafe { cast::transmute(doc) }
        }
    }

    unsafe fn transmute<T, R>(&self, f: &fn(&T) -> R) -> R {
        let box: *rust_box<T> = cast::transmute(self.document);
        f(&(*box).payload)
    }

    unsafe fn transmute_mut<T, R>(&self, f: &fn(&mut T) -> R) -> R {
        let box: *mut rust_box<T> = cast::transmute(self.document);
        f(&mut (*box).payload)
    }

    pub fn with_base<R>(&self, callback: &fn(&Document) -> R) -> R {
        unsafe {
            self.transmute(callback)
        }
    }

    pub fn with_mut_base<R>(&self, callback: &fn(&mut Document) -> R) -> R {
        unsafe {
            self.transmute_mut(callback)
        }
    }

    pub fn with_html<R>(&self, callback: &fn(&HTMLDocument) -> R) -> R {
        match self.with_base(|doc| doc.doctype) {
            HTML => unsafe { self.transmute(callback) },
            _ => fail!("attempt to downcast a non-HTMLDocument to HTMLDocument")
        }
    }
}

pub enum DocumentType {
    HTML,
    SVG,
    XML
}

pub struct Document {
    root: AbstractNode<ScriptView>,
    wrapper: WrapperCache,
    window: Option<@mut Window>,
    doctype: DocumentType,
    title: ~str
}

impl Document {
    #[fixed_stack_segment]
    pub fn new(root: AbstractNode<ScriptView>, window: Option<@mut Window>, doctype: DocumentType) -> Document {
        Document {
            root: root,
            wrapper: WrapperCache::new(),
            window: window,
            doctype: doctype,
            title: ~""
        }
    }

    pub fn Constructor(owner: @mut Window, _rv: &mut ErrorResult) -> AbstractDocument {
        let root = @HTMLHtmlElement {
            parent: HTMLElement::new(HTMLHtmlElementTypeId, ~"html")
        };

        let cx = owner.page.js_info.get_ref().js_compartment.cx.ptr;
        let root = unsafe { Node::as_abstract_node(cx, root) };
        AbstractDocument::as_abstract(cx, @mut Document::new(root, None, XML))
    }
}

impl WrappableDocument for Document {
    fn init_wrapper(@mut self, cx: *JSContext) {
        self.wrap_object_shared(cx, ptr::null()); //XXXjdm a proper scope would be nice
    }
}

impl CacheableWrapper for AbstractDocument {
    fn get_wrappercache(&mut self) -> &mut WrapperCache {
        do self.with_mut_base |doc| {
            doc.get_wrappercache()
        }
    }

    fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
        match self.with_base(|doc| doc.doctype) {
            HTML => {
                let doc: @mut HTMLDocument = unsafe { cast::transmute(self.document) };
                doc.wrap_object_shared(cx, scope)
            }
            XML | SVG => {
                fail!("no wrapping for documents that don't exist")
            }
        }
    }
}

impl BindingObject for AbstractDocument {
    fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
        do self.with_mut_base |doc| {
            doc.GetParentObject(cx)
        }
    }
}

impl DerivedWrapper for AbstractDocument {
    #[fixed_stack_segment]
    fn wrap(&mut self, _cx: *JSContext, _scope: *JSObject, vp: *mut JSVal) -> i32 {
        let cache = self.get_wrappercache();
        let wrapper = cache.get_wrapper();
        unsafe { *vp = RUST_OBJECT_TO_JSVAL(wrapper) };
        return 1;
    }

    fn wrap_shared(@mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
        fail!(~"nyi")
    }
}

impl CacheableWrapper for Document {
    fn get_wrappercache(&mut self) -> &mut WrapperCache {
        unsafe {
            cast::transmute(&self.wrapper)
        }
    }

    fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
        let mut unused = false;
        DocumentBinding::Wrap(cx, scope, self, &mut unused)
    }
}

impl BindingObject for Document {
    fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut CacheableWrapper> {
        match self.window {
            Some(win) => Some(win as @mut CacheableWrapper),
            None => None
        }
    }
}

impl Document {
    pub fn URL(&self) -> DOMString {
        null_string
    }

    pub fn DocumentURI(&self) -> DOMString {
        null_string
    }

    pub fn CompatMode(&self) -> DOMString {
        null_string
    }

    pub fn CharacterSet(&self) -> DOMString {
        null_string
    }

    pub fn ContentType(&self) -> DOMString {
        null_string
    }

    pub fn GetDocumentElement(&self) -> Option<AbstractNode<ScriptView>> {
        Some(self.root)
    }

    fn get_cx(&self) -> *JSContext {
        let win = self.window.get_ref();
        win.page.js_info.get_ref().js_compartment.cx.ptr
    }

    fn get_scope_and_cx(&self) -> (*JSObject, *JSContext) {
        let win = self.window.get_ref();
        let cx = win.page.js_info.get_ref().js_compartment.cx.ptr;
        let cache = win.get_wrappercache();
        let scope = cache.get_wrapper();
        (scope, cx)
    }

    pub fn GetElementsByTagName(&self, tag: &DOMString) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, tag.to_str()))
    }

    pub fn GetElementsByTagNameNS(&self, _ns: &DOMString, _tag: &DOMString) -> @mut HTMLCollection {
        let (scope, cx) = self.get_scope_and_cx();
        HTMLCollection::new(~[], cx, scope)
    }

    pub fn GetElementsByClassName(&self, _class: &DOMString) -> @mut HTMLCollection {
        let (scope, cx) = self.get_scope_and_cx();
        HTMLCollection::new(~[], cx, scope)
    }

    pub fn GetElementById(&self, _id: &DOMString) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn CreateElement(&self, local_name: &DOMString, rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
        let cx = self.get_cx();
        let local_name = local_name.to_str();
        if !is_valid_element_name(local_name) {
            *rv = Err(InvalidCharacter);
            // FIXME #909: what to return here?
            fail!("invalid character");
        }
        let local_name = local_name.to_ascii_lower();
        build_element_from_tag(cx, local_name)
    }

    pub fn CreateElementNS(&self, _namespace: &DOMString, _qualified_name: &DOMString, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
        fail!("stub")
    }

    pub fn CreateTextNode(&self, data: &DOMString) -> AbstractNode<ScriptView> {
        let cx = self.get_cx();
        unsafe { Node::as_abstract_node(cx, @Text::new(data.to_str())) }
    }

    pub fn CreateEvent(&self, _interface: &DOMString, _rv: &mut ErrorResult) -> @mut Event {
        fail!("stub")
    }

    pub fn GetInputEncoding(&self) -> DOMString {
        null_string
    }

    pub fn Referrer(&self) -> DOMString {
        null_string
    }

    pub fn LastModified(&self) -> DOMString {
        null_string
    }

    pub fn ReadyState(&self) -> DOMString {
        null_string
    }

    pub fn Title(&self) -> DOMString {
        let mut title = ~"";
        match self.doctype {
            SVG => {
                fail!("no SVG document yet")
            },
            _ => {
                let _ = for node in self.root.traverse_preorder() {
                    if node.type_id() != ElementNodeTypeId(HTMLTitleElementTypeId) {
                        loop;
                    }
                    for child in node.children() {
                        if child.is_text() {
                            do child.with_imm_text() |text| {
                                let s = text.parent.Data();
                                title = title + s.to_str();
                            }
                        }
                    }
                    break;
                };
            }
        }
        let v: ~[&str] = title.word_iter().collect();
        title = v.connect(" ");
        title = title.trim().to_owned();
        str(title)
    }

    pub fn SetTitle(&self, title: &DOMString, _rv: &mut ErrorResult) {
        match self.doctype {
            SVG => {
                fail!("no SVG document yet")
            },
            _ => {
                let (_scope, cx) = self.get_scope_and_cx();
                let _ = for node in self.root.traverse_preorder() {
                    if node.type_id() != ElementNodeTypeId(HTMLHeadElementTypeId) {
                        loop;
                    }
                    let mut has_title = false;
                    for child in node.children() {
                        if child.type_id() != ElementNodeTypeId(HTMLTitleElementTypeId) {
                            loop;
                        }
                        has_title = true;
                        for title_child in child.children() {
                            child.remove_child(title_child);
                        }
                        let new_text = unsafe {
                            Node::as_abstract_node(cx, @Text::new(title.to_str()))
                        };
                        child.add_child(new_text);
                        break;
                    }
                    if !has_title {
                        let new_title = @HTMLTitleElement {
                            parent: HTMLElement::new(HTMLTitleElementTypeId, ~"title")
                        };
                        let new_title = unsafe {
                            Node::as_abstract_node(cx, new_title)
                        };
                        let new_text = unsafe {
                            Node::as_abstract_node(cx, @Text::new(title.to_str()))
                        };
                        new_title.add_child(new_text);
                        node.add_child(new_title);
                    }
                    break;
                };
            }
        }
    }

    pub fn Dir(&self) -> DOMString {
        null_string
    }

    pub fn SetDir(&self, _dir: &DOMString) {
    }

    pub fn GetDefaultView(&self) -> Option<@mut WindowProxy> {
        None
    }

    pub fn GetActiveElement(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn HasFocus(&self, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn GetCurrentScript(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn ReleaseCapture(&self) {
    }

    pub fn MozFullScreenEnabled(&self) -> bool {
        false
    }

    pub fn GetMozFullScreenElement(&self, _rv: &mut ErrorResult) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn GetMozPointerLockElement(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn MozExitPointerLock(&self) {
    }

    pub fn Hidden(&self) -> bool {
        false
    }

    pub fn MozHidden(&self) -> bool {
        self.Hidden()
    }

    pub fn VisibilityState(&self) -> DocumentBinding::VisibilityState {
        DocumentBinding::VisibilityStateValues::Visible
    }

    pub fn MozVisibilityState(&self) -> DocumentBinding::VisibilityState {
        self.VisibilityState()
    }

    pub fn GetSelectedStyleSheetSet(&self) -> DOMString {
        null_string
    }

    pub fn SetSelectedStyleSheetSet(&self, _sheet: &DOMString) {
    }

    pub fn GetLastStyleSheetSet(&self) -> DOMString {
        null_string
    }

    pub fn GetPreferredStyleSheetSet(&self) -> DOMString {
        null_string
    }

    pub fn EnableStyleSheetsForSet(&self, _name: &DOMString) {
    }

    pub fn ElementFromPoint(&self, _x: f32, _y: f32) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn QuerySelector(&self, _selectors: &DOMString, _rv: &mut ErrorResult) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn GetElementsByName(&self, name: &DOMString) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem|
            elem.get_attr("name").is_some() && eq_slice(elem.get_attr("name").unwrap(), name.to_str()))
    }

    pub fn createHTMLCollection(&self, callback: &fn(elem: &Element) -> bool) -> @mut HTMLCollection {
        let mut elements = ~[];
        let _ = for child in self.root.traverse_preorder() {
            if child.is_element() {
                do child.with_imm_element |elem| {
                    if callback(elem) {
                        elements.push(child);
                    }
                }
            }
        };
        let (scope, cx) = self.get_scope_and_cx();
        HTMLCollection::new(elements, cx, scope)
    }

    pub fn content_changed(&self) {
        for window in self.window.iter() {
            window.content_changed()
        }
    }
}

impl Traceable for Document {
    #[fixed_stack_segment]
    fn trace(&self, tracer: *mut JSTracer) {
        unsafe {
            (*tracer).debugPrinter = ptr::null();
            (*tracer).debugPrintIndex = -1;
            do "root".to_c_str().with_ref |name| {
                (*tracer).debugPrintArg = name as *libc::c_void;
                debug!("tracing root node");
                do self.root.with_base |node| {
                    JS_CallTracer(tracer as *JSTracer,
                                  node.wrapper.wrapper,
                                  JSTRACE_OBJECT as u32);
                }
            }
        }
    }
}
<commit_msg>Introduce a createText function.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::DocumentBinding;
use dom::bindings::utils::{DOMString, WrapperCache, ErrorResult, null_string, str};
use dom::bindings::utils::{BindingObject, CacheableWrapper, rust_box, DerivedWrapper};
use dom::bindings::utils::{is_valid_element_name, InvalidCharacter, Traceable};
use dom::element::{Element};
use dom::element::{HTMLHtmlElementTypeId, HTMLHeadElementTypeId, HTMLTitleElementTypeId};
use dom::event::Event;
use dom::htmlcollection::HTMLCollection;
use dom::htmldocument::HTMLDocument;
use dom::htmlelement::HTMLElement;
use dom::htmlhtmlelement::HTMLHtmlElement;
use dom::node::{AbstractNode, ScriptView, Node, ElementNodeTypeId};
use dom::text::Text;
use dom::window::Window;
use dom::windowproxy::WindowProxy;
use dom::htmltitleelement::HTMLTitleElement;
use html::hubbub_html_parser::build_element_from_tag;
use js::jsapi::{JSObject, JSContext, JSVal};
use js::jsapi::{JSTRACE_OBJECT, JSTracer, JS_CallTracer};
use js::glue::RUST_OBJECT_TO_JSVAL;
use servo_util::tree::TreeNodeRef;

use std::cast;
use std::ptr;
use std::str::eq_slice;
use std::libc;
use std::ascii::StrAsciiExt;

pub trait WrappableDocument {
    fn init_wrapper(@mut self, cx: *JSContext);
}

#[deriving(Eq)]
pub struct AbstractDocument {
    document: *Document
}

impl AbstractDocument {
    pub fn as_abstract<T: WrappableDocument>(cx: *JSContext, doc: @mut T) -> AbstractDocument {
        doc.init_wrapper(cx);
        AbstractDocument {
            document: unsafe { cast::transmute(doc) }
        }
    }

    unsafe fn transmute<T, R>(&self, f: &fn(&T) -> R) -> R {
        let box: *rust_box<T> = cast::transmute(self.document);
        f(&(*box).payload)
    }

    unsafe fn transmute_mut<T, R>(&self, f: &fn(&mut T) -> R) -> R {
        let box: *mut rust_box<T> = cast::transmute(self.document);
        f(&mut (*box).payload)
    }

    pub fn with_base<R>(&self, callback: &fn(&Document) -> R) -> R {
        unsafe {
            self.transmute(callback)
        }
    }

    pub fn with_mut_base<R>(&self, callback: &fn(&mut Document) -> R) -> R {
        unsafe {
            self.transmute_mut(callback)
        }
    }

    pub fn with_html<R>(&self, callback: &fn(&HTMLDocument) -> R) -> R {
        match self.with_base(|doc| doc.doctype) {
            HTML => unsafe { self.transmute(callback) },
            _ => fail!("attempt to downcast a non-HTMLDocument to HTMLDocument")
        }
    }
}

pub enum DocumentType {
    HTML,
    SVG,
    XML
}

pub struct Document {
    root: AbstractNode<ScriptView>,
    wrapper: WrapperCache,
    window: Option<@mut Window>,
    doctype: DocumentType,
    title: ~str
}

impl Document {
    #[fixed_stack_segment]
    pub fn new(root: AbstractNode<ScriptView>, window: Option<@mut Window>, doctype: DocumentType) -> Document {
        Document {
            root: root,
            wrapper: WrapperCache::new(),
            window: window,
            doctype: doctype,
            title: ~""
        }
    }

    pub fn Constructor(owner: @mut Window, _rv: &mut ErrorResult) -> AbstractDocument {
        let root = @HTMLHtmlElement {
            parent: HTMLElement::new(HTMLHtmlElementTypeId, ~"html")
        };

        let cx = owner.page.js_info.get_ref().js_compartment.cx.ptr;
        let root = unsafe { Node::as_abstract_node(cx, root) };
        AbstractDocument::as_abstract(cx, @mut Document::new(root, None, XML))
    }
}

impl WrappableDocument for Document {
    fn init_wrapper(@mut self, cx: *JSContext) {
        self.wrap_object_shared(cx, ptr::null()); //XXXjdm a proper scope would be nice
    }
}

impl CacheableWrapper for AbstractDocument {
    fn get_wrappercache(&mut self) -> &mut WrapperCache {
        do self.with_mut_base |doc| {
            doc.get_wrappercache()
        }
    }

    fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
        match self.with_base(|doc| doc.doctype) {
            HTML => {
                let doc: @mut HTMLDocument = unsafe { cast::transmute(self.document) };
                doc.wrap_object_shared(cx, scope)
            }
            XML | SVG => {
                fail!("no wrapping for documents that don't exist")
            }
        }
    }
}

impl BindingObject for AbstractDocument {
    fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
        do self.with_mut_base |doc| {
            doc.GetParentObject(cx)
        }
    }
}

impl DerivedWrapper for AbstractDocument {
    #[fixed_stack_segment]
    fn wrap(&mut self, _cx: *JSContext, _scope: *JSObject, vp: *mut JSVal) -> i32 {
        let cache = self.get_wrappercache();
        let wrapper = cache.get_wrapper();
        unsafe { *vp = RUST_OBJECT_TO_JSVAL(wrapper) };
        return 1;
    }

    fn wrap_shared(@mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
        fail!(~"nyi")
    }
}

impl CacheableWrapper for Document {
    fn get_wrappercache(&mut self) -> &mut WrapperCache {
        unsafe {
            cast::transmute(&self.wrapper)
        }
    }

    fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
        let mut unused = false;
        DocumentBinding::Wrap(cx, scope, self, &mut unused)
    }
}

impl BindingObject for Document {
    fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut CacheableWrapper> {
        match self.window {
            Some(win) => Some(win as @mut CacheableWrapper),
            None => None
        }
    }
}

impl Document {
    pub fn URL(&self) -> DOMString {
        null_string
    }

    pub fn DocumentURI(&self) -> DOMString {
        null_string
    }

    pub fn CompatMode(&self) -> DOMString {
        null_string
    }

    pub fn CharacterSet(&self) -> DOMString {
        null_string
    }

    pub fn ContentType(&self) -> DOMString {
        null_string
    }

    pub fn GetDocumentElement(&self) -> Option<AbstractNode<ScriptView>> {
        Some(self.root)
    }

    fn get_cx(&self) -> *JSContext {
        let win = self.window.get_ref();
        win.page.js_info.get_ref().js_compartment.cx.ptr
    }

    fn get_scope_and_cx(&self) -> (*JSObject, *JSContext) {
        let win = self.window.get_ref();
        let cx = win.page.js_info.get_ref().js_compartment.cx.ptr;
        let cache = win.get_wrappercache();
        let scope = cache.get_wrapper();
        (scope, cx)
    }

    pub fn GetElementsByTagName(&self, tag: &DOMString) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, tag.to_str()))
    }

    pub fn GetElementsByTagNameNS(&self, _ns: &DOMString, _tag: &DOMString) -> @mut HTMLCollection {
        let (scope, cx) = self.get_scope_and_cx();
        HTMLCollection::new(~[], cx, scope)
    }

    pub fn GetElementsByClassName(&self, _class: &DOMString) -> @mut HTMLCollection {
        let (scope, cx) = self.get_scope_and_cx();
        HTMLCollection::new(~[], cx, scope)
    }

    pub fn GetElementById(&self, _id: &DOMString) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn CreateElement(&self, local_name: &DOMString, rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
        let cx = self.get_cx();
        let local_name = local_name.to_str();
        if !is_valid_element_name(local_name) {
            *rv = Err(InvalidCharacter);
            // FIXME #909: what to return here?
            fail!("invalid character");
        }
        let local_name = local_name.to_ascii_lower();
        build_element_from_tag(cx, local_name)
    }

    pub fn CreateElementNS(&self, _namespace: &DOMString, _qualified_name: &DOMString, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
        fail!("stub")
    }

    pub fn CreateTextNode(&self, data: &DOMString) -> AbstractNode<ScriptView> {
        let cx = self.get_cx();
        unsafe { Node::as_abstract_node(cx, @Text::new(data.to_str())) }
    }

    pub fn CreateEvent(&self, _interface: &DOMString, _rv: &mut ErrorResult) -> @mut Event {
        fail!("stub")
    }

    pub fn GetInputEncoding(&self) -> DOMString {
        null_string
    }

    pub fn Referrer(&self) -> DOMString {
        null_string
    }

    pub fn LastModified(&self) -> DOMString {
        null_string
    }

    pub fn ReadyState(&self) -> DOMString {
        null_string
    }

    pub fn Title(&self) -> DOMString {
        let mut title = ~"";
        match self.doctype {
            SVG => {
                fail!("no SVG document yet")
            },
            _ => {
                let _ = for node in self.root.traverse_preorder() {
                    if node.type_id() != ElementNodeTypeId(HTMLTitleElementTypeId) {
                        loop;
                    }
                    for child in node.children() {
                        if child.is_text() {
                            do child.with_imm_text() |text| {
                                let s = text.parent.Data();
                                title = title + s.to_str();
                            }
                        }
                    }
                    break;
                };
            }
        }
        let v: ~[&str] = title.word_iter().collect();
        title = v.connect(" ");
        title = title.trim().to_owned();
        str(title)
    }

    pub fn SetTitle(&self, title: &DOMString, _rv: &mut ErrorResult) {
        match self.doctype {
            SVG => {
                fail!("no SVG document yet")
            },
            _ => {
                let (_scope, cx) = self.get_scope_and_cx();
                let _ = for node in self.root.traverse_preorder() {
                    if node.type_id() != ElementNodeTypeId(HTMLHeadElementTypeId) {
                        loop;
                    }
                    let mut has_title = false;
                    for child in node.children() {
                        if child.type_id() != ElementNodeTypeId(HTMLTitleElementTypeId) {
                            loop;
                        }
                        has_title = true;
                        for title_child in child.children() {
                            child.remove_child(title_child);
                        }
                        child.add_child(self.createText(title.to_str()));
                        break;
                    }
                    if !has_title {
                        let new_title = @HTMLTitleElement {
                            parent: HTMLElement::new(HTMLTitleElementTypeId, ~"title")
                        };
                        let new_title = unsafe {
                            Node::as_abstract_node(cx, new_title)
                        };
                        new_title.add_child(self.createText(title.to_str()));
                        node.add_child(new_title);
                    }
                    break;
                };
            }
        }
    }

    pub fn Dir(&self) -> DOMString {
        null_string
    }

    pub fn SetDir(&self, _dir: &DOMString) {
    }

    pub fn GetDefaultView(&self) -> Option<@mut WindowProxy> {
        None
    }

    pub fn GetActiveElement(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn HasFocus(&self, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn GetCurrentScript(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn ReleaseCapture(&self) {
    }

    pub fn MozFullScreenEnabled(&self) -> bool {
        false
    }

    pub fn GetMozFullScreenElement(&self, _rv: &mut ErrorResult) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn GetMozPointerLockElement(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn MozExitPointerLock(&self) {
    }

    pub fn Hidden(&self) -> bool {
        false
    }

    pub fn MozHidden(&self) -> bool {
        self.Hidden()
    }

    pub fn VisibilityState(&self) -> DocumentBinding::VisibilityState {
        DocumentBinding::VisibilityStateValues::Visible
    }

    pub fn MozVisibilityState(&self) -> DocumentBinding::VisibilityState {
        self.VisibilityState()
    }

    pub fn GetSelectedStyleSheetSet(&self) -> DOMString {
        null_string
    }

    pub fn SetSelectedStyleSheetSet(&self, _sheet: &DOMString) {
    }

    pub fn GetLastStyleSheetSet(&self) -> DOMString {
        null_string
    }

    pub fn GetPreferredStyleSheetSet(&self) -> DOMString {
        null_string
    }

    pub fn EnableStyleSheetsForSet(&self, _name: &DOMString) {
    }

    pub fn ElementFromPoint(&self, _x: f32, _y: f32) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn QuerySelector(&self, _selectors: &DOMString, _rv: &mut ErrorResult) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn GetElementsByName(&self, name: &DOMString) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem|
            elem.get_attr("name").is_some() && eq_slice(elem.get_attr("name").unwrap(), name.to_str()))
    }

    pub fn createText(&self, data: ~str) -> AbstractNode<ScriptView> {
        let (_scope, cx) = self.get_scope_and_cx();
        unsafe {
            Node::as_abstract_node(cx, @Text::new(data))
        }
    }

    pub fn createHTMLCollection(&self, callback: &fn(elem: &Element) -> bool) -> @mut HTMLCollection {
        let mut elements = ~[];
        let _ = for child in self.root.traverse_preorder() {
            if child.is_element() {
                do child.with_imm_element |elem| {
                    if callback(elem) {
                        elements.push(child);
                    }
                }
            }
        };
        let (scope, cx) = self.get_scope_and_cx();
        HTMLCollection::new(elements, cx, scope)
    }

    pub fn content_changed(&self) {
        for window in self.window.iter() {
            window.content_changed()
        }
    }
}

impl Traceable for Document {
    #[fixed_stack_segment]
    fn trace(&self, tracer: *mut JSTracer) {
        unsafe {
            (*tracer).debugPrinter = ptr::null();
            (*tracer).debugPrintIndex = -1;
            do "root".to_c_str().with_ref |name| {
                (*tracer).debugPrintArg = name as *libc::c_void;
                debug!("tracing root node");
                do self.root.with_base |node| {
                    JS_CallTracer(tracer as *JSTracer,
                                  node.wrapper.wrapper,
                                  JSTRACE_OBJECT as u32);
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>[x86] add support for software interrupts<commit_after>/*
 * diosix microkernel 'menchi'
 *
 * Manage software interrupts (SWIs) in x86 systems
 *
 * Maintainer: Chris Williams (diosix.org)
 *
 */

use ::hardware::interrupts;
use errors::KernelInternalError;

const SWI_IRQ_NR: usize = 127;

/* init()
 *
 * Initialize handler for kernel-provided SWIs.
 *
 */
pub fn init() -> Result<(), KernelInternalError>
{
    kprintln!("[x86] initializing software interrupts");

    /* use vector 127 / 0x7f and allow userspace to trigger it */
    try!(interrupts::set_boot_idt_gate(SWI_IRQ_NR, interrupt_127_handler));
    try!(interrupts::enable_gate_user_access(SWI_IRQ_NR));

    /* TODO: register default driver to these exceptions */

    Ok(())
}

/* let rustc know the interrupt entry handlers are defined elsewhere */
extern
{
    fn interrupt_127_handler();
}

<|endoftext|>


<commit_before><commit_msg>Add tests for EEWPhase<commit_after>#![cfg(test)]

extern crate chrono;
extern crate tina;

use chrono::*;
use tina::*;

fn make_base_eew() -> EEW
{
	EEW {
		issue_pattern: IssuePattern::HighAccuracy, source: Source::Tokyo, kind: Kind::Normal,
		issued_at: UTC.ymd(2010, 1, 1).and_hms(1, 0, 2),
		occurred_at: UTC.ymd(2010, 1, 1).and_hms(0, 55, 59),
		id: "ND20100101005559".to_owned(), status: Status::Normal, number: 10,
		detail: Some(make_base_eew_detail()),
	}
}

fn make_base_eew_detail() -> EEWDetail
{
	EEWDetail {
		epicenter_name: "奈良県".to_owned(), epicenter: (34.4, 135.7),
		depth: Some(10.0), magnitude: Some(5.9),
		maximum_intensity: Some(IntensityClass::FiveLower),
		epicenter_accuracy: EpicenterAccuracy::GridSearchLow,
		depth_accuracy: DepthAccuracy::GridSearchLow,
		magnitude_accuracy: MagnitudeAccuracy::SWave,
		epicenter_category: EpicenterCategory::Land,
		warning_status: WarningStatus::Forecast,
		intensity_change: IntensityChange::Unknown,
		change_reason: ChangeReason::Unknown,
		area_info: vec!{},
	}
}

#[test]
fn it_should_output_none_for_low_accuracy_eew_without_detail()
{
	let eew = EEW {
		issue_pattern: IssuePattern::LowAccuracy,
		detail: None,
		.. make_base_eew()
	};

	let result = eew.get_eew_phase();

	assert_eq!(result, None);
}
<|endoftext|>


<commit_before>use std::io::Write;
use std::io::stderr;

use log::{Log, LogLevel, LogRecord, LogMetadata};

pub struct ImagLogger {
    lvl: LogLevel,
}

impl ImagLogger {

    pub fn new(lvl: LogLevel) -> ImagLogger {
        ImagLogger {
            lvl: lvl,
        }
    }

}

impl Log for ImagLogger {

    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= self.lvl
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            // TODO: This is just simple logging. Maybe we can enhance this lateron
            if record.metadata().level() == LogLevel::Debug {
                let loc = record.location();
                writeln!(stderr(), "[imag][{: <5}][{}][{: >5}]: {}",
                         record.level(), loc.file(), loc.line(), record.args()).ok();
            } else {
                writeln!(stderr(), "[imag][{: <5}]: {}", record.level(), record.args()).ok();
            }
        }
    }
}

<commit_msg>Color log output<commit_after>use std::io::Write;
use std::io::stderr;

use log::{Log, LogLevel, LogRecord, LogMetadata};

pub struct ImagLogger {
    lvl: LogLevel,
}

impl ImagLogger {

    pub fn new(lvl: LogLevel) -> ImagLogger {
        ImagLogger {
            lvl: lvl,
        }
    }

}

impl Log for ImagLogger {

    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= self.lvl
    }

    fn log(&self, record: &LogRecord) {
        use ansi_term::Colour::Red;
        use ansi_term::Colour::Yellow;
        use ansi_term::Colour::Cyan;

        if self.enabled(record.metadata()) {
            // TODO: This is just simple logging. Maybe we can enhance this lateron
            let loc = record.location();
            match record.metadata().level() {
                LogLevel::Debug => {
                    let lvl  = Cyan.paint(format!("{}", record.level()));
                    let file = Cyan.paint(format!("{}", loc.file()));
                    let ln   = Cyan.paint(format!("{}", loc.line()));
                    let args = Cyan.paint(format!("{}", record.args()));

                    writeln!(stderr(), "[imag][{: <5}][{}][{: >5}]: {}", lvl, file, ln, args).ok();
                },
                LogLevel::Warn | LogLevel::Error => {
                    let lvl  = Red.blink().paint(format!("{}", record.level()));
                    let args = Red.paint(format!("{}", record.args()));

                    writeln!(stderr(), "[imag][{: <5}]: {}", lvl, args).ok();
                },
                LogLevel::Info => {
                    let lvl  = Yellow.paint(format!("{}", record.level()));
                    let args = Yellow.paint(format!("{}", record.args()));

                    writeln!(stderr(), "[imag][{: <5}]: {}", lvl, args).ok();
                },
                _ => {
                    writeln!(stderr(), "[imag][{: <5}]: {}", record.level(), record.args()).ok();
                },
            }
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Initial proof-of-concept BigUint bindings using gmp<commit_after>use std::libc::{c_int,c_char,c_void,c_uint,size_t};
use std::{str,vec,fmt};
use std::mem::uninit;

struct Mpz {
    alloc: c_int,
    size: c_int,
    data: *c_void // Not sure if unsigned int, unsigned long, or unsigned long long
}

type MpzPtr = *Mpz;

#[link(name = "gmp")]
extern "C" {
    // Initializing
    fn __gmpz_init(rop: MpzPtr);
    fn __gmpz_init_set_ui(rop: MpzPtr, op: c_uint);

    // Arithmetic
    fn __gmpz_add(rop: MpzPtr, op1: MpzPtr, op2: MpzPtr);
    fn __gmpz_sub(rop: MpzPtr, op1: MpzPtr, op2: MpzPtr);
    fn __gmpz_mul(rop: MpzPtr, op1: MpzPtr, op2: MpzPtr);

    // Conversion
    fn __gmpz_sizeinbase(op: MpzPtr, base: c_int) -> size_t;
    fn __gmpz_get_str(outstr: *c_char, base: c_int, op: MpzPtr) -> *c_char;
}

struct BigUint {
    data: Mpz
}

pub trait ToBigUint {
    fn to_biguint(&self) -> Option<BigUint>;
}

impl ToBigUint for uint {
    fn to_biguint(&self) -> Option<BigUint> {
        unsafe {
            let data = uninit();
            __gmpz_init_set_ui(&data, *self as c_uint);
            Some(BigUint { data: data })
        }
    }
}

impl ToStrRadix for BigUint {
    fn to_str_radix(&self, radix: uint) -> ~str {
        unsafe {
            let len = __gmpz_sizeinbase(&self.data, radix as c_int) as uint;
            let dstptr = vec::from_elem(len, 0 as c_char).as_ptr();
            let cstr = __gmpz_get_str(dstptr as *c_char, radix as c_int, &self.data);
            str::raw::from_c_str(cstr)
        }
    }
}

impl ToStr for BigUint {
    fn to_str(&self) -> ~str { self.to_str_radix(10) }
}

impl fmt::Show for BigUint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f.buf, "{}", self.to_str_radix(10))
    }
}

impl Add<BigUint, BigUint> for BigUint {
    fn add(&self, other: &BigUint) -> BigUint {
        unsafe {
            let dstdata = uninit();
            __gmpz_init(&dstdata);
            __gmpz_add(&dstdata, &self.data, &other.data);
            BigUint { data: dstdata }
        }
    }
}

impl Sub<BigUint, BigUint> for BigUint {
    fn sub(&self, other: &BigUint) -> BigUint {
        unsafe {
            let dstdata = uninit();
            __gmpz_init(&dstdata);
            __gmpz_sub(&dstdata, &self.data, &other.data);
            BigUint { data: dstdata }
        }
    }
}

impl Mul<BigUint, BigUint> for BigUint {
    fn mul(&self, other: &BigUint) -> BigUint {
        unsafe {
            let dstdata = uninit();
            __gmpz_init(&dstdata);
            __gmpz_mul(&dstdata, &self.data, &other.data);
            BigUint { data: dstdata }
        }
    }
}

#[test]
fn test_to_and_fro() {
    let two = 2u.to_biguint().unwrap();
    assert_eq!(two.to_str(), ~"2");
}

#[test]
fn test_printing() {
    println!("{} == 2!", 2u.to_biguint().unwrap()); // Doesn't fail
}

#[test]
fn test_add() {
    let two = 2u.to_biguint().unwrap();
    let three = 3u.to_biguint().unwrap();

    assert_eq!(two.add(&three).to_str(), ~"5");
    assert_eq!((two + three).to_str(), ~"5");
}

#[test]
fn test_simple_sub() {
    let two = 2u.to_biguint().unwrap();
    let three = 3u.to_biguint().unwrap();

    assert_eq!(three.sub(&two).to_str(), ~"1");
    assert_eq!((three - two).to_str(), ~"1");
}

#[test]
fn test_mul() {
    let two = 2u.to_biguint().unwrap();
    let three = 3u.to_biguint().unwrap();

    assert_eq!(two.mul(&three).to_str(), ~"6");
    assert_eq!((two * three).to_str(), ~"6");
}
<|endoftext|>


<commit_before><commit_msg>Example rust solver<commit_after>use std::ops::{Add, Sub, Mul, Div, Neg};
use std::cmp::{PartialOrd, Ordering, PartialEq, Ord};
use std::collections::BinaryHeap;

#[derive(Debug, Copy, Clone)]
struct Interval {
    inf: f64,
    sup: f64,
}

impl Interval {
    fn new(inf: f64,
           sup: f64) -> Interval{
        if inf > sup {
            panic!("Improper interval");
        }
        Interval{inf: inf, sup: sup}
    }
}

struct Quple {
    p: f64,
    pf: u32,
    data: Vec<Interval>,
}

impl PartialEq for Quple {
    fn eq(&self, other: &Quple) -> bool {
        self.pf == other.pf
    }
}

impl Eq for Quple { }

impl PartialOrd for Quple {
    fn partial_cmp(&self, other: &Quple) -> Option<Ordering> {
        if self.p > other.p {
            Some(Ordering::Greater)
        }
        else if self.pf > other.pf {
            Some(Ordering::Greater)
        }
        else {
            Some(Ordering::Less)
        }
    }
}

impl Ord for Quple {
    fn cmp(&self, other: &Quple) -> Ordering {
        if self.p > other.p {
            Ordering::Greater
        }
        else if self.pf > other.pf {
            Ordering::Greater
        }
        else if self.pf == other.pf {
            Ordering::Equal
        }
        else {
            Ordering::Less
        }
    }
}

impl Add for Interval {
    type Output = Interval;

    fn add(self, other: Interval) -> Interval {
        Interval::new(self.inf + other.inf,
                      self.sup + other.sup)
    }
}

impl Sub for Interval {
    type Output = Interval;

    fn sub(self, other: Interval) -> Interval {
        Interval::new(self.inf - other.sup,
                      self.sup - other.inf)
    }
}

impl Mul for Interval {
    type Output = Interval;

    fn mul(self, other: Interval) -> Interval {
        let a = self.inf;
        let b = self.sup;
        let c = other.inf;
        let d = other.sup;
        let ac = a*c;
        let ad = a*d;
        let bc = b*c;
        let bd = b*d;
        Interval::new(min(&[ac, ad, bc, bd]),
                      max(&[ac, ad, bc, bd]))
    }
}

impl Div for Interval {
    type Output = Interval;

    fn div(self, other: Interval) -> Interval {
        let a = self.inf;
        let b = self.sup;
        let c = other.inf;
        let d = other.sup;
        let ac = a/c;
        let ad = a/d;
        let bc = b/c;
        let bd = b/d;
        Interval::new(min(&[ac, ad, bc, bd]),
                      max(&[ac, ad, bc, bd]))
    }
}

impl Neg for Interval {
    type Output = Interval;

    fn neg(self) -> Interval {
        Interval::new(-self.sup,
                      -self.inf)
    }
}

fn min(args: &[f64]) -> f64 {
    let mut min = std::f64::INFINITY;
    for &arg in args {
        if arg < min {
            min = arg;
        }
    }
    min
}

fn max(args: &[f64]) -> f64 {
    let mut max = std::f64::NEG_INFINITY;
    for &arg in args {
        if arg > max {
            max = arg;
        }
    }
    max
}

fn pow(a: Interval, b: u32) -> Interval {
    if b == 0 {
        Interval{inf: 1.0, sup: 1.0}
    }
    else if b == 1 {
        a
    }
    else {
        let mut result;
        let half_pow = pow(a, b/2);
        if (b % 2) == 1 {
            result = half_pow*half_pow*a;
        }
        else { // Power is even. Optimized so that the infimum
               // of the interval is never negative.
            result = half_pow*half_pow;
            let linf = result.inf;
            result = Interval::new(max(&[linf, 0.0]),
                                   result.sup);
        }
        result
    }
}

// Answer: ~500.488
fn func(_x: &Vec<Interval>) -> Interval {
    let x = _x[0];
    let y = _x[1];
    let z = _x[2];
    let a = _x[3];
    let b = _x[4];
    let c = _x[5];
    (-y * z - x * a + y * b + z * c - b * c + x * (-x + y + z - a + b + c))
}

fn width(i: &Interval) -> f64 {
    let w = i.sup - i.inf;
    if w < 0.0 {
        -w
    }
    else {
        w
    }
}

fn width_box(x: &Vec<Interval>) -> f64 {
    let mut result = std::f64::NEG_INFINITY;
    for i in x {
        let w = width(i);
        if w > result {
            result = w;
        }
    }
    result
}

fn split(x: &Vec<Interval>) -> Vec<Vec<Interval>> {
    let mut widest = std::f64::NEG_INFINITY;
    let mut idx = -1;
    for i in (0..x.len()) {
        let w = width(&x[i]);
        if w > widest {
            widest = w;
            idx = i;
        }
    }

    let mid = (x[idx].inf +x[idx].sup)/2.0;

    let mut result = vec![x.clone(), x.clone()];
    result[0][idx].sup = mid;
    result[1][idx].inf = mid;
    result
}

fn midpoint(x: &Vec<Interval>) -> Vec<Interval> {
    let mut result = Vec::new();
    for i in x {
        let mid = (i.inf + i.sup)/2.0;
        result.push(Interval::new(mid,
                                  mid));
    }
    result
}

fn ibba(x_0: &Vec<Interval>, e_x: f64, e_f: f64) -> (f64, Vec<Interval>) {
    let mut f_best_high = std::f64::NEG_INFINITY;
    let mut f_best_low  = std::f64::NEG_INFINITY;
    let mut best_x = x_0.clone();

    let mut q = BinaryHeap::new();
    let mut i: u32 = 0;

    q.push(Quple{p: std::f64::INFINITY, pf: i, data: x_0.clone()});
    while q.len() != 0 {
        let v = q.pop();
        let ref x =
            match v {
                // The division was valid
                Some(y) => y.data,
                // The division was invalid
                None    => panic!("wtf")
            };

        let xw = width_box(x);
        let fx = func(x);
        let fw = width(&fx);

        if fx.sup < f_best_low ||
            xw < e_x ||
            fw < e_f {
                if f_best_high < fx.sup {
                    f_best_high = fx.sup;
                    best_x = x.clone();
                }
                continue;
            }
        else {
            let x_s = split(x);
            for sx in x_s {
                let mid = midpoint(&sx);
                let est = func(&mid);
                if f_best_low < est.inf  {
                    f_best_low = est.inf;
                }
                i += 1;
                q.push(Quple{p:est.sup,
                             pf: i,
                             data: sx});
            }
        }
    }
    (f_best_high, best_x)
}

fn main() {
    let bound = Interval::new(-10.0, 10.0);
    let x_0 = vec![bound, bound, bound,
                   bound, bound, bound];
    let (max, interval) = ibba(&x_0, 0.001, 0.001);
    println!("{:?}, {:?}", max, interval)
}
<|endoftext|>


<commit_before><commit_msg>Don't panic please, just show an error<commit_after><|endoftext|>


<commit_before><commit_msg>Add `debug-words` example<commit_after>use textwrap::word_separators::WordSeparator;

fn main() {
    #[cfg(feature = "unicode-linebreak")]
    let word_separator = textwrap::word_separators::UnicodeBreakProperties;
    #[cfg(not(feature = "unicode-linebreak"))]
    let word_separator = textwrap::word_separators::AsciiSpace;

    let args = std::env::args().skip(1).collect::<Vec<_>>();
    let text = args.join(" ");
    let words = word_separator.find_words(&text).collect::<Vec<_>>();

    println!("word_separator = {:?}", word_separator);
    println!("text = {:?}", text);
    println!("words = {:#?}", words);
}
<|endoftext|>


<commit_before>static NTASKS: int = 10;

fn main() {
    for i in range(0, NTASKS) {
        // Spin up a task
        spawn(proc() {
            println!("this is task number {}", i)
        });
    }
}
<commit_msg>tasks: tweak comments<commit_after>static NTASKS: int = 10;

// This is the `main` task
fn main() {
    for i in range(0, NTASKS) {
        // Spin up another task
        spawn(proc() {
            println!("this is task number {}", i)
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Simple binary tree with add function<commit_after>enum BinaryTree<T> {
    Empty,
    NonEmpty(Box<TreeNode<T>>)
}

struct TreeNode<T> {
    element: T,
    left: BinaryTree<T>,
    right: BinaryTree<T>
}

impl<T: Ord> BinaryTree<T> {
    fn add(&mut self, value: T) {
        match *self {
            BinaryTree::Empty =>
                *self = BinaryTree::NonEmpty(Box::new(TreeNode {
                    element: value,
                    left: BinaryTree::Empty,
                    right: BinaryTree::Empty
                })),
            BinaryTree::NonEmpty(ref mut node) =>
                if value <= node.element {
                    node.left.add(value);
                } else {
                    node.right.add(value);
                }
        }
    }
}

fn main() {

}
<|endoftext|>


<commit_before><commit_msg>Add test case for issue 2766, which resolve 3 fixes<commit_after>mod stream {
    enum stream<T: send> { send(T, server::stream<T>), }
    mod server {
        impl recv<T: send> for stream<T> {
            fn recv() -> extern fn(+stream<T>) -> stream::stream<T> {
              // resolve really should report just one error here.
              // Change the test case when it changes.
              fn recv(+pipe: stream<T>) -> stream::stream<T> { //~ ERROR attempt to use a type argument out of scope
                //~^ ERROR use of undeclared type name
                //~^^ ERROR attempt to use a type argument out of scope
                //~^^^ ERROR use of undeclared type name
                    option::unwrap(pipes::recv(pipe))
                }
                recv
            }
        }
        type stream<T: send> = pipes::recv_packet<stream::stream<T>>;
    }
}

fn main() {}
<|endoftext|>