<commit_before>use chrono::{DateTime, Duration};
use chrono::offset::Local;
use hyper::server::Request;
use hyper_fs::Config;
use askama::Template;

use views::IndexTemplate;
use tools::url_for_parent;

use std::fs::{self, DirEntry, FileType};
use std::path::{Path, PathBuf};
use std::cmp::Ordering;
use std::fmt;
use std::io;

pub fn render_html(title: &str, index: &PathBuf, req: &Request, order: &EntryOrder, config: &Config) -> io::Result<String> {
    let metadatas = EntryMetadata::read_dir(
        index,
        config.get_follow_links(),
        config.get_hide_entry(),
        order,
    )?;
    let next_order = order.next();
    let remote_addr = req.remote_addr().unwrap();
    let parent = url_for_parent(req.uri().path());
    let template = IndexTemplate::new(title, title, &parent, &remote_addr, next_order, &metadatas);
    let html = template.render().unwrap();

    Ok(html)
}

pub struct EntryMetadata {
    pub name: String,
    pub size: Option<u64>,
    pub modified: Option<DateTime<Local>>,
    pub typo: Option<FileType>,
}

impl EntryMetadata {
    pub fn new(d: &DirEntry, follow_links: bool, hide_entry: bool) -> Option<Self> {
        let name = d.file_name().to_string_lossy().into_owned().to_owned();
        if hide_entry && name.starts_with('.') {
            return None;
        }
        let metadata = d.metadata().ok();
        let typo = metadata.as_ref().map(|md| md.file_type());
        if !follow_links && typo.as_ref().map(|t| t.is_symlink()).unwrap_or(true) {
            return None;
        }
        Some(Self {
            name,
            typo,
            size: metadata.as_ref().map(|md| md.len()),
            modified: metadata.as_ref().and_then(|md| {
                md.modified()
                    .ok()
                    .and_then(|mt| mt.elapsed().ok())
                    .and_then(|sd| Duration::from_std(sd).ok())
                    .and_then(|du| Local::now().checked_sub_signed(du))
            }),
        })
    }
    pub fn read_dir<P: AsRef<Path>>(dir: P, follow_links: bool, hide_entry: bool, order: &EntryOrder) -> io::Result<Vec<Self>> {
        let entries = fs::read_dir(dir)?;
        let mut entries_vec = Vec::new();
        // let mut name_len_max = 0;
        entries.into_iter().filter_map(|e| e.ok()).for_each(|e| {
            if let Some(d) = EntryMetadata::new(&e, follow_links, hide_entry) {
                entries_vec.push(d)
            }
        });
        order.sort(&mut entries_vec);
        Ok(entries_vec)
    }
}

#[derive(Debug)]
pub enum EntryOrder {
    /// if use None, conflicts with Option::None,
    Empty,
    Name,
    NameRev,
    Size,
    SizeRev,
    Modified,
    ModifiedRev,
}

