<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/. */

//! The high-level interface from script to layout. Using this abstract interface helps reduce
/// coupling between these two components, and enables the DOM to be placed in a separate crate
/// from layout.

use dom::node::LayoutDataRef;

use geom::point::Point2D;
use geom::rect::Rect;
use script_traits::{ScriptControlChan, OpaqueScriptLayoutChannel, UntrustedNodeAddress};
use servo_msg::constellation_msg::{PipelineExitType, WindowSizeData};
use util::geometry::Au;
use std::any::Any;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::boxed::BoxAny;
use style::stylesheets::Stylesheet;
use url::Url;

pub use dom::node::TrustedNodeAddress;

/// Asynchronous messages that script can send to layout.
pub enum Msg {
    /// Adds the given stylesheet to the document.
    AddStylesheet(Stylesheet),

    /// Adds the given stylesheet to the document.
    LoadStylesheet(Url),

    /// Puts a document into quirks mode, causing the quirks mode stylesheet to be loaded.
    SetQuirksMode,

    /// Requests a reflow.
    Reflow(Box<Reflow>),

    /// Get an RPC interface.
    GetRPC(Sender<Box<LayoutRPC + Send>>),

    /// Destroys layout data associated with a DOM node.
    ///
    /// TODO(pcwalton): Maybe think about batching to avoid message traffic.
    ReapLayoutData(LayoutDataRef),

    /// Requests that the layout task enter a quiescent state in which no more messages are
    /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
    /// this happens.
    PrepareToExit(Sender<()>),

    /// Requests that the layout task immediately shut down. There must be no more nodes left after
    /// this, or layout will crash.
    ExitNow(PipelineExitType),
}

/// Synchronous messages that script can send to layout.
///
/// In general, you should use messages to talk to Layout. Use the RPC interface
/// if and only if the work is
///
///   1) read-only with respect to LayoutTaskData,
///   2) small,
//    3) and really needs to be fast.
pub trait LayoutRPC {
    /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call.
    fn content_box(&self) -> ContentBoxResponse;
    /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call.
    fn content_boxes(&self) -> ContentBoxesResponse;
    /// Requests the node containing the point of interest
    fn hit_test(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()>;
    fn mouse_over(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<MouseOverResponse, ()>;
}

pub struct ContentBoxResponse(pub Rect<Au>);
pub struct ContentBoxesResponse(pub Vec<Rect<Au>>);
pub struct HitTestResponse(pub UntrustedNodeAddress);
pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>);

/// Why we're doing reflow.
#[derive(PartialEq, Show)]
pub enum ReflowGoal {
    /// We're reflowing in order to send a display list to the screen.
    ForDisplay,
    /// We're reflowing in order to satisfy a script query. No display list will be created.
    ForScriptQuery,
}

/// Any query to perform with this reflow.
pub enum ReflowQueryType {
    NoQuery,
    ContentBoxQuery(TrustedNodeAddress),
    ContentBoxesQuery(TrustedNodeAddress),
}

/// Information needed for a reflow.
pub struct Reflow {
    /// The document node.
    pub document_root: TrustedNodeAddress,
    /// The goal of reflow: either to render to the screen or to flush layout info for script.
    pub goal: ReflowGoal,
    /// The URL of the page.
    pub url: Url,
    /// Is the current reflow of an iframe, as opposed to a root window?
    pub iframe: bool,
    /// The channel through which messages can be sent back to the script task.
    pub script_chan: ScriptControlChan,
    /// The current window size.
    pub window_size: WindowSizeData,
    /// The channel that we send a notification to.
    pub script_join_chan: Sender<()>,
    /// Unique identifier
    pub id: uint,
    /// The type of query if any to perform during this reflow.
    pub query_type: ReflowQueryType,
    ///  A clipping rectangle for the page, an enlarged rectangle containing the viewport.
    pub page_clip_rect: Rect<Au>,
}

/// Encapsulates a channel to the layout task.
#[derive(Clone)]
pub struct LayoutChan(pub Sender<Msg>);

impl LayoutChan {
    pub fn new() -> (Receiver<Msg>, LayoutChan) {
        let (chan, port) = channel();
        (port, LayoutChan(chan))
    }
}

/// A trait to manage opaque references to script<->layout channels without needing
/// to expose the message type to crates that don't need to know about them.
pub trait ScriptLayoutChan {
    fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> Self;
    fn sender(&self) -> Sender<Msg>;
    fn receiver(self) -> Receiver<Msg>;
}

impl ScriptLayoutChan for OpaqueScriptLayoutChannel {
    fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> OpaqueScriptLayoutChannel {
        let inner = (box sender as Box<Any+Send>, box receiver as Box<Any+Send>);
        OpaqueScriptLayoutChannel(inner)
    }

    fn sender(&self) -> Sender<Msg> {
        let &OpaqueScriptLayoutChannel((ref sender, _)) = self;
        (*sender.downcast_ref::<Sender<Msg>>().unwrap()).clone()
    }

    fn receiver(self) -> Receiver<Msg> {
        let OpaqueScriptLayoutChannel((_, receiver)) = self;
        *receiver.downcast::<Receiver<Msg>>().unwrap()
    }
}
<commit_msg>auto merge of #4814 : Ms2ger/servo/layout_interface-doc, r=jdm<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/. */

//! The high-level interface from script to layout. Using this abstract
//! interface helps reduce coupling between these two components, and enables
//! the DOM to be placed in a separate crate from layout.

use dom::node::LayoutDataRef;

use geom::point::Point2D;
use geom::rect::Rect;
use script_traits::{ScriptControlChan, OpaqueScriptLayoutChannel, UntrustedNodeAddress};
use servo_msg::constellation_msg::{PipelineExitType, WindowSizeData};
use util::geometry::Au;
use std::any::Any;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::boxed::BoxAny;
use style::stylesheets::Stylesheet;
use url::Url;

pub use dom::node::TrustedNodeAddress;

/// Asynchronous messages that script can send to layout.
pub enum Msg {
    /// Adds the given stylesheet to the document.
    AddStylesheet(Stylesheet),

    /// Adds the given stylesheet to the document.
    LoadStylesheet(Url),

    /// Puts a document into quirks mode, causing the quirks mode stylesheet to be loaded.
    SetQuirksMode,

    /// Requests a reflow.
    Reflow(Box<Reflow>),

    /// Get an RPC interface.
    GetRPC(Sender<Box<LayoutRPC + Send>>),

    /// Destroys layout data associated with a DOM node.
    ///
    /// TODO(pcwalton): Maybe think about batching to avoid message traffic.
    ReapLayoutData(LayoutDataRef),

    /// Requests that the layout task enter a quiescent state in which no more messages are
    /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
    /// this happens.
    PrepareToExit(Sender<()>),

    /// Requests that the layout task immediately shut down. There must be no more nodes left after
    /// this, or layout will crash.
    ExitNow(PipelineExitType),
}

/// Synchronous messages that script can send to layout.
///
/// In general, you should use messages to talk to Layout. Use the RPC interface
/// if and only if the work is
///
///   1) read-only with respect to LayoutTaskData,
///   2) small,
//    3) and really needs to be fast.
pub trait LayoutRPC {
    /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call.
    fn content_box(&self) -> ContentBoxResponse;
    /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call.
    fn content_boxes(&self) -> ContentBoxesResponse;
    /// Requests the node containing the point of interest
    fn hit_test(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()>;
    fn mouse_over(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<MouseOverResponse, ()>;
}

pub struct ContentBoxResponse(pub Rect<Au>);
pub struct ContentBoxesResponse(pub Vec<Rect<Au>>);
pub struct HitTestResponse(pub UntrustedNodeAddress);
pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>);

/// Why we're doing reflow.
#[derive(PartialEq, Show)]
pub enum ReflowGoal {
    /// We're reflowing in order to send a display list to the screen.
    ForDisplay,
    /// We're reflowing in order to satisfy a script query. No display list will be created.
    ForScriptQuery,
}

/// Any query to perform with this reflow.
pub enum ReflowQueryType {
    NoQuery,
    ContentBoxQuery(TrustedNodeAddress),
    ContentBoxesQuery(TrustedNodeAddress),
}

/// Information needed for a reflow.
pub struct Reflow {
    /// The document node.
    pub document_root: TrustedNodeAddress,
    /// The goal of reflow: either to render to the screen or to flush layout info for script.
    pub goal: ReflowGoal,
    /// The URL of the page.
    pub url: Url,
    /// Is the current reflow of an iframe, as opposed to a root window?
    pub iframe: bool,
    /// The channel through which messages can be sent back to the script task.
    pub script_chan: ScriptControlChan,
    /// The current window size.
    pub window_size: WindowSizeData,
    /// The channel that we send a notification to.
    pub script_join_chan: Sender<()>,
    /// Unique identifier
    pub id: uint,
    /// The type of query if any to perform during this reflow.
    pub query_type: ReflowQueryType,
    ///  A clipping rectangle for the page, an enlarged rectangle containing the viewport.
    pub page_clip_rect: Rect<Au>,
}

/// Encapsulates a channel to the layout task.
#[derive(Clone)]
pub struct LayoutChan(pub Sender<Msg>);

impl LayoutChan {
    pub fn new() -> (Receiver<Msg>, LayoutChan) {
        let (chan, port) = channel();
        (port, LayoutChan(chan))
    }
}

/// A trait to manage opaque references to script<->layout channels without needing
/// to expose the message type to crates that don't need to know about them.
pub trait ScriptLayoutChan {
    fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> Self;
    fn sender(&self) -> Sender<Msg>;
    fn receiver(self) -> Receiver<Msg>;
}

impl ScriptLayoutChan for OpaqueScriptLayoutChannel {
    fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> OpaqueScriptLayoutChannel {
        let inner = (box sender as Box<Any+Send>, box receiver as Box<Any+Send>);
        OpaqueScriptLayoutChannel(inner)
    }

