<commit_before>import run::spawn_process;
import io::writer_util;
import libc::{c_int, pid_t};

export run;

#[cfg(target_os = "win32")]
fn target_env(lib_path: str, prog: str) -> [(str,str)] {

    let mut env = os::env();

    // Make sure we include the aux directory in the path
    assert prog.ends_with(".exe");
    let aux_path = prog.slice(0u, prog.len() - 4u) + ".libaux";

    env = vec::map(env) {|pair|
        let (k,v) = pair;
        if k == "PATH" { ("PATH", v + ";" + lib_path + ";" + aux_path) }
        else { (k,v) }
    };
    if str::ends_with(prog, "rustc.exe") {
        env += [("RUST_THREADS", "1")]
    }
    ret env;
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn target_env(_lib_path: str, _prog: str) -> [(str,str)] {
    []
}

// FIXME: This code is duplicated in core::run::program_output
fn run(lib_path: str,
       prog: str,
       args: [str],
       env: [(str, str)],
       input: option<str>) -> {status: int, out: str, err: str} {

    let pipe_in = os::pipe();
    let pipe_out = os::pipe();
    let pipe_err = os::pipe();
    let pid = spawn_process(prog, args,
                            some(env + target_env(lib_path, prog)),
                            none, pipe_in.in, pipe_out.out, pipe_err.out);

    os::close(pipe_in.in);
    os::close(pipe_out.out);
    os::close(pipe_err.out);
    if pid == -1i32 {
        os::close(pipe_in.out);
        os::close(pipe_out.in);
        os::close(pipe_err.in);
        fail;
    }

    writeclose(pipe_in.out, input);
    let p = comm::port();
    let ch = comm::chan(p);
    task::spawn_sched(task::single_threaded) {||
        let errput = readclose(pipe_err.in);
        comm::send(ch, (2, errput));
    };
    task::spawn_sched(task::single_threaded) {||
        let output = readclose(pipe_out.in);
        comm::send(ch, (1, output));
    };
    let status = run::waitpid(pid);
    let mut errs = "";
    let mut outs = "";
    let mut count = 2;
    while count > 0 {
        let stream = comm::recv(p);
        alt check stream {
            (1, s) {
                outs = s;
            }
            (2, s) {
                errs = s;
            }
        };
        count -= 1;
    };
    ret {status: status, out: outs, err: errs};
}

fn writeclose(fd: c_int, s: option<str>) {
    if option::is_some(s) {
        let writer = io::fd_writer(fd, false);
        writer.write_str(option::get(s));
    }

    os::close(fd);
}

fn readclose(fd: c_int) -> str {
    // Copied from run::program_output
    let file = os::fdopen(fd);
    let reader = io::FILE_reader(file, false);
    let mut buf = "";
    while !reader.eof() {
        let bytes = reader.read_bytes(4096u);
        buf += str::from_bytes(bytes);
    }
    os::fclose(file);
    ret buf;
}
<commit_msg>Comment only: annotate FIXME<commit_after>import run::spawn_process;
import io::writer_util;
import libc::{c_int, pid_t};

export run;

#[cfg(target_os = "win32")]
fn target_env(lib_path: str, prog: str) -> [(str,str)] {

    let mut env = os::env();

    // Make sure we include the aux directory in the path
    assert prog.ends_with(".exe");
    let aux_path = prog.slice(0u, prog.len() - 4u) + ".libaux";

    env = vec::map(env) {|pair|
        let (k,v) = pair;
        if k == "PATH" { ("PATH", v + ";" + lib_path + ";" + aux_path) }
        else { (k,v) }
    };
    if str::ends_with(prog, "rustc.exe") {
        env += [("RUST_THREADS", "1")]
    }
    ret env;
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn target_env(_lib_path: str, _prog: str) -> [(str,str)] {
    []
}

// FIXME: This code is duplicated in core::run::program_output (#2659)
fn run(lib_path: str,
       prog: str,
       args: [str],
       env: [(str, str)],
       input: option<str>) -> {status: int, out: str, err: str} {

    let pipe_in = os::pipe();
    let pipe_out = os::pipe();
    let pipe_err = os::pipe();
    let pid = spawn_process(prog, args,
                            some(env + target_env(lib_path, prog)),
                            none, pipe_in.in, pipe_out.out, pipe_err.out);

    os::close(pipe_in.in);
    os::close(pipe_out.out);
    os::close(pipe_err.out);
    if pid == -1i32 {
        os::close(pipe_in.out);
        os::close(pipe_out.in);
        os::close(pipe_err.in);
        fail;
    }

    writeclose(pipe_in.out, input);
    let p = comm::port();
    let ch = comm::chan(p);
    task::spawn_sched(task::single_threaded) {||
        let errput = readclose(pipe_err.in);
        comm::send(ch, (2, errput));
    };
    task::spawn_sched(task::single_threaded) {||
        let output = readclose(pipe_out.in);
        comm::send(ch, (1, output));
    };
    let status = run::waitpid(pid);
    let mut errs = "";
    let mut outs = "";
    let mut count = 2;
    while count > 0 {
        let stream = comm::recv(p);
        alt check stream {
            (1, s) {
                outs = s;
            }
            (2, s) {
                errs = s;
            }
        };
        count -= 1;
    };
    ret {status: status, out: outs, err: errs};
}

fn writeclose(fd: c_int, s: option<str>) {
    if option::is_some(s) {
        let writer = io::fd_writer(fd, false);
        writer.write_str(option::get(s));
    }

    os::close(fd);
}

fn readclose(fd: c_int) -> str {
    // Copied from run::program_output
    let file = os::fdopen(fd);
    let reader = io::FILE_reader(file, false);
    let mut buf = "";
    while !reader.eof() {
        let bytes = reader.read_bytes(4096u);
        buf += str::from_bytes(bytes);
    }
    os::fclose(file);
    ret buf;
}
<|endoftext|>


<commit_before><commit_msg>read from standard input<commit_after><|endoftext|>


<commit_before><commit_msg>Revert the device lost recovery paths<commit_after><|endoftext|>


<commit_before><commit_msg>Implement routing table node insertion<commit_after>use node_bucket::NodeBucket;
use address::{Address, Addressable, LENGTH};

pub struct RoutingTable<A: Addressable> {
    self_address: Address,
    buckets: Vec<NodeBucket<A>>
}

impl<A: Addressable> RoutingTable<A> {
    pub fn new(k: usize, self_address: Address) -> RoutingTable<A> {
        let bucket = NodeBucket::new(k);
        RoutingTable {
            self_address: self_address,
            buckets: vec![bucket]
        }
    }

    pub fn insert(&mut self, node: A) {
        self.bucket_for(&node.address(), {move |bucket|
            bucket.insert(node)
        });
    }

    fn bucket_for<F>(&mut self, address: &Address, func: F)
        where F : FnOnce(&mut NodeBucket<A>) -> () {
        let index: usize;
        let split: bool;
        let buckets_maxed = self.buckets_maxed();
        let self_address = self.self_address;
        {
            let (idx, mut bucket) = self.buckets
                .iter_mut()
                .enumerate()
                .find(|&(_, ref b)| b.covers(address))
                .unwrap();

            index = idx;
            split = !buckets_maxed && bucket.is_full() && bucket.covers(&self_address);
        }

        if split {
            let mut bucket = self.buckets.remove(index);
            let (a, b) = bucket.split();
            self.buckets.extend(vec![a, b]);
            self.bucket_for(address, func);
        } else {
            let ref mut bucket = self.buckets.get_mut(index).unwrap();
            func(bucket);
        }
    }

    fn buckets_maxed(&self) -> bool {
        self.buckets.len() >= LENGTH
    }
}

#[cfg(test)]
mod tests {
    use super::RoutingTable;
    use address::{Address, Addressable};

    #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    struct TestNode {
        pub address: Address
    }

    impl TestNode {
        fn new(address: Address) -> TestNode {
            TestNode { address: address }
        }
    }

    impl Addressable for TestNode {
        fn address(&self) -> Address {
            self.address
        }
    }

    #[test]
    fn test_insert() {
        let self_node = Address::from_str("0000000000000000000000000000000000000000");
        let mut table: RoutingTable<TestNode> = RoutingTable::new(2, self_node);
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("ffffffffffffffffffffffffffffffffffffffff")));
        assert_eq!(table.buckets.len(), 1);

        // Splits buckets upon adding a k+1th node in the same space as self node
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 2);
        table.insert(TestNode::new(Address::from_str("7fffffffffffffffffffffffffffffffffffffff")));
        table.insert(TestNode::new(Address::from_str("7ffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 3);

        // Replaces instead of duplicates existing nodes
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        assert_eq!(table.buckets.len(), 3);

        // Disregards new nodes for full, non-self space buckets
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffd")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffc")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffb")));
        assert_eq!(table.buckets.len(), 3);
    }
}
<|endoftext|>


<commit_before>// 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(generic_associated_types)]

// Checking the interaction with this other feature
#![feature(associated_type_defaults)]

//FIXME(#44265): "undeclared lifetime" errors will be addressed in a follow-up PR

use std::fmt::{Display, Debug};

trait Foo {
    type Assoc where Self: Sized;
    type Assoc2<T> where T: Display;
    type WithDefault<T> where T: Debug = Iterator<Item=T>;
    type NoGenerics;
}

struct Bar;

impl Foo for Bar {
    type Assoc = usize;
    type Assoc2<T> = Vec<T>;
    type WithDefault<'a, T> = &'a Iterator<T>;
    //~^ ERROR undeclared lifetime
    type NoGenerics = ::std::cell::Cell<i32>;
}

fn main() {}
<commit_msg>Added case for when impl generic associated type has a where clause<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(generic_associated_types)]

