<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::io::ErrorKind;
use std::fs::{OpenOptions, read_dir};
use std::os::linux::fs::MetadataExt;
use std::path::PathBuf;
use std::str::FromStr;

use nix::Errno;
use nix::sys::stat::{S_IFBLK, S_IFMT};
use serde_json;

use devicemapper::Device;

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

use super::blockdev::BlockDev;
use super::device::blkdev_size;
use super::engine::DevOwnership;
use super::metadata::{BDA, StaticHeader};
use super::range_alloc::RangeAllocator;
use super::serde_structs::PoolSave;

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

    let mut pool_map = HashMap::new();
    for dir_e in try!(read_dir("/dev")) {
        let dir_e = try!(dir_e);
        let mode = try!(dir_e.metadata()).st_mode();

        // Device node can't belong to Stratis if it is not a block device
        if mode & S_IFMT.bits() != S_IFBLK.bits() {
            continue;
        }

        let devnode = dir_e.path();

        let f = OpenOptions::new().read(true).open(&devnode);

        // 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.
        if f.is_err() {
            let err = f.unwrap_err();
            match err.kind() {
                ErrorKind::NotFound => {
                    continue;
                }
                _ => {
                    if let Some(errno) = err.raw_os_error() {
                        match Errno::from_i32(errno) {
                            Errno::ENXIO | Errno::ENOMEDIUM => continue,
                            _ => return Err(EngineError::Io(err)),
                        };
                    } else {
                        return Err(EngineError::Io(err));
                    }
                }
            }
        }

        let mut f = f.expect("unreachable if f is err");
        if let DevOwnership::Ours(uuid) = try!(StaticHeader::determine_ownership(&mut f)) {
            pool_map
                .entry(uuid)
                .or_insert_with(Vec::new)
                .push(devnode)
        };
    }

    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.