    fn sender(&self) -> Sender<Msg> {
        let &OpaqueScriptLayoutChannel((ref sender, _)) = self;
        (*sender.downcast_ref::<Sender<Msg>>().unwrap()).clone()
    }

    fn receiver(self) -> Receiver<Msg> {
        let OpaqueScriptLayoutChannel((_, receiver)) = self;
        *receiver.downcast::<Receiver<Msg>>().unwrap()
    }
}
<|endoftext|>


<commit_before><commit_msg>Add an example FTP client that uses our test certificate to connect to the test server<commit_after><|endoftext|>


<commit_before><commit_msg>examples: Add simple usage example<commit_after>extern crate rs_release;

use rs_release::get_os_release;

fn main() {
    match get_os_release() {
        Ok(os_release) => {
            println!("Parsed os-release:");
            for (k, v) in os_release {
                println!("{}={}", k, v);
            }
        }
        Err(e) => println!("ERROR: {:?}", e),
    }
}
<|endoftext|>


<commit_before><commit_msg>parse<commit_after><|endoftext|>


<commit_before><commit_msg>Implementing parts of CompiledMethod<commit_after><|endoftext|>


<commit_before><commit_msg>Renumber uniform blocks, reusing the block for view matrices<commit_after><|endoftext|>


<commit_before><commit_msg>Fix BlockPos.proto_decode for negative coords<commit_after><|endoftext|>


<commit_before><commit_msg>of the year passed<commit_after><|endoftext|>


<commit_before>use std::env::home_dir;
use std::path::PathBuf;

#[cfg(not(windows))]
pub fn base() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel");
        path
    })
}

#[cfg(windows)]
pub fn base() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel");
        path
    })
}

#[cfg(not(windows))]
pub fn processed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel/processed");
        path
    })
}

#[cfg(windows)]
pub fn processed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel/processed");
        path
    })
}

#[cfg(not(windows))]
pub fn unprocessed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel/unprocessed");
        path
    })
}

#[cfg(windows)]
pub fn unprocessed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel/unprocessed");
        path
    })
}

#[cfg(not(windows))]
pub fn errors() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel/errors");
        path
    })
}

#[cfg(windows)]
pub fn errors() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel/errors");
        path
    })
}

#[cfg(not(windows))]
pub fn outputs_path() -> PathBuf {
    PathBuf::from("/tmp/parallel/")
}

#[cfg(not(windows))]
pub fn job(id: usize) -> (PathBuf, PathBuf) {
    let stdout = PathBuf::from(format!("/tmp/parallel/stdout_{}", id));
    let stderr = PathBuf::from(format!("/tmp/parallel/stderr_{}", id));
    (stdout, stderr)
}

#[cfg(windows)]
pub fn job(id: usize) -> (PathBuf, PathBuf) {
    home_dir().map(|mut stdout| {
        let mut stderr = stdout.clone();
        stdout.push(format!("AppData/Local/Temp/parallel/stdout_{}", id));
        stderr.push(format!("AppData/Local/Temp/parallel/stderr_{}", id));
        (stdout, stderr)
    }).expect("parallel: unable to open home folder")
}
<commit_msg>Windows Build Fix<commit_after>use std::env::home_dir;
use std::path::PathBuf;

#[cfg(not(windows))]
pub fn base() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel");
        path
    })
}

#[cfg(windows)]
pub fn base() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel");
        path
    })
}

#[cfg(not(windows))]
pub fn processed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel/processed");
        path
    })
}

#[cfg(windows)]
pub fn processed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel/processed");
        path
    })
}

#[cfg(not(windows))]
pub fn unprocessed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel/unprocessed");
        path
    })
}

#[cfg(windows)]
pub fn unprocessed() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel/unprocessed");
        path
    })
}

#[cfg(not(windows))]
pub fn errors() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push(".local/share/parallel/errors");
        path
    })
}

#[cfg(windows)]
pub fn errors() -> Option<PathBuf> {
    home_dir().map(|mut path| {
        path.push("AppData/Local/Temp/parallel/errors");
        path
    })
}

pub fn outputs_path() -> PathBuf {
    PathBuf::from("/tmp/parallel/")
}

#[cfg(not(windows))]
pub fn job(id: usize) -> (PathBuf, PathBuf) {
    let stdout = PathBuf::from(format!("/tmp/parallel/stdout_{}", id));
    let stderr = PathBuf::from(format!("/tmp/parallel/stderr_{}", id));
    (stdout, stderr)
}

#[cfg(windows)]
pub fn job(id: usize) -> (PathBuf, PathBuf) {
    home_dir().map(|mut stdout| {
        let mut stderr = stdout.clone();
        stdout.push(format!("AppData/Local/Temp/parallel/stdout_{}", id));
        stderr.push(format!("AppData/Local/Temp/parallel/stderr_{}", id));
        (stdout, stderr)
    }).expect("parallel: unable to open home folder")
}
<|endoftext|>


<commit_before><commit_msg>nbt: Use consistent naming for `io::Write` variables.<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::callback::eReportExceptions;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, NodeDerived};
use dom::bindings::js::JS;
use dom::eventtarget::{Capturing, Bubbling, EventTarget};
use dom::event::{Event, Phase_At_Target, Phase_None, Phase_Bubbling, Phase_Capturing};
use dom::node::{Node, NodeHelpers};

// See http://dom.spec.whatwg.org/#concept-event-dispatch for the full dispatch algorithm
pub fn dispatch_event(target: &JS<EventTarget>,
                      pseudo_target: Option<JS<EventTarget>>,
                      event: &mut JS<Event>) -> bool {
    assert!(!event.get().dispatching);

    {
        let event = event.get_mut();
        event.target = match pseudo_target {
            Some(pseudo_target) => Some(pseudo_target),
            None => Some(target.clone())
        };
        event.dispatching = true;
    }

    let type_ = event.get().type_.clone();
    let mut chain = ~[];

    //TODO: no chain if not participating in a tree
    if target.get().is_node() {
        let target_node: JS<Node> = NodeCast::to(target);
        for ancestor in target_node.ancestors() {
            let ancestor_target: JS<EventTarget> = EventTargetCast::from(&ancestor);
            chain.push(ancestor_target);
        }
    }

    event.get_mut().phase = Phase_Capturing;

    //FIXME: The "callback this value" should be currentTarget

    /* capturing */
    for cur_target in chain.rev_iter() {
        let stopped = match cur_target.get().get_listeners_for(type_, Capturing) {
            Some(listeners) => {
                event.get_mut().current_target = Some(cur_target.clone());
                for listener in listeners.iter() {
                    listener.HandleEvent__(event, eReportExceptions);

                    if event.get().stop_immediate {
                        break;
                    }
                }

                event.get().stop_propagation
            }
            None => false
        };

        if stopped {
            break;
        }
    }

    /* at target */
    if !event.get().stop_propagation {
        {
            let event = event.get_mut();
            event.phase = Phase_At_Target;
            event.current_target = Some(target.clone());
        }

        let opt_listeners = target.get().get_listeners(type_);
        for listeners in opt_listeners.iter() {
            for listener in listeners.iter() {
                listener.HandleEvent__(event, eReportExceptions);
                if event.get().stop_immediate {
                    break;
                }
            }
        }
    }

    /* bubbling */
    if event.get().bubbles && !event.get().stop_propagation {
        event.get_mut().phase = Phase_Bubbling;

        for cur_target in chain.iter() {
            let stopped = match cur_target.get().get_listeners_for(type_, Bubbling) {
                Some(listeners) => {
                    event.get_mut().current_target = Some(cur_target.clone());
                    for listener in listeners.iter() {
                        listener.HandleEvent__(event, eReportExceptions);

                        if event.get().stop_immediate {
                            break;
                        }
                    }

                    event.get().stop_propagation
                }
                None => false
            };
            if stopped {
                break;
            }
        }
    }

    let event = event.get_mut();
    event.dispatching = false;
    event.phase = Phase_None;
    event.current_target = None;

    !event.DefaultPrevented()
}
<commit_msg>Use Option::or_else in eventdispatcher::dispatch_event.<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::callback::eReportExceptions;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, NodeDerived};
use dom::bindings::js::JS;
use dom::eventtarget::{Capturing, Bubbling, EventTarget};
use dom::event::{Event, Phase_At_Target, Phase_None, Phase_Bubbling, Phase_Capturing};
use dom::node::{Node, NodeHelpers};