// Checking the interaction with this other feature
#![feature(associated_type_defaults)]

//FIXME(#44265): "undeclared lifetime" errors will be addressed in a follow-up PR

use std::fmt::{Display, Debug};

trait Foo {
    type Assoc where Self: Sized;
    type Assoc2<T> where T: Display;
    type Assoc3<T>;
    type WithDefault<T> where T: Debug = Iterator<Item=T>;
    type NoGenerics;
}

struct Bar;

impl Foo for Bar {
    type Assoc = usize;
    type Assoc2<T> = Vec<T>;
    type Assoc3<T> where T: Iterator = Vec<T>;
    type WithDefault<'a, T> = &'a Iterator<T>;
    //~^ ERROR undeclared lifetime
    type NoGenerics = ::std::cell::Cell<i32>;
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add literals example<commit_after>fn main() {
    // Suffixed literals, their types are known at initialization
    let x = 1u8;
    let y = 2u32;
    let z = 3_f32;

    // Unsuffixed literal, their types depend on how they are used
    let i = 1;
    let f = 1.0;

    // `size_of_val` returns the size of a variable in bytes
    println!("size of `x` in bytes: {}", std::mem::size_of_val(&x));
    println!("size of `y` in bytes: {}", std::mem::size_of_val(&y));
    println!("size of `z` in bytes: {}", std::mem::size_of_val(&z));
    println!("size of `i` in bytes: {}", std::mem::size_of_val(&i));
    println!("size of `f` in bytes: {}", std::mem::size_of_val(&f));
}
<|endoftext|>


<commit_before><commit_msg>Add a test for #2197<commit_after>// rustfmt-max_width: 79
// rustfmt-wrap_comments: true
// rustfmt-error_on_line_overflow: false

/// ```rust
/// unsafe fn sum_sse2(x: i32x4) -> i32 {
///     let x = vendor::_mm_add_epi32(x, vendor::_mm_srli_si128(x.into(), 8).into());
///     let x = vendor::_mm_add_epi32(x, vendor::_mm_srli_si128(x.into(), 4).into());
///     vendor::_mm_cvtsi128_si32(x)
/// }
/// ```
fn foo() {}
<|endoftext|>


<commit_before><commit_msg>shell/child<commit_after>use std::process::Command;

// shell

static FILE_CMD :& 'static str = "file";

fn main() {

    let output = Command::new(FILE_CMD)
            .arg("--version1")
            .output().unwrap_or_else( |e|
                panic!("failed to run cmd: {} with {}", FILE_CMD, e)
            );

    if output.status.success() {
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
    } else {
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
    }

}<|endoftext|>


<commit_before><commit_msg>remove unnecessary lifetime indentifiers<commit_after><|endoftext|>


<commit_before>use std::ops::Range;
use {pso, target, Backend, IndexCount, InstanceCount, VertexCount, VertexOffset};
use buffer::IndexBufferView;
use queue::{Supports, Graphics};
use super::{AttachmentClear, ClearValue, CommandBuffer, RawCommandBuffer};

/// Specifies how commands for the following renderpasses will be recorded.
pub enum SubpassContents {
    ///
    Inline,
    ///
    SecondaryBuffers,
}

///
pub struct RenderPassInlineEncoder<'a, B: Backend>(pub(crate) &'a mut B::CommandBuffer)
where B::CommandBuffer: 'a;

impl<'a, B: Backend> RenderPassInlineEncoder<'a, B> {
    ///
    pub fn new<C>(
        cmd_buffer: &'a mut CommandBuffer<B, C>,
        render_pass: &B::RenderPass,
        frame_buffer: &B::Framebuffer,
        render_area: target::Rect,
        clear_values: &[ClearValue],
    ) -> Self
    where
        C: Supports<Graphics>,
    {
        cmd_buffer.raw.begin_renderpass(
            render_pass,
            frame_buffer,
            render_area,
            clear_values,
            SubpassContents::Inline);
        RenderPassInlineEncoder(cmd_buffer.raw)
    }

    ///
    pub fn next_subpass_inline(self) -> Self {
        self.0.next_subpass(SubpassContents::Inline);
        self
    }

    ///
    pub fn clear_attachments(&mut self, clears: &[AttachmentClear], rects: &[target::Rect]) {
        self.0.clear_attachments(clears, rects)
    }

    ///
    pub fn draw(&mut self, vertices: Range<VertexCount>, instances: Range<InstanceCount>) {
        self.0.draw(vertices, instances)
    }
    ///
    pub fn draw_indexed(&mut self, indices: Range<IndexCount>, base_vertex: VertexOffset, instances: Range<InstanceCount>) {
        self.0.draw_indexed(indices, base_vertex, instances)
    }
    ///
    pub fn draw_indirect(&mut self, buffer: &B::Buffer, offset: u64, draw_count: u32, stride: u32) {
        self.0.draw_indirect(buffer, offset, draw_count, stride)
    }
    ///
    pub fn draw_indexed_indirect(&mut self, buffer: &B::Buffer, offset: u64, draw_count: u32, stride: u32) {
        self.0.draw_indexed_indirect(buffer, offset, draw_count, stride)
    }

    /// Bind index buffer view.
    pub fn bind_index_buffer(&mut self, ibv: IndexBufferView<B>) {
        self.0.bind_index_buffer(ibv)
    }

    /// Bind vertex buffers.
    pub fn bind_vertex_buffers(&mut self, vbs: pso::VertexBufferSet<B>) {
        self.0.bind_vertex_buffers(vbs);
    }

    /// Bind a graphics pipeline.
    ///
    /// There is only *one* pipeline slot for compute and graphics.
    /// Calling the corresponding `bind_pipeline` functions will override the slot.
    pub fn bind_graphics_pipeline(&mut self, pipeline: &B::GraphicsPipeline) {
        self.0.bind_graphics_pipeline(pipeline)
    }

    ///
    pub fn bind_graphics_descriptor_sets(
        &mut self,
        layout: &B::PipelineLayout,
        first_set: usize,
        sets: &[&B::DescriptorSet],
    ) {
        self.0.bind_graphics_descriptor_sets(layout, first_set, sets)
    }

    // TODO: set_viewports
    // TODO: set_scissors
    // TODO: set_line_width
    // TODO: set_depth_bounds
    // TODO: set_depth_bias
    // TODO: set_blend_constants
    // TODO: set_stencil_compare_mask
    // TODO: set_stencil_reference
    // TODO: set_stencil_write_mask

    // TODO: push constants
    // TODO: pipeline barrier
    // TODO: begin/end query

}

impl<'a, B: Backend> Drop for RenderPassInlineEncoder<'a, B> {
    fn drop(&mut self) {
        self.0.end_renderpass();
    }
}
<commit_msg>add more methods to renderpass<commit_after>use std::ops::Range;
use {pso, target, Backend, IndexCount, InstanceCount, VertexCount, VertexOffset, Viewport};
use buffer::IndexBufferView;
use queue::{Supports, Graphics};
use super::{AttachmentClear, ClearValue, CommandBuffer, RawCommandBuffer};

/// Specifies how commands for the following renderpasses will be recorded.
pub enum SubpassContents {
    ///
    Inline,
    ///
    SecondaryBuffers,
}

///
pub struct RenderPassInlineEncoder<'a, B: Backend>(pub(crate) &'a mut B::CommandBuffer)
where B::CommandBuffer: 'a;

impl<'a, B: Backend> RenderPassInlineEncoder<'a, B> {
    ///
    pub fn new<C>(
        cmd_buffer: &'a mut CommandBuffer<B, C>,
        render_pass: &B::RenderPass,
        frame_buffer: &B::Framebuffer,
        render_area: target::Rect,
        clear_values: &[ClearValue],
    ) -> Self
    where
        C: Supports<Graphics>,
    {
        cmd_buffer.raw.begin_renderpass(
            render_pass,
            frame_buffer,
            render_area,
            clear_values,
            SubpassContents::Inline);
        RenderPassInlineEncoder(cmd_buffer.raw)
    }

    ///
    pub fn next_subpass_inline(self) -> Self {
        self.0.next_subpass(SubpassContents::Inline);
        self
    }

    ///
    pub fn clear_attachments(&mut self, clears: &[AttachmentClear], rects: &[target::Rect]) {
        self.0.clear_attachments(clears, rects)
    }

    ///
    pub fn draw(&mut self, vertices: Range<VertexCount>, instances: Range<InstanceCount>) {
        self.0.draw(vertices, instances)
    }
    ///
    pub fn draw_indexed(&mut self, indices: Range<IndexCount>, base_vertex: VertexOffset, instances: Range<InstanceCount>) {
        self.0.draw_indexed(indices, base_vertex, instances)
    }
    ///
    pub fn draw_indirect(&mut self, buffer: &B::Buffer, offset: u64, draw_count: u32, stride: u32) {
        self.0.draw_indirect(buffer, offset, draw_count, stride)
    }
    ///
    pub fn draw_indexed_indirect(&mut self, buffer: &B::Buffer, offset: u64, draw_count: u32, stride: u32) {
        self.0.draw_indexed_indirect(buffer, offset, draw_count, stride)
    }

    /// Bind index buffer view.
    pub fn bind_index_buffer(&mut self, ibv: IndexBufferView<B>) {
        self.0.bind_index_buffer(ibv)
    }

    /// Bind vertex buffers.
    pub fn bind_vertex_buffers(&mut self, vbs: pso::VertexBufferSet<B>) {
        self.0.bind_vertex_buffers(vbs);
    }