impl EntryOrder {
    pub fn new(req_query: Option<&str>) -> Self {
        use self::EntryOrder::*;
        match req_query {
            None => Empty,
            Some(s) => {
                let lower = s.to_lowercase();
                match lower.as_str() {
                    "sort=name" => Name,
                    "sort=namerev" => NameRev,
                    "sort=size" => Size,
                    "sort=sizerev" => SizeRev,
                    "sort=modified" => Modified,
                    "sort=modifiedrev" => ModifiedRev,
                    _ => Empty,
                }
            }
        }
    }
    pub fn next(&self) -> (&'static str, &'static str, &'static str) {
        use self::EntryOrder::*;
        match *self {
            Empty | NameRev | ModifiedRev | SizeRev => ("Name", "Modified", "Size"),
            Name => ("NameRev", "Modified", "Size"),
            Size => ("Name", "Modified", "SizeRev"),
            Modified => ("Name", "ModifiedRev", "Size"),
        }
    }
    pub fn sort(&self, entries: &mut Vec<EntryMetadata>) {
        use self::EntryOrder::*;
        match *self {
            Empty => {}
            Name => entries.sort_by(|a, b| a.name.cmp(&b.name)),
            NameRev => entries.sort_by(|b, a| a.name.cmp(&b.name)),
            Size => entries.sort_by(|b, a| match (a.size.as_ref(), b.size.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
            SizeRev => entries.sort_by(|a, b| match (a.size.as_ref(), b.size.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
            Modified => entries.sort_by(|b, a| match (a.modified.as_ref(), b.modified.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
            ModifiedRev => entries.sort_by(|a, b| match (a.modified.as_ref(), b.modified.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
        }
    }
}

impl fmt::Display for EntryOrder {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::EntryOrder::*;
        f.write_str(match *self {
            Empty => "Empty",
            Name => "Name",
            NameRev => "NameRev",
            Size => "Size",
            SizeRev => "SizeRev",
            Modified => "Modified",
            ModifiedRev => "ModifiedRev",
        })
    }
}
<commit_msg>fix the computing method for the modified-time in the future.<commit_after>use askama::Template;
use chrono::{DateTime, Local, TimeZone};
use hyper::server::Request;
use hyper_fs::Config;

use tools::url_for_parent;
use views::IndexTemplate;

use std::cmp::Ordering;
use std::fmt;
use std::fs::{self, DirEntry, FileType};
use std::io;
use std::path::{Path, PathBuf};
use std::time;

pub fn render_html(title: &str, index: &PathBuf, req: &Request, order: &EntryOrder, config: &Config) -> io::Result<String> {
    let metadatas = EntryMetadata::read_dir(index, config.get_follow_links(), config.get_hide_entry(), order)?;
    let next_order = order.next();
    let remote_addr = req.remote_addr().unwrap();
    let parent = url_for_parent(req.uri().path());
    let template = IndexTemplate::new(title, title, &parent, &remote_addr, next_order, &metadatas);
    let html = template.render().unwrap();

    Ok(html)
}

pub struct EntryMetadata {
    pub name: String,
    pub size: Option<u64>,
    pub modified: Option<DateTime<Local>>,
    pub typo: Option<FileType>,
}

impl EntryMetadata {
    pub fn new(d: &DirEntry, follow_links: bool, hide_entry: bool) -> Option<Self> {
        let name = d.file_name().to_string_lossy().into_owned().to_owned();
        if hide_entry && name.starts_with('.') {
            return None;
        }
        let metadata = d.metadata().ok();
        let typo = metadata.as_ref().map(|md| md.file_type());
        if !follow_links && typo.as_ref().map(|t| t.is_symlink()).unwrap_or(true) {
            return None;
        }
        Some(Self {
            name,
            typo,
            size: metadata.as_ref().map(|md| md.len()),
            modified: metadata.as_ref().and_then(|md| {
                md.modified()
                    .ok()
                    .and_then(|mt| mt.duration_since(time::UNIX_EPOCH).ok())
                    .map(|sd| Local.timestamp(sd.as_secs() as i64, sd.subsec_nanos()))
            }),
        })
    }
    pub fn read_dir<P: AsRef<Path>>(dir: P, follow_links: bool, hide_entry: bool, order: &EntryOrder) -> io::Result<Vec<Self>> {
        let entries = fs::read_dir(dir)?;
        let mut entries_vec = Vec::new();
        // let mut name_len_max = 0;
        entries.into_iter().filter_map(|e| e.ok()).for_each(|e| {
            if let Some(d) = EntryMetadata::new(&e, follow_links, hide_entry) {
                entries_vec.push(d)
            }
        });
        order.sort(&mut entries_vec);
        Ok(entries_vec)
    }
}

#[derive(Debug)]
pub enum EntryOrder {
    /// if use None, conflicts with Option::None,
    Empty,
    Name,
    NameRev,
    Size,
    SizeRev,
    Modified,
    ModifiedRev,
}

impl EntryOrder {
    pub fn new(req_query: Option<&str>) -> Self {
        use self::EntryOrder::*;
        match req_query {
            None => Empty,
            Some(s) => {
                let lower = s.to_lowercase();
                match lower.as_str() {
                    "sort=name" => Name,
                    "sort=namerev" => NameRev,
                    "sort=size" => Size,
                    "sort=sizerev" => SizeRev,
                    "sort=modified" => Modified,
                    "sort=modifiedrev" => ModifiedRev,
                    _ => Empty,
                }
            }
        }
    }
    pub fn next(&self) -> (&'static str, &'static str, &'static str) {
        use self::EntryOrder::*;
        match *self {
            Empty | NameRev | ModifiedRev | SizeRev => ("Name", "Modified", "Size"),
            Name => ("NameRev", "Modified", "Size"),
            Size => ("Name", "Modified", "SizeRev"),
            Modified => ("Name", "ModifiedRev", "Size"),
        }
    }
    pub fn sort(&self, entries: &mut Vec<EntryMetadata>) {
        use self::EntryOrder::*;
        match *self {
            Empty => {}
            Name => entries.sort_by(|a, b| a.name.cmp(&b.name)),
            NameRev => entries.sort_by(|b, a| a.name.cmp(&b.name)),
            Size => entries.sort_by(|b, a| match (a.size.as_ref(), b.size.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
            SizeRev => entries.sort_by(|a, b| match (a.size.as_ref(), b.size.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
            Modified => entries.sort_by(|b, a| match (a.modified.as_ref(), b.modified.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
            ModifiedRev => entries.sort_by(|a, b| match (a.modified.as_ref(), b.modified.as_ref()) {
                (Some(aa), Some(bb)) => aa.cmp(bb),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            }),
        }
    }
}

impl fmt::Display for EntryOrder {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::EntryOrder::*;
        f.write_str(match *self {
            Empty => "Empty",
            Name => "Name",
            NameRev => "NameRev",
            Size => "Size",
            SizeRev => "SizeRev",
            Modified => "Modified",
            ModifiedRev => "ModifiedRev",
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Adds a binary that generates a single X-Ray tile. (#131)<commit_after>extern crate cgmath;
#[macro_use]
extern crate clap;
extern crate collision;
extern crate fnv;
extern crate image;
extern crate point_viewer;
extern crate protobuf;
extern crate quadtree;
extern crate scoped_pool;
extern crate xray;

use cgmath::{Point2, Point3};
use collision::{Aabb, Aabb2, Aabb3};
use octree::OnDiskOctree;
use point_viewer::octree;
use std::error::Error;
use std::path::Path;
use xray::generation::{xray_from_points, ColoringStrategyKind};

fn parse_arguments() -> clap::ArgMatches<'static> {
    clap::App::new("build_xray_tile")
        .version("1.0")
        .author("Holger H. Rapp <hrapp@lyft.com>")
        .args(&[
            clap::Arg::with_name("output_filename")
                .help("Output filename to write into.")
                .default_value("output.png")
                .long("output_filename")
                .takes_value(true),
            clap::Arg::with_name("resolution")
                .help("Size of 1px in meters.")
                .long("resolution")
                .default_value("0.01"),
            clap::Arg::with_name("coloring_strategy")
                .long("coloring_strategy")
                .takes_value(true)
                .possible_values(&ColoringStrategyKind::variants())
                .default_value("xray"),
            clap::Arg::with_name("octree_directory")
                .help("Octree directory to turn into xrays.")
                .index(1)
                .required(true),
            clap::Arg::with_name("min_x")
                .long("min_x")
                .takes_value(true)
                .help("Bounding box minimum x in meters.")
                .required(true),
            clap::Arg::with_name("min_y")
                .long("min_y")
                .takes_value(true)
                .help("Bounding box minimum y in meters.")
                .required(true),
            clap::Arg::with_name("max_x")
                .long("max_x")
                .takes_value(true)
                .help("Bounding box maximum x in meters.")
                .required(true),
            clap::Arg::with_name("max_y")
                .long("max_y")
                .takes_value(true)
                .help("Bounding box maximum y in meters.")
                .required(true),
        ])
        .get_matches()
}

fn run(
    octree_directory: &Path,
    output_filename: &Path,
    resolution: f32,
    coloring_strategy_kind: ColoringStrategyKind,
    bbox2: &Aabb2<f32>,
) -> Result<(), Box<Error>> {
    let octree = &OnDiskOctree::new(octree_directory)?;
    let bbox3 = octree.bounding_box();
    let bbox3 = Aabb3::new(
        Point3::new(
            bbox2.min().x.max(bbox3.min().x),
            bbox2.min().y.max(bbox3.min().y),
            bbox3.min().z,
        ),
        Point3::new(
            bbox2.max().x.min(bbox3.max().x),
            bbox2.max().y.min(bbox3.max().y),
            bbox3.max().z,
        ),
    );
    let image_width = (bbox2.dim().x / resolution).ceil() as u32;
    let image_height = (bbox2.dim().y / resolution).ceil() as u32;
    if !xray_from_points(
        octree,
        &bbox3,
        output_filename,
        image_width,
        image_height,
        coloring_strategy_kind.new_strategy(),
    ) {
        println!("No points in bounding box. No output written.");
    }
    Ok(())
}

pub fn main() {
    let matches = parse_arguments();
    let resolution = value_t!(matches, "resolution", f32).expect("resolution could not be parsed.");
    let coloring_strategy_kind = value_t!(matches, "coloring_strategy", ColoringStrategyKind)
        .expect("coloring_strategy is invalid");
    let octree_directory = Path::new(matches.value_of("octree_directory").unwrap());
    let output_filename = Path::new(matches.value_of("output_filename").unwrap());
    let min_x = value_t!(matches, "min_x", f32).expect("min_x could not be parsed.");
    let min_y = value_t!(matches, "min_y", f32).expect("min_y could not be parsed.");
    let max_x = value_t!(matches, "max_x", f32).expect("max_x could not be parsed.");
    let max_y = value_t!(matches, "max_y", f32).expect("max_y could not be parsed.");

    let bbox2 = Aabb2::new(Point2::new(min_x, min_y), Point2::new(max_x, max_y));
    run(
        octree_directory,
        output_filename,
        resolution,
        coloring_strategy_kind,
        &bbox2,
    ).unwrap();
}
<|endoftext|>


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

#![sanitizer_runtime]
#![feature(alloc_system)]
#![feature(sanitizer_runtime)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
            reason = "internal implementation detail of sanitizers",
            issue = "0")]

extern crate alloc_system;

use alloc_system::System;

#[global_allocator]
static ALLOC: System = System;
<commit_msg>[nll] librustc_asan: enable feature(nll) for bootstrap<commit_after>// Copyright 2016 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.

#![sanitizer_runtime]
#![feature(alloc_system)]
#![cfg_attr(not(stage0), feature(nll))]
#![feature(sanitizer_runtime)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
            reason = "internal implementation detail of sanitizers",
            issue = "0")]

extern crate alloc_system;

use alloc_system::System;

#[global_allocator]
static ALLOC: System = System;
<|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/1-chapter/hello_world/src/main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Integrate Instruction.<commit_after>// Copyright (C) 2014 The 6502-rs Developers
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the names of the copyright holders nor the names of any
//    contributors may be used to endorse or promote products derived from this
//    software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#[deriving(Show, PartialEq, Eq)]
pub enum Instruction
      // Abbreviations
      //
      // General
      //
      //        M | `Memory location`
      //
      // Registers
      //
      //        A | accumulator
      //        X | general purpose register
      //        Y | general purpose register
      // NV-BDIZC | processor status flags -- see ProcessorStatus bitflags
      //       SP | stack pointer
      //       PC | program counter
      //                                  i/o vars should be listed as follows:
      //                                  NV BDIZC A X Y SP PC M
      //
      //                                | outputs                | inputs
{ ADC // ADd with Carry................ | NV ...ZC A             = A + M + C
, AND // logical AND (bitwise)......... | N. ...Z. A             = A && M
, ASL // Arithmetic Shift Left......... | N. ...ZC A             = M << 1
, BCC // Branch if Carry Clear......... | .. .....          PC   = !C
, BCS // Branch if Carry Set........... | .. .....          PC   = C
, BEQ // Branch if Equal (to zero?).... | .. .....          PC   = Z
, BIT // BIT test...................... | NV ...Z.               = A & M
, BMI // Branch if Minus............... | .. .....          PC   = N
, BNE // Branch if Not Equal........... | .. .....          PC   = !Z
, BPL // Branch if Positive............ | .. .....          PC   = Z
, BRK // BReaK......................... | .. B....       SP PC   =
, BVC // Branch if oVerflow Clear...... | .. .....          PC   = !V
, BVS // Branch if oVerflow Set........ | .. .....          PC   = V
, CLC // CLear Carry flag.............. | .. ....C               = 0
, CLD // Clear Decimal Mode............ | .. .D...               = 0
, CLI // Clear Interrupt Disable....... | .. ..I..               = 0
, CLV // Clear oVerflow flag........... | .V .....               = 0
, CMP // Compare....................... | N. ...ZC               = A - M
, CPX // Compare X register............ | N. ...ZC               = X - M
, CPY // Compare Y register............ | N. ...ZC               = Y - M
, DEC // DECrement memory.............. | N. ...Z.             M = M - 1
, DEX // DEcrement X register.......... | N. ...Z.   X           = X - 1
, DEY // DEcrement Y register.......... | N. ...Z.     Y         = Y - 1
, EOR // Exclusive OR (bitwise)........ | N. ...Z. A             = A ^ M
, INC // INCrement memory.............. | N. ...Z.             M = M + 1
, INX // INcrement X register.......... | N. ...Z.   X           = X + 1
, INY // INcrement Y register.......... | N. ...Z.     Y         = Y + 1
, JMP // JuMP.......................... | .. .....          PC   =
, JSR // Jump to SubRoutine............ | .. .....
, LDA // LoaD Accumulator.............. | .. .....
, LDX // LoaD X register............... | .. .....
, LDY // LoaD Y register............... | .. .....
, LSR // Logical Shift Right........... | .. .....
, NOP // No OPeration.................. | .. .....
, ORA // inclusive OR.................. | .. .....
, PHA // PusH Accumulator.............. | .. .....
, PHP // PusH Processor status......... | .. .....
, PLA // PuLl Accumulator.............. | .. .....
, PLP // PuLl Processor status......... | .. .....
, ROL // ROtate Left................... | .. .....
, ROR // ROtate Right.................. | .. .....
, RTI // ReTurn from Interrupt......... | .. .....
, RTS // ReTurn from Subroutine........ | .. .....
, SBC // SuBtract with Carry........... | .. .....
, SEC // SEt Carry flag................ | .. .....
, SED // SEt Decimal flag.............. | .. .....
, SEI // SEt Interrupt disable......... | .. .....
, STA // STore Accumulator............. | .. .....
, STX // STore X register.............. | .. .....
, STY // STore Y register.............. | .. .....
, TAX // Transfer Accumulator to X..... | .. .....
, TAY // Transfer Accumulator to Y..... | .. .....
, TSX // Transfer Stack pointer to X... | .. .....
, TXA // Transfer X to Accumulator..... | .. .....
, TXS // Transfer X to Stack pointer... | .. .....
, TYA // Transfer Y to Accumulator..... | .. .....
}<|endoftext|>


<commit_before>#![deny(warnings)]

#[macro_use]
// TODO: only import header!, blocked by https://github.com/rust-lang/rust/issues/25003
extern crate hyper;

// A header in the form of `X-Foo: some random string`
header! {
    (Foo, "X-Foo") => [String]
}

fn main() {
}
<commit_msg>fix(examples): "cargo test --features serde-serialization"<commit_after>#![deny(warnings)]

#[macro_use]
// TODO: only import header!, blocked by https://github.com/rust-lang/rust/issues/25003
extern crate hyper;

#[cfg(feature = "serde-serialization")]
extern crate serde;

// A header in the form of `X-Foo: some random string`
header! {
    (Foo, "X-Foo") => [String]
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Regression test for issue 84297.<commit_after>// check-pass

fn main() {
    let _unused = if true {
        core::ptr::copy::<i32>
    } else {
        core::ptr::copy_nonoverlapping::<i32>
    };
}
<|endoftext|>


<commit_before><commit_msg>Add a test for 128-bit return values<commit_after>//! This test checks that types of up to 128 bits are returned by-value instead of via out-pointer.

// compile-flags: -C no-prepopulate-passes -O
// only-x86_64

#![crate_type = "lib"]

pub struct S {
    a: u64,
    b: u32,
    c: u32,
}

// CHECK: define i128 @modify(%S* noalias nocapture dereferenceable(16) %s)
#[no_mangle]
pub fn modify(s: S) -> S {
    S { a: s.a + s.a, b: s.b + s.b, c: s.c + s.c }
}

#[repr(packed)]
pub struct TooBig {
    a: u64,
    b: u32,
    c: u32,
    d: u8,
}

// CHECK: define void @m_big(%TooBig* [[ATTRS:.*sret.*]], %TooBig* [[ATTRS2:.*]] %s)
#[no_mangle]
pub fn m_big(s: TooBig) -> TooBig {
    TooBig { a: s.a + s.a, b: s.b + s.b, c: s.c + s.c, d: s.d + s.d }
}
<|endoftext|>


<commit_before><commit_msg>Added missing file<commit_after>use rustwlc::{Point, Size, ResizeEdge,
              RESIZE_LEFT, RESIZE_RIGHT, RESIZE_TOP, RESIZE_BOTTOM};

static MIN_SIZE: Size = Size { w: 80u32, h: 40u32 };

use super::super::{Action, LayoutTree, TreeError};
use super::super::commands::{CommandResult};
use super::super::core::container::{ContainerType, Handle};
use uuid::Uuid;

#[derive(Debug, Clone, Copy)]
pub enum ResizeErr {
    /// Expected the node associated with the UUID to be floating.
    ExpectedFloating(Uuid)
}

impl LayoutTree {
    /// Resizes a floating container. If the container was not floating, an Err is returned.
    pub fn resize_floating(&mut self, id: Uuid, edges: ResizeEdge, point: Point,
                           action: &mut Action) -> CommandResult {
        let grab = action.grab;
        //let edges = action.edges;
        action.grab = point;
        let container = try!(self.lookup(id));
        if !container.floating() {
            return Err(TreeError::Resize(ResizeErr::ExpectedFloating(container.get_id())))
        }
        if container.get_type() != ContainerType::View {
            return Err(TreeError::UuidWrongType(container.get_id(),
                                                vec!(ContainerType::View)))
        }
        let handle = match container.get_handle() {
            Some(Handle::View(view)) => view,
            _ => unreachable!()
        };
        let mut geo = handle.get_geometry()
            .expect("Could not get geometry of a view");
        let mut new_geo = geo.clone();

        let dx = point.x - grab.x;
        let dy = point.y - grab.y;
        if edges.contains(RESIZE_LEFT) {
            if dx < 0 {
                new_geo.size.w += dx.abs() as u32;
            } else {
                new_geo.size.w -= dx.abs() as u32;
            }
            new_geo.origin.x += dx;
        }
        else if edges.contains(RESIZE_RIGHT) {
            if dx < 0 {
                new_geo.size.w -= dx.abs() as u32;
            } else {
                new_geo.size.w += dx.abs() as u32;
            }
        }

        if edges.contains(RESIZE_TOP) {
            if dy < 0 {
                new_geo.size.h += dy.abs() as u32;
            } else {
                new_geo.size.h -= dy.abs() as u32;
            }
            new_geo.origin.y += dy;
        }
        else if edges.contains(RESIZE_BOTTOM) {
            if dy < 0 {
                new_geo.size.h -= dy.abs() as u32;
            } else {
                new_geo.size.h += dy.abs() as u32;
            }
        }

        if new_geo.size.w >= MIN_SIZE.w {
            geo.origin.x = new_geo.origin.x;
            geo.size.w = new_geo.size.w;
        }

        if new_geo.size.h >= MIN_SIZE.h {
            geo.origin.y = new_geo.origin.y;
            geo.size.h = new_geo.size.h;
        }

        handle.set_geometry(edges, geo);
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>Add ecdh wrapper module for x25519<commit_after><|endoftext|>


<commit_before><commit_msg>Added a new version of pfib that's better suited for benchmarking the task system. It generates gnuplot output.<commit_after>// -*- rust -*-

/*
  A parallel version of fibonacci numbers.

  This version is meant mostly as a way of stressing and benchmarking
  the task system. It supports a lot of command-line arguments to
  control how it runs.

*/

use std;

import std::vec;
import std::uint;
import std::time;
import std::str;
import std::int::range;
import std::io;

fn recv[T](&port[T] p) -> T {
    let T x;
    p |> x;
    ret x;
}

fn fib(int n) -> int {
    fn pfib(chan[int] c, int n) {
        if (n == 0) {
            c <| 0;
        }
        else if (n <= 2) {
            c <| 1;
        }
        else {
            let port[int] p = port();

            auto t1 = spawn pfib(chan(p), n - 1);
            auto t2 = spawn pfib(chan(p), n - 2);

            c <| recv(p) + recv(p);
        }
    }

    let port[int] p = port();
    auto t = spawn pfib(chan(p), n);
    ret recv(p);
}

fn main(vec[str] argv) {
    if(vec::len(argv) == 1u) {
        assert (fib(8) == 21);
        assert (fib(15) == 610);
        log fib(8);
        log fib(15);
    }
    else {
        // Interactive mode! Wooo!!!!

        auto max = uint::parse_buf(str::bytes(argv.(1)), 10u) as int;

        auto num_trials = 10;

        auto out = io::stdout();

        for each(int n in range(1, max + 1)) {
            for each(int i in range(0, num_trials)) {
                auto start = time::precise_time_ns();
                auto fibn = fib(n);
                auto stop = time::precise_time_ns();

                auto elapsed = (stop - start) as int;

                out.write_line(#fmt("%d\t%d\t%d", n, fibn, elapsed));
            }
        }

    }
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #28435 - apasel422:issue-24533, r=nikomatsakis<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.

use std::slice::Iter;
use std::io::{Error, ErrorKind, Result};
use std::vec::*;

fn foo(it: &mut Iter<u8>) -> Result<u8> {
    Ok(*it.next().unwrap())
}

fn bar() -> Result<u8> {
    let data: Vec<u8> = Vec::new();

    if true {
        return Err(Error::new(ErrorKind::NotFound, "msg"));
    }

    let mut it = data.iter();
    foo(&mut it)
}

fn main() {
    bar();
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #48610 - ishitatsuyuki:ishitatsuyuki-patch-1, r=nikomatsakis<commit_after>// Copyright 2018 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.

// Regression test for #48551. Covers a case where duplicate candidates
// arose during associated type projection.

use std::ops::{Mul, MulAssign};

pub trait ClosedMul<Right>: Sized + Mul<Right, Output = Self> + MulAssign<Right> {}
impl<T, Right> ClosedMul<Right> for T
where
    T: Mul<Right, Output = T> + MulAssign<Right>,
{
}

pub trait InnerSpace: ClosedMul<<Self as InnerSpace>::Real> {
    type Real;
}

pub trait FiniteDimVectorSpace: ClosedMul<<Self as FiniteDimVectorSpace>::Field> {
    type Field;
}

pub trait FiniteDimInnerSpace
    : InnerSpace + FiniteDimVectorSpace<Field = <Self as InnerSpace>::Real> {
}

pub trait EuclideanSpace: ClosedMul<<Self as EuclideanSpace>::Real> {
    type Coordinates: FiniteDimInnerSpace<Real = Self::Real>
        + Mul<Self::Real, Output = Self::Coordinates>
        + MulAssign<Self::Real>;

    type Real;
}

fn main() {}
<|endoftext|>


<commit_before>// xfail-pretty

use std;
import std::timer::sleep;
import std::uv;

import pipes::{recv, select};

proto! oneshot {
    waiting:send {
        signal -> signaled
    }

    signaled:send { }
}

proto! stream {
    stream:send<T:send> {
        send(T) -> stream<T>
    }
}

fn main() {
    import oneshot::client::*;
    import stream::client::*;

    let iotask = uv::global_loop::get();

    let c = pipes::spawn_service(stream::init, |p| {
        #error("waiting for pipes");
        let stream::send(x, p) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 0;

        #error("waiting for pipes");
        let stream::send(x, _) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 1;
    });

    let (c1, p1) = oneshot::init();
    let (_c2, p2) = oneshot::init();

    let c = send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c1);

    let (_c1, p1) = oneshot::init();
    let (c2, p2) = oneshot::init();

    send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c2);

    test_select2();
}

fn test_select2() {
    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(ac, 42);

    alt pipes::select2(ap, bp) {
      either::left(*) { }
      either::right(*) { fail }
    }

    stream::client::send(bc, "abc");

    #error("done with first select2");

    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(bc, "abc");

    alt pipes::select2(ap, bp) {
      either::left(*) { fail }
      either::right(*) { }
    }

    stream::client::send(ac, 42);
}
<commit_msg>xfailing pipe-select on Windows, because it also uses fail.<commit_after>// xfail-pretty
// xfail-win32

use std;
import std::timer::sleep;
import std::uv;

import pipes::{recv, select};

proto! oneshot {
    waiting:send {
        signal -> signaled
    }

    signaled:send { }
}

proto! stream {
    stream:send<T:send> {
        send(T) -> stream<T>
    }
}

fn main() {
    import oneshot::client::*;
    import stream::client::*;

    let iotask = uv::global_loop::get();

    let c = pipes::spawn_service(stream::init, |p| {
        #error("waiting for pipes");
        let stream::send(x, p) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 0;

        #error("waiting for pipes");
        let stream::send(x, _) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 1;
    });

    let (c1, p1) = oneshot::init();
    let (_c2, p2) = oneshot::init();

    let c = send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c1);

    let (_c1, p1) = oneshot::init();
    let (c2, p2) = oneshot::init();

    send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c2);

    test_select2();
}

fn test_select2() {
    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(ac, 42);

    alt pipes::select2(ap, bp) {
      either::left(*) { }
      either::right(*) { fail }
    }

    stream::client::send(bc, "abc");

    #error("done with first select2");

    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(bc, "abc");

    alt pipes::select2(ap, bp) {
      either::left(*) { fail }
      either::right(*) { }
    }

    stream::client::send(ac, 42);
}
<|endoftext|>


<commit_before><commit_msg>[add] cesar cipher<commit_after>fn cesar_encrypt(text: &str, shift: u8) -> String {
    let n = 'z' as u8 - 'a' as u8 + 1;
    let mut buffer = String::with_capacity(n as usize);
    for character in text.to_lowercase().chars() {
        buffer.push(match character {
            'a'...'z' => (((character as u8 - 'a' as u8 + shift) % n) + 'a' as u8) as char,
            _ => character
        });
    }
    buffer
}

fn cesar_decrypt(text: &str, shift: u8) -> String {
    let shift = 'z' as u8 - 'a' as u8 + 1 - shift;
    cesar_encrypt(text, shift)
}

#[test]
fn cesar_test() {
    let text = "this is simple text for cesar encryption/decryption algorithm";
    let shift = 3;
    let encrypt = cesar_encrypt(text, shift);
    let decrypt = cesar_decrypt(&encrypt, shift);
    assert_eq!(text, decrypt)
}

fn main() {
    let text = "test string z";
    let shift = 1;
    let encrypt = cesar_encrypt(text, shift);
    let decrypt = cesar_decrypt(&encrypt, shift);
    println!("`{}` --> `{}` --> `{}`", text, encrypt, decrypt);
}<|endoftext|>


<commit_before><commit_msg>:hammer: Add #[cfg(test)] derive<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/.

// Code to handle initial setup steps for a pool.
// Initial setup steps are steps that do not alter the environment.

use std::collections::{HashMap, HashSet};
use std::fs::{OpenOptions, read_dir};
use std::io::ErrorKind;
use std::path::PathBuf;

use nix::errno::Errno;
use serde_json;

use devicemapper::{Device, devnode_to_devno};

use super::super::super::errors::{EngineError, EngineResult, ErrorEnum};
use super::super::super::types::PoolUuid;

use super::super::engine::DevOwnership;
use super::super::serde_structs::{BackstoreSave, PoolSave};

use super::blockdev::StratBlockDev;
use super::device::blkdev_size;
use super::metadata::{BDA, StaticHeader};

/// Determine if devnode is a stratis device, if it is we will add  pool uuid and device
/// information to pool_map and return pool uuid.
pub fn is_stratis_device(devnode: &PathBuf) -> EngineResult<Option<PoolUuid>> {
    match OpenOptions::new().read(true).open(&devnode) {
        Ok(mut f) => {
            if let DevOwnership::Ours(pool_uuid, _) = StaticHeader::determine_ownership(&mut f)? {
                Ok(Some(pool_uuid))
            } else {
                Ok(None)
            }
        }
        Err(err) => {
            // There are some reasons for OpenOptions::open() to return an error
            // which are not reasons for this method to return an error.
            // Try to distinguish. Non-error conditions are:
            //
            // 1. ENXIO: The device does not exist anymore. This means that the device
            // was volatile for some reason; in that case it can not belong to
            // Stratis so it is safe to ignore it.
            //
            // 2. ENOMEDIUM: The device has no medium. An example of this case is an
            // empty optical drive.
            //
            // Note that it is better to be conservative and return with an
            // error in any case where failure to read the device could result
            // in bad data for Stratis. Additional exceptions may be added,
            // but only with a complete justification.
            match err.kind() {
                ErrorKind::NotFound => Ok(None),
                _ => {
                    if let Some(errno) = err.raw_os_error() {
                        match Errno::from_i32(errno) {
                            Errno::ENXIO | Errno::ENOMEDIUM => Ok(None),
                            _ => Err(EngineError::Io(err)),
                        }
                    } else {
                        Err(EngineError::Io(err))
                    }
                }
            }
        }
    }
}

/// Find all Stratis devices.
///
/// Returns a map of pool uuids to a map of devices to devnodes for each pool.
pub fn find_all() -> EngineResult<HashMap<PoolUuid, HashMap<Device, PathBuf>>> {

    let mut pool_map = HashMap::new();
    let mut devno_set = HashSet::new();
    for dir_e in read_dir("/dev")? {
        let dir_e = dir_e?;
        let devnode = dir_e.path();

        match devnode_to_devno(&devnode)? {
            None => continue,
            Some(devno) => {
                if devno_set.insert(devno) {
                    is_stratis_device(&devnode)?
                        .and_then(|pool_uuid| {
                                      pool_map
                                          .entry(pool_uuid)
                                          .or_insert_with(HashMap::new)
                                          .insert(Device::from(devno), devnode)
                                  });
                } else {
                    continue;
                }
            }
        }
    }

    Ok(pool_map)
}

/// Get the most recent metadata from a set of Devices for a given pool UUID.
/// Returns None if no metadata found for this pool.
#[allow(implicit_hasher)]
pub fn get_metadata(pool_uuid: PoolUuid,
                    devnodes: &HashMap<Device, PathBuf>)
                    -> EngineResult<Option<PoolSave>> {

    // Get pairs of device nodes and matching BDAs
    // If no BDA, or BDA UUID does not match pool UUID, skip.
    // If there is an error reading the BDA, error. There could have been
    // vital information on that BDA, for example, it may have contained
    // the newest metadata.
    let mut bdas = Vec::new();
    for devnode in devnodes.values() {
        let bda = BDA::load(&mut OpenOptions::new().read(true).open(devnode)?)?;
        if let Some(bda) = bda {
            if bda.pool_uuid() == pool_uuid {
                bdas.push((devnode, bda));
            }
        }
    }

    // Most recent time should never be None if this was a properly
    // created pool; this allows for the method to be called in other
    // circumstances.
    let most_recent_time = {
        match bdas.iter()
                  .filter_map(|&(_, ref bda)| bda.last_update_time())
                  .max() {
            Some(time) => time,
            None => return Ok(None),
        }
    };

    // Try to read from all available devnodes that could contain most
    // recent metadata. In the event of errors, continue to try until all are
    // exhausted.
    for &(devnode, ref bda) in
        bdas.iter()
            .filter(|&&(_, ref bda)| bda.last_update_time() == Some(most_recent_time)) {

        let poolsave = OpenOptions::new()
            .read(true)
            .open(devnode)
            .ok()
            .and_then(|mut f| bda.load_state(&mut f).ok())
            .and_then(|opt| opt)
            .and_then(|data| serde_json::from_slice(&data).ok());

        if poolsave.is_some() {
            return Ok(poolsave);
        }
    }

    // If no data has yet returned, we have an error. That is, we should have
    // some metadata, because we have a most recent time, but we failed to
    // get any.
    let err_str = "timestamp indicates data was written, but no data successfully read";
    Err(EngineError::Engine(ErrorEnum::NotFound, err_str.into()))
}

/// Get all the blockdevs corresponding to this pool that can be obtained from
/// the given devices. Return them in the order in which they were written
/// in the metadata.
/// Returns an error if the blockdevs obtained do not match the metadata.
#[allow(implicit_hasher)]
pub fn get_blockdevs(pool_uuid: PoolUuid,
                     backstore_save: &BackstoreSave,
                     devnodes: &HashMap<Device, PathBuf>)
                     -> EngineResult<Vec<StratBlockDev>> {
    let segments = &backstore_save.segments;

    let mut segment_table = HashMap::new();
    for seg in segments {
        segment_table
            .entry(seg.0)
            .or_insert_with(Vec::default)
            .push((seg.1, seg.2))
    }

    let mut blockdevs = vec![];
    for (device, devnode) in devnodes {
        let bda = BDA::load(&mut OpenOptions::new().read(true).open(devnode)?)?;
        if let Some(bda) = bda {
            if bda.pool_uuid() == pool_uuid {
                let actual_size = blkdev_size(&OpenOptions::new().read(true).open(devnode)?)?
                    .sectors();

                let bd_save = backstore_save
                    .block_devs
                    .iter()
                    .find(|bds| bds.uuid == bda.dev_uuid())
                    .ok_or_else(|| {
                                    let err_msg = format!("Blockdev {} not found in metadata",
                                                          bda.dev_uuid());
                                    EngineError::Engine(ErrorEnum::NotFound, err_msg)
                                })?;

                // If the size of the device has changed and is less,
                // then it is possible that the segments previously allocated
                // for this blockdev no longer exist. If that is the case,
                // StratBlockDev::new will return an error.
                let segments = segment_table.get(&bda.dev_uuid());
                blockdevs.push(StratBlockDev::new(*device,
                                                  devnode.to_owned(),
                                                  actual_size,
                                                  bda,
                                                  segments.unwrap_or(&vec![]),
                                                  bd_save.user_info.clone(),
                                                  bd_save.hardware_info.clone())?);
            }
        }
    }

    // Verify that blockdevs found match blockdevs recorded.
    let current_uuids: HashSet<_> = blockdevs.iter().map(|b| b.uuid()).collect();
    let recorded_uuids: HashSet<_> = backstore_save
        .block_devs
        .iter()
        .map(|bds| bds.uuid)
        .collect();

    if current_uuids != recorded_uuids {
        let err_msg = "Recorded block dev UUIDs != discovered blockdev UUIDs";
        return Err(EngineError::Engine(ErrorEnum::Invalid, err_msg.into()));
    }

    if blockdevs.len() != current_uuids.len() {
        let err_msg = "Duplicate block devices found in environment";
        return Err(EngineError::Engine(ErrorEnum::Invalid, err_msg.into()));
    }

    Ok(blockdevs)
}
<commit_msg>Add a comment about blockdev size decrease<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/.

// Code to handle initial setup steps for a pool.
// Initial setup steps are steps that do not alter the environment.

use std::collections::{HashMap, HashSet};
use std::fs::{OpenOptions, read_dir};
use std::io::ErrorKind;
use std::path::PathBuf;

use nix::errno::Errno;
use serde_json;

use devicemapper::{Device, devnode_to_devno};

use super::super::super::errors::{EngineError, EngineResult, ErrorEnum};
use super::super::super::types::PoolUuid;

use super::super::engine::DevOwnership;
use super::super::serde_structs::{BackstoreSave, PoolSave};

use super::blockdev::StratBlockDev;
use super::device::blkdev_size;
use super::metadata::{BDA, StaticHeader};

/// Determine if devnode is a stratis device, if it is we will add  pool uuid and device
/// information to pool_map and return pool uuid.
pub fn is_stratis_device(devnode: &PathBuf) -> EngineResult<Option<PoolUuid>> {
    match OpenOptions::new().read(true).open(&devnode) {
        Ok(mut f) => {
            if let DevOwnership::Ours(pool_uuid, _) = StaticHeader::determine_ownership(&mut f)? {
                Ok(Some(pool_uuid))
            } else {
                Ok(None)
            }
        }
        Err(err) => {
            // There are some reasons for OpenOptions::open() to return an error
            // which are not reasons for this method to return an error.
            // Try to distinguish. Non-error conditions are:
            //
            // 1. ENXIO: The device does not exist anymore. This means that the device
            // was volatile for some reason; in that case it can not belong to
            // Stratis so it is safe to ignore it.
            //
            // 2. ENOMEDIUM: The device has no medium. An example of this case is an
            // empty optical drive.
            //
            // Note that it is better to be conservative and return with an
            // error in any case where failure to read the device could result
            // in bad data for Stratis. Additional exceptions may be added,
            // but only with a complete justification.
            match err.kind() {
                ErrorKind::NotFound => Ok(None),
                _ => {
                    if let Some(errno) = err.raw_os_error() {
                        match Errno::from_i32(errno) {
                            Errno::ENXIO | Errno::ENOMEDIUM => Ok(None),
                            _ => Err(EngineError::Io(err)),
                        }
                    } else {
                        Err(EngineError::Io(err))
                    }
                }
            }
        }
    }
}

/// Find all Stratis devices.
///
/// Returns a map of pool uuids to a map of devices to devnodes for each pool.
pub fn find_all() -> EngineResult<HashMap<PoolUuid, HashMap<Device, PathBuf>>> {

    let mut pool_map = HashMap::new();
    let mut devno_set = HashSet::new();
    for dir_e in read_dir("/dev")? {
        let dir_e = dir_e?;
        let devnode = dir_e.path();

        match devnode_to_devno(&devnode)? {
            None => continue,
            Some(devno) => {
                if devno_set.insert(devno) {
                    is_stratis_device(&devnode)?
                        .and_then(|pool_uuid| {
                                      pool_map
                                          .entry(pool_uuid)
                                          .or_insert_with(HashMap::new)
                                          .insert(Device::from(devno), devnode)
                                  });
                } else {
                    continue;
                }
            }
        }
    }

    Ok(pool_map)
}

/// Get the most recent metadata from a set of Devices for a given pool UUID.
/// Returns None if no metadata found for this pool.
#[allow(implicit_hasher)]
pub fn get_metadata(pool_uuid: PoolUuid,
                    devnodes: &HashMap<Device, PathBuf>)
                    -> EngineResult<Option<PoolSave>> {

    // Get pairs of device nodes and matching BDAs
    // If no BDA, or BDA UUID does not match pool UUID, skip.
    // If there is an error reading the BDA, error. There could have been
    // vital information on that BDA, for example, it may have contained
    // the newest metadata.
    let mut bdas = Vec::new();
    for devnode in devnodes.values() {
        let bda = BDA::load(&mut OpenOptions::new().read(true).open(devnode)?)?;
        if let Some(bda) = bda {
            if bda.pool_uuid() == pool_uuid {
                bdas.push((devnode, bda));
            }
        }
    }

    // Most recent time should never be None if this was a properly
    // created pool; this allows for the method to be called in other
    // circumstances.
    let most_recent_time = {
        match bdas.iter()
                  .filter_map(|&(_, ref bda)| bda.last_update_time())
                  .max() {
            Some(time) => time,
            None => return Ok(None),
        }
    };

    // Try to read from all available devnodes that could contain most
    // recent metadata. In the event of errors, continue to try until all are
    // exhausted.
    for &(devnode, ref bda) in
        bdas.iter()
            .filter(|&&(_, ref bda)| bda.last_update_time() == Some(most_recent_time)) {

        let poolsave = OpenOptions::new()
            .read(true)
            .open(devnode)
            .ok()
            .and_then(|mut f| bda.load_state(&mut f).ok())
            .and_then(|opt| opt)
            .and_then(|data| serde_json::from_slice(&data).ok());

        if poolsave.is_some() {
            return Ok(poolsave);
        }
    }

    // If no data has yet returned, we have an error. That is, we should have
    // some metadata, because we have a most recent time, but we failed to
    // get any.
    let err_str = "timestamp indicates data was written, but no data successfully read";
    Err(EngineError::Engine(ErrorEnum::NotFound, err_str.into()))
}

/// Get all the blockdevs corresponding to this pool that can be obtained from
/// the given devices. Return them in the order in which they were written
/// in the metadata.
/// Returns an error if the blockdevs obtained do not match the metadata.
#[allow(implicit_hasher)]
pub fn get_blockdevs(pool_uuid: PoolUuid,
                     backstore_save: &BackstoreSave,
                     devnodes: &HashMap<Device, PathBuf>)
                     -> EngineResult<Vec<StratBlockDev>> {
    let segments = &backstore_save.segments;

    let mut segment_table = HashMap::new();
    for seg in segments {
        segment_table
            .entry(seg.0)
            .or_insert_with(Vec::default)
            .push((seg.1, seg.2))
    }

    let mut blockdevs = vec![];
    for (device, devnode) in devnodes {
        let bda = BDA::load(&mut OpenOptions::new().read(true).open(devnode)?)?;
        if let Some(bda) = bda {
            if bda.pool_uuid() == pool_uuid {
                let actual_size = blkdev_size(&OpenOptions::new().read(true).open(devnode)?)?
                    .sectors();

                let bd_save = backstore_save
                    .block_devs
                    .iter()
                    .find(|bds| bds.uuid == bda.dev_uuid())
                    .ok_or_else(|| {
                                    let err_msg = format!("Blockdev {} not found in metadata",
                                                          bda.dev_uuid());
                                    EngineError::Engine(ErrorEnum::NotFound, err_msg)
                                })?;

                // If the size of the device has changed and is less,
                // then it is possible that the segments previously allocated
                // for this blockdev no longer exist. If that is the case,
                // StratBlockDev::new will return an error.
                // NOTE: Currently, all blockdevs have all their space
                // allocated to the DM device in the data tier. As long as
                // that is the case, this block will always return an error
                // if the blockdev size has decreased.
                let segments = segment_table.get(&bda.dev_uuid());
                blockdevs.push(StratBlockDev::new(*device,
                                                  devnode.to_owned(),
                                                  actual_size,
                                                  bda,
                                                  segments.unwrap_or(&vec![]),
                                                  bd_save.user_info.clone(),
                                                  bd_save.hardware_info.clone())?);
            }
        }
    }

    // Verify that blockdevs found match blockdevs recorded.
    let current_uuids: HashSet<_> = blockdevs.iter().map(|b| b.uuid()).collect();
    let recorded_uuids: HashSet<_> = backstore_save
        .block_devs
        .iter()
        .map(|bds| bds.uuid)
        .collect();

    if current_uuids != recorded_uuids {
        let err_msg = "Recorded block dev UUIDs != discovered blockdev UUIDs";
        return Err(EngineError::Engine(ErrorEnum::Invalid, err_msg.into()));
    }

    if blockdevs.len() != current_uuids.len() {
        let err_msg = "Duplicate block devices found in environment";
        return Err(EngineError::Engine(ErrorEnum::Invalid, err_msg.into()));
    }

    Ok(blockdevs)
}
<|endoftext|>


<commit_before><commit_msg>comment about PartialEq and Eq trait difference<commit_after>// Why is this trait called PartialEq?

// The traditional mathematical definition of an equivalence relation, of which equality is one instance, imposes three requirements.

// For any values x and y:
// • If x == y is true, then y == x must be true as well.
//   In other words, swapping the two sides of an equality comparison doesn’t affect the result.
//
// • If x == y and y == z, then it must be the case that x == z.
//   Given any chain of values, each equal to the next, each value in the chain is directly equal to every other.
//   Equality is contagious.
//
// • It must always be true that x == x.

// That last requirement might seem too obvious to be worth stating, but this is exactly where things go awry.
// Rust’s f32 and f64 are IEEE standard floating-point values.
// According to that standard, expressions like 0.0/0.0 and others with no appropriate value must produce special not-a-number values, usually referred to as NaN values.
// The standard further requires that a NaN value be treated as unequal to every other value — including itself.

// Eq is full equlality constraint.
// PartialEq is Eq, but without x == x guarantee. (Wow, spirit of Haskell I feel).
<|endoftext|>


<commit_before><commit_msg>remove conflicr<commit_after><|endoftext|>


<commit_before>//
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.12
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3

#![feature(globs)]

use std::io::*;
use std::str;

fn main() {

    let ip_addres = "127.0.0.1";
    let port = 4414;
    let mut acceptor = net::tcp::TcpListener::bind(ip_addres, port).listen().unwrap();

    println!("Listening on [{}] ...", ip_addres);

    for stream in acceptor.incoming() {
        // Spawn a task to handle the connection
        spawn(proc() {

            let mut stream = stream;

            match stream {
                Ok(ref mut s) => {
                    match s.peer_name() {
                        Ok(pn) => println!("Received connection from: [{}]", pn),
                        Err(_) => ()
                    }
                },
                Err(_) => ()
            }

            let mut buf = [0, ..500];
            stream.read(buf);
            let request_str = str::from_utf8(buf);
            println!("Received request :\n{}", request_str);

            let response: Box<&str> =
                box "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
                 <doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

                 \r\n";
            stream.write(response.as_bytes());
            println!("Connection terminates.");
        });
    }
}
<commit_msg>Rust 0.13<commit_after>//
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.12
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3

#![feature(globs)]

use std::io::*;
use std::str;

fn main() {

    let addr = "127.0.0.1:4414";
    let mut acceptor = net::tcp::TcpListener::bind(addr).listen().unwrap();

    println!("Listening on [{}] ...", addr);

    for stream in acceptor.incoming() {
        // Spawn a task to handle the connection
        spawn(proc() {

            let mut stream = stream;

            match stream {
                Ok(ref mut s) => {
                    match s.peer_name() {
                        Ok(pn) => println!("Received connection from: [{}]", pn),
                        Err(_) => ()
                    }
                },
                Err(_) => ()
            }

            let mut buf = [0, ..500];
            stream.read(&mut buf);
            let request_str = str::from_utf8(&buf);
            println!("Received request :\n{}", request_str);

            let response: Box<&str> =
                box "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
                 <doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

                 \r\n";
            stream.write(response.as_bytes());
            println!("Connection terminates.");
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>fix pattern<commit_after><|endoftext|>


<commit_before><commit_msg>Adjusting offset bins to match expected low mass cutoff.<commit_after><|endoftext|>


<commit_before><commit_msg>Ifdef in shader<commit_after><|endoftext|>


<commit_before><commit_msg>ToString generics for Content<commit_after><|endoftext|>


<commit_before><commit_msg>Remove send_query and receive_response<commit_after><|endoftext|>


<commit_before><commit_msg>Adding test case dealing with communication and hashmaps.<commit_after>/**
   A somewhat reduced test case to expose some Valgrind issues.

   This originally came from the word-count benchmark.
*/

use std;

import std::io;
import option = std::option::t;
import std::option::some;
import std::option::none;
import std::str;
import std::vec;
import std::map;

fn map(str filename, map_reduce::putter emit) {
    emit(filename, "1");
}

mod map_reduce {
    export putter;
    export mapper;
    export map_reduce;

    type putter = fn(str, str) -> ();

    type mapper = fn(str, putter);

    tag ctrl_proto {
        find_reducer(str, chan[int]);
        mapper_done;
    }

    fn start_mappers(chan[ctrl_proto] ctrl,
                     vec[str] inputs) {
        for(str i in inputs) {
            spawn map_task(ctrl, i);
        }
    }

    fn map_task(chan[ctrl_proto] ctrl,
                str input) {

        auto intermediates = map::new_str_hash();

        fn emit(&map::hashmap[str, int] im,
                chan[ctrl_proto] ctrl,
                str key, str val) {
            auto c;
            alt(im.find(key)) {
                case(some(?_c)) {
                    c = _c
                }
                case(none) {
                    auto p = port();
                    log_err "sending find_reducer";
                    ctrl <| find_reducer(key, chan(p));
                    log_err "receiving";
                    p |> c;
                    log_err c;
                    im.insert(key, c);
                }
            }
        }

        map(input, bind emit(intermediates, ctrl, _, _));
        ctrl <| mapper_done;
    }

    fn map_reduce (vec[str] inputs) {
        auto ctrl = port[ctrl_proto]();

        // This task becomes the master control task. It spawns others
        // to do the rest.

        let map::hashmap[str, int] reducers;

        reducers = map::new_str_hash();

        start_mappers(chan(ctrl), inputs);

        auto num_mappers = vec::len(inputs) as int;

        while(num_mappers > 0) {
            auto m;
            ctrl |> m;

            alt(m) {
                case(mapper_done) { num_mappers -= 1; }
                case(find_reducer(?k, ?cc)) {
                    auto c;
                    alt(reducers.find(k)) {
                        case(some(?_c)) { c = _c; }
                        case(none) {
                            c = 0;
                        }
                    }
                    cc <| c;
                }
            }
        }
    }
}

fn main(vec[str] argv) {
    map_reduce::map_reduce(["../src/test/run-pass/hashmap-memory.rs"]);
}
<|endoftext|>


<commit_before><commit_msg>Add cube example.<commit_after>//! A simple particle program to demostrate how to use sprite component.

extern crate crayon;
extern crate rand;

use crayon::prelude::*;

struct Window {
    scene: Scene,
    cubes: Vec<Entity>,
    light: Entity,
    far: f32,
    camera: Entity,
}

impl Window {
    fn new(mut app: &mut Application) -> errors::Result<Window> {
        let mut scene = Scene::new(&mut app)?;

        let camera = {
            // Create and bind main camera of scene.
            let c = Scene::camera(&mut scene.world_mut());
            scene.set_main_camera(c);

            {
                let dimensions = app.window.dimensions().unwrap();
                let mut camera = scene.world_mut().fetch_mut::<Camera>(c).unwrap();
                camera.set_aspect(dimensions.0 as f32 / dimensions.1 as f32);
                camera.set_projection(Projection::Perspective(30.0));
            }

            {
                let mut arena = scene.world_mut().arena::<Transform>().unwrap();
                let mut position = Transform::world_position(&arena, c).unwrap();
                position.z = 500f32;
                Transform::set_world_position(&mut arena, c, position).unwrap();
            }

            c
        };

        let cubes = {
            let mut cubes = Vec::new();
            for i in 0..1 {
                let cube = Window::spwan(&mut app, &mut scene)?;
                let mut transform = scene.world().fetch_mut::<Transform>(cube).unwrap();

                transform.set_scale(25.0);
                transform.translate(math::Vector3::unit_x() * i as f32 * 60.0);
                cubes.push(cube);
            }
            cubes
        };

        let light = {
            let parent = scene
                .world_mut()
                .build()
                .with_default::<Transform>()
                .finish();

            let light = Window::spawn_color_cube(&mut app, &mut scene)?;

            {
                let data = DirectionalLight::default();
                scene
                    .world_mut()
                    .assign::<Light>(light, Light::Directional(data));
            }

            {
                let mut arena = scene.world().arena::<Transform>().unwrap();

                {
                    let mut transform = arena.get_mut(*light).unwrap();
                    transform.set_scale(15.0);
                    transform.translate(math::Vector3::unit_z() * 80.0);
                }

                Transform::set_parent(&mut arena, light, Some(parent), true)?;
                Transform::look_at(&mut arena, light, parent, math::Vector3::unit_y())?;
            }

            parent
        };

        Ok(Window {
               scene: scene,
               cubes: cubes,
               light: light,
               far: 1000.0,
               camera: camera,
           })
    }

    fn spwan(mut app: &mut Application, scene: &mut Scene) -> errors::Result<Entity> {
        let mesh = crayon::resource::factory::primitive::cube(&mut app.resources)?;
        let mat = crayon::resource::factory::material::phong(&mut app.resources)?;

        {
            let mut mat = mat.write().unwrap();
            mat.set_uniform_variable("u_Ambient", Vector3::new(1.0, 0.5, 0.31).into())?;
            mat.set_uniform_variable("u_Diffuse", Vector3::new(1.0, 0.5, 0.31).into())?;
            mat.set_uniform_variable("u_Specular", Vector3::new(0.5, 0.5, 0.5).into())?;
            mat.set_uniform_variable("u_Shininess", 32.0f32.into())?;
        }

        let cube = scene
            .world_mut()
            .build()
            .with_default::<Transform>()
            .with::<Mesh>(Mesh::new(mesh, Some(mat)))
            .finish();

        Ok(cube)
    }

    fn spawn_color_cube(mut app: &mut Application, scene: &mut Scene) -> errors::Result<Entity> {
        let mesh = crayon::resource::factory::primitive::cube(&mut app.resources)?;
        let mat = crayon::resource::factory::material::color(&mut app.resources)?;

        {
            let mut mat = mat.write().unwrap();
            let color = graphics::UniformVariable::Vector3f(Color::gray().rgb());
            mat.set_uniform_variable("u_Color", color)?;
        }

        let cube = scene
            .world_mut()
            .build()
            .with_default::<Transform>()
            .with::<Mesh>(Mesh::new(mesh, Some(mat)))
            .finish();
        Ok(cube)
    }
}

impl ApplicationInstance for Window {
    fn on_update(&mut self, mut app: &mut Application) -> errors::Result<()> {
        // Rotate cube.
        let translation = if app.input.is_key_down(KeyboardButton::W) {
            Vector3::unit_z()
        } else if app.input.is_key_down(KeyboardButton::S) {
            Vector3::unit_z() * -1.0
        } else if app.input.is_key_down(KeyboardButton::D) {
            Vector3::unit_x()
        } else if app.input.is_key_down(KeyboardButton::A) {
            Vector3::unit_x() * -1.0
        } else if app.input.is_key_down(KeyboardButton::Q) {
            Vector3::unit_y()
        } else if app.input.is_key_down(KeyboardButton::E) {
            Vector3::unit_y() * -1.0
        } else {
            Vector3::new(0.0, 0.0, 0.0)
        };

        let rotation = Quaternion::from(math::Euler {
                                            x: math::Deg(0.0f32),
                                            y: math::Deg(1.0f32),
                                            z: math::Deg(0.0f32),
                                        });

        for cube in &self.cubes {
            self.scene
                .world()
                .fetch_mut::<Transform>(*cube)
                .unwrap()
                .translate(translation);

            // self.scene
            //     .world()
            //     .fetch_mut::<Transform>(*cube)
            //     .unwrap()
            //     .rotate(rotation);
        }

        self.scene
            .world()
            .fetch_mut::<Transform>(self.light)
            .unwrap()
            .rotate(rotation);

        {
            let mut camera = self.scene
                .world_mut()
                .fetch_mut::<Camera>(self.camera)
                .unwrap();
            camera.set_clip_plane(0.1, self.far);
        }

        // Run one frame of scene.
        self.scene.run_one_frame(&mut app)?;

        Ok(())
    }
}

fn main() {
    let mut settings = Settings::default();
    settings.engine.max_fps = 60;
    settings.window.width = 480;
    settings.window.height = 480;

    let manifest = "examples/compiled-resources/manifest";
    let mut app = Application::new_with(settings).unwrap();
    app.resources.load_manifest(manifest).unwrap();

    let mut window = Window::new(&mut app).unwrap();
    app.run(&mut window).unwrap();
}<|endoftext|>


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

//! The Rust Prelude
//!
//! Because `std` is required by most serious Rust software, it is
//! imported at the topmost level of every crate by default, as if
//! each crate contains the following:
//!
//! ```ignore
//! extern crate std;
//! ```
//!
//! This means that the contents of std can be accessed from any context
//! with the `std::` path prefix, as in `use std::vec`, `use std::thread::spawn`,
//! etc.
//!
//! Additionally, `std` contains a versioned *prelude* that reexports many of the
//! most common traits, types, and functions. *The contents of the prelude are
//! imported into every module by default*.  Implicitly, all modules behave as if
//! they contained the following [`use` statement][book-use]:
//!
//! [book-use]: ../../book/crates-and-modules.html#importing-modules-with-use
//!
//! ```ignore
//! use std::prelude::v1::*;
//! ```
//!
//! The prelude is primarily concerned with exporting *traits* that
//! are so pervasive that they would be onerous to import for every use,
//! particularly those that are commonly mentioned in [generic type
//! bounds][book-traits].
//!
//! The current version of the prelude (version 1) lives in
//! [`std::prelude::v1`](v1/index.html), and reexports the following.
//!
//! * `std::marker::`{
//!     [`Copy`](../marker/trait.Copy.html),
//!     [`Send`](../marker/trait.Send.html),
//!     [`Sized`](../marker/trait.Sized.html),
//!     [`Sync`](../marker/trait.Sync.html)
//!   }.
//!   The marker traits indicate fundamental properties of types.
//! * `std::ops::`{
//!     [`Drop`](../ops/trait.Drop.html),
//!     [`Fn`](../ops/trait.Fn.html),
//!     [`FnMut`](../ops/trait.FnMut.html),
//!     [`FnOnce`](../ops/trait.FnOnce.html)
//!   }.
//!   The [destructor][book-dtor] trait and the
//!   [closure][book-closures] traits, reexported from the same
//!   [module that also defines overloaded
//!   operators](../ops/index.html).
//! * `std::mem::`[`drop`](../mem/fn.drop.html).
//!   A convenience function for explicitly dropping a value.
//! * `std::boxed::`[`Box`](../boxed/struct.Box.html).
//!   The owned heap pointer.
//! * `std::borrow::`[`ToOwned`](../borrow/trait.ToOwned.html).
//!   The conversion trait that defines `to_owned`, the generic method
//!   for creating an owned type from a borrowed type.
//! * `std::clone::`[`Clone`](../clone/trait.Clone.html).
//!   The ubiquitous trait that defines `clone`, the method for
//!   producing copies of values that are consider expensive to copy.
//! * `std::cmp::`{
//!     [`PartialEq`](../cmp/trait.PartialEq.html),
//!     [`PartialOrd`](../cmp/trait.PartialOrd.html),
//!     [`Eq`](../cmp/trait.Eq.html),
//!     [`Ord`](../cmp/trait.Ord.html)
//!   }.
//!   The comparision traits, which implement the comparison operators
//!   and are often seen in trait bounds.
//! * `std::convert::`{
//!     [`AsRef`](../convert/trait.AsRef.html),
//!     [`AsMut`](../convert/trait.AsMut.html),
//!     [`Into`](../convert/trait.Into.html),
//!     [`From`](../convert/trait.From.html)
//!   }.
//!   Generic conversions, used by savvy API authors to create
//!   overloaded methods.
//! * `std::default::`[`Default`](../default/trait.Default).
//!   Types that have default values.
//! * `std::iter::`{
//!     [`Iterator`](../iter/trait.Iterator.html),
//!     [`Extend`](../iter/trait.Extend.html),
//!     [`IntoIterator`](../iter/trait.IntoIterator.html),
//!     [`DoubleEndedIterator`](../iter/trait.DoubleEndedIterator.html),
//!     [`ExactSizeIterator`](../iter/trait.ExactSizeIterator.html)
//!   }.
//!   [Iterators][book-iter].
//! * `std::option::Option::`{
//!     [`self`](../option/enum.Option.html),
//!     [`Some`](../option/enum.Option.html),
//!     [`None`](../option/enum.Option.html)
//!   }.
//!   The ubiquitous `Option` type and its two [variants][book-enums],
//!   `Some` and `None`.
//! * `std::result::Result::`{
//!     [`self`](../result/enum.Result.html),
//!     [`Some`](../result/enum.Result.html),
//!     [`None`](../result/enum.Result.html)
//!   }.
//!   The ubiquitous `Result` type and its two [variants][book-enums],
//!   `Ok` and `Err`.
//! * `std::slice::`[`SliceConcatExt`](../slice/trait.SliceConcatExt.html).
//!   An unstable extension to slices that shouldn't have to exist.
//! * `std::string::`{
//!     [`String`](../string/struct.String.html),
//!     [`ToString`](../string/trait.ToString.html)
//!   }.
//!   Heap allocated strings.
//! * `std::vec::`[`Vec`](../vec/struct.Vec.html).
//!   Heap allocated vectors.
//!
//! [book-traits]: ../../book/traits.html
//! [book-closures]: ../../book/closures.html
//! [book-dtor]: ../../book/drop.html
//! [book-iter]: ../../book/iterators.html
//! [book-enums]: ../../book/enums.html

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

pub mod v1;
<commit_msg>Rollup merge of #28253 - murarth:prelude-typo, r=steveklabnik<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! The Rust Prelude
//!
//! Because `std` is required by most serious Rust software, it is
//! imported at the topmost level of every crate by default, as if
//! each crate contains the following:
//!
//! ```ignore
//! extern crate std;
//! ```
//!
//! This means that the contents of std can be accessed from any context
//! with the `std::` path prefix, as in `use std::vec`, `use std::thread::spawn`,
//! etc.
//!
//! Additionally, `std` contains a versioned *prelude* that reexports many of the
//! most common traits, types, and functions. *The contents of the prelude are
//! imported into every module by default*.  Implicitly, all modules behave as if
//! they contained the following [`use` statement][book-use]:
//!
//! [book-use]: ../../book/crates-and-modules.html#importing-modules-with-use
//!
//! ```ignore
//! use std::prelude::v1::*;
//! ```
//!
//! The prelude is primarily concerned with exporting *traits* that
//! are so pervasive that they would be onerous to import for every use,
//! particularly those that are commonly mentioned in [generic type
//! bounds][book-traits].
//!
//! The current version of the prelude (version 1) lives in
//! [`std::prelude::v1`](v1/index.html), and reexports the following.
//!
//! * `std::marker::`{
//!     [`Copy`](../marker/trait.Copy.html),
//!     [`Send`](../marker/trait.Send.html),
//!     [`Sized`](../marker/trait.Sized.html),
//!     [`Sync`](../marker/trait.Sync.html)
//!   }.
//!   The marker traits indicate fundamental properties of types.
//! * `std::ops::`{
//!     [`Drop`](../ops/trait.Drop.html),
//!     [`Fn`](../ops/trait.Fn.html),
//!     [`FnMut`](../ops/trait.FnMut.html),
//!     [`FnOnce`](../ops/trait.FnOnce.html)
//!   }.
//!   The [destructor][book-dtor] trait and the
//!   [closure][book-closures] traits, reexported from the same
//!   [module that also defines overloaded
//!   operators](../ops/index.html).
//! * `std::mem::`[`drop`](../mem/fn.drop.html).
//!   A convenience function for explicitly dropping a value.
//! * `std::boxed::`[`Box`](../boxed/struct.Box.html).
//!   The owned heap pointer.
//! * `std::borrow::`[`ToOwned`](../borrow/trait.ToOwned.html).
//!   The conversion trait that defines `to_owned`, the generic method
//!   for creating an owned type from a borrowed type.
//! * `std::clone::`[`Clone`](../clone/trait.Clone.html).
//!   The ubiquitous trait that defines `clone`, the method for
//!   producing copies of values that are consider expensive to copy.
//! * `std::cmp::`{
//!     [`PartialEq`](../cmp/trait.PartialEq.html),
//!     [`PartialOrd`](../cmp/trait.PartialOrd.html),
//!     [`Eq`](../cmp/trait.Eq.html),
//!     [`Ord`](../cmp/trait.Ord.html)
//!   }.
//!   The comparision traits, which implement the comparison operators
//!   and are often seen in trait bounds.
//! * `std::convert::`{
//!     [`AsRef`](../convert/trait.AsRef.html),
//!     [`AsMut`](../convert/trait.AsMut.html),
//!     [`Into`](../convert/trait.Into.html),
//!     [`From`](../convert/trait.From.html)
//!   }.
//!   Generic conversions, used by savvy API authors to create
//!   overloaded methods.
//! * `std::default::`[`Default`](../default/trait.Default).
//!   Types that have default values.
//! * `std::iter::`{
//!     [`Iterator`](../iter/trait.Iterator.html),
//!     [`Extend`](../iter/trait.Extend.html),
//!     [`IntoIterator`](../iter/trait.IntoIterator.html),
//!     [`DoubleEndedIterator`](../iter/trait.DoubleEndedIterator.html),
//!     [`ExactSizeIterator`](../iter/trait.ExactSizeIterator.html)
//!   }.
//!   [Iterators][book-iter].
//! * `std::option::Option::`{
//!     [`self`](../option/enum.Option.html),
//!     [`Some`](../option/enum.Option.html),
//!     [`None`](../option/enum.Option.html)
//!   }.
//!   The ubiquitous `Option` type and its two [variants][book-enums],
//!   `Some` and `None`.
//! * `std::result::Result::`{
//!     [`self`](../result/enum.Result.html),
//!     [`Ok`](../result/enum.Result.html),
//!     [`Err`](../result/enum.Result.html)
//!   }.
//!   The ubiquitous `Result` type and its two [variants][book-enums],
//!   `Ok` and `Err`.
//! * `std::slice::`[`SliceConcatExt`](../slice/trait.SliceConcatExt.html).
//!   An unstable extension to slices that shouldn't have to exist.
//! * `std::string::`{
//!     [`String`](../string/struct.String.html),
//!     [`ToString`](../string/trait.ToString.html)
//!   }.
//!   Heap allocated strings.
//! * `std::vec::`[`Vec`](../vec/struct.Vec.html).
//!   Heap allocated vectors.
//!
//! [book-traits]: ../../book/traits.html
//! [book-closures]: ../../book/closures.html
//! [book-dtor]: ../../book/drop.html
//! [book-iter]: ../../book/iterators.html
//! [book-enums]: ../../book/enums.html

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

pub mod v1;
<|endoftext|>


<commit_before><commit_msg>Just produce one at a time.<commit_after><|endoftext|>


<commit_before><commit_msg>Working on it more<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2014, David Renshaw (dwrenshaw@gmail.com)
 *
 * See the LICENSE file in the capnproto-rust root directory.
 */

use std;
use std::vec::Vec;
use any_pointer;
use capability::ClientHook;
use common::*;
use arena::{BuilderArena, ReaderArena, SegmentBuilder, SegmentReader, NumWords, ZeroedWords};
use layout;
use layout::{FromStructBuilder, HasStructSize};

pub struct ReaderOptions {
    pub traversal_limit_in_words : u64,
    pub nesting_limit : i32,

    // If true, malformed messages trigger task failure.
    // If false, malformed messages fall back to default values.
    pub fail_fast : bool,
}

pub const DEFAULT_READER_OPTIONS : ReaderOptions =
    ReaderOptions { traversal_limit_in_words : 8 * 1024 * 1024, nesting_limit : 64,
                    fail_fast : true };

impl ReaderOptions {
    pub fn new() -> ReaderOptions { DEFAULT_READER_OPTIONS }

    pub fn nesting_limit<'a>(&'a mut self, value : i32) -> &'a mut ReaderOptions {
        self.nesting_limit = value;
        return self;
    }

    pub fn traversal_limit_in_words<'a>(&'a mut self, value : u64) -> &'a mut ReaderOptions {
        self.traversal_limit_in_words = value;
        return self;
    }

    pub fn fail_fast<'a>(&'a mut self, value : bool) -> &'a mut ReaderOptions {
        self.fail_fast = value;
        return self;
    }
}

type SegmentId = u32;

pub trait MessageReader<'a> {
    fn get_segment(&self, id : uint) -> &[Word];
    fn arena(&self) -> &ReaderArena;
    fn mut_arena(&mut self) -> &mut ReaderArena;
    fn get_options(&self) -> &ReaderOptions;

    fn get_root_internal(&self) -> any_pointer::Reader {
        unsafe {
            let segment : *const SegmentReader = &self.arena().segment0;

            let pointer_reader = layout::PointerReader::get_root(
                segment, (*segment).get_start_ptr(), self.get_options().nesting_limit);

            any_pointer::Reader::new(pointer_reader)
        }
    }

    fn get_root<T : layout::FromStructReader<'a>>(&'a self) -> T {
        self.get_root_internal().get_as_struct()
    }

    fn init_cap_table(&mut self, cap_table : Vec<Option<Box<ClientHook+Send>>>) {
        self.mut_arena().init_cap_table(cap_table);
    }
}

pub struct SegmentArrayMessageReader<'a> {
    segments : &'a [ &'a [Word]],
    options : ReaderOptions,
    arena : Box<ReaderArena>
}

impl <'a> MessageReader<'a> for SegmentArrayMessageReader<'a> {
    fn get_segment<'b>(&'b self, id : uint) -> &'b [Word] {
        self.segments[id]
    }

    fn arena<'b>(&'b self) -> &'b ReaderArena { &*self.arena }
    fn mut_arena<'b>(&'b mut self) -> &'b mut ReaderArena { &mut *self.arena }

    fn get_options<'b>(&'b self) -> &'b ReaderOptions {
        return &self.options;
    }
}

impl <'a> SegmentArrayMessageReader<'a> {