// See http://dom.spec.whatwg.org/#concept-event-dispatch for the full dispatch algorithm
pub fn dispatch_event(target: &JS<EventTarget>,
                      pseudo_target: Option<JS<EventTarget>>,
                      event: &mut JS<Event>) -> bool {
    assert!(!event.get().dispatching);

    {
        let event = event.get_mut();
        event.target = pseudo_target.or_else(|| {
            Some(target.clone())
        });
        event.dispatching = true;
    }

    let type_ = event.get().type_.clone();
    let mut chain = ~[];

    //TODO: no chain if not participating in a tree
    if target.get().is_node() {
        let target_node: JS<Node> = NodeCast::to(target);
        for ancestor in target_node.ancestors() {
            let ancestor_target: JS<EventTarget> = EventTargetCast::from(&ancestor);
            chain.push(ancestor_target);
        }
    }

    event.get_mut().phase = Phase_Capturing;

    //FIXME: The "callback this value" should be currentTarget

    /* capturing */
    for cur_target in chain.rev_iter() {
        let stopped = match cur_target.get().get_listeners_for(type_, Capturing) {
            Some(listeners) => {
                event.get_mut().current_target = Some(cur_target.clone());
                for listener in listeners.iter() {
                    listener.HandleEvent__(event, eReportExceptions);

                    if event.get().stop_immediate {
                        break;
                    }
                }

                event.get().stop_propagation
            }
            None => false
        };

        if stopped {
            break;
        }
    }

    /* at target */
    if !event.get().stop_propagation {
        {
            let event = event.get_mut();
            event.phase = Phase_At_Target;
            event.current_target = Some(target.clone());
        }

        let opt_listeners = target.get().get_listeners(type_);
        for listeners in opt_listeners.iter() {
            for listener in listeners.iter() {
                listener.HandleEvent__(event, eReportExceptions);
                if event.get().stop_immediate {
                    break;
                }
            }
        }
    }

    /* bubbling */
    if event.get().bubbles && !event.get().stop_propagation {
        event.get_mut().phase = Phase_Bubbling;

        for cur_target in chain.iter() {
            let stopped = match cur_target.get().get_listeners_for(type_, Bubbling) {
                Some(listeners) => {
                    event.get_mut().current_target = Some(cur_target.clone());
                    for listener in listeners.iter() {
                        listener.HandleEvent__(event, eReportExceptions);

                        if event.get().stop_immediate {
                            break;
                        }
                    }

                    event.get().stop_propagation
                }
                None => false
            };
            if stopped {
                break;
            }
        }
    }

    let event = event.get_mut();
    event.dispatching = false;
    event.phase = Phase_None;
    event.current_target = None;

    !event.DefaultPrevented()
}
<|endoftext|>


<commit_before><commit_msg>#24468 call submit_resource_timing after creating the document parser<commit_after><|endoftext|>


<commit_before><commit_msg>Fix benchmark import<commit_after><|endoftext|>


<commit_before><commit_msg>bench: Add tests for setting functions<commit_after>#![feature(test)]

extern crate test;
extern crate rle_vec;

use std::iter::FromIterator;
use std::iter::repeat;
use test::Bencher;
use rle_vec::RleVec;

#[bench]
fn rle_set_middle_10_000_unique_values(b: &mut Bencher) {
    b.iter(|| {
        let mut rle = RleVec::from_iter(0..10_000);
        rle.set(5_000, 424242);
    })
}

#[bench]
fn vec_set_middle_10_000_unique_values(b: &mut Bencher) {
    b.iter(|| {
        let mut vec = Vec::from_iter(0..10_000);
        vec[5_000] = 424242;
    })
}

#[bench]
fn rle_set_middle_10_000_equal_values(b: &mut Bencher) {
    b.iter(|| {
        let mut rle = RleVec::from_iter(repeat(0).take(10_000));
        rle.set(5_000, 424242);
    })
}

#[bench]
fn vec_set_middle_10_000_equal_values(b: &mut Bencher) {
    b.iter(|| {
        let mut vec = Vec::from_iter(repeat(0).take(10_000));
        vec[5_000] = 424242;
    })
}

#[bench]
fn rle_set_middle_10_000_runs_of_10_values(b: &mut Bencher) {
    b.iter(|| {
        let zeros = repeat(0).take(10);
        let ones = repeat(1).take(10);
        let iter = repeat(zeros.chain(ones)).flat_map(|x| x).take(10_000);

        let mut rle = RleVec::from_iter(iter);
        rle.set(5_000, 424242);
    })
}

#[bench]
fn vec_set_middle_10_000_runs_of_10_values(b: &mut Bencher) {
    b.iter(|| {
        let zeros = repeat(0).take(10);
        let ones = repeat(1).take(10);
        let iter = repeat(zeros.chain(ones)).flat_map(|x| x).take(10_000);

        let mut vec = Vec::from_iter(iter);
        vec[5_000] = 424242;
    })
}

#[bench]
fn rle_set_middle_same_value_10_000_equal_values(b: &mut Bencher) {
    b.iter(|| {
        let mut rle = RleVec::from_iter(repeat(0).take(10_000));
        rle.set(5_000, 0);
    })
}

#[bench]
fn vec_set_middle_same_value_10_000_equal_values(b: &mut Bencher) {
    b.iter(|| {
        let mut vec = Vec::from_iter(repeat(0).take(10_000));
        vec[5_000] = 0;
    })
}
<|endoftext|>


<commit_before><commit_msg>Add a cross-crate test for casting classes to ifaces<commit_after>import to_str::*;
import to_str::to_str;

class cat implements to_str {
  priv {
    let mut meows : uint;
    fn meow() {
      #error("Meow");
      self.meows += 1u;
      if self.meows % 5u == 0u {
          self.how_hungry += 1;
      }
    }
  }

  let mut how_hungry : int;
  let name : str;

  new(in_x : uint, in_y : int, in_name: str)
    { self.meows = in_x; self.how_hungry = in_y; self.name = in_name; }

  fn speak() { self.meow(); }

  fn eat() -> bool {
    if self.how_hungry > 0 {
        #error("OM NOM NOM");
        self.how_hungry -= 2;
        ret true;
    }
    else {
        #error("Not hungry!");
        ret false;
    }
  }

  fn to_str() -> str { self.name }
}

fn print_out<T: to_str>(thing: T, expected: str) {
  let actual = thing.to_str();
  #debug("%s", actual);
  assert(actual == expected);
}

fn main() {
  let nyan : to_str  = cat(0u, 2, "nyan") as to_str;
  print_out(nyan, "nyan");
}<|endoftext|>


<commit_before>// Copyright 2017 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 std::ffi::CString;
use std::ptr;

use libc::c_uint;
use rustc::middle::allocator::AllocatorKind;
use rustc::ty::TyCtxt;
use rustc_allocator::{ALLOCATOR_METHODS, AllocatorTy};

use ModuleLlvm;
use llvm::{self, False, True};

pub(crate) unsafe fn trans(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
    let llcx = mods.llcx;
    let llmod = mods.llmod;
    let usize = match &tcx.sess.target.target.target_pointer_width[..] {
        "16" => llvm::LLVMInt16TypeInContext(llcx),
        "32" => llvm::LLVMInt32TypeInContext(llcx),
        "64" => llvm::LLVMInt64TypeInContext(llcx),
        tws => bug!("Unsupported target word size for int: {}", tws),
    };
    let i8 = llvm::LLVMInt8TypeInContext(llcx);
    let i8p = llvm::LLVMPointerType(i8, 0);
    let void = llvm::LLVMVoidTypeInContext(llcx);

    for method in ALLOCATOR_METHODS {
        let mut args = Vec::new();
        for ty in method.inputs.iter() {
            match *ty {
                AllocatorTy::Layout => {
                    args.push(usize); // size
                    args.push(usize); // align
                }
                AllocatorTy::Ptr => args.push(i8p),
                AllocatorTy::Usize => args.push(usize),

                AllocatorTy::ResultPtr |
                AllocatorTy::Unit => panic!("invalid allocator arg"),
            }
        }
        let output = match method.output {
            AllocatorTy::ResultPtr => Some(i8p),
            AllocatorTy::Unit => None,

            AllocatorTy::Layout |
            AllocatorTy::Usize |
            AllocatorTy::Ptr => panic!("invalid allocator output"),
        };
        let ty = llvm::LLVMFunctionType(output.unwrap_or(void),
                                        args.as_ptr(),
                                        args.len() as c_uint,
                                        False);
        let name = CString::new(format!("__rust_{}", method.name)).unwrap();
        let llfn = llvm::LLVMRustGetOrInsertFunction(llmod,
                                                     name.as_ptr(),
                                                     ty);

        if tcx.sess.target.target.options.default_hidden_visibility {
            llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
        }

        let callee = CString::new(kind.fn_name(method.name)).unwrap();
        let callee = llvm::LLVMRustGetOrInsertFunction(llmod,
                                                       callee.as_ptr(),
                                                       ty);

        let llbb = llvm::LLVMAppendBasicBlockInContext(llcx,
                                                       llfn,
                                                       "entry\0".as_ptr() as *const _);

        let llbuilder = llvm::LLVMCreateBuilderInContext(llcx);
        llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb);
        let args = args.iter().enumerate().map(|(i, _)| {
            llvm::LLVMGetParam(llfn, i as c_uint)
        }).collect::<Vec<_>>();
        let ret = llvm::LLVMRustBuildCall(llbuilder,
                                          callee,
                                          args.as_ptr(),
                                          args.len() as c_uint,
                                          ptr::null_mut(),
                                          "\0".as_ptr() as *const _);
        llvm::LLVMSetTailCall(ret, True);
        if output.is_some() {
            llvm::LLVMBuildRet(llbuilder, ret);
        } else {
            llvm::LLVMBuildRetVoid(llbuilder);
        }
        llvm::LLVMDisposeBuilder(llbuilder);
    }
}
<commit_msg>rustc: Emit `uwtable` for allocator shims<commit_after>// Copyright 2017 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 std::ffi::CString;
use std::ptr;