    /// Bind a graphics pipeline.
    ///
    /// There is only *one* pipeline slot for compute and graphics.
    /// Calling the corresponding `bind_pipeline` functions will override the slot.
    pub fn bind_graphics_pipeline(&mut self, pipeline: &B::GraphicsPipeline) {
        self.0.bind_graphics_pipeline(pipeline)
    }

    ///
    pub fn bind_graphics_descriptor_sets(
        &mut self,
        layout: &B::PipelineLayout,
        first_set: usize,
        sets: &[&B::DescriptorSet],
    ) {
        self.0.bind_graphics_descriptor_sets(layout, first_set, sets)
    }

    ///
    pub fn set_viewports(&mut self, viewports: &[Viewport]) {
        self.0.set_viewports(viewports)
    }

    ///
    pub fn set_scissors(&mut self, scissors: &[target::Rect]) {
        self.0.set_scissors(scissors)
    }

    ///
    pub fn set_stencil_reference(&mut self, front: target::Stencil, back: target::Stencil) {
        self.0.set_stencil_reference(front, back)
    }

    ///
    pub fn set_blend_constants(&mut self, cv: target::ColorValue) {
        self.0.set_blend_constants(cv)
    }

    // TODO: set_line_width
    // TODO: set_depth_bounds
    // TODO: set_depth_bias
    // TODO: set_stencil_compare_mask
    // TODO: set_stencil_write_mask
    // TODO: push constants
    // TODO: pipeline barrier (postponed)
    // TODO: begin/end query

}

impl<'a, B: Backend> Drop for RenderPassInlineEncoder<'a, B> {
    fn drop(&mut self) {
        self.0.end_renderpass();
    }
}
<|endoftext|>


<commit_before>//! Provides a struct for quality values.
//!
//! [RFC7231 Section 5.3.1](https://tools.ietf.org/html/rfc7231#section-5.3.1)
//! gives more information on quality values in HTTP header fields.

use std::fmt;
use std::str;
#[cfg(test)] use super::encoding::*;

/// Represents an item with a quality value as defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.3.1).
#[derive(Clone, PartialEq, Debug)]
pub struct QualityItem<T> {
    /// The actual contents of the field.
    pub item: T,
    /// The quality (client or server preference) for the value.
    pub quality: f32,
}

impl<T> QualityItem<T> {
    /// Creates a new `QualityItem` from an item and a quality.
    /// The item can be of any type.
    /// The quality should be a value in the range [0, 1].
    pub fn new(item: T, quality: f32) -> QualityItem<T> {
        QualityItem{item: item, quality: quality}
    }
}

impl<T: fmt::Display> fmt::Display for QualityItem<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.quality == 1.0 {
            write!(f, "{}", self.item)
        } else {
            write!(f, "{}; q={}", self.item,
                   format!("{:.3}", self.quality).trim_right_matches(&['0', '.'][]))
        }
    }
}

impl<T: str::FromStr> str::FromStr for QualityItem<T> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, ()> {
        // Set defaults used if parsing fails.
        let mut raw_item = s;
        let mut quality = 1f32;

        let parts: Vec<&str> = s.rsplitn(1, ';').map(|x| x.trim()).collect();
        if parts.len() == 2 {
            let start = &parts[0][0..2];
            if start == "q=" || start == "Q=" {
                let q_part = &parts[0][2..parts[0].len()];
                if q_part.len() > 5 {
                    return Err(());
                }
                let x: Result<f32, _> = q_part.parse();
                match x {
                    Ok(q_value) => {
                        if 0f32 <= q_value && q_value <= 1f32 {
                            quality = q_value;
                            raw_item = parts[1];
                            } else {
                                return Err(());
                            }
                        },
                    Err(_) => return Err(()),
                }
            }
        }
        let x: Result<T, _> = raw_item.parse();
        match x {
            Ok(item) => {
                Ok(QualityItem{ item: item, quality: quality, })
            },
            Err(_) => return Err(()),
        }
    }
}

/// Convinience function to wrap a value in a `QualityItem`
/// Sets `q` to the default 1.0
pub fn qitem<T>(item: T) -> QualityItem<T> {
    QualityItem::new(item, 1.0)
}

#[test]
fn test_quality_item_show1() {
    let x = qitem(Chunked);
    assert_eq!(format!("{}", x), "chunked");
}
#[test]
fn test_quality_item_show2() {
    let x = QualityItem::new(Chunked, 0.001);
    assert_eq!(format!("{}", x), "chunked; q=0.001");
}
#[test]
fn test_quality_item_show3() {
    // Custom value
    let x = QualityItem{
        item: EncodingExt("identity".to_string()),
        quality: 0.5f32,
    };
    assert_eq!(format!("{}", x), "identity; q=0.5");
}

#[test]
fn test_quality_item_from_str1() {
    let x: Result<QualityItem<Encoding>, ()> = "chunked".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
}
#[test]
fn test_quality_item_from_str2() {
    let x: Result<QualityItem<Encoding>, ()> = "chunked; q=1".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
}
#[test]
fn test_quality_item_from_str3() {
    let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.5".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.5f32, });
}
#[test]
fn test_quality_item_from_str4() {
    let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.273".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.273f32, });
}
#[test]
fn test_quality_item_from_str5() {
    let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.2739999".parse();
    assert_eq!(x, Err(()));
}
<commit_msg>feat(headers): Implement PartialOrd for QualityItem<commit_after>//! Provides a struct for quality values.
//!
//! [RFC7231 Section 5.3.1](https://tools.ietf.org/html/rfc7231#section-5.3.1)
//! gives more information on quality values in HTTP header fields.

use std::fmt;
use std::str;
use std::cmp;
#[cfg(test)] use super::encoding::*;

/// Represents an item with a quality value as defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.3.1).
#[derive(Clone, PartialEq, Debug)]
pub struct QualityItem<T> {
    /// The actual contents of the field.
    pub item: T,
    /// The quality (client or server preference) for the value.
    pub quality: f32,
}

impl<T> QualityItem<T> {
    /// Creates a new `QualityItem` from an item and a quality.
    /// The item can be of any type.
    /// The quality should be a value in the range [0, 1].
    pub fn new(item: T, quality: f32) -> QualityItem<T> {
        QualityItem{item: item, quality: quality}
    }
}

impl<T: PartialEq> cmp::PartialOrd for QualityItem<T> {
    fn partial_cmp(&self, other: &QualityItem<T>) -> Option<cmp::Ordering> {
        self.quality.partial_cmp(&other.quality)
    }
}

impl<T: fmt::Display> fmt::Display for QualityItem<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.quality == 1.0 {
            write!(f, "{}", self.item)
        } else {
            write!(f, "{}; q={}", self.item,
                   format!("{:.3}", self.quality).trim_right_matches(&['0', '.'][]))
        }
    }
}

impl<T: str::FromStr> str::FromStr for QualityItem<T> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, ()> {
        // Set defaults used if parsing fails.
        let mut raw_item = s;
        let mut quality = 1f32;

        let parts: Vec<&str> = s.rsplitn(1, ';').map(|x| x.trim()).collect();
        if parts.len() == 2 {
            let start = &parts[0][0..2];
            if start == "q=" || start == "Q=" {
                let q_part = &parts[0][2..parts[0].len()];
                if q_part.len() > 5 {
                    return Err(());
                }
                let x: Result<f32, _> = q_part.parse();
                match x {
                    Ok(q_value) => {
                        if 0f32 <= q_value && q_value <= 1f32 {
                            quality = q_value;
                            raw_item = parts[1];
                            } else {
                                return Err(());
                            }
                        },
                    Err(_) => return Err(()),
                }
            }
        }
        let x: Result<T, _> = raw_item.parse();
        match x {
            Ok(item) => {
                Ok(QualityItem{ item: item, quality: quality, })
            },
            Err(_) => return Err(()),
        }
    }
}

/// Convinience function to wrap a value in a `QualityItem`
/// Sets `q` to the default 1.0
pub fn qitem<T>(item: T) -> QualityItem<T> {
    QualityItem::new(item, 1.0)
}

#[test]
fn test_quality_item_show1() {
    let x = qitem(Chunked);
    assert_eq!(format!("{}", x), "chunked");
}
#[test]
fn test_quality_item_show2() {
    let x = QualityItem::new(Chunked, 0.001);
    assert_eq!(format!("{}", x), "chunked; q=0.001");
}
#[test]
fn test_quality_item_show3() {
    // Custom value
    let x = QualityItem{
        item: EncodingExt("identity".to_string()),
        quality: 0.5f32,
    };
    assert_eq!(format!("{}", x), "identity; q=0.5");
}

#[test]
fn test_quality_item_from_str1() {
    let x: Result<QualityItem<Encoding>, ()> = "chunked".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
}
#[test]
fn test_quality_item_from_str2() {
    let x: Result<QualityItem<Encoding>, ()> = "chunked; q=1".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
}
#[test]
fn test_quality_item_from_str3() {
    let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.5".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.5f32, });
}
#[test]
fn test_quality_item_from_str4() {
    let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.273".parse();
    assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.273f32, });
}
#[test]
fn test_quality_item_from_str5() {
    let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.2739999".parse();
    assert_eq!(x, Err(()));
}
#[test]
fn test_quality_item_ordering() {
    let x: QualityItem<Encoding> = "gzip; q=0.5".parse().ok().unwrap();
    let y: QualityItem<Encoding> = "gzip; q=0.273".parse().ok().unwrap();
    let comparision_result: bool = x.gt(&y);
    assert_eq!(comparision_result, true)
}
<|endoftext|>


<commit_before><commit_msg>feat(examples): add example of using PAL<commit_after>extern crate rsrl;
#[macro_use]
extern crate slog;