    pub fn new<'b>(segments : &'b [&'b [Word]], options : ReaderOptions) -> SegmentArrayMessageReader<'b> {
        assert!(segments.len() > 0);
        SegmentArrayMessageReader {
            segments : segments,
            arena : ReaderArena::new(segments, options),
            options : options
        }
    }
}

pub enum AllocationStrategy {
    FixedSize,
    GrowHeuristically
}

pub const SUGGESTED_FIRST_SEGMENT_WORDS : u32 = 1024;
pub const SUGGESTED_ALLOCATION_STRATEGY : AllocationStrategy = GrowHeuristically;

pub struct BuilderOptions {
    pub first_segment_words : u32,
    pub allocation_strategy : AllocationStrategy,

    // If true, malformed messages trigger task failure.
    // If false, malformed messages fall back to default values.
    pub fail_fast : bool,
}

impl BuilderOptions {
    pub fn new() -> BuilderOptions {
        BuilderOptions {first_segment_words : SUGGESTED_FIRST_SEGMENT_WORDS,
                        allocation_strategy : GrowHeuristically,
                        fail_fast : true }
    }

    pub fn first_segment_words<'a>(&'a mut self, value : u32) -> &'a mut BuilderOptions {
        self.first_segment_words = value;
        return self;
    }

    pub fn allocation_strategy<'a>(&'a mut self, value : AllocationStrategy) -> &'a mut BuilderOptions {
        self.allocation_strategy = value;
        return self;
    }

    pub fn fail_fast<'a>(&'a mut self, value : bool) -> &'a mut BuilderOptions {
        self.fail_fast = value;
        return self;
    }
}