use attributes;
use libc::c_uint;
use rustc::middle::allocator::AllocatorKind;
use rustc::ty::TyCtxt;
use rustc_allocator::{ALLOCATOR_METHODS, AllocatorTy};

use ModuleLlvm;
use llvm::{self, False, True};

pub(crate) unsafe fn trans(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
    let llcx = mods.llcx;
    let llmod = mods.llmod;
    let usize = match &tcx.sess.target.target.target_pointer_width[..] {
        "16" => llvm::LLVMInt16TypeInContext(llcx),
        "32" => llvm::LLVMInt32TypeInContext(llcx),
        "64" => llvm::LLVMInt64TypeInContext(llcx),
        tws => bug!("Unsupported target word size for int: {}", tws),
    };
    let i8 = llvm::LLVMInt8TypeInContext(llcx);
    let i8p = llvm::LLVMPointerType(i8, 0);
    let void = llvm::LLVMVoidTypeInContext(llcx);

    for method in ALLOCATOR_METHODS {
        let mut args = Vec::new();
        for ty in method.inputs.iter() {
            match *ty {
                AllocatorTy::Layout => {
                    args.push(usize); // size
                    args.push(usize); // align
                }
                AllocatorTy::Ptr => args.push(i8p),
                AllocatorTy::Usize => args.push(usize),

                AllocatorTy::ResultPtr |
                AllocatorTy::Unit => panic!("invalid allocator arg"),
            }
        }
        let output = match method.output {
            AllocatorTy::ResultPtr => Some(i8p),
            AllocatorTy::Unit => None,

            AllocatorTy::Layout |
            AllocatorTy::Usize |
            AllocatorTy::Ptr => panic!("invalid allocator output"),
        };
        let ty = llvm::LLVMFunctionType(output.unwrap_or(void),
                                        args.as_ptr(),
                                        args.len() as c_uint,
                                        False);
        let name = CString::new(format!("__rust_{}", method.name)).unwrap();
        let llfn = llvm::LLVMRustGetOrInsertFunction(llmod,
                                                     name.as_ptr(),
                                                     ty);

        if tcx.sess.target.target.options.default_hidden_visibility {
            llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
        }
       if tcx.sess.target.target.options.requires_uwtable {
           attributes::emit_uwtable(llfn, true);
       }

        let callee = CString::new(kind.fn_name(method.name)).unwrap();
        let callee = llvm::LLVMRustGetOrInsertFunction(llmod,
                                                       callee.as_ptr(),
                                                       ty);

        let llbb = llvm::LLVMAppendBasicBlockInContext(llcx,
                                                       llfn,
                                                       "entry\0".as_ptr() as *const _);

        let llbuilder = llvm::LLVMCreateBuilderInContext(llcx);
        llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb);
        let args = args.iter().enumerate().map(|(i, _)| {
            llvm::LLVMGetParam(llfn, i as c_uint)
        }).collect::<Vec<_>>();
        let ret = llvm::LLVMRustBuildCall(llbuilder,
                                          callee,
                                          args.as_ptr(),
                                          args.len() as c_uint,
                                          ptr::null_mut(),
                                          "\0".as_ptr() as *const _);
        llvm::LLVMSetTailCall(ret, True);
        if output.is_some() {
            llvm::LLVMBuildRet(llbuilder, ret);
        } else {
            llvm::LLVMBuildRetVoid(llbuilder);
        }
        llvm::LLVMDisposeBuilder(llbuilder);
    }
}
<|endoftext|>


<commit_before>// Copyright 2017 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 syntax_pos::symbol::Symbol;
use back::write::create_target_machine;
use llvm;
use rustc::session::Session;
use rustc::session::config::PrintRequest;
use libc::c_int;
use std::ffi::{CStr, CString};

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;

static POISONED: AtomicBool = AtomicBool::new(false);
static INIT: Once = Once::new();

pub(crate) fn init(sess: &Session) {
    unsafe {
        // Before we touch LLVM, make sure that multithreading is enabled.
        INIT.call_once(|| {
            if llvm::LLVMStartMultithreaded() != 1 {
                // use an extra bool to make sure that all future usage of LLVM
                // cannot proceed despite the Once not running more than once.
                POISONED.store(true, Ordering::SeqCst);
            }

            configure_llvm(sess);
        });

        if POISONED.load(Ordering::SeqCst) {
            bug!("couldn't enable multi-threaded LLVM");
        }
    }
}

fn require_inited() {
    INIT.call_once(|| bug!("llvm is not initialized"));
    if POISONED.load(Ordering::SeqCst) {
        bug!("couldn't enable multi-threaded LLVM");
    }
}

unsafe fn configure_llvm(sess: &Session) {
    let mut llvm_c_strs = Vec::new();
    let mut llvm_args = Vec::new();

    {
        let mut add = |arg: &str| {
            let s = CString::new(arg).unwrap();
            llvm_args.push(s.as_ptr());
            llvm_c_strs.push(s);
        };
        add("rustc"); // fake program name
        if sess.time_llvm_passes() { add("-time-passes"); }
        if sess.print_llvm_passes() { add("-debug-pass=Structure"); }

        for arg in &sess.opts.cg.llvm_args {
            add(&(*arg));
        }
    }

    llvm::LLVMInitializePasses();

    llvm::initialize_available_targets();

    llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
                                 llvm_args.as_ptr());
}

// WARNING: the features must be known to LLVM or the feature
// detection code will walk past the end of the feature array,
// leading to crashes.

const ARM_WHITELIST: &'static [&'static str] = &["neon", "v7", "vfp2", "vfp3", "vfp4"];

const AARCH64_WHITELIST: &'static [&'static str] = &["neon", "v7"];

const X86_WHITELIST: &'static [&'static str] = &["avx", "avx2", "bmi", "bmi2", "sse",
                                                 "sse2", "sse3", "sse4.1", "sse4.2",
                                                 "ssse3", "tbm", "lzcnt", "popcnt",
                                                 "sse4a", "rdrnd", "rdseed", "fma",
                                                 "xsave", "xsaveopt", "xsavec",
                                                 "xsaves", "aes", "pclmulqdq",
                                                 "avx512bw", "avx512cd",
                                                 "avx512dq", "avx512er",
                                                 "avx512f", "avx512ifma",
                                                 "avx512pf", "avx512vbmi",
                                                 "avx512vl", "avx512vpopcntdq",
                                                 "mmx", "fxsr"];

const HEXAGON_WHITELIST: &'static [&'static str] = &["hvx", "hvx-double"];

const POWERPC_WHITELIST: &'static [&'static str] = &["altivec",
                                                     "power8-altivec", "power9-altivec",
                                                     "power8-vector", "power9-vector",
                                                     "vsx"];

const MIPS_WHITELIST: &'static [&'static str] = &["msa"];

pub fn to_llvm_feature(s: &str) -> &str {
    match s {
        "pclmulqdq" => "pclmul",
        s => s,
    }
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
    let target_machine = create_target_machine(sess);
    target_feature_whitelist(sess)
        .iter()
        .filter(|feature| {
            let llvm_feature = to_llvm_feature(feature);
            let ptr = CString::new(llvm_feature).as_ptr();
            unsafe { llvm::LLVMRustHasFeature(target_machine, ptr) }
        })
        .map(Symbol::intern).collect()
}

pub fn target_feature_whitelist(sess: &Session) -> &'static [&'static str] {
    let whitelist = match &*sess.target.target.arch {
        "arm" => ARM_WHITELIST,
        "aarch64" => AARCH64_WHITELIST,
        "x86" | "x86_64" => X86_WHITELIST,
        "hexagon" => HEXAGON_WHITELIST,
        "mips" | "mips64" => MIPS_WHITELIST,
        "powerpc" | "powerpc64" => POWERPC_WHITELIST,
        _ => &[],
    }
}