use rsrl::{
    logging, run, Evaluation, Parameter, SerialExperiment,
    agents::control::td::PAL,
    domains::{Domain, MountainCar},
    fa::{MultiLinear, projection::Fourier},
    geometry::Space,
    policies::EpsilonGreedy
};

fn main() {
    let domain = MountainCar::default();
    let mut agent = {
        let n_actions = domain.action_space().span().into();

        // Build the linear value function using a fourier basis projection and the
        // appropriate eligibility trace.
        let bases = Fourier::from_space(3, domain.state_space());
        let q_func = MultiLinear::new(bases, n_actions);

        // Build a stochastic behaviour policy with exponential epsilon.
        let eps = Parameter::exponential(0.99, 0.05, 0.99);
        let policy = EpsilonGreedy::new(eps);

        PAL::new(q_func, policy, 0.1, 0.99)
    };

    let logger = logging::root(logging::stdout());
    let domain_builder = Box::new(MountainCar::default);

    // Training phase:
    let _training_result = {
        // Start a serial learning experiment up to 1000 steps per episode.
        let e = SerialExperiment::new(&mut agent, domain_builder.clone(), 1000);

        // Realise 1000 episodes of the experiment generator.
        run(e, 1000, Some(logger.clone()))
    };

    // Testing phase:
    let testing_result = Evaluation::new(&mut agent, domain_builder).next().unwrap();

    info!(logger, "solution"; testing_result);
}
<|endoftext|>


<commit_before><commit_msg>Test for rustc-macro<commit_after>extern crate cargotest;
extern crate hamcrest;

use cargotest::is_nightly;
use cargotest::support::{project, execs};
use hamcrest::assert_that;

#[test]
fn noop() {
    if !is_nightly() {
        return;
    }

    let client = project("client")
        .file("Cargo.toml", r#"
            [package]
            name = "client"
            version = "0.0.1"
            authors = []

            [dependencies.noop]
            path = "../noop"
        "#)
        .file("src/main.rs", r#"
            #![feature(rustc_macro)]

            #[macro_use]
            extern crate noop;

            #[derive(Noop)]
            struct X;

            fn main() {}
        "#);
    let noop = project("noop")
        .file("Cargo.toml", r#"
            [package]
            name = "noop"
            version = "0.0.1"
            authors = []

            [lib]
            rustc-macro = true
        "#)
        .file("src/lib.rs", r#"
            #![feature(rustc_macro, rustc_macro_lib)]

            extern crate rustc_macro;
            use rustc_macro::TokenStream;

            #[rustc_macro_derive(Noop)]
            pub fn noop(input: TokenStream) -> TokenStream {
                input
            }
        "#);
    noop.build();

    assert_that(client.cargo_process("build"),
                execs().with_status(0));
    assert_that(client.cargo("build"),
                execs().with_status(0));
}

#[test]
fn impl_and_derive() {
    if !is_nightly() {
        return;
    }

    let client = project("client")
        .file("Cargo.toml", r#"
            [package]
            name = "client"
            version = "0.0.1"
            authors = []

            [dependencies.transmogrify]
            path = "../transmogrify"
        "#)
        .file("src/main.rs", r#"
            #![feature(rustc_macro)]

            #[macro_use]
            extern crate transmogrify;

            trait ImplByTransmogrify {
                fn impl_by_transmogrify(&self) -> bool;
            }

            #[derive(Transmogrify)]
            struct X;

            fn main() {
                let x = X::new();
                assert!(x.impl_by_transmogrify());
                println!("{:?}", x);
            }
        "#);
    let transmogrify = project("transmogrify")
        .file("Cargo.toml", r#"
            [package]
            name = "transmogrify"
            version = "0.0.1"
            authors = []

            [lib]
            rustc-macro = true
        "#)
        .file("src/lib.rs", r#"
            #![feature(rustc_macro, rustc_macro_lib)]

            extern crate rustc_macro;
            use rustc_macro::TokenStream;

            #[rustc_macro_derive(Transmogrify)]
            #[doc(hidden)]
            pub fn transmogrify(input: TokenStream) -> TokenStream {
                assert_eq!(input.to_string(), "struct X;\n");

                "
                    impl X {
                        fn new() -> Self {
                            X { success: true }
                        }
                    }

                    impl ImplByTransmogrify for X {
                        fn impl_by_transmogrify(&self) -> bool {
                            true
                        }
                    }

                    #[derive(Debug)]
                    struct X {
                        success: bool,
                    }
                ".parse().unwrap()
            }
        "#);
    transmogrify.build();

    assert_that(client.cargo_process("build"),
                execs().with_status(0));
    assert_that(client.cargo("run"),
                execs().with_status(0).with_stdout("X { success: true }"));
}
<|endoftext|>


<commit_before><commit_msg>use more efficient (?) implementation of is_power_of_two for Integers<commit_after><|endoftext|>


<commit_before><commit_msg>Add module to launch network benchmarks<commit_after>use client::GetResponse;
use hyper::Client;
use hyper::header::{ByteRangeSpec, Headers, Range};
use URL;
use std::path::Path;
use std::time::{Duration, Instant};

/// Number of times to ping the remote server
const PING_TIMES: usize = 5;
/// Number of bytes to download from the remote server
const LEN_BENCH_CHUNK: u64 = 64;

/// MirrorsList is an alias that contain fast URLs to download the file
type MirrorsList<'a> = Vec<URL<'a>>;

/// Launch a benchmark on a single URL
/// This benchmark tests the network for this URL, downloading five times a 64 bits packet
/// The result is the mean of the five measures
fn launch_bench<'a>(bench_client: &Client, url: URL<'a>) -> u32 {
    let mut c_ping_time: [u32; PING_TIMES] = [0; PING_TIMES];
    for index in 0..PING_TIMES {
        let now = Instant::now();
        let mut header = Headers::new();
        header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(0, LEN_BENCH_CHUNK)]));
        match bench_client.get_head_response_using_headers(url, header) {
            Ok(_) => c_ping_time[index] = now.elapsed().subsec_nanos(),
            Err(_) => break,
        }
    }
    // Return 0 if an error occured - the mirror is automatically removed
    if c_ping_time.iter().any(|&x| x == 0) {
        return 0;
    }
    // Return the mean value
    let sum: u32 = c_ping_time.iter().sum();
    sum / PING_TIMES as u32
}

/// Test each URL to download the required file
/// This function returns a list of URLs, which is sorted by median measures (the first URL is the fastest server)
pub fn bench_mirrors<'a>(mirrors: MirrorsList<'a>, filename: &str) -> MirrorsList<'a> {
    // Hyper client to make benchmarks
    let mut bench_client = Client::default();
    bench_client.set_read_timeout(Some(Duration::from_secs(3)));
    // Get mirrors list
    let mut b_mirrors: Vec<(&'a str, u32)> = Vec::with_capacity(PING_TIMES);
    for mirror in mirrors.iter() {
        let mirror_file = Path::new(mirror).join(filename);
        match mirror_file.to_str() {
            Some(_mirror) => {
                let subsec_nano = launch_bench(&bench_client, _mirror);
                if subsec_nano != 0 {
                    b_mirrors.push((mirror, subsec_nano));
                }
                println!("{}: {}", mirror, subsec_nano);
            }
            None => (),
        }
    }
    b_mirrors.sort_by_key(|k| k.1);
    b_mirrors.iter().map(|x| x.0).collect()
}
<|endoftext|>


<commit_before><commit_msg>fix up last part of rustdoc intergration<commit_after><|endoftext|>


<commit_before><commit_msg>remove bug comment<commit_after><|endoftext|>


<commit_before><commit_msg>Remove extraneous spaces at the ends of lines.<commit_after><|endoftext|>


<commit_before><commit_msg>Make test_register_multiple_event_loops use Poll API (#652)<commit_after><|endoftext|>


<commit_before>extern crate libc;

use self::libc::{c_char, c_uchar};

#[no_mangle]
pub extern fn anoncreds_create_claim(client_id: i32, command_id: i32,
                                     schema_id: *const c_char, attributes: *const c_char,
                                     claim_request: *const c_char,
                                     cb: extern fn(xcommand_id: i32, err: i32, claim: *const c_char)) {
    unimplemented!();
}

#[no_mangle]
pub extern fn anoncreds_create_claim_request(client_id: i32, command_id: i32,
                                             schema_id: *const c_char,
                                             request_non_revocation: bool,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                           claim_req: *const c_char)) {
    unimplemented!();
}

#[no_mangle]
pub extern fn anoncreds_create_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32,
                                                   proof: *const c_char, attrs: *const c_char)) {
    unimplemented!();
}

#[no_mangle]
pub extern fn anoncreds_verify_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     proof: *const c_uchar,
                                     revealed_attributes: *const c_uchar,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32)) {
    unimplemented!();
}<commit_msg>removed unnecessary parameter<commit_after>extern crate libc;

use self::libc::{c_char, c_uchar};

#[no_mangle]
pub extern fn anoncreds_create_claim(client_id: i32, command_id: i32,
                                     schema_id: *const c_char, attributes: *const c_char,
                                     claim_request: *const c_char,
                                     cb: extern fn(xcommand_id: i32, err: i32, claim: *const c_char)) {
    unimplemented!();
}

#[no_mangle]
pub extern fn anoncreds_create_claim_request(client_id: i32, command_id: i32,
                                             schema_id: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                           claim_req: *const c_char)) {
    unimplemented!();
}

#[no_mangle]
pub extern fn anoncreds_create_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32,
                                                   proof: *const c_char, attrs: *const c_char)) {
    unimplemented!();
}

#[no_mangle]
pub extern fn anoncreds_verify_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     proof: *const c_uchar,
                                     revealed_attributes: *const c_uchar,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32)) {
    unimplemented!();
}<|endoftext|>