pub trait MessageBuilder<'a> {
    fn mut_arena(&mut self) -> &mut BuilderArena;
    fn arena(&self) -> &BuilderArena;

    // XXX is there a way to make this private?
    fn get_root_internal(&mut self) -> any_pointer::Builder<'a> {
        let root_segment = &mut self.mut_arena().segment0 as *mut SegmentBuilder;

        if self.arena().segment0.current_size() == 0 {
            match self.mut_arena().segment0.allocate(WORDS_PER_POINTER as u32) {
                None => {panic!("could not allocate root pointer") }
                Some(location) => {
                    assert!(location == self.arena().segment0.get_ptr_unchecked(0),
                            "First allocated word of new segment was not at offset 0");

                    any_pointer::Builder::new(layout::PointerBuilder::get_root(root_segment, location))

                }
            }
        } else {
            any_pointer::Builder::new(
                layout::PointerBuilder::get_root(root_segment,
                                                 self.arena().segment0.get_ptr_unchecked(0)))
        }

    }

    fn init_root<T : FromStructBuilder<'a> + HasStructSize>(&mut self) -> T {
        self.get_root_internal().init_as_struct()
    }

    fn get_root<T : FromStructBuilder<'a> + HasStructSize>(&mut self) -> T {
        self.get_root_internal().get_as_struct()
    }

    fn set_root<T : layout::ToStructReader<'a>>(&mut self, value : &T) {
        self.get_root_internal().set_as_struct(value);
    }

    fn get_segments_for_output<T>(&self, cont : |&[&[Word]]| -> T) -> T {
        self.arena().get_segments_for_output(cont)
    }

    fn get_cap_table<'a>(&'a self) -> &'a [Option<Box<ClientHook+Send>>] {
        self.arena().get_cap_table()
    }
}