pub fn print_version() {
    // Can be called without initializing LLVM
    unsafe {
        println!("LLVM version: {}.{}",
                 llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
    }
}

pub fn print_passes() {
    // Can be called without initializing LLVM
    unsafe { llvm::LLVMRustPrintPasses(); }
}

pub(crate) fn print(req: PrintRequest, sess: &Session) {
    require_inited();
    let tm = create_target_machine(sess);
    unsafe {
        match req {
            PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
            PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
            _ => bug!("rustc_trans can't handle print request: {:?}", req),
        }
    }
}
<commit_msg>fixed errors<commit_after>// Copyright 2017 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 syntax_pos::symbol::Symbol;
use back::write::create_target_machine;
use llvm;
use rustc::session::Session;
use rustc::session::config::PrintRequest;
use libc::c_int;
use std::ffi::CString;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;

static POISONED: AtomicBool = AtomicBool::new(false);
static INIT: Once = Once::new();

pub(crate) fn init(sess: &Session) {
    unsafe {
        // Before we touch LLVM, make sure that multithreading is enabled.
        INIT.call_once(|| {
            if llvm::LLVMStartMultithreaded() != 1 {
                // use an extra bool to make sure that all future usage of LLVM
                // cannot proceed despite the Once not running more than once.
                POISONED.store(true, Ordering::SeqCst);
            }

            configure_llvm(sess);
        });

        if POISONED.load(Ordering::SeqCst) {
            bug!("couldn't enable multi-threaded LLVM");
        }
    }
}

fn require_inited() {
    INIT.call_once(|| bug!("llvm is not initialized"));
    if POISONED.load(Ordering::SeqCst) {
        bug!("couldn't enable multi-threaded LLVM");
    }
}

unsafe fn configure_llvm(sess: &Session) {
    let mut llvm_c_strs = Vec::new();
    let mut llvm_args = Vec::new();

    {
        let mut add = |arg: &str| {
            let s = CString::new(arg).unwrap();
            llvm_args.push(s.as_ptr());
            llvm_c_strs.push(s);
        };
        add("rustc"); // fake program name
        if sess.time_llvm_passes() { add("-time-passes"); }
        if sess.print_llvm_passes() { add("-debug-pass=Structure"); }

        for arg in &sess.opts.cg.llvm_args {
            add(&(*arg));
        }
    }

    llvm::LLVMInitializePasses();

    llvm::initialize_available_targets();

    llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
                                 llvm_args.as_ptr());
}

// WARNING: the features must be known to LLVM or the feature
// detection code will walk past the end of the feature array,
// leading to crashes.

const ARM_WHITELIST: &'static [&'static str] = &["neon", "v7", "vfp2", "vfp3", "vfp4"];

const AARCH64_WHITELIST: &'static [&'static str] = &["neon", "v7"];

const X86_WHITELIST: &'static [&'static str] = &["avx", "avx2", "bmi", "bmi2", "sse",
                                                 "sse2", "sse3", "sse4.1", "sse4.2",
                                                 "ssse3", "tbm", "lzcnt", "popcnt",
                                                 "sse4a", "rdrnd", "rdseed", "fma",
                                                 "xsave", "xsaveopt", "xsavec",
                                                 "xsaves", "aes", "pclmulqdq",
                                                 "avx512bw", "avx512cd",
                                                 "avx512dq", "avx512er",
                                                 "avx512f", "avx512ifma",
                                                 "avx512pf", "avx512vbmi",
                                                 "avx512vl", "avx512vpopcntdq",
                                                 "mmx", "fxsr"];

const HEXAGON_WHITELIST: &'static [&'static str] = &["hvx", "hvx-double"];

const POWERPC_WHITELIST: &'static [&'static str] = &["altivec",
                                                     "power8-altivec", "power9-altivec",
                                                     "power8-vector", "power9-vector",
                                                     "vsx"];

const MIPS_WHITELIST: &'static [&'static str] = &["msa"];

pub fn to_llvm_feature(s: &str) -> &str {
    match s {
        "pclmulqdq" => "pclmul",
        s => s,
    }
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
    let target_machine = create_target_machine(sess);
    target_feature_whitelist(sess)
        .iter()
        .filter(|feature| {
            let llvm_feature = to_llvm_feature(feature);
            let ptr = CString::new(llvm_feature).unwrap().as_ptr();
            unsafe { llvm::LLVMRustHasFeature(target_machine, ptr) }
        })
        .map(|feature| Symbol::intern(feature)).collect()
}

pub fn target_feature_whitelist(sess: &Session) -> &'static [&'static str] {
    match &*sess.target.target.arch {
        "arm" => ARM_WHITELIST,
        "aarch64" => AARCH64_WHITELIST,
        "x86" | "x86_64" => X86_WHITELIST,
        "hexagon" => HEXAGON_WHITELIST,
        "mips" | "mips64" => MIPS_WHITELIST,
        "powerpc" | "powerpc64" => POWERPC_WHITELIST,
        _ => &[],
    }
}