<commit_before><commit_msg>day 6 solved.<commit_after>use std::io::prelude::*;
use std::fs::File;
use std::path::Path;

// necessary in order to enforce copy rather than move semantics!
#[derive(Clone, Copy)]
enum Op {
    Nop,
    On,
    Off,
    Toggle(i32),
    MinusPlus(i32, i32)
}

struct TreeNode {
    val : i32,
    prop: Op
}

struct Quadtree {
    len_x: usize,
    len_y: usize,
    tree : Vec<TreeNode>
}

impl TreeNode {
    fn new() -> TreeNode {
        TreeNode {
            val : 0,
            prop: Op::Nop
        }
    }

    fn update(&mut self, op: Op) {
        // if let is pretty cool!
        if let Op::MinusPlus(x, y) = op {
            self.val -= x;
            if self.val < 0 {
                self.val = 0;
            }
            self.val += y;
            if let Op::MinusPlus(a, b) = self.prop {
                self.prop = if b >= x {
                    Op::MinusPlus(a, b - x + y)
                } else {
                    Op::MinusPlus(a + x - b, y)
                }
            } else {
                self.prop = op;
            }
        } else {
            match op {
                Op::On        => {
                    self.val  = 1;
                    self.prop = Op::On;
                },
                Op::Off       => {
                    self.val  = 0;
                    self.prop = Op::Off;
                },
                Op::Toggle(x) => {
                    self.val = (self.val + x) % 2;
                    match self.prop {
                        Op::On        => {
                            if x % 2 == 1 {
                                self.prop = Op::Off;
                            } else {
                                self.prop = Op::On;
                            }
                        },
                        Op::Off       => {
                            if x % 2 == 1 {
                                self.prop = Op::On;
                            } else {
                                self.prop = Op::Off;
                            }
                        },
                        Op::Toggle(y) => {
                            self.prop = Op::Toggle(x + y);
                        },
                        _             => {
                            self.prop = op;
                        }
                    }
                },
                _             => { }
            };
        }
    }
}

impl Quadtree {
    fn new(len_x: usize, len_y: usize) -> Quadtree {
        let size = (len_x * len_y) << 2; // reserve at least 4*N*M nodes
        Quadtree {
            len_x: len_x,
            len_y: len_y,
            tree : (0..size).map(|_i| {
                TreeNode::new()
            }).collect()
        }
    }

    fn propagate(&mut self, idx: usize) {
        let op = self.tree[idx].prop;
        for i in 1..5 {
            let chd = (idx << 2) + i;
            if chd < self.tree.len() {
                self.tree[chd].update(op);
            }
        }
        self.tree[idx].prop = Op::Nop;
    }

    fn core_update(&mut self, idx: usize, l: usize, r: usize, u: usize, d: usize, op: Op, left: usize, right: usize, up: usize, down: usize) {
        self.propagate(idx);
        if l <= left && right <= r && u <= up && down <= d {
            self.tree[idx].update(op);
        } else {
            let mid_x = (left + right) >> 1;
            let mid_y = (up + down) >> 1;
            if l <= mid_x && u <= mid_y {
                self.core_update((idx << 2) + 1, l, r, u, d, op, left, mid_x, up, mid_y);
            }
            if r > mid_x && u <= mid_y {
                self.core_update((idx << 2) + 2, l, r, u, d, op, mid_x + 1, right, up, mid_y);
            }
            if l <= mid_x && d > mid_y {
                self.core_update((idx << 2) + 3, l, r, u, d, op, left, mid_x, mid_y + 1, down);
            }
            if r > mid_x && d > mid_y {
                self.core_update((idx << 2) + 4, l, r, u, d, op, mid_x + 1, right, mid_y + 1, down);
            }
        }
    }

    fn core_query(&mut self, idx: usize, left: usize, right: usize, up: usize, down: usize) -> i32 {
        self.propagate(idx);
        if left == right && up == down {
            self.tree[idx].val
        } else {
            let mid_x = (left + right) >> 1;
            let mid_y = (up + down) >> 1;
            let top_left = self.core_query((idx << 2) + 1, left, mid_x, up, mid_y);
            let top_right = if mid_x < right {
                self.core_query((idx << 2) + 2, mid_x + 1, right, up, mid_y)
            } else {
                0
            };
            let bottom_left = if mid_y < down {
                self.core_query((idx << 2) + 3, left, mid_x, mid_y + 1, down)
            } else {
                0
            };
            let bottom_right = if mid_x < right && mid_y < down {
                self.core_query((idx << 2) + 4, mid_x + 1, right, mid_y + 1, down)
            } else {
                0
            };
            top_left + top_right + bottom_left + bottom_right
        }
    }

    fn update(&mut self, l: usize, r: usize, u:usize, d:usize, op: Op) {
        /*
         must compute separately, as the borrows checker
         concludes that self.len could get invalidated
        */
        let max_x = self.len_x - 1;
        let max_y = self.len_y - 1;
        self.core_update(0, l, r, u, d, op, 0, max_x, 0, max_y);
    }

    fn query(&mut self) -> i32 {
        let max_x = self.len_x - 1;
        let max_y = self.len_y - 1;
        self.core_query(0, 0, max_x, 0, max_y)
    }
}

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let mut qtree = Quadtree::new(1000, 1000);

    for line in input.lines() {
        let parts: Vec<_> = line.split_whitespace().collect();
        let lu: Vec<_>;
        let rd: Vec<_>;
        let op;

        if parts[0] == "toggle" {
            lu = parts[1].split(',').collect();
            rd = parts[3].split(',').collect();
            op = Op::Toggle(1);
        } else {
            lu = parts[2].split(',').collect();
            rd = parts[4].split(',').collect();
            if parts[1] == "on" {
                op = Op::On;
            } else {
                op = Op::Off;
            }
        }
        let l = lu[0].parse().ok().expect("Could not parse into an integer!");
        let u = lu[1].parse().ok().expect("Could not parse into an integer!");
        let r = rd[0].parse().ok().expect("Could not parse into an integer!");
        let d = rd[1].parse().ok().expect("Could not parse into an integer!");

        qtree.update(l, r, u, d, op);
    }

    let ret = qtree.query();

    println!("{} lights are turned on at the end.", ret);

    let mut qtree = Quadtree::new(1000, 1000);

    for line in input.lines() {
        let parts: Vec<_> = line.split_whitespace().collect();
        let lu: Vec<_>;
        let rd: Vec<_>;
        let op;

        if parts[0] == "toggle" {
            lu = parts[1].split(',').collect();
            rd = parts[3].split(',').collect();
            op = Op::MinusPlus(0, 2);
        } else {
            lu = parts[2].split(',').collect();
            rd = parts[4].split(',').collect();
            if parts[1] == "on" {
                op = Op::MinusPlus(0, 1);
            } else {
                op = Op::MinusPlus(1, 0);
            }
        }
        let l = lu[0].parse().ok().expect("Could not parse into an integer!");
        let u = lu[1].parse().ok().expect("Could not parse into an integer!");
        let r = rd[0].parse().ok().expect("Could not parse into an integer!");
        let d = rd[1].parse().ok().expect("Could not parse into an integer!");

        qtree.update(l, r, u, d, op);
    }

    let ret = qtree.query();

    println!("The total brightness of the lights is {}.", ret);
}<|endoftext|>


<commit_before><commit_msg>Solution for day17<commit_after><|endoftext|>


<commit_before><commit_msg>shadowing one var with other var of same name<commit_after><|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 rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc::hir;
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::lint;
use rustc::traits::{self, Reveal};
use rustc::ty::{self, TyCtxt};

use syntax_pos::DUMMY_SP;

pub fn crate_inherent_impls_overlap_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                    crate_num: CrateNum) {
    assert_eq!(crate_num, LOCAL_CRATE);
    let krate = tcx.hir.krate();
    krate.visit_all_item_likes(&mut InherentOverlapChecker { tcx });
}

struct InherentOverlapChecker<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>
}

impl<'a, 'tcx> InherentOverlapChecker<'a, 'tcx> {
    fn check_for_common_items_in_impls(&self, impl1: DefId, impl2: DefId) {
        #[derive(Copy, Clone, PartialEq)]
        enum Namespace {
            Type,
            Value,
        }

        let name_and_namespace = |def_id| {
            let item = self.tcx.associated_item(def_id);
            (item.name, match item.kind {
                ty::AssociatedKind::Type => Namespace::Type,
                ty::AssociatedKind::Const |
                ty::AssociatedKind::Method => Namespace::Value,
            })
        };

        let impl_items1 = self.tcx.associated_item_def_ids(impl1);
        let impl_items2 = self.tcx.associated_item_def_ids(impl2);

        for &item1 in &impl_items1[..] {
            let (name, namespace) = name_and_namespace(item1);

            for &item2 in &impl_items2[..] {
                if (name, namespace) == name_and_namespace(item2) {
                    let msg = format!("duplicate definitions with name `{}`", name);
                    let node_id = self.tcx.hir.as_local_node_id(item1).unwrap();
                    self.tcx.sess.add_lint(lint::builtin::OVERLAPPING_INHERENT_IMPLS,
                                           node_id,
                                           self.tcx.span_of_impl(item1).unwrap(),
                                           msg);
                }
            }
        }
    }

    fn check_for_overlapping_inherent_impls(&self, ty_def_id: DefId) {
        let impls = ty::queries::inherent_impls::get(self.tcx, DUMMY_SP, ty_def_id);

        for (i, &impl1_def_id) in impls.iter().enumerate() {
            for &impl2_def_id in &impls[(i + 1)..] {
                self.tcx.infer_ctxt((), Reveal::UserFacing).enter(|infcx| {
                    if traits::overlapping_impls(&infcx, impl1_def_id, impl2_def_id).is_some() {
                        self.check_for_common_items_in_impls(impl1_def_id, impl2_def_id)
                    }
                });
            }
        }
    }
}

impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for InherentOverlapChecker<'a, 'tcx> {
    fn visit_item(&mut self, item: &'v hir::Item) {
        match item.node {
            hir::ItemEnum(..) |
            hir::ItemStruct(..) |
            hir::ItemTrait(..) |
            hir::ItemUnion(..) => {
                let type_def_id = self.tcx.hir.local_def_id(item.id);
                self.check_for_overlapping_inherent_impls(type_def_id);
            }
            _ => {}
        }
    }

    fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
    }

    fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
    }
}

<commit_msg>Make 'overlapping_inherent_impls' lint a hard error<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 rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc::hir;
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::traits::{self, Reveal};
use rustc::ty::{self, TyCtxt};

use syntax_pos::DUMMY_SP;

pub fn crate_inherent_impls_overlap_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                    crate_num: CrateNum) {
    assert_eq!(crate_num, LOCAL_CRATE);
    let krate = tcx.hir.krate();
    krate.visit_all_item_likes(&mut InherentOverlapChecker { tcx });
}

struct InherentOverlapChecker<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>
}

impl<'a, 'tcx> InherentOverlapChecker<'a, 'tcx> {
    fn check_for_common_items_in_impls(&self, impl1: DefId, impl2: DefId) {
        #[derive(Copy, Clone, PartialEq)]
        enum Namespace {
            Type,
            Value,
        }

        let name_and_namespace = |def_id| {
            let item = self.tcx.associated_item(def_id);
            (item.name, match item.kind {
                ty::AssociatedKind::Type => Namespace::Type,
                ty::AssociatedKind::Const |
                ty::AssociatedKind::Method => Namespace::Value,
            })
        };

        let impl_items1 = self.tcx.associated_item_def_ids(impl1);
        let impl_items2 = self.tcx.associated_item_def_ids(impl2);

        for &item1 in &impl_items1[..] {
            let (name, namespace) = name_and_namespace(item1);

            for &item2 in &impl_items2[..] {
                if (name, namespace) == name_and_namespace(item2) {
                    struct_span_err!(self.tcx.sess,
                                     self.tcx.span_of_impl(item1).unwrap(),
                                     E0592,
                                     "duplicate definitions with name `{}`",
                                     name)
                        .span_label(self.tcx.span_of_impl(item1).unwrap(),
                                    &format!("duplicate definitions for `{}`", name))
                        .span_label(self.tcx.span_of_impl(item2).unwrap(),
                                    &format!("other definition for `{}`", name))
                        .emit();
                }
            }
        }
    }

    fn check_for_overlapping_inherent_impls(&self, ty_def_id: DefId) {
        let impls = ty::queries::inherent_impls::get(self.tcx, DUMMY_SP, ty_def_id);

        for (i, &impl1_def_id) in impls.iter().enumerate() {
            for &impl2_def_id in &impls[(i + 1)..] {
                self.tcx.infer_ctxt((), Reveal::UserFacing).enter(|infcx| {
                    if traits::overlapping_impls(&infcx, impl1_def_id, impl2_def_id).is_some() {
                        self.check_for_common_items_in_impls(impl1_def_id, impl2_def_id)
                    }
                });
            }
        }
    }
}

impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for InherentOverlapChecker<'a, 'tcx> {
    fn visit_item(&mut self, item: &'v hir::Item) {
        match item.node {
            hir::ItemEnum(..) |
            hir::ItemStruct(..) |
            hir::ItemTrait(..) |
            hir::ItemUnion(..) => {
                let type_def_id = self.tcx.hir.local_def_id(item.id);
                self.check_for_overlapping_inherent_impls(type_def_id);
            }
            _ => {}
        }
    }

    fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
    }

    fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
    }
}

<|endoftext|>


<commit_before>use common::GeneralError;
use ctrl::GameController;
use ctrl::Gesture;
use gfx::ShaderLoader;
use gfx::Window;
use level::Level;
use player::Player;
use sdl2::keyboard::Scancode;
use sdl2::{self, Sdl};
use std::default::Default;
use std::error::Error;
use std::path::PathBuf;
use super::SHADER_ROOT;
use time;
use wad::{Archive, TextureDirectory};

pub struct GameConfig {
    pub wad_file: PathBuf,
    pub metadata_file: PathBuf,
    pub level_index: usize,
    pub fov: f32,
    pub width: u32,
    pub height: u32,
}

pub struct Game {
    window: Window,
    player: Player,
    level: Level,
    sdl: Sdl,
}

impl Game {
    pub fn new(config: GameConfig) -> Result<Game, Box<Error>> {
        let sdl = try!(sdl2::init().video().build().map_err(GeneralError));
        let window = try!(Window::new(&sdl, config.width, config.height));

        let shader_loader = ShaderLoader::new(PathBuf::from(SHADER_ROOT));

        let mut wad = try!(Archive::open(&config.wad_file, &config.metadata_file));
        let textures = try!(TextureDirectory::from_archive(&mut wad));
        let level = try!(Level::new(&shader_loader, &mut wad, &textures, config.level_index));

        let mut player = Player::new(config.fov, window.aspect_ratio(), Default::default());
        player.set_position(level.start_pos());

        Ok(Game {
            window: window,
            player: player,
            level: level,
            sdl: sdl,
        })
    }

    pub fn run(&mut self) {
        let quit_gesture = Gesture::AnyOf(
            vec![Gesture::QuitTrigger,
                 Gesture::KeyTrigger(Scancode::Escape)]);
        let grab_toggle_gesture = Gesture::KeyTrigger(Scancode::Grave);

        let mut cum_time = 0.0;
        let mut cum_updates_time = 0.0;
        let mut num_frames = 0.0;
        let mut t0 = time::precise_time_s();
        let mut control = GameController::new(self.sdl.event_pump());
        let mut mouse_grabbed = true;
        loop {
            self.window.clear();
            let t1 = time::precise_time_s();
            let mut delta = (t1 - t0) as f32;
            if delta < 1e-10 { delta = 1.0 / 60.0; }
            let delta = delta;
            t0 = t1;

            let updates_t0 = time::precise_time_s();

            control.update();
            if control.poll_gesture(&quit_gesture) {
                break;
            } else if control.poll_gesture(&grab_toggle_gesture) {
                mouse_grabbed = !mouse_grabbed;
                control.set_mouse_enabled(mouse_grabbed);
                control.set_cursor_grabbed(mouse_grabbed);
            }

            self.player.update(delta, &control, &self.level);
            self.level.render(delta,
                              self.player.camera().projection(), self.player.camera().modelview());

            let updates_t1 = time::precise_time_s();
            cum_updates_time += updates_t1 - updates_t0;

            cum_time += delta as f64;
            num_frames += 1.0;
            if cum_time > 2.0 {
                let fps = num_frames / cum_time;
                let cpums = 1000.0 * cum_updates_time / num_frames;
                info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
                      1000.0 / fps, cpums, fps);
                cum_time = 0.0;
                cum_updates_time = 0.0;
                num_frames = 0.0;
            }

            self.window.swap_buffers();
        }
    }
}
<commit_msg>Introduce aspect ratio correction.<commit_after>use common::GeneralError;
use ctrl::GameController;
use ctrl::Gesture;
use gfx::ShaderLoader;
use gfx::Window;
use level::Level;
use player::Player;
use sdl2::keyboard::Scancode;
use sdl2::{self, Sdl};
use std::default::Default;
use std::error::Error;
use std::path::PathBuf;
use super::SHADER_ROOT;
use time;
use wad::{Archive, TextureDirectory};

pub struct GameConfig {
    pub wad_file: PathBuf,
    pub metadata_file: PathBuf,
    pub level_index: usize,
    pub fov: f32,
    pub width: u32,
    pub height: u32,
}

pub struct Game {
    window: Window,
    player: Player,
    level: Level,
    sdl: Sdl,
}

impl Game {
    pub fn new(config: GameConfig) -> Result<Game, Box<Error>> {
        let sdl = try!(sdl2::init().video().build().map_err(GeneralError));
        let window = try!(Window::new(&sdl, config.width, config.height));

        let shader_loader = ShaderLoader::new(PathBuf::from(SHADER_ROOT));

        let mut wad = try!(Archive::open(&config.wad_file, &config.metadata_file));
        let textures = try!(TextureDirectory::from_archive(&mut wad));
        let level = try!(Level::new(&shader_loader, &mut wad, &textures, config.level_index));

        let mut player = Player::new(config.fov,
                                     window.aspect_ratio(),
                                     Default::default());
        player.set_position(level.start_pos());

        Ok(Game {
            window: window,
            player: player,
            level: level,
            sdl: sdl,
        })
    }