pub struct MallocMessageBuilder {
    arena : Box<BuilderArena>,
}

impl Drop for MallocMessageBuilder {
    fn drop(&mut self) { }
}

impl MallocMessageBuilder {

    pub fn new(options : BuilderOptions) -> MallocMessageBuilder {
        let arena = BuilderArena::new(options.allocation_strategy,
                                      NumWords(options.first_segment_words),
                                      options.fail_fast);

        MallocMessageBuilder { arena : arena }
    }

    pub fn new_default() -> MallocMessageBuilder {
        MallocMessageBuilder::new(BuilderOptions::new())
    }

}

impl <'a> MessageBuilder<'a> for MallocMessageBuilder {
    fn mut_arena(&mut self) -> &mut BuilderArena {
        &mut *self.arena
    }
    fn arena(&self) -> &BuilderArena {
        & *self.arena
    }
}

pub struct ScratchSpaceMallocMessageBuilder<'a> {
    arena : Box<BuilderArena>,
    scratch_space : &'a mut [Word],
}

// TODO: figure out why rust thinks this is unsafe.
#[unsafe_destructor]
impl <'a> Drop for ScratchSpaceMallocMessageBuilder<'a> {
    fn drop(&mut self) {
        let ptr = self.scratch_space.as_mut_ptr();
        self.get_segments_for_output(|segments| {
                unsafe {
                    std::ptr::zero_memory(ptr, segments[0].len());
                }
            });
    }
}