pub fn print_version() {
    // Can be called without initializing LLVM
    unsafe {
        println!("LLVM version: {}.{}",
                 llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
    }
}

pub fn print_passes() {
    // Can be called without initializing LLVM
    unsafe { llvm::LLVMRustPrintPasses(); }
}

pub(crate) fn print(req: PrintRequest, sess: &Session) {
    require_inited();
    let tm = create_target_machine(sess);
    unsafe {
        match req {
            PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
            PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
            _ => bug!("rustc_trans can't handle print request: {:?}", req),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Regression test for #9951<commit_after>// Copyright 2015 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.

#![allow(unused_variables)]

trait Bar {
  fn noop(&self);
}
impl Bar for u8 {
  fn noop(&self) {}
}

fn main() {
    let (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
    let (c, d): (&Bar, &Bar) = (a, b);

    let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
    let (c, d): (&Bar, &Bar) = (&*a, &*b);

    let (c, d): (&Bar, &Bar) = (&5, &9);
}
<|endoftext|>


<commit_before>// This function takes ownership of a box and destroys it
fn eat_box(boxed_int: Box<i32>) {
    println!("Destroying box that contains {}", boxed_int);
}

// This function borrows an i32
fn borrow_box(borrowed_int: &i32) {
    println!("This int is: {}", borrowed_int);
}

fn main() {
    // Create a boxed integer
    let boxed_int = Box::new(5);

    // Borrow the contents of the box. Ownership is not taken,
    // so the contents can be borrowed again.
    borrow_box(&boxed_int);
    borrow_box(&boxed_int);

    {
        // Take a reference to the data contained inside the box
        let _ref_to_int: &i32 = &boxed_int;

        // Error!
        // Can't destroy `boxed_int` while the inner value is borrowed.
        eat_box(boxed_int);
        // FIXME ^ Comment out this line

        // `_ref_to_int` goes out of scope and is no longer borrowed.
    }

    // Box can now give up ownership to `eat_box` and be destroyed
    eat_box(boxed_int);
}
<commit_msg>More emphasis on the type system<commit_after>// This function takes ownership of a box and destroys it
fn eat_box_i32(boxed_i32: Box<i32>) {
    println!("Destroying box that contains {}", boxed_i32);
}

// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
    println!("This int is: {}", borrowed_i32);
}

fn main() {
    // Create a boxed i32, and a stacked i32
    let boxed_i32 = Box::new(5_i32);
    let stacked_i32 = 6_i32;

    // Borrow the contents of the box. Ownership is not taken,
    // so the contents can be borrowed again.
    borrow_i32(&boxed_i32);
    borrow_i32(&stacked_i32);

    {
        // Take a reference to the data contained inside the box
        let _ref_to_i32: &i32 = &boxed_i32;

        // Error!
        // Can't destroy `boxed_i32` while the inner value is borrowed.
        eat_box_i32(boxed_i32);
        // FIXME ^ Comment out this line

        // `_ref_to_i32` goes out of scope and is no longer borrowed.
    }

    // `boxed_i32` can now give up ownership to `eat_box` and be destroyed
    eat_box_i32(boxed_i32);
}
<|endoftext|>


<commit_before><commit_msg>Euler p5<commit_after><|endoftext|>


<commit_before><commit_msg>added networked example<commit_after>#![feature(hash)]
#![feature(core)]
#![feature(alloc)]
#![feature(std_misc)]
#![feature(unsafe_destructor)]

extern crate timely;
extern crate core;

extern crate docopt;
use docopt::Docopt;

use timely::communication::Communicator;
use timely::communication::channels::Data;
use timely::progress::{Timestamp, PathSummary};
use timely::progress::subgraph::{Subgraph, Summary, new_graph};
use timely::progress::broadcast::Progcaster;
use timely::progress::subgraph::Summary::Local;
use timely::progress::scope::Scope;
use timely::progress::graph::{Graph, GraphExtension};
use timely::example::input::InputExtensionTrait;
use timely::example::concat::ConcatExtensionTrait;
use timely::example::feedback::FeedbackExtensionTrait;
use timely::example::distinct::DistinctExtensionTrait;
use timely::example::stream::Stream;
use timely::example::graph_builder::GraphBoundary;
use timely::networking::initialize_networking;

use core::fmt::Debug;
use std::thread::Thread;

use std::rc::{Rc, try_unwrap};
use std::cell::RefCell;
use std::hash::{Hash, SipHasher};

static USAGE: &'static str = "
Usage: networked [options] [<arguments>...]

Options:
    -t <arg>, --threads <arg>    number of threads per worker [default: 1]
    -p <arg>, --processid <arg>  identity of this process     [default: 0]
    -n <arg>, --processes <arg>  number of processes involved [default: 1]
";

fn main() {
    let args = Docopt::new(USAGE).and_then(|dopt| dopt.parse()).unwrap_or_else(|e| e.exit());

    let threads: u64 = if let Ok(threads) = args.get_str("-t").parse() { threads }
                       else { panic!("invalid setting for --threads: {}", args.get_str("-t")) };
    let process_id: u64 = if let Ok(proc_id) = args.get_str("-p").parse() { proc_id }
                          else { panic!("invalid setting for --processid: {}", args.get_str("-p")) };
    let processes: u64 = if let Ok(processes) = args.get_str("-n").parse() { processes }
                         else { panic!("invalid setting for --processes: {}", args.get_str("-n")) };

    let addresses = range(0, processes).map(|index| format!("localhost:{}", 2101 + index).to_string()).collect();
    let network_communicator = initialize_networking(addresses, process_id, threads).ok().expect("error initializing networking");

    let mut guards = Vec::new();
    for communicator in network_communicator.into_iter() {
        guards.push(Thread::scoped(move || _queue(communicator)));
    }
}

fn _queue(allocator: Communicator) {
    let allocator = Rc::new(RefCell::new(allocator));
    // no "base scopes" yet, so the root pretends to be a subscope of some parent with a () timestamp type.
    let mut graph = new_graph(Progcaster::new(&mut (*allocator.borrow_mut())));

    // try building some input scopes
    let (mut input1, mut stream1) = graph.new_input::<u64>(allocator.clone());
    let (mut input2, mut stream2) = graph.new_input::<u64>(allocator.clone());

    // prepare some feedback edges
    let (mut feedback1, mut feedback1_output) = stream1.feedback(((), 1000), Local(1));
    let (mut feedback2, mut feedback2_output) = stream2.feedback(((), 1000), Local(1));

    // build up a subgraph using the concatenated inputs/feedbacks
    let progcaster = Progcaster::new(&mut (*allocator.borrow_mut()));
    let (mut egress1, mut egress2) = _create_subgraph(&mut graph.clone(),
                                                      &mut stream1.concat(&mut feedback1_output),
                                                      &mut stream2.concat(&mut feedback2_output),
                                                      progcaster);

    // connect feedback sources. notice that we have swapped indices ...
    feedback1.connect_input(&mut egress2);
    feedback2.connect_input(&mut egress1);

    // finalize the graph/subgraph
    graph.borrow_mut().get_internal_summary();
    graph.borrow_mut().set_external_summary(Vec::new(), &mut Vec::new());

    // do one round of push progress, pull progress ...
    graph.borrow_mut().push_external_progress(&mut Vec::new());
    graph.borrow_mut().pull_internal_progress(&mut Vec::new(), &mut Vec::new(), &mut Vec::new());

    // move some data into the dataflow graph.
    input1.send_messages(&((), 0), vec![1u64]);
    input2.send_messages(&((), 0), vec![2u64]);

    // see what everyone thinks about that ...
    graph.borrow_mut().pull_internal_progress(&mut Vec::new(), &mut Vec::new(), &mut Vec::new());

    input1.advance(&((), 0), &((), 1000000));
    input2.advance(&((), 0), &((), 1000000));
    input1.close_at(&((), 1000000));
    input2.close_at(&((), 1000000));

    // spin
    while graph.borrow_mut().pull_internal_progress(&mut Vec::new(), &mut Vec::new(), &mut Vec::new()) { }
}

fn _create_subgraph<T1, T2, S1, S2, D>(graph: &mut Rc<RefCell<Subgraph<T1, S1, T2, S2>>>,
                                       source1: &mut Stream<(T1, T2), Summary<S1, S2>, D>,
                                       source2: &mut Stream<(T1, T2), Summary<S1, S2>, D>,
                                       progcaster: Progcaster<((T1,T2),u64)>)
                 -> (Stream<(T1, T2), Summary<S1, S2>, D>, Stream<(T1, T2), Summary<S1, S2>, D>)
where T1: Timestamp, S1: PathSummary<T1>,
      T2: Timestamp, S2: PathSummary<T2>,
      D:  Data+Hash<SipHasher>+Eq+Debug,
{
    // build up a subgraph using the concatenated inputs/feedbacks
    let mut subgraph = graph.new_subgraph::<_, u64>(0, progcaster);

    let (sub_egress1, sub_egress2) = {
        // create new ingress nodes, passing in a reference to the subgraph for them to use.
        let mut sub_ingress1 = subgraph.add_input(source1);
        let mut sub_ingress2 = subgraph.add_input(source2);

        // putting a distinct scope into the subgraph!
        let mut queue = sub_ingress1.distinct();

        // egress each of the streams from the subgraph.
        let sub_egress1 = subgraph.add_output_to_graph(&mut queue, graph.as_box());
        let sub_egress2 = subgraph.add_output_to_graph(&mut sub_ingress2, graph.as_box());

        (sub_egress1, sub_egress2)
    };

    // sort of a mess, but the way to get the subgraph out of the Rc<RefCell<...>>.
    // will explode if anyone else is still sitting on a reference to subgraph.
    graph.add_scope(try_unwrap(subgraph).ok().expect("hm").into_inner());

    return (sub_egress1, sub_egress2);
}
<|endoftext|>


<commit_before><commit_msg>Add rust code for sieve case<commit_after>pub fn primes_up_to(limit: u32) -> Vec<u32> {
    if limit < 2 {
        return Vec::new();
    }

    let upper = (limit as f64).sqrt().ceil() as usize;

    let mut board = vec![true; limit as usize - 1];

    for i in 2..upper {
        if !board[i - 2] {
            continue;
        }

        let mut v = i * i;

        while v <= limit as usize {
            board[v - 2] = false;

            v += i;
        }
    }

    (2..limit + 1)
        .filter(|&x| board[x as usize - 2])
        .collect::<Vec<u32>>()
}
<|endoftext|>


<commit_before><commit_msg>Implement send_server_packet and add test.<commit_after><|endoftext|>


<commit_before><commit_msg>Impossible usage of `rust-scrypt` on Windows OS due to mmap call Added conditional dependency<commit_after><|endoftext|>


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

// Type Names for Debug Info.

use common::CrateContext;
use rustc::hir::def_id::DefId;
use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty};

use rustc::hir;

// Compute the name of the type as it should be stored in debuginfo. Does not do
// any caching, i.e. calling the function twice with the same type will also do
// the work twice. The `qualified` parameter only affects the first level of the
// type name, further levels (i.e. type parameters) are always fully qualified.
pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                             t: Ty<'tcx>,
                                             qualified: bool)
                                             -> String {
    let mut result = String::with_capacity(64);
    push_debuginfo_type_name(cx, t, qualified, &mut result);
    result
}

// Pushes the name of the type as it should be stored in debuginfo on the
// `output` String. See also compute_debuginfo_type_name().
pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                          t: Ty<'tcx>,
                                          qualified: bool,
                                          output: &mut String) {
    match t.sty {
        ty::TyBool => output.push_str("bool"),
        ty::TyChar => output.push_str("char"),
        ty::TyStr => output.push_str("str"),
        ty::TyNever => output.push_str("!"),
        ty::TyInt(int_ty) => output.push_str(int_ty.ty_to_string()),
        ty::TyUint(uint_ty) => output.push_str(uint_ty.ty_to_string()),
        ty::TyFloat(float_ty) => output.push_str(float_ty.ty_to_string()),
        ty::TyAdt(def, substs) => {
            push_item_name(cx, def.did, qualified, output);
            push_type_params(cx, substs, output);
        },
        ty::TyTuple(component_types, _) => {
            output.push('(');
            for &component_type in component_types {
                push_debuginfo_type_name(cx, component_type, true, output);
                output.push_str(", ");
            }
            if !component_types.is_empty() {
                output.pop();
                output.pop();
            }
            output.push(')');
        },
        ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
            let is_like_msvc = cx.sess().target.target.options.is_like_msvc;

            if !is_like_msvc {output.push('*');}
            match mutbl {
                hir::MutImmutable => output.push_str("const "),
                hir::MutMutable => output.push_str("mut "),
            }

            push_debuginfo_type_name(cx, inner_type, true, output);
            if is_like_msvc {output.push('*');}
        },
        ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
            let is_like_msvc = cx.sess().target.target.options.is_like_msvc;

            if !is_like_msvc {output.push('&');}
            if mutbl == hir::MutMutable {
                output.push_str("mut ");
            }

            push_debuginfo_type_name(cx, inner_type, true, output);
            if is_like_msvc {output.push('*');}
        },
        ty::TyArray(inner_type, len) => {
            output.push('[');
            push_debuginfo_type_name(cx, inner_type, true, output);
            output.push_str(&format!("; {}", len));
            output.push(']');
        },
        ty::TySlice(inner_type) => {
            let is_like_msvc = cx.sess().target.target.options.is_like_msvc;
            output.push_str(if is_like_msvc {"slice<"} else {"["});
            push_debuginfo_type_name(cx, inner_type, true, output);
            output.push(if is_like_msvc {'>'} else {']'});
        },
        ty::TyDynamic(ref trait_data, ..) => {
            if let Some(principal) = trait_data.principal() {
                let principal = cx.tcx().erase_late_bound_regions_and_normalize(
                    &principal);
                push_item_name(cx, principal.def_id, false, output);
                push_type_params(cx, principal.substs, output);
            }
        },
        ty::TyFnDef(..) | ty::TyFnPtr(_) => {
            let sig = t.fn_sig(cx.tcx());
            if sig.unsafety() == hir::Unsafety::Unsafe {
                output.push_str("unsafe ");
            }

            let abi = sig.abi();
            if abi != ::abi::Abi::Rust {
                output.push_str("extern \"");
                output.push_str(abi.name());
                output.push_str("\" ");
            }

            output.push_str("fn(");

            let sig = cx.tcx().erase_late_bound_regions_and_normalize(&sig);
            if !sig.inputs().is_empty() {
                for &parameter_type in sig.inputs() {
                    push_debuginfo_type_name(cx, parameter_type, true, output);
                    output.push_str(", ");
                }
                output.pop();
                output.pop();
            }

            if sig.variadic {
                if !sig.inputs().is_empty() {
                    output.push_str(", ...");
                } else {
                    output.push_str("...");
                }
            }

            output.push(')');

            if !sig.output().is_nil() {
                output.push_str(" -> ");
                push_debuginfo_type_name(cx, sig.output(), true, output);
            }
        },
        ty::TyClosure(..) => {
            output.push_str("closure");
        }
        ty::TyError |
        ty::TyInfer(_) |
        ty::TyProjection(..) |
        ty::TyAnon(..) |
        ty::TyParam(_) => {
            bug!("debuginfo: Trying to create type name for \
                unexpected type: {:?}", t);
        }
    }

    fn push_item_name(cx: &CrateContext,
                      def_id: DefId,
                      qualified: bool,
                      output: &mut String) {
        if qualified {
            output.push_str(&cx.tcx().crate_name(def_id.krate).as_str());
            for path_element in cx.tcx().def_path(def_id).data {
                output.push_str("::");
                output.push_str(&path_element.data.as_interned_str());
            }
        } else {
            output.push_str(&cx.tcx().item_name(def_id).as_str());
        }
    }

    // Pushes the type parameters in the given `Substs` to the output string.
    // This ignores region parameters, since they can't reliably be
    // reconstructed for items from non-local crates. For local crates, this
    // would be possible but with inlining and LTO we have to use the least
    // common denominator - otherwise we would run into conflicts.
    fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                  substs: &Substs<'tcx>,
                                  output: &mut String) {
        if substs.types().next().is_none() {
            return;
        }

        output.push('<');

        for type_parameter in substs.types() {
            push_debuginfo_type_name(cx, type_parameter, true, output);
            output.push_str(", ");
        }

        output.pop();
        output.pop();

        output.push('>');
    }
}
<commit_msg>Expand one-liners, rename is_like_msvc to cpp_like_names and explain.<commit_after>// Copyright 2015 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.