    pub fn run(&mut self) {
        let quit_gesture = Gesture::AnyOf(
            vec![Gesture::QuitTrigger,
                 Gesture::KeyTrigger(Scancode::Escape)]);
        let grab_toggle_gesture = Gesture::KeyTrigger(Scancode::Grave);

        let mut cum_time = 0.0;
        let mut cum_updates_time = 0.0;
        let mut num_frames = 0.0;
        let mut t0 = time::precise_time_s();
        let mut control = GameController::new(self.sdl.event_pump());
        let mut mouse_grabbed = true;
        loop {
            self.window.clear();
            let t1 = time::precise_time_s();
            let mut delta = (t1 - t0) as f32;
            if delta < 1e-10 { delta = 1.0 / 60.0; }
            let delta = delta;
            t0 = t1;

            let updates_t0 = time::precise_time_s();

            control.update();
            if control.poll_gesture(&quit_gesture) {
                break;
            } else if control.poll_gesture(&grab_toggle_gesture) {
                mouse_grabbed = !mouse_grabbed;
                control.set_mouse_enabled(mouse_grabbed);
                control.set_cursor_grabbed(mouse_grabbed);
            }

            self.player.update(delta, &control, &self.level);
            self.level.render(delta,
                              self.player.camera().projection(), self.player.camera().modelview());

            let updates_t1 = time::precise_time_s();
            cum_updates_time += updates_t1 - updates_t0;

            cum_time += delta as f64;
            num_frames += 1.0;
            if cum_time > 2.0 {
                let fps = num_frames / cum_time;
                let cpums = 1000.0 * cum_updates_time / num_frames;
                info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
                      1000.0 / fps, cpums, fps);
                cum_time = 0.0;
                cum_updates_time = 0.0;
                num_frames = 0.0;
            }

            self.window.swap_buffers();
        }
    }
}
<|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 std::collections::HashMap;
use std::path::Path;
use std::vec::Vec;

use dbus;
use dbus::Message;
use dbus::MessageItem;
use dbus::arg::Array;
use dbus::arg::IterAppend;
use dbus::tree::Access;
use dbus::tree::EmitsChangedSignal;
use dbus::tree::Factory;
use dbus::tree::MethodErr;
use dbus::tree::MTFn;
use dbus::tree::MethodResult;
use dbus::tree::MethodInfo;
use dbus::tree::PropInfo;

use uuid::Uuid;

use engine::RenameAction;

use super::filesystem::create_dbus_filesystem;
use super::types::{DbusContext, DbusErrorEnum, OPContext, TData};

use super::util::STRATIS_BASE_PATH;
use super::util::STRATIS_BASE_SERVICE;
use super::util::code_to_message_items;
use super::util::engine_to_dbus_err;
use super::util::get_next_arg;
use super::util::get_uuid;
use super::util::ok_message_items;