impl <'a> ScratchSpaceMallocMessageBuilder<'a> {

    pub fn new<'b>(scratch_space : &'b mut [Word], options : BuilderOptions)
               -> ScratchSpaceMallocMessageBuilder<'b> {
        let arena = BuilderArena::new(options.allocation_strategy, ZeroedWords(scratch_space),
                                      options.fail_fast);

        ScratchSpaceMallocMessageBuilder { arena : arena, scratch_space : scratch_space }
    }

    pub fn new_default<'b>(scratch_space : &'b mut [Word]) -> ScratchSpaceMallocMessageBuilder<'b> {
        ScratchSpaceMallocMessageBuilder::new(scratch_space, BuilderOptions::new())
    }

}

impl <'a> MessageBuilder<'a> for ScratchSpaceMallocMessageBuilder<'a> {
    fn mut_arena(&mut self) -> &mut BuilderArena {
        &mut *self.arena
    }
    fn arena(&self) -> &BuilderArena {
        & *self.arena
    }
}
<commit_msg>add missing lifetime parameters for #18<commit_after>/*
 * Copyright (c) 2013-2014, David Renshaw (dwrenshaw@gmail.com)
 *
 * See the LICENSE file in the capnproto-rust root directory.
 */

use std;
use std::vec::Vec;
use any_pointer;
use capability::ClientHook;
use common::*;
use arena::{BuilderArena, ReaderArena, SegmentBuilder, SegmentReader, NumWords, ZeroedWords};
use layout;
use layout::{FromStructBuilder, HasStructSize};