// Type Names for Debug Info.

use common::CrateContext;
use rustc::hir::def_id::DefId;
use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty};

use rustc::hir;

// Compute the name of the type as it should be stored in debuginfo. Does not do
// any caching, i.e. calling the function twice with the same type will also do
// the work twice. The `qualified` parameter only affects the first level of the
// type name, further levels (i.e. type parameters) are always fully qualified.
pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                             t: Ty<'tcx>,
                                             qualified: bool)
                                             -> String {
    let mut result = String::with_capacity(64);
    push_debuginfo_type_name(cx, t, qualified, &mut result);
    result
}

// Pushes the name of the type as it should be stored in debuginfo on the
// `output` String. See also compute_debuginfo_type_name().
pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                          t: Ty<'tcx>,
                                          qualified: bool,
                                          output: &mut String) {
    // When targeting MSVC, emit C++ style type names for compatability with
    // .natvis visualizers (and perhaps other existing native debuggers?)
    let cpp_like_names = cx.sess().target.target.options.is_like_msvc;

    match t.sty {
        ty::TyBool => output.push_str("bool"),
        ty::TyChar => output.push_str("char"),
        ty::TyStr => output.push_str("str"),
        ty::TyNever => output.push_str("!"),
        ty::TyInt(int_ty) => output.push_str(int_ty.ty_to_string()),
        ty::TyUint(uint_ty) => output.push_str(uint_ty.ty_to_string()),
        ty::TyFloat(float_ty) => output.push_str(float_ty.ty_to_string()),
        ty::TyAdt(def, substs) => {
            push_item_name(cx, def.did, qualified, output);
            push_type_params(cx, substs, output);
        },
        ty::TyTuple(component_types, _) => {
            output.push('(');
            for &component_type in component_types {
                push_debuginfo_type_name(cx, component_type, true, output);
                output.push_str(", ");
            }
            if !component_types.is_empty() {
                output.pop();
                output.pop();
            }
            output.push(')');
        },
        ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
            if !cpp_like_names {
                output.push('*');
            }
            match mutbl {
                hir::MutImmutable => output.push_str("const "),
                hir::MutMutable => output.push_str("mut "),
            }

            push_debuginfo_type_name(cx, inner_type, true, output);

            if cpp_like_names {
                output.push('*');
            }
        },
        ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
            if !cpp_like_names {
                output.push('&');
            }
            if mutbl == hir::MutMutable {
                output.push_str("mut ");
            }

            push_debuginfo_type_name(cx, inner_type, true, output);

            if cpp_like_names {
                output.push('*');
            }
        },
        ty::TyArray(inner_type, len) => {
            output.push('[');
            push_debuginfo_type_name(cx, inner_type, true, output);
            output.push_str(&format!("; {}", len));
            output.push(']');
        },
        ty::TySlice(inner_type) => {
            if cpp_like_names {
                output.push_str("slice<");
            } else {
                output.push('[');
            }

            push_debuginfo_type_name(cx, inner_type, true, output);

            if cpp_like_names {
                output.push('>');
            } else {
                output.push(']');
            }
        },
        ty::TyDynamic(ref trait_data, ..) => {
            if let Some(principal) = trait_data.principal() {
                let principal = cx.tcx().erase_late_bound_regions_and_normalize(
                    &principal);
                push_item_name(cx, principal.def_id, false, output);
                push_type_params(cx, principal.substs, output);
            }
        },
        ty::TyFnDef(..) | ty::TyFnPtr(_) => {
            let sig = t.fn_sig(cx.tcx());
            if sig.unsafety() == hir::Unsafety::Unsafe {
                output.push_str("unsafe ");
            }

            let abi = sig.abi();
            if abi != ::abi::Abi::Rust {
                output.push_str("extern \"");
                output.push_str(abi.name());
                output.push_str("\" ");
            }

            output.push_str("fn(");

            let sig = cx.tcx().erase_late_bound_regions_and_normalize(&sig);
            if !sig.inputs().is_empty() {
                for &parameter_type in sig.inputs() {
                    push_debuginfo_type_name(cx, parameter_type, true, output);
                    output.push_str(", ");
                }
                output.pop();
                output.pop();
            }

            if sig.variadic {
                if !sig.inputs().is_empty() {
                    output.push_str(", ...");
                } else {
                    output.push_str("...");
                }
            }

            output.push(')');

            if !sig.output().is_nil() {
                output.push_str(" -> ");
                push_debuginfo_type_name(cx, sig.output(), true, output);
            }
        },
        ty::TyClosure(..) => {
            output.push_str("closure");
        }
        ty::TyError |
        ty::TyInfer(_) |
        ty::TyProjection(..) |
        ty::TyAnon(..) |
        ty::TyParam(_) => {
            bug!("debuginfo: Trying to create type name for \
                unexpected type: {:?}", t);
        }
    }

    fn push_item_name(cx: &CrateContext,
                      def_id: DefId,
                      qualified: bool,
                      output: &mut String) {
        if qualified {
            output.push_str(&cx.tcx().crate_name(def_id.krate).as_str());
            for path_element in cx.tcx().def_path(def_id).data {
                output.push_str("::");
                output.push_str(&path_element.data.as_interned_str());
            }
        } else {
            output.push_str(&cx.tcx().item_name(def_id).as_str());
        }
    }

    // Pushes the type parameters in the given `Substs` to the output string.
    // This ignores region parameters, since they can't reliably be
    // reconstructed for items from non-local crates. For local crates, this
    // would be possible but with inlining and LTO we have to use the least
    // common denominator - otherwise we would run into conflicts.
    fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                  substs: &Substs<'tcx>,
                                  output: &mut String) {
        if substs.types().next().is_none() {
            return;
        }

        output.push('<');

        for type_parameter in substs.types() {
            push_debuginfo_type_name(cx, type_parameter, true, output);
            output.push_str(", ");
        }

        output.pop();
        output.pop();

        output.push('>');
    }
}
<|endoftext|>