fn create_filesystems(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let filesystems: Array<&str, _> = try!(get_next_arg(&mut iter, 0));
    let dbus_context = m.tree.get_data();

    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let return_sig = "(os)";
    let default_return = MessageItem::Array(vec![], return_sig.into());

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = get_pool!(engine; pool_uuid; default_return; return_message);

    let result = pool.create_filesystems(&filesystems.collect::<Vec<&str>>());

    let msg = match result {
        Ok(ref infos) => {
            let mut return_value = Vec::new();
            for &(name, uuid) in infos {
                let fs_object_path: dbus::Path =
                    create_dbus_filesystem(dbus_context, object_path.clone(), uuid);
                return_value.push((fs_object_path, name));
            }

            let return_value = return_value
                .iter()
                .map(|x| {
                         MessageItem::Struct(vec![MessageItem::ObjectPath(x.0.clone()),
                                                  MessageItem::Str((*x.1).into())])
                     })
                .collect();
            let return_value = MessageItem::Array(return_value, return_sig.into());
            let (rc, rs) = ok_message_items();
            return_message.append3(return_value, rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])

}

fn destroy_filesystems(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let filesystems: Array<dbus::Path<'static>, _> = try!(get_next_arg(&mut iter, 0));

    let dbus_context = m.tree.get_data();
    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let return_sig = "s";
    let default_return = MessageItem::Array(vec![], return_sig.into());

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = get_pool!(engine; pool_uuid; default_return; return_message);

    let mut filesystem_map: HashMap<Uuid, dbus::Path<'static>> = HashMap::new();
    for op in filesystems {
        if let Some(filesystem_path) = m.tree.get(&op) {
            let filesystem_uuid = get_data!(filesystem_path; default_return; return_message).uuid;
            filesystem_map.insert(filesystem_uuid.clone(), op);
        }
    }

    let result = pool.destroy_filesystems(&filesystem_map.keys().collect::<Vec<&Uuid>>());
    let msg = match result {
        Ok(ref uuids) => {
            for uuid in uuids {
                let op = filesystem_map
                    .get(uuid)
                    .expect("'uuids' is a subset of filesystem_map.keys()")
                    .clone();
                dbus_context.actions.borrow_mut().push_remove(op);
            }

            let return_value = uuids
                .iter()
                .map(|n| MessageItem::Str(format!("{}", n.simple())))
                .collect();
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Array(return_value, return_sig.into()), rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn add_devs(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let force: bool = try!(get_next_arg(&mut iter, 0));
    let devs: Array<&str, _> = try!(get_next_arg(&mut iter, 1));

    let dbus_context = m.tree.get_data();
    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let return_sig = "s";
    let default_return = MessageItem::Array(vec![], return_sig.into());

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = get_pool!(engine; pool_uuid; default_return; return_message);

    let blockdevs = devs.map(|x| Path::new(x)).collect::<Vec<&Path>>();

    let msg = match pool.add_blockdevs(&blockdevs, force) {
        Ok(devnodes) => {
            let paths = devnodes
                .iter()
                .map(|d| {
                         d.to_str()
                             .expect("'d' originated in the 'devs' D-Bus argument.")
                             .into()
                     });
            let paths = paths.map(MessageItem::Str).collect();
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Array(paths, return_sig.into()), rc, rs)
        }
        Err(x) => {
            let (rc, rs) = engine_to_dbus_err(&x);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn rename_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let new_name: &str = try!(get_next_arg(&mut iter, 0));

    let dbus_context = m.tree.get_data();
    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let default_return = MessageItem::Bool(false);

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let msg = match dbus_context
              .engine
              .borrow_mut()
              .rename_pool(&pool_uuid, new_name) {
        Ok(RenameAction::NoSource) => {
            let error_message = format!("engine doesn't know about pool {}", pool_uuid);
            let (rc, rs) = code_to_message_items(DbusErrorEnum::INTERNAL_ERROR, error_message);
            return_message.append3(default_return, rc, rs)
        }
        Ok(RenameAction::Identity) => {
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Bool(false), rc, rs)
        }
        Ok(RenameAction::Renamed) => {
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Bool(true), rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn get_pool_name(i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
    let dbus_context = p.tree.get_data();
    let object_path = p.path.get_name();
    let pool_path = p.tree
        .get(object_path)
        .expect("implicit argument must be in tree");

    let data = try!(pool_path
                        .get_data()
                        .as_ref()
                        .ok_or_else(|| {
                                        MethodErr::failed(&format!("no data for object path {}",
                                                                   object_path))
                                    }));

    i.append(try!(dbus_context
                      .engine
                      .borrow_mut()
                      .get_pool(&data.uuid)
                      .map(|x| MessageItem::Str(x.name().to_owned()))
                      .ok_or(MethodErr::failed(&format!("no name for pool with uuid {}",
                                                        &data.uuid)))));
    Ok(())
}

pub fn create_dbus_pool<'a>(dbus_context: &DbusContext,
                            parent: dbus::Path<'static>,
                            uuid: Uuid)
                            -> dbus::Path<'a> {

    let f = Factory::new_fn();

    let create_filesystems_method = f.method("CreateFilesystems", (), create_filesystems)
        .in_arg(("specs", "as"))
        .out_arg(("filesystems", "a(os)"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let destroy_filesystems_method = f.method("DestroyFilesystems", (), destroy_filesystems)
        .in_arg(("filesystems", "ao"))
        .out_arg(("results", "as"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let add_devs_method = f.method("AddDevs", (), add_devs)
        .in_arg(("force", "b"))
        .in_arg(("devices", "as"))
        .out_arg(("results", "as"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let rename_method = f.method("SetName", (), rename_pool)
        .in_arg(("name", "s"))
        .out_arg(("action", "b"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let name_property = f.property::<&str, _>("Name", ())
        .access(Access::Read)
        .emits_changed(EmitsChangedSignal::False)
        .on_get(get_pool_name);

    let uuid_property = f.property::<&str, _>("Uuid", ())
        .access(Access::Read)
        .emits_changed(EmitsChangedSignal::Const)
        .on_get(get_uuid);

    let object_name = format!("{}/{}",
                              STRATIS_BASE_PATH,
                              dbus_context.get_next_id().to_string());

    let interface_name = format!("{}.{}", STRATIS_BASE_SERVICE, "pool");

    let object_path = f.object_path(object_name, Some(OPContext::new(parent, uuid)))
        .introspectable()
        .add(f.interface(interface_name, ())
                 .add_m(create_filesystems_method)
                 .add_m(destroy_filesystems_method)
                 .add_m(add_devs_method)
                 .add_m(rename_method)
                 .add_p(name_property)
                 .add_p(uuid_property));

    let path = object_path.get_name().to_owned();
    dbus_context.actions.borrow_mut().push_add(object_path);
    path
}
<commit_msg>Factor out the code for getting a property from the pool<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 std::collections::HashMap;
use std::path::Path;
use std::vec::Vec;

use dbus;
use dbus::Message;
use dbus::MessageItem;
use dbus::arg::Array;
use dbus::arg::IterAppend;
use dbus::tree::Access;
use dbus::tree::EmitsChangedSignal;
use dbus::tree::Factory;
use dbus::tree::MethodErr;
use dbus::tree::MTFn;
use dbus::tree::MethodResult;
use dbus::tree::MethodInfo;
use dbus::tree::PropInfo;

use uuid::Uuid;

use engine::{Pool, RenameAction};

use super::filesystem::create_dbus_filesystem;
use super::types::{DbusContext, DbusErrorEnum, OPContext, TData};

use super::util::STRATIS_BASE_PATH;
use super::util::STRATIS_BASE_SERVICE;
use super::util::code_to_message_items;
use super::util::engine_to_dbus_err;
use super::util::get_next_arg;
use super::util::get_uuid;
use super::util::ok_message_items;

fn create_filesystems(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let filesystems: Array<&str, _> = try!(get_next_arg(&mut iter, 0));
    let dbus_context = m.tree.get_data();

    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let return_sig = "(os)";
    let default_return = MessageItem::Array(vec![], return_sig.into());

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = get_pool!(engine; pool_uuid; default_return; return_message);

    let result = pool.create_filesystems(&filesystems.collect::<Vec<&str>>());

    let msg = match result {
        Ok(ref infos) => {
            let mut return_value = Vec::new();
            for &(name, uuid) in infos {
                let fs_object_path: dbus::Path =
                    create_dbus_filesystem(dbus_context, object_path.clone(), uuid);
                return_value.push((fs_object_path, name));
            }

            let return_value = return_value
                .iter()
                .map(|x| {
                         MessageItem::Struct(vec![MessageItem::ObjectPath(x.0.clone()),
                                                  MessageItem::Str((*x.1).into())])
                     })
                .collect();
            let return_value = MessageItem::Array(return_value, return_sig.into());
            let (rc, rs) = ok_message_items();
            return_message.append3(return_value, rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])

}

fn destroy_filesystems(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let filesystems: Array<dbus::Path<'static>, _> = try!(get_next_arg(&mut iter, 0));

    let dbus_context = m.tree.get_data();
    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let return_sig = "s";
    let default_return = MessageItem::Array(vec![], return_sig.into());

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = get_pool!(engine; pool_uuid; default_return; return_message);

    let mut filesystem_map: HashMap<Uuid, dbus::Path<'static>> = HashMap::new();
    for op in filesystems {
        if let Some(filesystem_path) = m.tree.get(&op) {
            let filesystem_uuid = get_data!(filesystem_path; default_return; return_message).uuid;
            filesystem_map.insert(filesystem_uuid.clone(), op);
        }
    }

    let result = pool.destroy_filesystems(&filesystem_map.keys().collect::<Vec<&Uuid>>());
    let msg = match result {
        Ok(ref uuids) => {
            for uuid in uuids {
                let op = filesystem_map
                    .get(uuid)
                    .expect("'uuids' is a subset of filesystem_map.keys()")
                    .clone();
                dbus_context.actions.borrow_mut().push_remove(op);
            }

            let return_value = uuids
                .iter()
                .map(|n| MessageItem::Str(format!("{}", n.simple())))
                .collect();
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Array(return_value, return_sig.into()), rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn add_devs(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let force: bool = try!(get_next_arg(&mut iter, 0));
    let devs: Array<&str, _> = try!(get_next_arg(&mut iter, 1));

    let dbus_context = m.tree.get_data();
    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let return_sig = "s";
    let default_return = MessageItem::Array(vec![], return_sig.into());

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = get_pool!(engine; pool_uuid; default_return; return_message);

    let blockdevs = devs.map(|x| Path::new(x)).collect::<Vec<&Path>>();

    let msg = match pool.add_blockdevs(&blockdevs, force) {
        Ok(devnodes) => {
            let paths = devnodes
                .iter()
                .map(|d| {
                         d.to_str()
                             .expect("'d' originated in the 'devs' D-Bus argument.")
                             .into()
                     });
            let paths = paths.map(MessageItem::Str).collect();
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Array(paths, return_sig.into()), rc, rs)
        }
        Err(x) => {
            let (rc, rs) = engine_to_dbus_err(&x);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn rename_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let new_name: &str = try!(get_next_arg(&mut iter, 0));

    let dbus_context = m.tree.get_data();
    let object_path = m.path.get_name();
    let return_message = message.method_return();
    let default_return = MessageItem::Bool(false);

    let pool_path = m.tree
        .get(object_path)
        .expect("implicit argument must be in tree");
    let pool_uuid = &get_data!(pool_path; default_return; return_message).uuid;

    let msg = match dbus_context
              .engine
              .borrow_mut()
              .rename_pool(&pool_uuid, new_name) {
        Ok(RenameAction::NoSource) => {
            let error_message = format!("engine doesn't know about pool {}", pool_uuid);
            let (rc, rs) = code_to_message_items(DbusErrorEnum::INTERNAL_ERROR, error_message);
            return_message.append3(default_return, rc, rs)
        }
        Ok(RenameAction::Identity) => {
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Bool(false), rc, rs)
        }
        Ok(RenameAction::Renamed) => {
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Bool(true), rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

/// Get a pool property and place it on the D-Bus. The property is
/// found by means of the getter method which takes a reference to a
/// Pool and obtains the property from the pool.
fn get_pool_property<F>(i: &mut IterAppend,
                        p: &PropInfo<MTFn<TData>, TData>,
                        getter: F)
                        -> Result<(), MethodErr>
    where F: Fn(&Pool) -> Result<MessageItem, MethodErr>
{
    let dbus_context = p.tree.get_data();
    let object_path = p.path.get_name();
    let pool_path = p.tree
        .get(object_path)
        .expect("implicit argument must be in tree");

    let pool_uuid = try!(pool_path
                        .get_data()
                        .as_ref()
                        .ok_or_else(|| {
                                        MethodErr::failed(&format!("no data for object path {}",
                                                                   object_path))
                                    }))
            .uuid;

    let mut engine = dbus_context.engine.borrow_mut();
    let pool = try!(engine
                        .get_pool(&pool_uuid)
                        .ok_or(MethodErr::failed(&format!("no pool corresponding to uuid {}",
                                                          &pool_uuid))));

    i.append(try!(getter(pool)));
    Ok(())
}

fn get_pool_name(i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
    get_pool_property(i, p, |p| Ok(MessageItem::Str(p.name().to_owned())))
}

pub fn create_dbus_pool<'a>(dbus_context: &DbusContext,
                            parent: dbus::Path<'static>,
                            uuid: Uuid)
                            -> dbus::Path<'a> {

    let f = Factory::new_fn();

    let create_filesystems_method = f.method("CreateFilesystems", (), create_filesystems)
        .in_arg(("specs", "as"))
        .out_arg(("filesystems", "a(os)"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let destroy_filesystems_method = f.method("DestroyFilesystems", (), destroy_filesystems)
        .in_arg(("filesystems", "ao"))
        .out_arg(("results", "as"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let add_devs_method = f.method("AddDevs", (), add_devs)
        .in_arg(("force", "b"))
        .in_arg(("devices", "as"))
        .out_arg(("results", "as"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let rename_method = f.method("SetName", (), rename_pool)
        .in_arg(("name", "s"))
        .out_arg(("action", "b"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let name_property = f.property::<&str, _>("Name", ())
        .access(Access::Read)
        .emits_changed(EmitsChangedSignal::False)
        .on_get(get_pool_name);

    let uuid_property = f.property::<&str, _>("Uuid", ())
        .access(Access::Read)
        .emits_changed(EmitsChangedSignal::Const)
        .on_get(get_uuid);

    let object_name = format!("{}/{}",
                              STRATIS_BASE_PATH,
                              dbus_context.get_next_id().to_string());

    let interface_name = format!("{}.{}", STRATIS_BASE_SERVICE, "pool");

    let object_path = f.object_path(object_name, Some(OPContext::new(parent, uuid)))
        .introspectable()
        .add(f.interface(interface_name, ())
                 .add_m(create_filesystems_method)
                 .add_m(destroy_filesystems_method)
                 .add_m(add_devs_method)
                 .add_m(rename_method)
                 .add_p(name_property)
                 .add_p(uuid_property));

    let path = object_path.get_name().to_owned();
    dbus_context.actions.borrow_mut().push_add(object_path);
    path
}
<|endoftext|>


<commit_before><commit_msg>	modified:   dr-daemon.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Updated to add new sorting<commit_after><|endoftext|>


<commit_before><commit_msg>refactor: Resolve App::help deprecation<commit_after><|endoftext|>


<commit_before><commit_msg>Added files via upload<commit_after>//
#[macro_use] extern crate nickel;

use nickel::{Nickel, HttpRouter, Request, Response,Middleware, MiddlewareResult};
use std::env;

#[cfg(unix)]
fn is_executable() {
   println!("is unix");
   }
#[cfg(windows)]
fn is_executable() {
   println!("is windows");
   }

pub fn pargs() {
    for (key,value) in env::vars_os() {
    println!("{:?}: {:?}", key, value);
    }
}

fn hello_world<'mw>(_req: &mut Request, res: Response<'mw>) -> MiddlewareResult<'mw> {
    res.send("Hello World")
}

fn logger_fn<'mw>(req: &mut Request, res: Response<'mw>) -> MiddlewareResult<'mw> {
    println!("logging request from logger fn: {:?}", req.origin.uri);
    res.next_middleware()
}

struct Logger;

impl<D> Middleware<D> for Logger {
    fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>)
    -> MiddlewareResult<'mw, D> {
        println!("logging request from logger middleware: {:?}", req.origin.uri);
        res.next_middleware()
    }
}
fn main() {
	pargs();
	is_executable();
	println!("Beispiel1");

    let mut server = Nickel::new();
	  // Middleware is optional and can be registered with `utilize`

    // This is an example middleware function that just logs each request
    // The middleware! macro wraps a closure which can capture variables
    // from the outer scope. See `example_route_data` for an example.
	 server.utilize(middleware! { |request|
        println!("logging request from middleware! macro: {:?}", request.origin.uri);
    });

    // Middleware can also be regular rust functions or anything that implements
    // the `Middleware` trait.
    server.utilize(logger_fn);
    server.utilize(Logger);

    server.get("**", hello_world);
    server.listen("127.0.0.1:8000");
}

<|endoftext|>


<commit_before><commit_msg>passing a mutable reference<commit_after><|endoftext|>