pub struct ReaderOptions {
    pub traversal_limit_in_words : u64,
    pub nesting_limit : i32,

    // If true, malformed messages trigger task failure.
    // If false, malformed messages fall back to default values.
    pub fail_fast : bool,
}

pub const DEFAULT_READER_OPTIONS : ReaderOptions =
    ReaderOptions { traversal_limit_in_words : 8 * 1024 * 1024, nesting_limit : 64,
                    fail_fast : true };

impl ReaderOptions {
    pub fn new() -> ReaderOptions { DEFAULT_READER_OPTIONS }

    pub fn nesting_limit<'a>(&'a mut self, value : i32) -> &'a mut ReaderOptions {
        self.nesting_limit = value;
        return self;
    }

    pub fn traversal_limit_in_words<'a>(&'a mut self, value : u64) -> &'a mut ReaderOptions {
        self.traversal_limit_in_words = value;
        return self;
    }

    pub fn fail_fast<'a>(&'a mut self, value : bool) -> &'a mut ReaderOptions {
        self.fail_fast = value;
        return self;
    }
}

type SegmentId = u32;

pub trait MessageReader<'a> {
    fn get_segment(&self, id : uint) -> &[Word];
    fn arena(&self) -> &ReaderArena;
    fn mut_arena(&mut self) -> &mut ReaderArena;
    fn get_options(&self) -> &ReaderOptions;

    fn get_root_internal(&self) -> any_pointer::Reader {
        unsafe {
            let segment : *const SegmentReader = &self.arena().segment0;

            let pointer_reader = layout::PointerReader::get_root(
                segment, (*segment).get_start_ptr(), self.get_options().nesting_limit);

            any_pointer::Reader::new(pointer_reader)
        }
    }

    fn get_root<T : layout::FromStructReader<'a>>(&'a self) -> T {
        self.get_root_internal().get_as_struct()
    }

    fn init_cap_table(&mut self, cap_table : Vec<Option<Box<ClientHook+Send>>>) {
        self.mut_arena().init_cap_table(cap_table);
    }
}