<commit_before><commit_msg>Reorder spanmap module.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>clippy<commit_after><|endoftext|>


<commit_before>extern crate rand;
extern crate timely;
extern crate timely_sort;
extern crate differential_dataflow;
extern crate vec_map;

use timely::dataflow::*;
use timely::dataflow::operators::*;

use rand::{Rng, SeedableRng, StdRng};

use differential_dataflow::AsCollection;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::trace::{Cursor, Trace};

fn main() {

    let nodes: u32 = std::env::args().nth(1).unwrap().parse().unwrap();
    let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(3).unwrap().parse().unwrap();

    // define a new timely dataflow computation.
    timely::execute_from_args(std::env::args().skip(4), move |worker| {

    	let index = worker.index();
    	let peers = worker.peers();

    	// create a a degree counting differential dataflow
    	let (mut input, probe, trace) = worker.scoped(|scope| {

    		// create edge input, count a few ways.
    		let (input, edges) = scope.new_input();

    		// pull off source, and count.
    		let arranged = edges.as_collection()
    							.arrange_by_key_hashed();

		    (input, arranged.stream.probe().0, arranged.trace.clone())
    	});

        let seed: &[_] = &[1, 2, 3, index];
        let mut rng1: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions
        let mut rng2: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions

        // load up graph dataz
        let &time = input.time();
        for edge in 0..edges {
        	if edge % peers == index {
        		input.send(((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)), time, 1));
        	}

        	// move the data along a bit
        	if edge % 10000 == 9999 {
        		worker.step();
        	}
		}

		let timer = ::std::time::Instant::now();

		input.advance_to(1);
		worker.step_while(|| probe.lt(input.time()));

		if index == 0 {
			let timer = timer.elapsed();
			let nanos = timer.as_secs() * 1000000000 + timer.subsec_nanos() as u64;
			println!("Loading finished after {:?}", nanos);
		}

		// change graph, forever
		if batch > 0 {

			for edge in 0usize .. {
				let &time = input.time();
				if edge % peers == index {
	        		input.send(((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)), time, 1));
	        		input.send(((rng2.gen_range(0, nodes), rng2.gen_range(0, nodes)), time,-1));
				}

	        	if edge % batch == (batch - 1) {

	        		let timer = ::std::time::Instant::now();

	        		let next = input.epoch() + 1;
	        		input.advance_to(next);
					worker.step_while(|| probe.lt(input.time()));

					if index == 0 {
						let timer = timer.elapsed();
						let nanos = timer.as_secs() * 1000000000 + timer.subsec_nanos() as u64;
						println!("Round {} finished after {:?}", next - 1, nanos);

						let mut count = 0;
		        		let timer = ::std::time::Instant::now();
		        		let mut cursor = trace.cursor();
		        		while cursor.key_valid() {
		        			while cursor.val_valid() {
								let mut sum = 0;
								cursor.map_times(|_,d| sum += d);
								if sum > 0 { count += 1; }
								cursor.step_val();
		        			}

		        			cursor.step_key()
		        		}

		        		println!("count: {} in {:?}", count, timer.elapsed());
					}
	        	}
	        }
	    }

    }).unwrap();
}<commit_msg>removed unused reference<commit_after>extern crate rand;
extern crate timely;
extern crate timely_sort;
extern crate differential_dataflow;
extern crate vec_map;

use timely::dataflow::*;
use timely::dataflow::operators::*;

use rand::{Rng, SeedableRng, StdRng};

use differential_dataflow::AsCollection;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::trace::Cursor;

fn main() {

    let nodes: u32 = std::env::args().nth(1).unwrap().parse().unwrap();
    let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(3).unwrap().parse().unwrap();

    // define a new timely dataflow computation.
    timely::execute_from_args(std::env::args().skip(4), move |worker| {

    	let index = worker.index();
    	let peers = worker.peers();

    	// create a a degree counting differential dataflow
    	let (mut input, probe, trace) = worker.scoped(|scope| {

    		// create edge input, count a few ways.
    		let (input, edges) = scope.new_input();

    		// pull off source, and count.
    		let arranged = edges.as_collection()
    							.arrange_by_key_hashed();

		    (input, arranged.stream.probe().0, arranged.trace.clone())
    	});

        let seed: &[_] = &[1, 2, 3, index];
        let mut rng1: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions
        let mut rng2: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions

        // load up graph dataz
        let &time = input.time();
        for edge in 0..edges {
        	if edge % peers == index {
        		input.send(((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)), time, 1));
        	}

        	// move the data along a bit
        	if edge % 10000 == 9999 {
        		worker.step();
        	}
		}

		let timer = ::std::time::Instant::now();

		input.advance_to(1);
		worker.step_while(|| probe.lt(input.time()));

		if index == 0 {
			let timer = timer.elapsed();
			let nanos = timer.as_secs() * 1000000000 + timer.subsec_nanos() as u64;
			println!("Loading finished after {:?}", nanos);
		}

		// change graph, forever
		if batch > 0 {

			for edge in 0usize .. {
				let &time = input.time();
				if edge % peers == index {
	        		input.send(((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)), time, 1));
	        		input.send(((rng2.gen_range(0, nodes), rng2.gen_range(0, nodes)), time,-1));
				}

	        	if edge % batch == (batch - 1) {

	        		let timer = ::std::time::Instant::now();

	        		let next = input.epoch() + 1;
	        		input.advance_to(next);
					worker.step_while(|| probe.lt(input.time()));

					if index == 0 {
						let timer = timer.elapsed();
						let nanos = timer.as_secs() * 1000000000 + timer.subsec_nanos() as u64;
						println!("Round {} finished after {:?}", next - 1, nanos);

						let mut count = 0;
		        		let timer = ::std::time::Instant::now();
		        		let mut cursor = trace.cursor();
		        		while cursor.key_valid() {
		        			while cursor.val_valid() {
								let mut sum = 0;
								cursor.map_times(|_,d| sum += d);
								if sum > 0 { count += 1; }
								cursor.step_val();
		        			}

		        			cursor.step_key()
		        		}

		        		println!("count: {} in {:?}", count, timer.elapsed());
					}
	        	}
	        }
	    }

    }).unwrap();
}<|endoftext|>


<commit_before><commit_msg>Add example based on into_header_for_infinite_file<commit_after>// Generate endless screeching noise to stdout

// Usage: cargo run --example wavstdout | mpv -

extern crate hound;
use std::io::Write;

fn main() {
    let spec = hound::WavSpec {
        bits_per_sample: 16,
        channels: 1,
        sample_format: hound::SampleFormat::Int,
        sample_rate: 16000,
    };

    let v = spec.into_header_for_infinite_file();

    let so = std::io::stdout();
    let mut so = so.lock();
    so.write_all(&v[..]).unwrap();

    loop {
        for i in 0..126 {
            use hound::Sample;
            let x : i16 = (i * 256) as i16;
            if x.write(&mut so, 16).is_err() {
                return;
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>ZINTERSTORE/ZUNIONSTORE invalid parameters error messages<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for MIR printing changes<commit_after>// Test that we don't ICE when trying to dump MIR for unusual item types and
// that we don't create filenames containing `<` and `>`

struct A;

impl A {
    const ASSOCIATED_CONSTANT: i32 = 2;
}

enum E {
    V = 5,
}

fn main() {
    let v = Vec::<i32>::new();
}

// END RUST SOURCE

// START rustc.{{impl}}-ASSOCIATED_CONSTANT.mir_map.0.mir
// bb0: {
//     _0 = const 2i32;
//     return;
// }
// bb1: {
//     resume;
// }
// END rustc.{{impl}}-ASSOCIATED_CONSTANT.mir_map.0.mir

// START rustc.E-V-{{constant}}.mir_map.0.mir
// bb0: {
//     _0 = const 5isize;
//     return;
// }
// bb1: {
//     resume;
// }
// END rustc.E-V-{{constant}}.mir_map.0.mir

// START rustc.ptr-real_drop_in_place.std__vec__Vec_i32_.AddMovesForPackedDrops.before.mir
//     bb0: {
//     goto -> bb7;
// }
// bb1: {
//     return;
// }
// bb2: {
//     resume;
// }
// bb3: {
//     goto -> bb1;
// }
// bb4: {
//     goto -> bb2;
// }
// bb5: {
//     drop(((*_1).0: alloc::raw_vec::RawVec<i32>)) -> bb4;
// }
// bb6: {
//     drop(((*_1).0: alloc::raw_vec::RawVec<i32>)) -> [return: bb3, unwind: bb4];
// }
// bb7: {
//     _2 = &mut (*_1);
//     _3 = const std::ops::Drop::drop(move _2) -> [return: bb6, unwind: bb5];
// }
// END rustc.ptr-real_drop_in_place.std__vec__Vec_i32_.AddMovesForPackedDrops.before.mir
<|endoftext|>


<commit_before><commit_msg>Add a test for #6976<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[feature(macro_rules)];

macro_rules! define_vec (
    () => (
        mod foo {
            #[deriving(Eq)]
            pub struct bar;
        }
    )
)

define_vec!()

pub fn main() {}
<|endoftext|>