pub fn get_metadata(pool_uuid: PoolUuid, devnodes: &[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 {
        let bda = try!(BDA::load(&mut try!(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 succesfully read";
    Err(EngineError::Engine(ErrorEnum::NotFound, err_str.into()))
}

/// Get all the blockdevs corresponding to this pool that can be obtained from
/// this list of devnodes.
/// Returns an error if the blockdevs obtained do not match the metadata.
pub fn get_blockdevs(pool_uuid: PoolUuid,
                     pool_save: &PoolSave,
                     devnodes: &[PathBuf])
                     -> EngineResult<Vec<BlockDev>> {
    let segments = pool_save
        .flex_devs
        .meta_dev
        .iter()
        .chain(pool_save.flex_devs.thin_meta_dev.iter())
        .chain(pool_save.flex_devs.thin_data_dev.iter());

    let mut segment_table = HashMap::new();
    for seg in segments {
        segment_table
            .entry(seg.0)
            .or_insert(vec![])
            .push((seg.1, seg.2))
    }

    let mut blockdevs = vec![];
    let mut devices = HashSet::new();
    for dev in devnodes {
        let device = try!(Device::from_str(&dev.to_string_lossy()));

        // If we've seen this device already, skip it.
        if !devices.insert(device) {
            continue;
        }

        let bda = try!(BDA::load(&mut try!(OpenOptions::new().read(true).open(dev))));
        if let Some(bda) = bda {
            if *bda.pool_uuid() == pool_uuid {
                let actual_size = try!(blkdev_size(&try!(OpenOptions::new().read(true).open(dev))))
                    .sectors();

                // If size of 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,
                // RangeAllocator::new() will return an error.
                let allocator =
                    try!(RangeAllocator::new(actual_size,
                                             segment_table.get(bda.dev_uuid()).unwrap_or(&vec![])));

                blockdevs.push(BlockDev::new(device, dev.clone(), bda, allocator));
            }
        }
    }

    // Verify that blockdevs found match blockdevs recorded.
    let current_uuids: HashSet<_> = blockdevs.iter().map(|b| *b.uuid()).collect();
    let recorded_uuids: HashSet<_> = pool_save.block_devs.keys().map(|u| *u).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>Construct the default Vec lazily<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::io::ErrorKind;
use std::fs::{OpenOptions, read_dir};
use std::os::linux::fs::MetadataExt;
use std::path::PathBuf;
use std::str::FromStr;

use nix::Errno;
use nix::sys::stat::{S_IFBLK, S_IFMT};
use serde_json;

use devicemapper::Device;

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

use super::blockdev::BlockDev;
use super::device::blkdev_size;
use super::engine::DevOwnership;
use super::metadata::{BDA, StaticHeader};
use super::range_alloc::RangeAllocator;
use super::serde_structs::PoolSave;

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

    let mut pool_map = HashMap::new();
    for dir_e in try!(read_dir("/dev")) {
        let dir_e = try!(dir_e);
        let mode = try!(dir_e.metadata()).st_mode();

        // Device node can't belong to Stratis if it is not a block device
        if mode & S_IFMT.bits() != S_IFBLK.bits() {
            continue;
        }

        let devnode = dir_e.path();

        let f = OpenOptions::new().read(true).open(&devnode);

        // 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.
        if f.is_err() {
            let err = f.unwrap_err();
            match err.kind() {
                ErrorKind::NotFound => {
                    continue;
                }
                _ => {
                    if let Some(errno) = err.raw_os_error() {
                        match Errno::from_i32(errno) {
                            Errno::ENXIO | Errno::ENOMEDIUM => continue,
                            _ => return Err(EngineError::Io(err)),
                        };
                    } else {
                        return Err(EngineError::Io(err));
                    }
                }
            }
        }

        let mut f = f.expect("unreachable if f is err");
        if let DevOwnership::Ours(uuid) = try!(StaticHeader::determine_ownership(&mut f)) {
            pool_map
                .entry(uuid)
                .or_insert_with(Vec::new)
                .push(devnode)
        };
    }

    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.
pub fn get_metadata(pool_uuid: PoolUuid, devnodes: &[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 {
        let bda = try!(BDA::load(&mut try!(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 succesfully read";
    Err(EngineError::Engine(ErrorEnum::NotFound, err_str.into()))
}

/// Get all the blockdevs corresponding to this pool that can be obtained from
/// this list of devnodes.
/// Returns an error if the blockdevs obtained do not match the metadata.
pub fn get_blockdevs(pool_uuid: PoolUuid,
                     pool_save: &PoolSave,
                     devnodes: &[PathBuf])
                     -> EngineResult<Vec<BlockDev>> {
    let segments = pool_save
        .flex_devs
        .meta_dev
        .iter()
        .chain(pool_save.flex_devs.thin_meta_dev.iter())
        .chain(pool_save.flex_devs.thin_data_dev.iter());

    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![];
    let mut devices = HashSet::new();
    for dev in devnodes {
        let device = try!(Device::from_str(&dev.to_string_lossy()));

        // If we've seen this device already, skip it.
        if !devices.insert(device) {
            continue;
        }

        let bda = try!(BDA::load(&mut try!(OpenOptions::new().read(true).open(dev))));
        if let Some(bda) = bda {
            if *bda.pool_uuid() == pool_uuid {
                let actual_size = try!(blkdev_size(&try!(OpenOptions::new().read(true).open(dev))))
                    .sectors();

                // If size of 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,
                // RangeAllocator::new() will return an error.
                let allocator =
                    try!(RangeAllocator::new(actual_size,
                                             segment_table.get(bda.dev_uuid()).unwrap_or(&vec![])));

                blockdevs.push(BlockDev::new(device, dev.clone(), bda, allocator));
            }
        }
    }

    // Verify that blockdevs found match blockdevs recorded.
    let current_uuids: HashSet<_> = blockdevs.iter().map(|b| *b.uuid()).collect();
    let recorded_uuids: HashSet<_> = pool_save.block_devs.keys().map(|u| *u).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>Added Rust code example of creating a default S3 client<commit_after>/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

// snippet-start:[s3.rust.client-use]
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::Client;
// snippet-end:[s3.rust.client-use]

/// Lists your buckets.
#[tokio::main]
async fn main() -> Result<(), aws_sdk_s3::Error> {
    // snippet-start:[s3.rust.client-client]
    let region_provider = RegionProviderChain::default_provider().or_else("us-east-1");
    let config = aws_config::from_env().region(region_provider).load().await;
    let client = Client::new(&config);
    // snippet-end:[s3.rust.client-client]

    let resp = client.list_buckets().send().await?;
    let buckets = resp.buckets.unwrap_or_default();
    let num_buckets = buckets.len();

    for bucket in &buckets {
        println!("{}", bucket.name.as_deref().unwrap_or_default());
    }

    println!();
    println!("Found {} buckets.", num_buckets);

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>add test for issue #20575<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.

// Test that overloaded calls work with zero arity closures

#![feature(box_syntax)]

fn main() {
    let functions: [Box<Fn() -> Option<()>>; 1] = [box || None];

    let _: Option<Vec<()>> = functions.iter().map(|f| (*f)()).collect();
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #20971. Fixes #20791.<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.

// Regression test for Issue #20971.

pub trait Parser {
    type Input;
    fn parse(&mut self, input: <Self as Parser>::Input);
}

impl Parser for () {
    type Input = ();
    fn parse(&mut self, input: ()) {

    }
}

pub fn many() -> Box<Parser<Input=<() as Parser>::Input> + 'static> {
    panic!()
}

fn main() {
    many()
        .parse(());
}
<|endoftext|>


<commit_before><commit_msg>CarbonStream doesn't need to be public.<commit_after><|endoftext|>


<commit_before><commit_msg>Added several consts from netdb.h<commit_after><|endoftext|>


<commit_before><commit_msg>Porting over pieces of the monte carlo utils from tray<commit_after>//! Defines various Monte Carlo sampling functions for sampling
//! points/directions on objects and computing the corresponding pdfs

use std::f32;
use std::num::Float;

use linalg::Vector;

/// Sample a hemisphere using a cosine distribution to produce cosine weighted samples
/// `samples` should be two random samples in range [0, 1)
/// directions returned will be in the hemisphere around (0, 0, 1)
pub fn cos_sample_hemisphere(u: &[f32]) -> Vector {
	//We use Malley's method here, generate samples on a disk then project
	//them up to the hemisphere
	let d = concentric_sample_disk(u);
	return Vector::new(d[0], d[1], Float::sqrt(Float::max(0.0, 1.0 - d[0] * d[0] - d[1] * d[1])));
}
/// Compute the PDF of the cosine weighted hemisphere sampling
pub fn cos_hemisphere_pdf(cos_theta: f32) -> f32 { cos_theta * f32::consts::FRAC_1_PI }
/// Compute concentric sample positions on a unit disk mapping input from range [0, 1)
/// to sample positions on a disk
/// `samples` should be two random samples in range [0, 1)
/// See: [Shirley and Chiu, A Low Distortion Map Between Disk and Square](https://mediatech.aalto.fi/~jaakko/T111-5310/K2013/JGT-97.pdf)
pub fn concentric_sample_disk(u: &[f32]) -> [f32; 2] {
	let mut s = [2.0 * u[0] - 1.0, 2.0 * u[1] - 1.0];
	let mut radius = 0f32;
    let mut theta = 0f32;
	if (s[0] == 0.0 && s[1] == 0.0){
		return s;
	}
	if (s[0] >= -s[1]){
		if (s[0] > s[1]){
			radius = s[0];

            if s[1] > 0.0 {
                theta = s[1] / s[0];
            } else {
                8.0 + s[1] / s[0];
            }
		}
		else {
			radius = s[1];
			theta = 2.0 - s[0] / s[1];
		}
	}
	else {
		if (s[0] <= s[1]){
			radius = -s[0];
			theta = 4.0 + s[1] / s[0];
		}
		else {
			radius = -s[1];
			if (s[1] != 0.0){
				theta = 6.0 - s[0] / s[1];
			}
			else {
				theta = 0.0;
			}
		}
	}
	theta *= f32::consts::PI / 4.0;
    s[0] = radius * Float::cos(theta);
    s[1] = radius * Float::sin(theta);
    s
}

<|endoftext|>


<commit_before>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate gfx_core;

mod vk {
    #![allow(dead_code)]
    #![allow(non_upper_case_globals)]
    #![allow(non_snake_case)]
    #![allow(non_camel_case_types)]
    include!(concat!(env!("OUT_DIR"), "/vk_bindings.rs"));
}

pub struct Backend {
    instance: vk::Instance,
}<commit_msg>[vk] basic application info<commit_after>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate gfx_core;

use std::ffi::CString;
use std::ptr;

mod vk {
    #![allow(dead_code)]
    #![allow(non_upper_case_globals)]
    #![allow(non_snake_case)]
    #![allow(non_camel_case_types)]
    include!(concat!(env!("OUT_DIR"), "/vk_bindings.rs"));
}

/// Information that can be given to the Vulkan driver so that it can identify your application.
pub struct ApplicationInfo<'a> {
    /// Name of the application.
    pub application_name: &'a str,
    /// An opaque number that contains the version number of the application.
    pub application_version: u32,
    /// Name of the engine used to power the application.
    pub engine_name: &'a str,
    /// An opaque number that contains the version number of the engine.
    pub engine_version: u32,
}

struct PhysicalDeviceInfo {
    device: vk::PhysicalDevice,
    properties: vk::PhysicalDeviceProperties,
    queue_families: Vec<vk::QueueFamilyProperties>,
    memory: vk::PhysicalDeviceMemoryProperties,
    //available_features: Features,
}

pub struct Backend {
    instance: vk::Instance,
    pointers: vk::InstancePointers,
    devices: Vec<PhysicalDeviceInfo>,
}

pub fn create(app_info: Option<&ApplicationInfo>) -> Backend {
    let mut c_app_name: CString;
    let mut c_engine_name: CString;
    let mut vk_info: vk::ApplicationInfo;

    let info_ptr = if let Some(info) = app_info {
        c_app_name = CString::new(info.application_name).unwrap();
        c_engine_name = CString::new(info.engine_name).unwrap();
        vk_info = vk::ApplicationInfo {
            sType: vk::STRUCTURE_TYPE_APPLICATION_INFO,
            pNext: ptr::null(),
            pApplicationName: c_app_name.as_ptr(),
            applicationVersion: info.application_version,
            pEngineName: c_engine_name.as_ptr(),
            engineVersion: info.engine_version,
            apiVersion: 0x1000, //TODO
        };
        &vk_info as *const _
    }else {
        ptr::null()
    };

    let create_info = vk::InstanceCreateInfo {
        sType: vk::STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
        pNext: ptr::null(),
        flags: 0,
        pApplicationInfo: info_ptr,
        enabledLayerCount: 0, //TODO
        ppEnabledLayerNames: ptr::null(), //TODO
        enabledExtensionCount: 0, //TODO
        ppEnabledExtensionNames: ptr::null(), //TODO
    };

    Backend {

    }
}
<|endoftext|>


<commit_before>extern crate orbclient;

extern crate tetrahedrane;

use tetrahedrane::vid::*;
use tetrahedrane::start;

fn main() {

    let mut window = start::Window::new(640, 480, "Hello!", 1 as usize);

    window.window.set(Color::new(20, 40, 60).orb_color());

    let mut point1 = DepthPoint::new(0.0, -0.5, 3.0);
    let mut point2 = DepthPoint::new(0.5, 0.5, 3.0);
    let mut point3 = DepthPoint::new(-0.5, 0.5, 3.0);

    let triangle = Triangle::new(point1, point2, point3, 0.0, 0.0, 0.0, Color::new(200, 200, 200));

    'game_loop: loop {
        window.window.set(Color::new(20, 40, 60).orb_color());

        window.camera_z += 0.01;

        window.render_queue.push(triangle);
        window.render();

        window.window.sync();

        std::thread::sleep(std::time::Duration::from_millis(33));
    }
}<commit_msg>Made triangle example better<commit_after>extern crate tetrahedrane;

use tetrahedrane::vid::*;
use tetrahedrane::start;

fn main() {

    let mut window = start::Window::new(640, 480, "Hello World!", 1 as usize);

    window.window.set(Color::new(20, 40, 60).orb_color());

    let triangle = Triangle::new(DepthPoint::new(0.0, -0.5, 3.0),
                                 DepthPoint::new(0.5, 0.5, 3.0),
                                 DepthPoint::new(-0.5, 0.5, 3.0),
                                 0.0, 0.0, 0.0,
                                 Color::new(200, 200, 200));

    'game_loop: loop {
        window.window.set(Color::new(20, 40, 60).orb_color());

        window.render_queue.push(triangle);
        window.render();

        window.window.sync();

        std::thread::sleep(std::time::Duration::from_millis(33));
    }
}<|endoftext|>


<commit_before><commit_msg>Add to_chain_id: allow converting addtional to actual chain_id<commit_after><|endoftext|>


<commit_before>extern crate futures;
extern crate futures_cpupool;

use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;

use futures::{Future, BoxFuture};
use futures::task::{Executor, Task, Run};
use futures_cpupool::CpuPool;

// TODO: centralize this?
pub trait ForgetExt {
    fn forget(self);
}

impl<F> ForgetExt for F
    where F: Future + Sized + Send + 'static,
          F::Item: Send,
          F::Error: Send
{
    fn forget(self) {
        use std::sync::Arc;

        struct ForgetExec;

        impl Executor for ForgetExec {
            fn execute(&self, run: Run) {
                run.run()
            }
        }

        Task::new(Arc::new(ForgetExec), self.then(|_| Ok(())).boxed()).unpark();
    }
}

fn get<F>(f: F) -> Result<F::Item, F::Error>
    where F: Future + Send + 'static,
          F::Item: Send,
          F::Error: Send,
{
    let (tx, rx) = channel();
    f.then(move |res| {
        tx.send(res).unwrap();
        futures::finished::<(), ()>(())
    }).forget();
    rx.recv().unwrap()
}

fn done<T: Send + 'static>(t: T) -> BoxFuture<T, ()> {
    futures::done(Ok(t)).boxed()
}

#[test]
fn join() {
    let pool = CpuPool::new(2);
    let a = pool.spawn(done(1));
    let b = pool.spawn(done(2));
    let res = get(a.join(b).map(|(a, b)| a + b));

    assert_eq!(res.unwrap(), 3);
}

#[test]
fn select() {
    let pool = CpuPool::new(2);
    let a = pool.spawn(done(1));
    let b = pool.spawn(done(2));
    let (item1, next) = get(a.select(b)).ok().unwrap();
    let item2 = get(next).unwrap();

    assert!(item1 != item2);
    assert!((item1 == 1 && item2 == 2) || (item1 == 2 && item2 == 1));
}

#[test]
fn threads_go_away() {
    static CNT: AtomicUsize = ATOMIC_USIZE_INIT;

    struct A;

    impl Drop for A {
        fn drop(&mut self) {
            CNT.fetch_add(1, Ordering::SeqCst);
        }
    }

    thread_local!(static FOO: A = A);

    let pool = CpuPool::new(2);
    get(pool.spawn(futures::lazy(|| {
        FOO.with(|_| ());
        let res: Result<(), ()> = Ok(());
        res
    }))).unwrap();
    drop(pool);

    for _ in 0..100 {
        if CNT.load(Ordering::SeqCst) == 1 {
            return
        }
        thread::sleep(Duration::from_millis(10));
    }
    panic!("thread didn't exit");
}
<commit_msg>Tweak cpupool tests a bit<commit_after>extern crate futures;
extern crate futures_cpupool;

use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::thread;
use std::time::Duration;

use futures::{Future, BoxFuture};
use futures_cpupool::CpuPool;

fn done<T: Send + 'static>(t: T) -> BoxFuture<T, ()> {
    futures::done(Ok(t)).boxed()
}

#[test]
fn join() {
    let pool = CpuPool::new(2);
    let a = pool.spawn(done(1));
    let b = pool.spawn(done(2));
    let res = a.join(b).map(|(a, b)| a + b).wait();

    assert_eq!(res.unwrap(), 3);
}

#[test]
fn select() {
    let pool = CpuPool::new(2);
    let a = pool.spawn(done(1));
    let b = pool.spawn(done(2));
    let (item1, next) = a.select(b).wait().ok().unwrap();
    let item2 = next.wait().unwrap();

    assert!(item1 != item2);
    assert!((item1 == 1 && item2 == 2) || (item1 == 2 && item2 == 1));
}

#[test]
fn threads_go_away() {
    static CNT: AtomicUsize = ATOMIC_USIZE_INIT;

    struct A;

    impl Drop for A {
        fn drop(&mut self) {
            CNT.fetch_add(1, Ordering::SeqCst);
        }
    }

    thread_local!(static FOO: A = A);

    let pool = CpuPool::new(2);
    let _handle = pool.spawn(futures::lazy(|| {
        FOO.with(|_| ());
        Ok::<(), ()>(())
    }));
    drop(pool);

    for _ in 0..100 {
        if CNT.load(Ordering::SeqCst) == 1 {
            return
        }
        thread::sleep(Duration::from_millis(10));
    }
    panic!("thread didn't exit");
}
<|endoftext|>


<commit_before>import lib.llvm.llvm;
import lib.llvm.llvm.ModuleRef;
import std._str;
import std._vec;
import std.os.target_os;
import util.common.istr;

const int wordsz = 4;

fn wstr(int i) -> str {
    ret istr(i * wordsz);
}

fn save_callee_saves() -> vec[str] {
    ret vec("pushl %ebp",
            "pushl %edi",
            "pushl %esi",
            "pushl %ebx");
}

fn restore_callee_saves() -> vec[str] {
    ret vec("popl  %ebx",
            "popl  %esi",
            "popl  %edi",
            "popl  %ebp");
}

fn load_esp_from_rust_sp() -> vec[str] {
    ret vec("movl  " + wstr(abi.task_field_rust_sp) + "(%ecx), %esp");
}

fn load_esp_from_runtime_sp() -> vec[str] {
    ret vec("movl  " + wstr(abi.task_field_runtime_sp) + "(%ecx), %esp");
}

fn store_esp_to_rust_sp() -> vec[str] {
    ret vec("movl  %esp, " + wstr(abi.task_field_rust_sp) + "(%ecx)");
}

fn store_esp_to_runtime_sp() -> vec[str] {
    ret vec("movl  %esp, " + wstr(abi.task_field_runtime_sp) + "(%ecx)");
}

/*
 * This is a bit of glue-code. It should be emitted once per
 * compilation unit.
 *
 *   - save regs on C stack
 *   - align sp on a 16-byte boundary
 *   - save sp to task.runtime_sp (runtime_sp is thus always aligned)
 *   - load saved task sp (switch stack)
 *   - restore saved task regs
 *   - return to saved task pc
 *
 * Our incoming stack looks like this:
 *
 *   *esp+4        = [arg1   ] = task ptr
 *   *esp          = [retpc  ]
 */

fn rust_activate_glue() -> vec[str] {
    ret vec("movl  4(%esp), %ecx    # ecx = rust_task")
        + save_callee_saves()
        + store_esp_to_runtime_sp()
        + load_esp_from_rust_sp()

        /*
         * There are two paths we can arrive at this code from:
         *
         *
         *   1. We are activating a task for the first time. When we switch
         *      into the task stack and 'ret' to its first instruction, we'll
         *      start doing whatever the first instruction says. Probably
         *      saving registers and starting to establish a frame. Harmless
         *      stuff, doesn't look at task->rust_sp again except when it
         *      clobbers it during a later upcall.
         *
         *
         *   2. We are resuming a task that was descheduled by the yield glue
         *      below.  When we switch into the task stack and 'ret', we'll be
         *      ret'ing to a very particular instruction:
         *
         *              "esp <- task->rust_sp"
         *
         *      this is the first instruction we 'ret' to after this glue,
         *      because it is the first instruction following *any* upcall,
         *      and the task we are activating was descheduled mid-upcall.
         *
         *      Unfortunately for us, we have already restored esp from
         *      task->rust_sp and are about to eat the 5 words off the top of
         *      it.
         *
         *
         *      | ...    | <-- where esp will be once we restore + ret, below,
         *      | retpc  |     and where we'd *like* task->rust_sp to wind up.
         *      | ebp    |
         *      | edi    |
         *      | esi    |
         *      | ebx    | <-- current task->rust_sp == current esp
         *
         *
         *      This is a problem. If we return to "esp <- task->rust_sp" it
         *      will push esp back down by 5 words. This manifests as a rust
         *      stack that grows by 5 words on each yield/reactivate. Not
         *      good.
         *
         *      So what we do here is just adjust task->rust_sp up 5 words as
         *      well, to mirror the movement in esp we're about to
         *      perform. That way the "esp <- task->rust_sp" we 'ret' to below
         *      will be a no-op. Esp won't move, and the task's stack won't
         *      grow.
         */
        + vec("addl  $20, " + wstr(abi.task_field_rust_sp) + "(%ecx)")

        /*
         * In most cases, the function we're returning to (activating)
         * will have saved any caller-saves before it yielded via upcalling,
         * so no work to do here. With one exception: when we're initially
         * activating, the task needs to be in the fastcall 2nd parameter
         * expected by the rust main function. That's edx.
         */
        + vec("mov  %ecx, %edx")

        + restore_callee_saves()
        + vec("ret");
}

/* More glue code, this time the 'bottom half' of yielding.
 *
 * We arrived here because an upcall decided to deschedule the
 * running task. So the upcall's return address got patched to the
 * first instruction of this glue code.
 *
 * When the upcall does 'ret' it will come here, and its esp will be
 * pointing to the last argument pushed on the C stack before making
 * the upcall: the 0th argument to the upcall, which is always the
 * task ptr performing the upcall. That's where we take over.
 *
 * Our goal is to complete the descheduling
 *
 *   - Switch over to the task stack temporarily.
 *
 *   - Save the task's callee-saves onto the task stack.
 *     (the task is now 'descheduled', safe to set aside)
 *
 *   - Switch *back* to the C stack.
 *
 *   - Restore the C-stack callee-saves.
 *
 *   - Return to the caller on the C stack that activated the task.
 *
 */

fn rust_yield_glue() -> vec[str] {
    ret vec("movl  0(%esp), %ecx    # ecx = rust_task")
        + load_esp_from_rust_sp()
        + save_callee_saves()
        + store_esp_to_rust_sp()
        + load_esp_from_runtime_sp()
        + restore_callee_saves()
        + vec("ret");
}

fn upcall_glue(int n_args) -> vec[str] {

    /*
     * 0, 4, 8, 12 are callee-saves
     * 16 is retpc
     * 20 .. (5+i) * 4 are args
     *
     * ecx is taskptr
     * edx is callee
     *
     */

    fn copy_arg(uint i) -> str {
        if (i == 0u) {
            ret "movl  %edx, (%esp)";
        }
        auto src_off = wstr(4 + (i as int));
        auto dst_off = wstr(0 + (i as int));
        auto m = vec("movl  " + src_off + "(%ebp),%eax",
                     "movl  %eax," + dst_off + "(%esp)");
        ret _str.connect(m, "\n\t");
    }

    auto carg = copy_arg;

    ret
        save_callee_saves()

        + vec("movl  %esp, %ebp     # ebp = rust_sp")

        + store_esp_to_rust_sp()
        + load_esp_from_runtime_sp()

        + vec("subl  $" + wstr(n_args + 1) + ", %esp   # esp -= args",
              "andl  $~0xf, %esp    # align esp down")

        + _vec.init_fn[str](carg, (n_args + 1) as uint)

        +  vec("movl  %edx, %edi     # save task from ecx to edi",
               "call  *%ecx          # call *%edx",
               "movl  %edi, %edx     # restore edi-saved task to ecx")

        + load_esp_from_rust_sp()
        + restore_callee_saves()
        + vec("ret");

}

fn decl_glue(int align, str prefix, str name, vec[str] insns) -> str {
    auto sym = prefix + name;
    ret "\t.globl " + sym + "\n" +
        "\t.balign " + istr(align) + "\n" +
        sym + ":\n" +
        "\t" + _str.connect(insns, "\n\t");
}

fn decl_upcall_glue(int align, str prefix, uint n) -> str {
    let int i = n as int;
    ret decl_glue(align, prefix,
                  abi.upcall_glue_name(i),
                  upcall_glue(i));
}

fn get_symbol_prefix() -> str {
    if (_str.eq(target_os(), "macos") ||
        _str.eq(target_os(), "win32")) {
        ret "_";
    } else {
        ret "";
    }
}

fn get_module_asm() -> str {
    auto align = 4;

    auto prefix = get_symbol_prefix();

    auto glues =
        vec(decl_glue(align, prefix,
                      abi.activate_glue_name(),
                      rust_activate_glue()),

            decl_glue(align, prefix,
                      abi.yield_glue_name(),
                      rust_yield_glue()))

        + _vec.init_fn[str](bind decl_upcall_glue(align, prefix, _),
                            abi.n_upcall_glues as uint);

    ret _str.connect(glues, "\n\n");
}

fn get_data_layout() -> str {
    if (_str.eq(target_os(), "macos")) {
      ret "e-p:32:32-f64:32:64-i64:32:64-f80:128:128-n8:16:32";
    }
    if (_str.eq(target_os(), "win32")) {
      ret "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32";
    }
    ret "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32";
}

fn get_target_triple() -> str {
    if (_str.eq(target_os(), "macos")) {
        ret "i686-apple-darwin";
    }
    if (_str.eq(target_os(), "win32")) {
        ret "i686-pc-mingw32";
    }
    ret "i686-pc-linux-gnu";
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C ../.. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>Fix access to the rust stack.<commit_after>import lib.llvm.llvm;
import lib.llvm.llvm.ModuleRef;
import std._str;
import std._vec;
import std.os.target_os;
import util.common.istr;

const int wordsz = 4;

fn wstr(int i) -> str {
    ret istr(i * wordsz);
}

fn save_callee_saves() -> vec[str] {
    ret vec("pushl %ebp",
            "pushl %edi",
            "pushl %esi",
            "pushl %ebx");
}

fn restore_callee_saves() -> vec[str] {
    ret vec("popl  %ebx",
            "popl  %esi",
            "popl  %edi",
            "popl  %ebp");
}

fn load_esp_from_rust_sp_first_arg() -> vec[str] {
    ret vec("movl  " + wstr(abi.task_field_rust_sp) + "(%ecx), %esp");
}

fn load_esp_from_runtime_sp_first_arg() -> vec[str] {
    ret vec("movl  " + wstr(abi.task_field_runtime_sp) + "(%ecx), %esp");
}

fn store_esp_to_rust_sp_first_arg() -> vec[str] {
    ret vec("movl  %esp, " + wstr(abi.task_field_rust_sp) + "(%ecx)");
}

fn store_esp_to_runtime_sp_first_arg() -> vec[str] {
    ret vec("movl  %esp, " + wstr(abi.task_field_runtime_sp) + "(%ecx)");
}

fn load_esp_from_rust_sp_second_arg() -> vec[str] {
    ret vec("movl  " + wstr(abi.task_field_rust_sp) + "(%edx), %esp");
}

fn load_esp_from_runtime_sp_second_arg() -> vec[str] {
    ret vec("movl  " + wstr(abi.task_field_runtime_sp) + "(%edx), %esp");
}

fn store_esp_to_rust_sp_second_arg() -> vec[str] {
    ret vec("movl  %esp, " + wstr(abi.task_field_rust_sp) + "(%edx)");
}

fn store_esp_to_runtime_sp_second_arg() -> vec[str] {
    ret vec("movl  %esp, " + wstr(abi.task_field_runtime_sp) + "(%edx)");
}

/*
 * This is a bit of glue-code. It should be emitted once per
 * compilation unit.
 *
 *   - save regs on C stack
 *   - align sp on a 16-byte boundary
 *   - save sp to task.runtime_sp (runtime_sp is thus always aligned)
 *   - load saved task sp (switch stack)
 *   - restore saved task regs
 *   - return to saved task pc
 *
 * Our incoming stack looks like this:
 *
 *   *esp+4        = [arg1   ] = task ptr
 *   *esp          = [retpc  ]
 */

fn rust_activate_glue() -> vec[str] {
    ret vec("movl  4(%esp), %ecx    # ecx = rust_task")
        + save_callee_saves()
        + store_esp_to_runtime_sp_first_arg()
        + load_esp_from_rust_sp_first_arg()

        /*
         * There are two paths we can arrive at this code from:
         *
         *
         *   1. We are activating a task for the first time. When we switch
         *      into the task stack and 'ret' to its first instruction, we'll
         *      start doing whatever the first instruction says. Probably
         *      saving registers and starting to establish a frame. Harmless
         *      stuff, doesn't look at task->rust_sp again except when it
         *      clobbers it during a later upcall.
         *
         *
         *   2. We are resuming a task that was descheduled by the yield glue
         *      below.  When we switch into the task stack and 'ret', we'll be
         *      ret'ing to a very particular instruction:
         *
         *              "esp <- task->rust_sp"
         *
         *      this is the first instruction we 'ret' to after this glue,
         *      because it is the first instruction following *any* upcall,
         *      and the task we are activating was descheduled mid-upcall.
         *
         *      Unfortunately for us, we have already restored esp from
         *      task->rust_sp and are about to eat the 5 words off the top of
         *      it.
         *
         *
         *      | ...    | <-- where esp will be once we restore + ret, below,
         *      | retpc  |     and where we'd *like* task->rust_sp to wind up.
         *      | ebp    |
         *      | edi    |
         *      | esi    |
         *      | ebx    | <-- current task->rust_sp == current esp
         *
         *
         *      This is a problem. If we return to "esp <- task->rust_sp" it
         *      will push esp back down by 5 words. This manifests as a rust
         *      stack that grows by 5 words on each yield/reactivate. Not
         *      good.
         *
         *      So what we do here is just adjust task->rust_sp up 5 words as
         *      well, to mirror the movement in esp we're about to
         *      perform. That way the "esp <- task->rust_sp" we 'ret' to below
         *      will be a no-op. Esp won't move, and the task's stack won't
         *      grow.
         */
        + vec("addl  $20, " + wstr(abi.task_field_rust_sp) + "(%ecx)")

        /*
         * In most cases, the function we're returning to (activating)
         * will have saved any caller-saves before it yielded via upcalling,
         * so no work to do here. With one exception: when we're initially
         * activating, the task needs to be in the fastcall 2nd parameter
         * expected by the rust main function. That's edx.
         */
        + vec("mov  %ecx, %edx")

        + restore_callee_saves()
        + vec("ret");
}

/* More glue code, this time the 'bottom half' of yielding.
 *
 * We arrived here because an upcall decided to deschedule the
 * running task. So the upcall's return address got patched to the
 * first instruction of this glue code.
 *
 * When the upcall does 'ret' it will come here, and its esp will be
 * pointing to the last argument pushed on the C stack before making
 * the upcall: the 0th argument to the upcall, which is always the
 * task ptr performing the upcall. That's where we take over.
 *
 * Our goal is to complete the descheduling
 *
 *   - Switch over to the task stack temporarily.
 *
 *   - Save the task's callee-saves onto the task stack.
 *     (the task is now 'descheduled', safe to set aside)
 *
 *   - Switch *back* to the C stack.
 *
 *   - Restore the C-stack callee-saves.
 *
 *   - Return to the caller on the C stack that activated the task.
 *
 */

fn rust_yield_glue() -> vec[str] {
    ret vec("movl  0(%esp), %ecx    # ecx = rust_task")
        + load_esp_from_rust_sp_first_arg()
        + save_callee_saves()
        + store_esp_to_rust_sp_first_arg()
        + load_esp_from_runtime_sp_first_arg()
        + restore_callee_saves()
        + vec("ret");
}

fn upcall_glue(int n_args) -> vec[str] {

    /*
     * 0, 4, 8, 12 are callee-saves
     * 16 is retpc
     * 20 .. (5+i) * 4 are args
     *
     * ecx is taskptr
     * edx is callee
     *
     */

    fn copy_arg(uint i) -> str {
        if (i == 0u) {
            ret "movl  %edx, (%esp)";
        }
        auto src_off = wstr(4 + (i as int));
        auto dst_off = wstr(0 + (i as int));
        auto m = vec("movl  " + src_off + "(%ebp),%eax",
                     "movl  %eax," + dst_off + "(%esp)");
        ret _str.connect(m, "\n\t");
    }

    auto carg = copy_arg;

    ret
        save_callee_saves()

        + vec("movl  %esp, %ebp     # ebp = rust_sp")

        + store_esp_to_rust_sp_second_arg()
        + load_esp_from_runtime_sp_second_arg()

        + vec("subl  $" + wstr(n_args + 1) + ", %esp   # esp -= args",
              "andl  $~0xf, %esp    # align esp down")

        + _vec.init_fn[str](carg, (n_args + 1) as uint)

        +  vec("movl  %edx, %edi     # save task from edx to edi",
               "call  *%ecx          # call *%ecx",
               "movl  %edi, %edx     # restore edi-saved task to edx")

        + load_esp_from_rust_sp_second_arg()
        + restore_callee_saves()
        + vec("ret");

}

fn decl_glue(int align, str prefix, str name, vec[str] insns) -> str {
    auto sym = prefix + name;
    ret "\t.globl " + sym + "\n" +
        "\t.balign " + istr(align) + "\n" +
        sym + ":\n" +
        "\t" + _str.connect(insns, "\n\t");
}

fn decl_upcall_glue(int align, str prefix, uint n) -> str {
    let int i = n as int;
    ret decl_glue(align, prefix,
                  abi.upcall_glue_name(i),
                  upcall_glue(i));
}

fn get_symbol_prefix() -> str {
    if (_str.eq(target_os(), "macos") ||
        _str.eq(target_os(), "win32")) {
        ret "_";
    } else {
        ret "";
    }
}

fn get_module_asm() -> str {
    auto align = 4;

    auto prefix = get_symbol_prefix();

    auto glues =
        vec(decl_glue(align, prefix,
                      abi.activate_glue_name(),
                      rust_activate_glue()),

            decl_glue(align, prefix,
                      abi.yield_glue_name(),
                      rust_yield_glue()))

        + _vec.init_fn[str](bind decl_upcall_glue(align, prefix, _),
                            abi.n_upcall_glues as uint);

    ret _str.connect(glues, "\n\n");
}

fn get_data_layout() -> str {
    if (_str.eq(target_os(), "macos")) {
      ret "e-p:32:32-f64:32:64-i64:32:64-f80:128:128-n8:16:32";
    }
    if (_str.eq(target_os(), "win32")) {
      ret "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32";
    }
    ret "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32";
}

fn get_target_triple() -> str {
    if (_str.eq(target_os(), "macos")) {
        ret "i686-apple-darwin";
    }
    if (_str.eq(target_os(), "win32")) {
        ret "i686-pc-mingw32";
    }
    ret "i686-pc-linux-gnu";
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C ../.. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|>


<commit_before><commit_msg>another try<commit_after><|endoftext|>


<commit_before><commit_msg>secret number generated and stored<commit_after><|endoftext|>


<commit_before><commit_msg>add regression test for #37154<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.

// Regression test for #37154: the problem here was that the cache
// results in a false error because it was caching skolemized results
// even after those skolemized regions had been popped.

trait Foo {
    fn method(&self) {}
}

struct Wrapper<T>(T);

impl<T> Foo for Wrapper<T> where for<'a> &'a T: IntoIterator<Item=&'a ()> {}

fn f(x: Wrapper<Vec<()>>) {
    x.method(); // This works.
    x.method(); // error: no method named `method`
}

fn main() { }
<|endoftext|>


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

//! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not have finalizers (i.e. they do not
//! contain owned boxes or implement `Drop`), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the `Clone` trait and calling
//! the `clone` method.

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

use marker::Sized;

/// A common trait for cloning an object.
///
/// This trait can be used with `#[derive]`.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Clone : Sized {
    /// Returns a copy of the value.
    ///
    /// # Examples
    ///
    /// ```
    /// let hello = "Hello"; // &str implements Clone
    ///
    /// assert_eq!("Hello", hello.clone());
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn clone(&self) -> Self;

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

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

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

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

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

clone_impl! { f32 }
clone_impl! { f64 }

clone_impl! { () }
clone_impl! { bool }
clone_impl! { char }
<commit_msg>Rollup merge of #32416 - GuillaumeGomez:patch-3, r=steveklabnik<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

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

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

use marker::Sized;

/// A common trait for cloning an object.
///
/// This trait can be used with `#[derive]`.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Clone : Sized {
    /// Returns a copy of the value.
    ///
    /// # Examples
    ///
    /// ```
    /// let hello = "Hello"; // &str implements Clone
    ///
    /// assert_eq!("Hello", hello.clone());
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn clone(&self) -> Self;

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

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

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

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

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

clone_impl! { f32 }
clone_impl! { f64 }

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


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

//! Logging macros

/// The standard logging macro
///
/// This macro will generically log over a provided level (of type u32) with a
/// format!-based argument list. See documentation in `std::fmt` for details on
/// how to use the syntax.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     log!(log::WARN, "this is a warning {}", "message");
///     log!(log::DEBUG, "this is a debug message");
///     log!(6, "this is a custom logging level: {level}", level=6);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=warn ./main
/// WARN:main: this is a warning message
/// ```
///
/// ```{.bash}
/// $ RUST_LOG=debug ./main
/// DEBUG:main: this is a debug message
/// WARN:main: this is a warning message
/// ```
///
/// ```{.bash}
/// $ RUST_LOG=6 ./main
/// DEBUG:main: this is a debug message
/// WARN:main: this is a warning message
/// 6:main: this is a custom logging level: 6
/// ```
#[macro_export]
macro_rules! log {
    ($lvl:expr, $($arg:tt)+) => ({
        static LOC: ::log::LogLocation = ::log::LogLocation {
            line: line!(),
            file: file!(),
            module_path: module_path!(),
        };
        let lvl = $lvl;
        if log_enabled!(lvl) {
            ::log::log(lvl, &LOC, format_args!($($arg)+))
        }
    })
}

/// A convenience macro for logging at the error log level.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     let error = 3;
///     error!("the build has failed with error code: {}", error);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=error ./main
/// ERROR:main: the build has failed with error code: 3
/// ```
///
#[macro_export]
macro_rules! error {
    ($($arg:tt)*) => (log!(::log::ERROR, $($arg)*))
}

/// A convenience macro for logging at the warning log level.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     let code = 3;
///     warn!("you may like to know that a process exited with: {}", code);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=warn ./main
/// WARN:main: you may like to know that a process exited with: 3
/// ```
#[macro_export]
macro_rules! warn {
    ($($arg:tt)*) => (log!(::log::WARN, $($arg)*))
}

/// A convenience macro for logging at the info log level.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     let ret = 3;
///     info!("this function is about to return: {}", ret);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=info ./main
/// INFO:main: this function is about to return: 3
/// ```
#[macro_export]
macro_rules! info {
    ($($arg:tt)*) => (log!(::log::INFO, $($arg)*))
}

/// A convenience macro for logging at the debug log level. This macro can also
/// be omitted at compile time by passing `--cfg ndebug` to the compiler. If
/// this option is not passed, then debug statements will be compiled.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     debug!("x = {x}, y = {y}", x=10, y=20);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=debug ./main
/// DEBUG:main: x = 10, y = 20
/// ```
#[macro_export]
macro_rules! debug {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { log!(::log::DEBUG, $($arg)*) })
}

/// A macro to test whether a log level is enabled for the current module.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// struct Point { x: int, y: int }
/// fn some_expensive_computation() -> Point { Point { x: 1, y: 2 } }
///
/// fn main() {
///     if log_enabled!(log::DEBUG) {
///         let x = some_expensive_computation();
///         debug!("x.x = {}, x.y = {}", x.x, x.y);
///     }
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=error ./main
/// ```
///
/// ```{.bash}
/// $ RUST_LOG=debug ./main
/// DEBUG:main: x.x = 1, x.y = 2
/// ```
#[macro_export]
macro_rules! log_enabled {
    ($lvl:expr) => ({
        let lvl = $lvl;
        (lvl != ::log::DEBUG || cfg!(debug_assertions)) &&
        lvl <= ::log::log_level() &&
        ::log::mod_enabled(lvl, module_path!())
    })
}
<commit_msg>Auto merge of #25045 - XuefengWu:1398_remove_ndebug, r=huonw<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.

//! Logging macros

/// The standard logging macro
///
/// This macro will generically log over a provided level (of type u32) with a
/// format!-based argument list. See documentation in `std::fmt` for details on
/// how to use the syntax.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     log!(log::WARN, "this is a warning {}", "message");
///     log!(log::DEBUG, "this is a debug message");
///     log!(6, "this is a custom logging level: {level}", level=6);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=warn ./main
/// WARN:main: this is a warning message
/// ```
///
/// ```{.bash}
/// $ RUST_LOG=debug ./main
/// DEBUG:main: this is a debug message
/// WARN:main: this is a warning message
/// ```
///
/// ```{.bash}
/// $ RUST_LOG=6 ./main
/// DEBUG:main: this is a debug message
/// WARN:main: this is a warning message
/// 6:main: this is a custom logging level: 6
/// ```
#[macro_export]
macro_rules! log {
    ($lvl:expr, $($arg:tt)+) => ({
        static LOC: ::log::LogLocation = ::log::LogLocation {
            line: line!(),
            file: file!(),
            module_path: module_path!(),
        };
        let lvl = $lvl;
        if log_enabled!(lvl) {
            ::log::log(lvl, &LOC, format_args!($($arg)+))
        }
    })
}

/// A convenience macro for logging at the error log level.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     let error = 3;
///     error!("the build has failed with error code: {}", error);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=error ./main
/// ERROR:main: the build has failed with error code: 3
/// ```
///
#[macro_export]
macro_rules! error {
    ($($arg:tt)*) => (log!(::log::ERROR, $($arg)*))
}

/// A convenience macro for logging at the warning log level.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     let code = 3;
///     warn!("you may like to know that a process exited with: {}", code);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=warn ./main
/// WARN:main: you may like to know that a process exited with: 3
/// ```
#[macro_export]
macro_rules! warn {
    ($($arg:tt)*) => (log!(::log::WARN, $($arg)*))
}

/// A convenience macro for logging at the info log level.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     let ret = 3;
///     info!("this function is about to return: {}", ret);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=info ./main
/// INFO:main: this function is about to return: 3
/// ```
#[macro_export]
macro_rules! info {
    ($($arg:tt)*) => (log!(::log::INFO, $($arg)*))
}

/// A convenience macro for logging at the debug log level. This macro can also
/// be omitted at compile time by passing `-C debug-assertions` to the compiler. If
/// this option is not passed, then debug statements will be compiled.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// fn main() {
///     debug!("x = {x}, y = {y}", x=10, y=20);
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=debug ./main
/// DEBUG:main: x = 10, y = 20
/// ```
#[macro_export]
macro_rules! debug {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { log!(::log::DEBUG, $($arg)*) })
}

/// A macro to test whether a log level is enabled for the current module.
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate log;
///
/// struct Point { x: int, y: int }
/// fn some_expensive_computation() -> Point { Point { x: 1, y: 2 } }
///
/// fn main() {
///     if log_enabled!(log::DEBUG) {
///         let x = some_expensive_computation();
///         debug!("x.x = {}, x.y = {}", x.x, x.y);
///     }
/// }
/// ```
///
/// Assumes the binary is `main`:
///
/// ```{.bash}
/// $ RUST_LOG=error ./main
/// ```
///
/// ```{.bash}
/// $ RUST_LOG=debug ./main
/// DEBUG:main: x.x = 1, x.y = 2
/// ```
#[macro_export]
macro_rules! log_enabled {
    ($lvl:expr) => ({
        let lvl = $lvl;
        (lvl != ::log::DEBUG || cfg!(debug_assertions)) &&
        lvl <= ::log::log_level() &&
        ::log::mod_enabled(lvl, module_path!())
    })
}
<|endoftext|>


<commit_before><commit_msg>Add test for #45044<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.

// https://github.com/rust-lang/rust/issues/45044

const X: [u8; 1] = [0; 1];

fn main() {
    match &X {
        &X => println!("a"),
        _ => println!("b"),
    };
}
<|endoftext|>