pub struct SegmentArrayMessageReader<'a> {
    segments : &'a [ &'a [Word]],
    options : ReaderOptions,
    arena : Box<ReaderArena>
}

impl <'a> MessageReader<'a> for SegmentArrayMessageReader<'a> {
    fn get_segment<'b>(&'b self, id : uint) -> &'b [Word] {
        self.segments[id]
    }

    fn arena<'b>(&'b self) -> &'b ReaderArena { &*self.arena }
    fn mut_arena<'b>(&'b mut self) -> &'b mut ReaderArena { &mut *self.arena }

    fn get_options<'b>(&'b self) -> &'b ReaderOptions {
        return &self.options;
    }
}

impl <'a> SegmentArrayMessageReader<'a> {

    pub fn new<'b>(segments : &'b [&'b [Word]], options : ReaderOptions) -> SegmentArrayMessageReader<'b> {
        assert!(segments.len() > 0);
        SegmentArrayMessageReader {
            segments : segments,
            arena : ReaderArena::new(segments, options),
            options : options
        }
    }
}

pub enum AllocationStrategy {
    FixedSize,
    GrowHeuristically
}

pub const SUGGESTED_FIRST_SEGMENT_WORDS : u32 = 1024;
pub const SUGGESTED_ALLOCATION_STRATEGY : AllocationStrategy = GrowHeuristically;

pub struct BuilderOptions {
    pub first_segment_words : u32,
    pub allocation_strategy : AllocationStrategy,

    // If true, malformed messages trigger task failure.
    // If false, malformed messages fall back to default values.
    pub fail_fast : bool,
}

impl BuilderOptions {
    pub fn new() -> BuilderOptions {
        BuilderOptions {first_segment_words : SUGGESTED_FIRST_SEGMENT_WORDS,
                        allocation_strategy : GrowHeuristically,
                        fail_fast : true }
    }

    pub fn first_segment_words<'a>(&'a mut self, value : u32) -> &'a mut BuilderOptions {
        self.first_segment_words = value;
        return self;
    }

    pub fn allocation_strategy<'a>(&'a mut self, value : AllocationStrategy) -> &'a mut BuilderOptions {
        self.allocation_strategy = value;
        return self;
    }

    pub fn fail_fast<'a>(&'a mut self, value : bool) -> &'a mut BuilderOptions {
        self.fail_fast = value;
        return self;
    }
}

pub trait MessageBuilder<'a> {
    fn mut_arena(&mut self) -> &mut BuilderArena;
    fn arena(&self) -> &BuilderArena;

    // XXX is there a way to make this private?
    fn get_root_internal(&mut self) -> any_pointer::Builder<'a> {
        let root_segment = &mut self.mut_arena().segment0 as *mut SegmentBuilder;

        if self.arena().segment0.current_size() == 0 {
            match self.mut_arena().segment0.allocate(WORDS_PER_POINTER as u32) {
                None => {panic!("could not allocate root pointer") }
                Some(location) => {
                    assert!(location == self.arena().segment0.get_ptr_unchecked(0),
                            "First allocated word of new segment was not at offset 0");

                    any_pointer::Builder::new(layout::PointerBuilder::get_root(root_segment, location))

                }
            }
        } else {
            any_pointer::Builder::new(
                layout::PointerBuilder::get_root(root_segment,
                                                 self.arena().segment0.get_ptr_unchecked(0)))
        }

    }

    fn init_root<T : FromStructBuilder<'a> + HasStructSize>(&'a mut self) -> T {
        self.get_root_internal().init_as_struct()
    }

    fn get_root<T : FromStructBuilder<'a> + HasStructSize>(&'a mut self) -> T {
        self.get_root_internal().get_as_struct()
    }

    fn set_root<T : layout::ToStructReader<'a>>(&'a mut self, value : &T) {
        self.get_root_internal().set_as_struct(value);
    }

    fn get_segments_for_output<T>(&self, cont : |&[&[Word]]| -> T) -> T {
        self.arena().get_segments_for_output(cont)
    }

    fn get_cap_table<'a>(&'a self) -> &'a [Option<Box<ClientHook+Send>>] {
        self.arena().get_cap_table()
    }
}

pub struct MallocMessageBuilder {
    arena : Box<BuilderArena>,
}

impl Drop for MallocMessageBuilder {
    fn drop(&mut self) { }
}

impl MallocMessageBuilder {

    pub fn new(options : BuilderOptions) -> MallocMessageBuilder {
        let arena = BuilderArena::new(options.allocation_strategy,
                                      NumWords(options.first_segment_words),
                                      options.fail_fast);

        MallocMessageBuilder { arena : arena }
    }

    pub fn new_default() -> MallocMessageBuilder {
        MallocMessageBuilder::new(BuilderOptions::new())
    }

}

impl <'a> MessageBuilder<'a> for MallocMessageBuilder {
    fn mut_arena(&mut self) -> &mut BuilderArena {
        &mut *self.arena
    }
    fn arena(&self) -> &BuilderArena {
        & *self.arena
    }
}

pub struct ScratchSpaceMallocMessageBuilder<'a> {
    arena : Box<BuilderArena>,
    scratch_space : &'a mut [Word],
}

// TODO: figure out why rust thinks this is unsafe.
#[unsafe_destructor]
impl <'a> Drop for ScratchSpaceMallocMessageBuilder<'a> {
    fn drop(&mut self) {
        let ptr = self.scratch_space.as_mut_ptr();
        self.get_segments_for_output(|segments| {
                unsafe {
                    std::ptr::zero_memory(ptr, segments[0].len());
                }
            });
    }
}

impl <'a> ScratchSpaceMallocMessageBuilder<'a> {

    pub fn new<'b>(scratch_space : &'b mut [Word], options : BuilderOptions)
               -> ScratchSpaceMallocMessageBuilder<'b> {
        let arena = BuilderArena::new(options.allocation_strategy, ZeroedWords(scratch_space),
                                      options.fail_fast);

        ScratchSpaceMallocMessageBuilder { arena : arena, scratch_space : scratch_space }
    }

    pub fn new_default<'b>(scratch_space : &'b mut [Word]) -> ScratchSpaceMallocMessageBuilder<'b> {
        ScratchSpaceMallocMessageBuilder::new(scratch_space, BuilderOptions::new())
    }

}

impl <'a> MessageBuilder<'a> for ScratchSpaceMallocMessageBuilder<'a> {
    fn mut_arena(&mut self) -> &mut BuilderArena {
        &mut *self.arena
    }
    fn arena(&self) -> &BuilderArena {
        & *self.arena
    }
}
<|endoftext|>


<commit_before><commit_msg>Add m.presence event.<commit_after><|endoftext|>