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

trait Fooable {
    fn yes(self);
}

impl Fooable for uint {
    fn yes(self) {
        for self.times {
            println("yes");
        }
    }
}

fn main() {
    2.yes();
}
<|endoftext|>


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

//! Vertex attribute types.

#![allow(missing_docs)]

use shade::BaseType;

/// Number of elements per attribute, only 1 to 4 are supported
pub type Count = u8;
/// Offset of an attribute from the start of the buffer, in bytes
pub type Offset = u32;
/// Offset between attribute values, in bytes
pub type Stride = u8;
/// The number of instances between each subsequent attribute value
pub type InstanceRate = u8;

/// The signedness of an attribute.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum SignFlag {
    Signed,
    Unsigned,
}

/// Describes how an integer value is interpreted by the shader.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum IntSubType {
    Raw,         // un-processed integer
    Normalized,  // normalized either to [0,1] or [-1,1] depending on the sign flag
    AsFloat,     // converted to float on the fly by the hardware
}

/// The size of an integer attribute, in bits.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum IntSize {
    U8,
    U16,
    U32,
}

/// Type of a floating point attribute on the shader side.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum FloatSubType {
    Default,    // 32-bit
    Precision,  // 64-bit
}

/// The size of a floating point attribute, in bits.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum FloatSize {
    F16,
    F32,
    F64,
}

/// The type of an attribute.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum Type {
    Int(IntSubType, IntSize, SignFlag),
    Float(FloatSubType, FloatSize),
    Special,
}

impl Type {
    /// Check if the attribute is compatible with a particular shader type.
    pub fn is_compatible(&self, bt: BaseType) -> Result<(), ()> {
        match (*self, bt) {
            (Type::Int(IntSubType::Raw, _, _), BaseType::I32) => Ok(()),
            (Type::Int(IntSubType::Raw, _, SignFlag::Unsigned), BaseType::U32) => Ok(()),
            (Type::Int(IntSubType::Raw, _, _), _) => Err(()),
            (Type::Int(_, _, _), BaseType::F32) => Ok(()),
            (Type::Int(_, _, _), _) => Err(()),
            (Type::Float(_, _), BaseType::F32) => Ok(()),
            (Type::Float(FloatSubType::Precision, FloatSize::F64), BaseType::F64) => Ok(()),
            (Type::Float(_, _), _) => Err(()),
            (_, BaseType::F64) => Err(()),
            (_, BaseType::Bool) => Err(()),
            _ => Err(()),
        }
    }
}

/// Complete format of a vertex attribute.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct Format {
    /// Number of elements per vertex
    pub elem_count: Count,
    /// Type of a single element
    pub elem_type: Type,
    /// Offset in bytes to the first vertex
    pub offset: Offset,
    /// Stride in bytes between consecutive vertices
    pub stride: Stride,
    /// Instance rate per vertex
    pub instance_rate: InstanceRate,
}
<commit_msg>Implemented a helper to compute the attribute size<commit_after>// Copyright 2014 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.

//! Vertex attribute types.

#![allow(missing_docs)]

use shade::BaseType;

/// Number of elements per attribute, only 1 to 4 are supported
pub type Count = u8;
/// Offset of an attribute from the start of the buffer, in bytes
pub type Offset = u32;
/// Offset between attribute values, in bytes
pub type Stride = u8;
/// The number of instances between each subsequent attribute value
pub type InstanceRate = u8;

/// The signedness of an attribute.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum SignFlag {
    Signed,
    Unsigned,
}

/// Describes how an integer value is interpreted by the shader.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum IntSubType {
    Raw,         // un-processed integer
    Normalized,  // normalized either to [0,1] or [-1,1] depending on the sign flag
    AsFloat,     // converted to float on the fly by the hardware
}

/// The size of an integer attribute, in bits.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum IntSize {
    U8,
    U16,
    U32,
}

/// Type of a floating point attribute on the shader side.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum FloatSubType {
    Default,    // 32-bit
    Precision,  // 64-bit
}

/// The size of a floating point attribute, in bits.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum FloatSize {
    F16,
    F32,
    F64,
}

/// The type of an attribute.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum Type {
    Int(IntSubType, IntSize, SignFlag),
    Float(FloatSubType, FloatSize),
    Special,
}

impl Type {
    /// Check if the attribute is compatible with a particular shader type.
    pub fn is_compatible(&self, bt: BaseType) -> Result<(), ()> {
        match (*self, bt) {
            (Type::Int(IntSubType::Raw, _, _), BaseType::I32) => Ok(()),
            (Type::Int(IntSubType::Raw, _, SignFlag::Unsigned), BaseType::U32) => Ok(()),
            (Type::Int(IntSubType::Raw, _, _), _) => Err(()),
            (Type::Int(_, _, _), BaseType::F32) => Ok(()),
            (Type::Int(_, _, _), _) => Err(()),
            (Type::Float(_, _), BaseType::F32) => Ok(()),
            (Type::Float(FloatSubType::Precision, FloatSize::F64), BaseType::F64) => Ok(()),
            (Type::Float(_, _), _) => Err(()),
            (_, BaseType::F64) => Err(()),
            (_, BaseType::Bool) => Err(()),
            _ => Err(()),
        }
    }

    /// Return the size of the type in bytes.
    pub fn get_size(&self) -> u8 {
        match *self {
            Type::Int(_, IntSize::U8, _) => 1,
            Type::Int(_, IntSize::U16, _) => 2,
            Type::Int(_, IntSize::U32, _) => 4,
            Type::Float(_, FloatSize::F16) => 2,
            Type::Float(_, FloatSize::F32) => 4,
            Type::Float(_, FloatSize::F64) => 8,
            Type::Special => 0,
        }
    }
}

/// Complete format of a vertex attribute.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct Format {
    /// Number of elements per vertex
    pub elem_count: Count,
    /// Type of a single element
    pub elem_type: Type,
    /// Offset in bytes to the first vertex
    pub offset: Offset,
    /// Stride in bytes between consecutive vertices
    pub stride: Stride,
    /// Instance rate per vertex
    pub instance_rate: InstanceRate,
}
<|endoftext|>


<commit_before>//! Definition of the Shared combinator, a future that is cloneable,
//! and can be polled in multiple threads.
//!
//! # Examples
//!
//! ```
//! use futures::future::*;
//!
//! let future = ok::<_, bool>(6);
//! let shared1 = future.shared();
//! let shared2 = shared1.clone();
//! assert_eq!(6, *shared1.wait().unwrap());
//! assert_eq!(6, *shared2.wait().unwrap());
//! ```

use std::mem;
use std::vec::Vec;
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;

use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;

/// A future that is cloneable and can be polled in multiple threads.
/// Use Future::shared() method to convert any future into a `Shared` future.
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
    where F: Future
{
    inner: Arc<Inner<F>>,
}

struct Inner<F>
    where F: Future
{
    /// The original future.
    original_future: Lock<Option<F>>,
    /// Indicates whether the result is ready, and the state is `State::Done`.
    result_ready: AtomicBool,
    /// The state of the shared future.
    state: RwLock<State<F::Item, F::Error>>,
}

/// The state of the shared future. It can be one of the following:
/// 1. Done - contains the result of the original future.
/// 2. Waiting - contains the waiting tasks.
enum State<T, E> {
    Waiting(Vec<Task>),
    Done(Result<SharedItem<T>, SharedError<E>>),
}

impl<F> Shared<F>
    where F: Future
{
    /// Creates a new `Shared` from another future.
    pub fn new(future: F) -> Self {
        Shared {
            inner: Arc::new(Inner {
                original_future: Lock::new(Some(future)),
                result_ready: AtomicBool::new(false),
                state: RwLock::new(State::Waiting(vec![])),
            }),
        }
    }

    /// Clones the result from self.inner.state.
    /// Assumes state is `State::Done`.
    fn read_result(&self) -> Result<Async<SharedItem<F::Item>>, SharedError<F::Error>> {
        match *self.inner.state.read().unwrap() {
            State::Done(ref result) => result.clone().map(Async::Ready),
            State::Waiting(_) => panic!("read_result() was called but State is not Done"),
        }
    }

    /// Stores the result in self.inner.state, unparks the waiting tasks,
    /// and returns the result.
    fn store_result(&self,
                    result: Result<SharedItem<F::Item>, SharedError<F::Error>>)
                    -> Result<Async<SharedItem<F::Item>>, SharedError<F::Error>> {
        let ref mut state = *self.inner.state.write().unwrap();

        match mem::replace(state, State::Done(result.clone())) {
            State::Waiting(waiters) => {
                drop(state);
                self.inner.result_ready.store(true, Ordering::Relaxed);
                for task in waiters {
                    task.unpark();
                }
            }
            State::Done(_) => panic!("store_result() was called twice"),
        }

        result.map(Async::Ready)
    }
}

impl<F> Future for Shared<F>
    where F: Future
{
    type Item = SharedItem<F::Item>;
    type Error = SharedError<F::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // The logic is as follows:
        // 1. Check if the result is ready (with result_ready)
        //  - If the result is ready, return it.
        //  - Otherwise:
        // 2. Try lock the self.inner.original_future:
        //    - If successfully locked, check again if the result is ready.
        //      If it's ready, just return it.
        //      Otherwise, poll the original future.
        //      If the future is ready, unpark the waiting tasks from
        //      self.inner.state and return the result.
        //    - If the future is not ready, or if the lock failed:
        // 3. Lock the state for write.
        // 4. If the state is `State::Done`, return the result. Otherwise:
        // 5. Create a task, push it to the waiters vector, and return `Ok(Async::NotReady)`.

        // If the result is ready, just return it
        if self.inner.result_ready.load(Ordering::Relaxed) {
            return self.read_result();
        }

        // The result was not ready.
        // Try lock the original future.
        match self.inner.original_future.try_lock() {
            Some(mut original_future_option) => {
                // Other thread could already poll the result, so we check if result_ready.
                if self.inner.result_ready.load(Ordering::Relaxed) {
                    return self.read_result();
                }

                let mut result = None;
                match *original_future_option {
                    Some(ref mut original_future) => {
                        match original_future.poll() {
                            Ok(Async::Ready(item)) => {
                                result = Some(self.store_result(Ok(SharedItem::new(item))));
                            }
                            Err(error) => {
                                result = Some(self.store_result(Err(SharedError::new(error))));
                            }
                            Ok(Async::NotReady) => {} // A task will be parked
                        }
                    }
                    None => panic!("result_ready is false but original_future is None"),
                }

                if let Some(result) = result {
                    *original_future_option = None;
                    return result;
                }
            }
            None => {} // A task will be parked
        }

        let ref mut state = *self.inner.state.write().unwrap();
        match state {
            &mut State::Done(ref result) => return result.clone().map(Async::Ready),
            &mut State::Waiting(ref mut waiters) => {
                waiters.push(task::park());
            }
        }

        Ok(Async::NotReady)
    }
}

impl<F> Clone for Shared<F>
    where F: Future
{
    fn clone(&self) -> Self {
        Shared { inner: self.inner.clone() }
    }
}

/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
    item: Arc<T>,
}

impl<T> SharedItem<T> {
    fn new(item: T) -> Self {
        SharedItem { item: Arc::new(item) }
    }
}

impl<T> Clone for SharedItem<T> {
    fn clone(&self) -> Self {
        SharedItem { item: self.item.clone() }
    }
}

impl<T> Deref for SharedItem<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.item.as_ref()
    }
}

/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
    error: Arc<E>,
}

impl<E> SharedError<E> {
    fn new(error: E) -> Self {
        SharedError { error: Arc::new(error) }
    }
}

impl<T> Clone for SharedError<T> {
    fn clone(&self) -> Self {
        SharedError { error: self.error.clone() }
    }
}

impl<E> Deref for SharedError<E> {
    type Target = E;

    fn deref(&self) -> &E {
        &self.error.as_ref()
    }
}
<commit_msg>Touch up the implementation of shared() slightly<commit_after>//! Definition of the Shared combinator, a future that is cloneable,
//! and can be polled in multiple threads.
//!
//! # Examples
//!
//! ```
//! use futures::future::*;
//!
//! let future = ok::<_, bool>(6);
//! let shared1 = future.shared();
//! let shared2 = shared1.clone();
//! assert_eq!(6, *shared1.wait().unwrap());
//! assert_eq!(6, *shared2.wait().unwrap());
//! ```

use std::mem;
use std::vec::Vec;
use std::sync::{Arc, RwLock};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::ops::Deref;

use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;

/// A future that is cloneable and can be polled in multiple threads.
/// Use Future::shared() method to convert any future into a `Shared` future.
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
    where F: Future
{
    inner: Arc<Inner<F>>,
}

struct Inner<F>
    where F: Future
{
    /// The original future.
    original_future: Lock<Option<F>>,
    /// Indicates whether the result is ready, and the state is `State::Done`.
    result_ready: AtomicBool,
    /// The state of the shared future.
    state: RwLock<State<F::Item, F::Error>>,
}

/// The state of the shared future. It can be one of the following:
/// 1. Done - contains the result of the original future.
/// 2. Waiting - contains the waiting tasks.
enum State<T, E> {
    Waiting(Vec<Task>),
    Done(Result<Arc<T>, Arc<E>>),
}

impl<F> Shared<F>
    where F: Future
{
    /// Creates a new `Shared` from another future.
    pub fn new(future: F) -> Self {
        Shared {
            inner: Arc::new(Inner {
                original_future: Lock::new(Some(future)),
                result_ready: AtomicBool::new(false),
                state: RwLock::new(State::Waiting(vec![])),
            }),
        }
    }

    fn park(&self) -> Poll<SharedItem<F::Item>, SharedError<F::Error>> {
        let me = task::park();
        match *self.inner.state.write().unwrap() {
            State::Waiting(ref mut list) => {
                list.push(me);
                Ok(Async::NotReady)
            }
            State::Done(Ok(ref e)) => Ok(SharedItem { item: e.clone() }.into()),
            State::Done(Err(ref e)) => Err(SharedError { error: e.clone() }),
        }
    }
}

impl<F> Future for Shared<F>
    where F: Future
{
    type Item = SharedItem<F::Item>;
    type Error = SharedError<F::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // The logic is as follows:
        // 1. Check if the result is ready (with result_ready)
        //  - If the result is ready, return it.
        //  - Otherwise:
        // 2. Try lock the self.inner.original_future:
        //    - If successfully locked, check again if the result is ready.
        //      If it's ready, just return it.
        //      Otherwise, poll the original future.
        //      If the future is ready, unpark the waiting tasks from
        //      self.inner.state and return the result.
        //    - If the future is not ready, or if the lock failed:
        // 3. Lock the state for write.
        // 4. If the state is `State::Done`, return the result. Otherwise:
        // 5. Create a task, push it to the waiters vector, and return `Ok(Async::NotReady)`.

        if !self.inner.result_ready.load(SeqCst) {
            match self.inner.original_future.try_lock() {
                // We already saw the result wasn't ready, but after we've
                // acquired the lock another thread could already have finished,
                // so we check `result_ready` again.
                Some(_) if self.inner.result_ready.load(SeqCst) => {}

                // If we lock the future, then try to push it towards
                // completion.
                Some(mut future) => {
                    let result = match future.as_mut().unwrap().poll() {
                        Ok(Async::NotReady) => {
                            drop(future);
                            return self.park()
                        }
                        Ok(Async::Ready(item)) => Ok(Arc::new(item)),
                        Err(error) => Err(Arc::new(error)),
                    };

                    // Free up resources associated with this future
                    *future = None;

                    // Wake up everyone waiting on the future and store the
                    // result at the same time, flagging future pollers that
                    // we're done.
                    let waiters = {
                        let mut state = self.inner.state.write().unwrap();
                        self.inner.result_ready.store(true, SeqCst);

                        match mem::replace(&mut *state, State::Done(result)) {
                            State::Waiting(waiters) => waiters,
                            State::Done(_) => panic!("store_result() was called twice"),
                        }
                    };
                    for task in waiters {
                        task.unpark();
                    }
                }

                // Looks like someone else is making progress on the future,
                // let's just wait for them.
                None => return self.park(),
            }
        }

        // If we're here then we should have finished the future, so assert the
        // `Done` state and return the item/error.
        let result = match *self.inner.state.read().unwrap() {
            State::Done(ref result) => result.clone(),
            State::Waiting(_) => panic!("still waiting, not done yet"),
        };
        match result {
            Ok(e) => Ok(SharedItem { item: e }.into()),
            Err(e) => Err(SharedError { error: e }),
        }
    }
}

impl<F> Clone for Shared<F>
    where F: Future
{
    fn clone(&self) -> Self {
        Shared { inner: self.inner.clone() }
    }
}

/// A wrapped item of the original future that is clonable and implements Deref
/// for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
    item: Arc<T>,
}

impl<T> Deref for SharedItem<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.item.as_ref()
    }
}

/// A wrapped error of the original future that is clonable and implements Deref
/// for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
    error: Arc<E>,
}

impl<E> Deref for SharedError<E> {
    type Target = E;

    fn deref(&self) -> &E {
        &self.error.as_ref()
    }
}
<|endoftext|>


<commit_before><commit_msg>oops... missing module<commit_after>pub use api::oauth::{OAuthApp, CreateApp, make_client};
<|endoftext|>


<commit_before><commit_msg>added tests and more constraint work<commit_after><|endoftext|>


<commit_before><commit_msg>Add some more tests for special parameters.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test, closes #20454<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::thread;

fn main() {
    thread::Thread::spawn(move || { // no need for -> ()
        loop {
            println!("hello");
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #29261 - apasel422:issue-22403, r=alexcrichton<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.

fn main() {
    let x = Box::new([1, 2, 3]);
    let y = x as Box<[i32]>;
    println!("y: {:?}", y);
}
<|endoftext|>


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

//! This module contains the linkage attributes to all runtime dependencies of
//! the standard library This varies per-platform, but these libraries are
//! necessary for running libstd.

// All platforms need to link to rustrt
#[link(name = "rustrt", kind = "static")]
extern {}

// LLVM implements the `frem` instruction as a call to `fmod`, which lives in
// libm. Hence, we must explicitly link to it.
//
// On linux librt and libdl are indirect dependencies via rustrt,
// and binutils 2.22+ won't add them automatically
#[cfg(target_os = "linux")]
#[link(name = "c")]
#[link(name = "dl")]
#[link(name = "m")]
#[link(name = "pthread")]
extern {}

#[cfg(target_os = "android")]
#[link(name = "dl")]
#[link(name = "log")]
#[link(name = "m")]
#[link(name = "c")]
extern {}

#[cfg(target_os = "freebsd")]
#[link(name = "execinfo")]
#[link(name = "pthread")]
extern {}

#[cfg(target_os = "macos")]
#[link(name = "System")]
extern {}
<commit_msg>std: Explicitly link to libm for freebsd<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! This module contains the linkage attributes to all runtime dependencies of
//! the standard library This varies per-platform, but these libraries are
//! necessary for running libstd.

// All platforms need to link to rustrt
#[link(name = "rustrt", kind = "static")]
extern {}

// LLVM implements the `frem` instruction as a call to `fmod`, which lives in
// libm. Hence, we must explicitly link to it.
//
// On linux librt and libdl are indirect dependencies via rustrt,
// and binutils 2.22+ won't add them automatically
#[cfg(target_os = "linux")]
#[link(name = "c")]
#[link(name = "dl")]
#[link(name = "m")]
#[link(name = "pthread")]
extern {}

#[cfg(target_os = "android")]
#[link(name = "dl")]
#[link(name = "log")]
#[link(name = "m")]
#[link(name = "c")]
extern {}

#[cfg(target_os = "freebsd")]
#[link(name = "execinfo")]
#[link(name = "pthread")]
#[link(name = "m")]
extern {}

#[cfg(target_os = "macos")]
#[link(name = "System")]
extern {}
<|endoftext|>


<commit_before><commit_msg>switch mutex to atomicbool<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Impl'ed new for IronFurnace.<commit_after><|endoftext|>


<commit_before><commit_msg>Dump the GL implementation's uniform block limits when --debug is specified<commit_after><|endoftext|>


<commit_before><commit_msg>Add configurable rotation size.<commit_after><|endoftext|>


<commit_before><commit_msg>Add logging for sending a mail<commit_after><|endoftext|>


<commit_before><commit_msg>New functionality for clear command<commit_after><|endoftext|>


<commit_before><commit_msg>Add test case for ecs parralle iteration.<commit_after>#[macro_use]
extern crate lemon3d;
#[macro_use]
extern crate lazy_static;

use lemon3d::*;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Position {
    x: u32,
    y: u32,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Velocity {
    x: u32,
    y: u32,
}

declare_component!(Position, VecStorage);
declare_component!(Velocity, VecStorage);

#[test]
fn iterate() {
    let master = ThreadPool::new(4);
    let mut world = World::new();
    world.register::<Position>();
    world.register::<Velocity>();

    for i in 0..50 {
        let ent = world.build().with_default::<Position>().finish();
        let velocity = Velocity {
            x: i,
            y: ent.version(),
        };
        world.assign::<Velocity>(ent, velocity);

        if i % 3 == 0 {
            world.free(ent);
        }
    }

    world.view_with_r1w1::<Velocity, Position>().for_each(&master,
                                                          100,
                                                          &|item| {
                                                              item.writables.x += item.readables.x;
                                                              item.writables.y += item.readables.y;
                                                          });
}<|endoftext|>


<commit_before><commit_msg>tests<commit_after><|endoftext|>


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

/*!

Lint mode to detect cases where we call non-Rust fns, which do not
have a stack growth check, from locations not annotated to request
large stacks.

*/

use middle::lint;
use middle::ty;
use syntax::ast;
use syntax::ast_map;
use syntax::attr;
use syntax::codemap::span;
use visit = syntax::oldvisit;
use util::ppaux::Repr;

#[deriving(Clone)]
struct Context {
    tcx: ty::ctxt,
    safe_stack: bool
}

pub fn stack_check_crate(tcx: ty::ctxt,
                         crate: &ast::Crate) {
    let new_cx = Context {
        tcx: tcx,
        safe_stack: false
    };
    let visitor = visit::mk_vt(@visit::Visitor {
        visit_item: stack_check_item,
        visit_fn: stack_check_fn,
        visit_expr: stack_check_expr,
        ..*visit::default_visitor()
    });
    visit::visit_crate(crate, (new_cx, visitor));
}

fn stack_check_item(item: @ast::item,
                    (in_cx, v): (Context, visit::vt<Context>)) {
    match item.node {
        ast::item_fn(_, ast::extern_fn, _, _, _) => {
            // an extern fn is already being called from C code...
            let new_cx = Context {safe_stack: true, ..in_cx};
            visit::visit_item(item, (new_cx, v));
        }
        ast::item_fn(*) => {
            let safe_stack = fixed_stack_segment(item.attrs);
            let new_cx = Context {safe_stack: safe_stack, ..in_cx};
            visit::visit_item(item, (new_cx, v));
        }
        ast::item_impl(_, _, _, ref methods) => {
            // visit_method() would make this nicer
            for &method in methods.iter() {
                let safe_stack = fixed_stack_segment(method.attrs);
                let new_cx = Context {safe_stack: safe_stack, ..in_cx};
                visit::visit_method_helper(method, (new_cx, v));
            }
        }
        _ => {
            visit::visit_item(item, (in_cx, v));
        }
    }

    fn fixed_stack_segment(attrs: &[ast::Attribute]) -> bool {
        attr::contains_name(attrs, "fixed_stack_segment")
    }
}

fn stack_check_fn<'a>(fk: &visit::fn_kind,
                      decl: &ast::fn_decl,
                      body: &ast::Block,
                      sp: span,
                      id: ast::NodeId,
                      (in_cx, v): (Context, visit::vt<Context>)) {
    let safe_stack = match *fk {
        visit::fk_method(*) | visit::fk_item_fn(*) => {
            in_cx.safe_stack // see stack_check_item above
        }
        visit::fk_anon(*) | visit::fk_fn_block => {
            match ty::get(ty::node_id_to_type(in_cx.tcx, id)).sty {
                ty::ty_bare_fn(*) |
                ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, _}) |
                ty::ty_closure(ty::ClosureTy {sigil: ast::ManagedSigil, _}) => {
                    false
                }
                _ => {
                    in_cx.safe_stack
                }
            }
        }
    };
    let new_cx = Context {safe_stack: safe_stack, ..in_cx};
    debug!("stack_check_fn(safe_stack=%b, id=%?)", safe_stack, id);
    visit::visit_fn(fk, decl, body, sp, id, (new_cx, v));
}

fn stack_check_expr<'a>(expr: @ast::expr,
                        (cx, v): (Context, visit::vt<Context>)) {
    debug!("stack_check_expr(safe_stack=%b, expr=%s)",
           cx.safe_stack, expr.repr(cx.tcx));
    if !cx.safe_stack {
        match expr.node {
            ast::expr_call(callee, _, _) => {
                let callee_ty = ty::expr_ty(cx.tcx, callee);
                debug!("callee_ty=%s", callee_ty.repr(cx.tcx));
                match ty::get(callee_ty).sty {
                    ty::ty_bare_fn(ref fty) => {
                        if !fty.abis.is_rust() && !fty.abis.is_intrinsic() {
                            call_to_extern_fn(cx, callee);
                        }
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }
    visit::visit_expr(expr, (cx, v));
}

fn call_to_extern_fn(cx: Context, callee: @ast::expr) {
    // Permit direct calls to extern fns that are annotated with
    // #[rust_stack]. This is naturally a horrible pain to achieve.
    match callee.node {
        ast::expr_path(*) => {
            match cx.tcx.def_map.find(&callee.id) {
                Some(&ast::def_fn(id, _)) if id.crate == ast::LOCAL_CRATE => {
                    match cx.tcx.items.find(&id.node) {
                        Some(&ast_map::node_foreign_item(item, _, _, _)) => {
                            if attr::contains_name(item.attrs, "rust_stack") {
                                return;
                            }
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }
        _ => {}
    }

    cx.tcx.sess.add_lint(lint::cstack,
                         callee.id,
                         callee.span,
                         fmt!("invoking non-Rust fn in fn without \
                              #[fixed_stack_segment]"));
}
<commit_msg>Port middle/stack_check.rs from oldvisit to <V:Visitor> trait API.<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.

/*!

Lint mode to detect cases where we call non-Rust fns, which do not
have a stack growth check, from locations not annotated to request
large stacks.

*/

use middle::lint;
use middle::ty;
use syntax::ast;
use syntax::ast_map;
use syntax::attr;
use syntax::codemap::span;
use syntax::visit;
use syntax::visit::Visitor;
use util::ppaux::Repr;

#[deriving(Clone)]
struct Context {
    tcx: ty::ctxt,
    safe_stack: bool
}

struct StackCheckVisitor;

impl Visitor<Context> for StackCheckVisitor {
    fn visit_item(&mut self, i:@ast::item, e:Context) {
        stack_check_item(*self, i, e);
    }
    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
                b:&ast::Block, s:span, n:ast::NodeId, e:Context) {
        stack_check_fn(*self, fk, fd, b, s, n, e);
    }
    fn visit_expr(&mut self, ex:@ast::expr, e:Context) {
        stack_check_expr(*self, ex, e);
    }
}

pub fn stack_check_crate(tcx: ty::ctxt,
                         crate: &ast::Crate) {
    let new_cx = Context {
        tcx: tcx,
        safe_stack: false
    };
    let mut visitor = StackCheckVisitor;
    visit::walk_crate(&mut visitor, crate, new_cx);
}

fn stack_check_item(v: StackCheckVisitor,
                    item: @ast::item,
                    in_cx: Context) {
    let mut v = v;
    match item.node {
        ast::item_fn(_, ast::extern_fn, _, _, _) => {
            // an extern fn is already being called from C code...
            let new_cx = Context {safe_stack: true, ..in_cx};
            visit::walk_item(&mut v, item, new_cx);
        }
        ast::item_fn(*) => {
            let safe_stack = fixed_stack_segment(item.attrs);
            let new_cx = Context {safe_stack: safe_stack, ..in_cx};
            visit::walk_item(&mut v, item, new_cx);
        }
        ast::item_impl(_, _, _, ref methods) => {
            // visit_method() would make this nicer
            for &method in methods.iter() {
                let safe_stack = fixed_stack_segment(method.attrs);
                let new_cx = Context {safe_stack: safe_stack, ..in_cx};
                visit::walk_method_helper(&mut v, method, new_cx);
            }
        }
        _ => {
            visit::walk_item(&mut v, item, in_cx);
        }
    }

    fn fixed_stack_segment(attrs: &[ast::Attribute]) -> bool {
        attr::contains_name(attrs, "fixed_stack_segment")
    }
}

fn stack_check_fn<'a>(v: StackCheckVisitor,
                      fk: &visit::fn_kind,
                      decl: &ast::fn_decl,
                      body: &ast::Block,
                      sp: span,
                      id: ast::NodeId,
                      in_cx: Context) {
    let safe_stack = match *fk {
        visit::fk_method(*) | visit::fk_item_fn(*) => {
            in_cx.safe_stack // see stack_check_item above
        }
        visit::fk_anon(*) | visit::fk_fn_block => {
            match ty::get(ty::node_id_to_type(in_cx.tcx, id)).sty {
                ty::ty_bare_fn(*) |
                ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, _}) |
                ty::ty_closure(ty::ClosureTy {sigil: ast::ManagedSigil, _}) => {
                    false
                }
                _ => {
                    in_cx.safe_stack
                }
            }
        }
    };
    let new_cx = Context {safe_stack: safe_stack, ..in_cx};
    debug!("stack_check_fn(safe_stack=%b, id=%?)", safe_stack, id);
    let mut v = v;
    visit::walk_fn(&mut v, fk, decl, body, sp, id, new_cx);
}

fn stack_check_expr<'a>(v: StackCheckVisitor,
                        expr: @ast::expr,
                        cx: Context) {
    debug!("stack_check_expr(safe_stack=%b, expr=%s)",
           cx.safe_stack, expr.repr(cx.tcx));
    if !cx.safe_stack {
        match expr.node {
            ast::expr_call(callee, _, _) => {
                let callee_ty = ty::expr_ty(cx.tcx, callee);
                debug!("callee_ty=%s", callee_ty.repr(cx.tcx));
                match ty::get(callee_ty).sty {
                    ty::ty_bare_fn(ref fty) => {
                        if !fty.abis.is_rust() && !fty.abis.is_intrinsic() {
                            call_to_extern_fn(cx, callee);
                        }
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }
    let mut v = v;
    visit::walk_expr(&mut v, expr, cx);
}

fn call_to_extern_fn(cx: Context, callee: @ast::expr) {
    // Permit direct calls to extern fns that are annotated with
    // #[rust_stack]. This is naturally a horrible pain to achieve.
    match callee.node {
        ast::expr_path(*) => {
            match cx.tcx.def_map.find(&callee.id) {
                Some(&ast::def_fn(id, _)) if id.crate == ast::LOCAL_CRATE => {
                    match cx.tcx.items.find(&id.node) {
                        Some(&ast_map::node_foreign_item(item, _, _, _)) => {
                            if attr::contains_name(item.attrs, "rust_stack") {
                                return;
                            }
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }
        _ => {}
    }

    cx.tcx.sess.add_lint(lint::cstack,
                         callee.id,
                         callee.span,
                         fmt!("invoking non-Rust fn in fn without \
                              #[fixed_stack_segment]"));
}
<|endoftext|>


<commit_before><commit_msg>Added integration test to verify gather command creates hidden .reqtangle dir<commit_after>use std::process::Command;
use assert_cmd::prelude::*;
use tempfile::tempdir;

#[test]
fn hidden_reqtangle_directory_is_created_if_not_exist() -> Result<(), Box<std::error::Error>> {
    let working_dir = tempdir()?;
    let mut cmd = Command::cargo_bin("reqtangle")?;
    cmd
        .current_dir(&working_dir)
        .arg("gather");
    cmd.assert().success();
    let hidden_reqtangle_dir = working_dir.path().canonicalize()?.join(".reqtangle");
    assert!(hidden_reqtangle_dir.exists());
    working_dir.close()?;
    Ok(())
}<|endoftext|>


<commit_before><commit_msg>- Adds integration tests.<commit_after>#![feature(rustc_private)]

#[macro_use]
extern crate log ;
extern crate nslogger ;

#[test]
fn it_works() {
    nslogger::init().unwrap() ;

    error!("This is an NSLogger info message") ;
    error!("This is an NSLogger info message") ;
    error!("This is an NSLogger info message") ;
    error!("This is an NSLogger info message") ;
    println!("TEST") ;
}

<|endoftext|>


<commit_before>use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    braced,
    parse::{Parse, ParseStream, Result},
    Field, FieldValue, Ident, Meta, Token,
};

mod metadata;
mod request;
mod response;

use self::{metadata::Metadata, request::Request, response::Response};

pub fn strip_serde_attrs(field: &Field) -> Field {
    let mut field = field.clone();

    field.attrs = field
        .attrs
        .into_iter()
        .filter(|attr| {
            let meta = attr
                .interpret_meta()
                .expect("ruma_api! could not parse field attributes");

            let meta_list = match meta {
                Meta::List(meta_list) => meta_list,
                _ => return true,
            };

            if &meta_list.ident.to_string() == "serde" {
                return false;
            }

            true
        })
        .collect();

    field
}

pub struct Api {
    metadata: Metadata,
    request: Request,
    response: Response,
}

impl From<RawApi> for Api {
    fn from(raw_api: RawApi) -> Self {
        Api {
            metadata: raw_api.metadata.into(),
            request: raw_api.request.into(),
            response: raw_api.response.into(),
        }
    }
}

impl ToTokens for Api {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let description = &self.metadata.description;
        let method = Ident::new(self.metadata.method.as_ref(), Span::call_site());
        let name = &self.metadata.name;
        let path = &self.metadata.path;
        let rate_limited = &self.metadata.rate_limited;
        let requires_authentication = &self.metadata.requires_authentication;

        let request = &self.request;
        let request_types = quote! { #request };
        let response = &self.response;
        let response_types = quote! { #response };

        let extract_request_path = if self.request.has_path_fields() {
            quote! {
                let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect();
            }
        } else {
            TokenStream::new()
        };

        let (set_request_path, parse_request_path) = if self.request.has_path_fields() {
            let path_str = path.as_str();

            assert!(path_str.starts_with('/'), "path needs to start with '/'");
            assert!(
                path_str.chars().filter(|c| *c == ':').count() == self.request.path_field_count(),
                "number of declared path parameters needs to match amount of placeholders in path"
            );

            let request_path_init_fields = self.request.request_path_init_fields();

            let path_segments = path_str[1..].split('/').into_iter();
            let path_segment_push = path_segments.clone().map(|segment| {
                let arg = if segment.starts_with(':') {
                    let path_var = &segment[1..];
                    let path_var_ident = Ident::new(path_var, Span::call_site());
                    quote!(&request_path.#path_var_ident.to_string())
                } else {
                    quote!(#segment)
                };

                quote! {
                    path_segments.push(#arg);
                }
            });

            let set_tokens = quote! {
                let request_path = RequestPath {
                    #request_path_init_fields
                };

                // This `unwrap()` can only fail when the url is a
                // cannot-be-base url like `mailto:` or `data:`, which is not
                // the case for our placeholder url.
                let mut path_segments = url.path_segments_mut().unwrap();
                #(#path_segment_push)*
            };

            let path_fields = path_segments
                .enumerate()
                .filter(|(_, s)| s.starts_with(':'))
                .map(|(i, segment)| {
                    let path_var = &segment[1..];
                    let path_var_ident = Ident::new(path_var, Span::call_site());
                    let path_field = self
                        .request
                        .path_field(path_var)
                        .expect("expected request to have path field");
                    let ty = &path_field.ty;

                    quote! {
                        #path_var_ident: {
                            let segment = path_segments.get(#i).unwrap().as_bytes();
                            let decoded =
                                ::url::percent_encoding::percent_decode(segment)
                                .decode_utf8_lossy();
                            #ty::deserialize(decoded.into_deserializer())
                                .map_err(|e: ::serde_json::error::Error| e)?
                        }
                    }
                });

            let parse_tokens = quote! {
                #(#path_fields,)*
            };

            (set_tokens, parse_tokens)
        } else {
            let set_tokens = quote! {
                url.set_path(metadata.path);
            };
            let parse_tokens = TokenStream::new();
            (set_tokens, parse_tokens)
        };

        let set_request_query = if self.request.has_query_fields() {
            let request_query_init_fields = self.request.request_query_init_fields();

            quote! {
                let request_query = RequestQuery {
                    #request_query_init_fields
                };

                url.set_query(Some(&::serde_urlencoded::to_string(request_query)?));
            }
        } else {
            TokenStream::new()
        };

        let extract_request_query = if self.request.has_query_fields() {
            quote! {
                let request_query: RequestQuery =
                    ::serde_urlencoded::from_str(&request.uri().query().unwrap_or(""))?;
            }
        } else {
            TokenStream::new()
        };

        let parse_request_query = if self.request.has_query_fields() {
            self.request.request_init_query_fields()
        } else {
            TokenStream::new()
        };

        let add_headers_to_request = if self.request.has_header_fields() {
            let add_headers = self.request.add_headers_to_request();
            quote! {
                let headers = http_request.headers_mut();
                #add_headers
            }
        } else {
            TokenStream::new()
        };

        let extract_request_headers = if self.request.has_header_fields() {
            quote! {
                let headers = request.headers();
            }
        } else {
            TokenStream::new()
        };

        let parse_request_headers = if self.request.has_header_fields() {
            self.request.parse_headers_from_request()
        } else {
            TokenStream::new()
        };

        let create_http_request = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field
                .ident
                .as_ref()
                .expect("expected field to have an identifier");

            quote! {
                let request_body = RequestBody(request.#field_name);

                let mut http_request = ::http::Request::new(::serde_json::to_vec(&request_body)?.into());
            }
        } else if self.request.has_body_fields() {
            let request_body_init_fields = self.request.request_body_init_fields();

            quote! {
                let request_body = RequestBody {
                    #request_body_init_fields
                };

                let mut http_request = ::http::Request::new(::serde_json::to_vec(&request_body)?.into());
            }
        } else {
            quote! {
                let mut http_request = ::http::Request::new(::hyper::Body::empty());
            }
        };

        let extract_request_body = if let Some(field) = self.request.newtype_body_field() {
            let ty = &field.ty;
            quote! {
                let request_body: #ty =
                    ::serde_json::from_slice(request.body().as_slice())?;
            }
        } else if self.request.has_body_fields() {
            quote! {
                let request_body: RequestBody =
                    ::serde_json::from_slice(request.body().as_slice())?;
            }
        } else {
            TokenStream::new()
        };

        let parse_request_body = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field
                .ident
                .as_ref()
                .expect("expected field to have an identifier");

            quote! {
                #field_name: request_body,
            }
        } else if self.request.has_body_fields() {
            self.request.request_init_body_fields()
        } else {
            TokenStream::new()
        };

        let deserialize_response_body = if let Some(field) = self.response.newtype_body_field() {
            let field_type = &field.ty;

            quote! {
                let future_response = http_response.into_body()
                    .fold(Vec::new(), |mut vec, chunk| {
                        vec.extend(chunk.iter());
                        ::futures::future::ok::<_, ::hyper::Error>(vec)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|data|
                              ::serde_json::from_slice::<#field_type>(data.as_slice())
                              .map_err(::ruma_api::Error::from)
                              .into_future()
                    )
            }
        } else if self.response.has_body_fields() {
            quote! {
                let future_response = http_response.into_body()
                    .fold(Vec::new(), |mut vec, chunk| {
                        vec.extend(chunk.iter());
                        ::futures::future::ok::<_, ::hyper::Error>(vec)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|data|
                              ::serde_json::from_slice::<ResponseBody>(data.as_slice())
                              .map_err(::ruma_api::Error::from)
                              .into_future()
                    )
            }
        } else {
            quote! {
                let future_response = ::futures::future::ok(())
            }
        };

        let extract_response_headers = if self.response.has_header_fields() {
            quote! {
                let mut headers = http_response.headers().clone();
            }
        } else {
            TokenStream::new()
        };

        let response_init_fields = if self.response.has_fields() {
            self.response.init_fields()
        } else {
            TokenStream::new()
        };

        let serialize_response_headers = self.response.apply_header_fields();

        let serialize_response_body = if self.response.has_body() {
            let body = self.response.to_body();
            quote! {
                .body(::hyper::Body::from(::serde_json::to_vec(&#body)?))
            }
        } else {
            quote! {
                .body(::hyper::Body::from("{}".as_bytes().to_vec()))
            }
        };

        let api = quote! {
            #[allow(unused_imports)]
            use ::futures::{Future as _Future, IntoFuture as _IntoFuture, Stream as _Stream};
            use ::ruma_api::Endpoint as _RumaApiEndpoint;
            use ::serde::Deserialize as _Deserialize;
            use ::serde::de::{Error as _SerdeError, IntoDeserializer as _IntoDeserializer};

            use ::std::convert::{TryInto as _TryInto};

            /// The API endpoint.
            #[derive(Debug)]
            pub struct Endpoint;

            #request_types

            impl ::std::convert::TryFrom<::http::Request<Vec<u8>>> for Request {
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn try_from(request: ::http::Request<Vec<u8>>) -> Result<Self, Self::Error> {
                    #extract_request_path
                    #extract_request_query
                    #extract_request_headers
                    #extract_request_body

                    Ok(Request {
                        #parse_request_path
                        #parse_request_query
                        #parse_request_headers
                        #parse_request_body
                    })
                }
            }

            impl ::futures::future::FutureFrom<::http::Request<::hyper::Body>> for Request {
                type Future = Box<_Future<Item = Self, Error = Self::Error> + Send>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(request: ::http::Request<::hyper::Body>) -> Self::Future {
                    let (parts, body) = request.into_parts();
                    let future = body.from_err().fold(Vec::new(), |mut vec, chunk| {
                        vec.extend(chunk.iter());
                        ::futures::future::ok::<_, Self::Error>(vec)
                    }).and_then(|body| {
                        ::http::Request::from_parts(parts, body)
                            .try_into()
                            .into_future()
                            .from_err()
                    });
                    Box::new(future)
                }
            }

            impl ::std::convert::TryFrom<Request> for ::http::Request<::hyper::Body> {
                type Error = ::ruma_api::Error;

                #[allow(unused_mut, unused_variables)]
                fn try_from(request: Request) -> Result<Self, Self::Error> {
                    let metadata = Endpoint::METADATA;

                    // Use dummy homeserver url which has to be overwritten in
                    // the calling code. Previously (with http::Uri) this was
                    // not required, but Url::parse only accepts absolute urls.
                    let mut url = ::url::Url::parse("http://invalid-host-please-change/").unwrap();

                    { #set_request_path }
                    { #set_request_query }

                    #create_http_request

                    *http_request.method_mut() = ::http::Method::#method;
                    *http_request.uri_mut() = url.into_string().parse().unwrap();

                    { #add_headers_to_request }

                    Ok(http_request)
                }
            }

            #response_types

            impl ::std::convert::TryFrom<Response> for ::http::Response<::hyper::Body> {
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn try_from(response: Response) -> Result<Self, Self::Error> {
                    let response = ::http::Response::builder()
                        .header(::http::header::CONTENT_TYPE, "application/json")
                        #serialize_response_headers
                        #serialize_response_body
                        .unwrap();
                    Ok(response)
                }
            }

            impl ::futures::future::FutureFrom<::http::Response<::hyper::Body>> for Response {
                type Future = Box<_Future<Item = Self, Error = Self::Error> + Send>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(http_response: ::http::Response<::hyper::Body>) -> Self::Future {
                    if http_response.status().is_success() {
                        #extract_response_headers

                        #deserialize_response_body
                        .and_then(move |response_body| {
                            let response = Response {
                                #response_init_fields
                            };

                            Ok(response)
                        });

                        Box::new(future_response)
                    } else {
                        Box::new(::futures::future::err(::ruma_api::Error::StatusCode(http_response.status().clone())))
                    }
                }
            }

            impl ::ruma_api::Endpoint for Endpoint {
                type Request = Request;
                type Response = Response;

                const METADATA: ::ruma_api::Metadata = ::ruma_api::Metadata {
                    description: #description,
                    method: ::http::Method::#method,
                    name: #name,
                    path: #path,
                    rate_limited: #rate_limited,
                    requires_authentication: #requires_authentication,
                };
            }
        };

        api.to_tokens(tokens);
    }
}

mod kw {
    use syn::custom_keyword;

    custom_keyword!(metadata);
    custom_keyword!(request);
    custom_keyword!(response);
}

pub struct RawApi {
    pub metadata: Vec<FieldValue>,
    pub request: Vec<Field>,
    pub response: Vec<Field>,
}

impl Parse for RawApi {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        input.parse::<kw::metadata>()?;
        let metadata;
        braced!(metadata in input);

        input.parse::<kw::request>()?;
        let request;
        braced!(request in input);

        input.parse::<kw::response>()?;
        let response;
        braced!(response in input);

        Ok(RawApi {
            metadata: metadata
                .parse_terminated::<FieldValue, Token![,]>(FieldValue::parse)?
                .into_iter()
                .collect(),
            request: request
                .parse_terminated::<Field, Token![,]>(Field::parse_named)?
                .into_iter()
                .collect(),
            response: response
                .parse_terminated::<Field, Token![,]>(Field::parse_named)?
                .into_iter()
                .collect(),
        })
    }
}
<commit_msg>Make trait imports more readable (#18)<commit_after>use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    braced,
    parse::{Parse, ParseStream, Result},
    Field, FieldValue, Ident, Meta, Token,
};

mod metadata;
mod request;
mod response;

use self::{metadata::Metadata, request::Request, response::Response};

pub fn strip_serde_attrs(field: &Field) -> Field {
    let mut field = field.clone();

    field.attrs = field
        .attrs
        .into_iter()
        .filter(|attr| {
            let meta = attr
                .interpret_meta()
                .expect("ruma_api! could not parse field attributes");

            let meta_list = match meta {
                Meta::List(meta_list) => meta_list,
                _ => return true,
            };

            if &meta_list.ident.to_string() == "serde" {
                return false;
            }

            true
        })
        .collect();

    field
}

pub struct Api {
    metadata: Metadata,
    request: Request,
    response: Response,
}

impl From<RawApi> for Api {
    fn from(raw_api: RawApi) -> Self {
        Api {
            metadata: raw_api.metadata.into(),
            request: raw_api.request.into(),
            response: raw_api.response.into(),
        }
    }
}

impl ToTokens for Api {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let description = &self.metadata.description;
        let method = Ident::new(self.metadata.method.as_ref(), Span::call_site());
        let name = &self.metadata.name;
        let path = &self.metadata.path;
        let rate_limited = &self.metadata.rate_limited;
        let requires_authentication = &self.metadata.requires_authentication;

        let request = &self.request;
        let request_types = quote! { #request };
        let response = &self.response;
        let response_types = quote! { #response };

        let extract_request_path = if self.request.has_path_fields() {
            quote! {
                let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect();
            }
        } else {
            TokenStream::new()
        };

        let (set_request_path, parse_request_path) = if self.request.has_path_fields() {
            let path_str = path.as_str();

            assert!(path_str.starts_with('/'), "path needs to start with '/'");
            assert!(
                path_str.chars().filter(|c| *c == ':').count() == self.request.path_field_count(),
                "number of declared path parameters needs to match amount of placeholders in path"
            );

            let request_path_init_fields = self.request.request_path_init_fields();

            let path_segments = path_str[1..].split('/').into_iter();
            let path_segment_push = path_segments.clone().map(|segment| {
                let arg = if segment.starts_with(':') {
                    let path_var = &segment[1..];
                    let path_var_ident = Ident::new(path_var, Span::call_site());
                    quote!(&request_path.#path_var_ident.to_string())
                } else {
                    quote!(#segment)
                };

                quote! {
                    path_segments.push(#arg);
                }
            });

            let set_tokens = quote! {
                let request_path = RequestPath {
                    #request_path_init_fields
                };

                // This `unwrap()` can only fail when the url is a
                // cannot-be-base url like `mailto:` or `data:`, which is not
                // the case for our placeholder url.
                let mut path_segments = url.path_segments_mut().unwrap();
                #(#path_segment_push)*
            };

            let path_fields = path_segments
                .enumerate()
                .filter(|(_, s)| s.starts_with(':'))
                .map(|(i, segment)| {
                    let path_var = &segment[1..];
                    let path_var_ident = Ident::new(path_var, Span::call_site());
                    let path_field = self
                        .request
                        .path_field(path_var)
                        .expect("expected request to have path field");
                    let ty = &path_field.ty;

                    quote! {
                        #path_var_ident: {
                            let segment = path_segments.get(#i).unwrap().as_bytes();
                            let decoded =
                                ::url::percent_encoding::percent_decode(segment)
                                .decode_utf8_lossy();
                            #ty::deserialize(decoded.into_deserializer())
                                .map_err(|e: ::serde_json::error::Error| e)?
                        }
                    }
                });

            let parse_tokens = quote! {
                #(#path_fields,)*
            };

            (set_tokens, parse_tokens)
        } else {
            let set_tokens = quote! {
                url.set_path(metadata.path);
            };
            let parse_tokens = TokenStream::new();
            (set_tokens, parse_tokens)
        };

        let set_request_query = if self.request.has_query_fields() {
            let request_query_init_fields = self.request.request_query_init_fields();

            quote! {
                let request_query = RequestQuery {
                    #request_query_init_fields
                };

                url.set_query(Some(&::serde_urlencoded::to_string(request_query)?));
            }
        } else {
            TokenStream::new()
        };

        let extract_request_query = if self.request.has_query_fields() {
            quote! {
                let request_query: RequestQuery =
                    ::serde_urlencoded::from_str(&request.uri().query().unwrap_or(""))?;
            }
        } else {
            TokenStream::new()
        };

        let parse_request_query = if self.request.has_query_fields() {
            self.request.request_init_query_fields()
        } else {
            TokenStream::new()
        };

        let add_headers_to_request = if self.request.has_header_fields() {
            let add_headers = self.request.add_headers_to_request();
            quote! {
                let headers = http_request.headers_mut();
                #add_headers
            }
        } else {
            TokenStream::new()
        };

        let extract_request_headers = if self.request.has_header_fields() {
            quote! {
                let headers = request.headers();
            }
        } else {
            TokenStream::new()
        };

        let parse_request_headers = if self.request.has_header_fields() {
            self.request.parse_headers_from_request()
        } else {
            TokenStream::new()
        };

        let create_http_request = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field
                .ident
                .as_ref()
                .expect("expected field to have an identifier");

            quote! {
                let request_body = RequestBody(request.#field_name);

                let mut http_request = ::http::Request::new(::serde_json::to_vec(&request_body)?.into());
            }
        } else if self.request.has_body_fields() {
            let request_body_init_fields = self.request.request_body_init_fields();

            quote! {
                let request_body = RequestBody {
                    #request_body_init_fields
                };

                let mut http_request = ::http::Request::new(::serde_json::to_vec(&request_body)?.into());
            }
        } else {
            quote! {
                let mut http_request = ::http::Request::new(::hyper::Body::empty());
            }
        };

        let extract_request_body = if let Some(field) = self.request.newtype_body_field() {
            let ty = &field.ty;
            quote! {
                let request_body: #ty =
                    ::serde_json::from_slice(request.body().as_slice())?;
            }
        } else if self.request.has_body_fields() {
            quote! {
                let request_body: RequestBody =
                    ::serde_json::from_slice(request.body().as_slice())?;
            }
        } else {
            TokenStream::new()
        };

        let parse_request_body = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field
                .ident
                .as_ref()
                .expect("expected field to have an identifier");

            quote! {
                #field_name: request_body,
            }
        } else if self.request.has_body_fields() {
            self.request.request_init_body_fields()
        } else {
            TokenStream::new()
        };

        let deserialize_response_body = if let Some(field) = self.response.newtype_body_field() {
            let field_type = &field.ty;

            quote! {
                let future_response = http_response.into_body()
                    .fold(Vec::new(), |mut vec, chunk| {
                        vec.extend(chunk.iter());
                        ::futures::future::ok::<_, ::hyper::Error>(vec)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|data|
                              ::serde_json::from_slice::<#field_type>(data.as_slice())
                              .map_err(::ruma_api::Error::from)
                              .into_future()
                    )
            }
        } else if self.response.has_body_fields() {
            quote! {
                let future_response = http_response.into_body()
                    .fold(Vec::new(), |mut vec, chunk| {
                        vec.extend(chunk.iter());
                        ::futures::future::ok::<_, ::hyper::Error>(vec)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|data|
                              ::serde_json::from_slice::<ResponseBody>(data.as_slice())
                              .map_err(::ruma_api::Error::from)
                              .into_future()
                    )
            }
        } else {
            quote! {
                let future_response = ::futures::future::ok(())
            }
        };

        let extract_response_headers = if self.response.has_header_fields() {
            quote! {
                let mut headers = http_response.headers().clone();
            }
        } else {
            TokenStream::new()
        };

        let response_init_fields = if self.response.has_fields() {
            self.response.init_fields()
        } else {
            TokenStream::new()
        };

        let serialize_response_headers = self.response.apply_header_fields();

        let serialize_response_body = if self.response.has_body() {
            let body = self.response.to_body();
            quote! {
                .body(::hyper::Body::from(::serde_json::to_vec(&#body)?))
            }
        } else {
            quote! {
                .body(::hyper::Body::from("{}".as_bytes().to_vec()))
            }
        };

        let api = quote! {
            #[allow(unused_imports)]
            use ::futures::{Future as _, IntoFuture as _, Stream as _};
            use ::ruma_api::Endpoint as _;
            use ::serde::Deserialize as _;
            use ::serde::de::{Error as _, IntoDeserializer as _};

            use ::std::convert::{TryInto as _};

            /// The API endpoint.
            #[derive(Debug)]
            pub struct Endpoint;

            #request_types

            impl ::std::convert::TryFrom<::http::Request<Vec<u8>>> for Request {
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn try_from(request: ::http::Request<Vec<u8>>) -> Result<Self, Self::Error> {
                    #extract_request_path
                    #extract_request_query
                    #extract_request_headers
                    #extract_request_body

                    Ok(Request {
                        #parse_request_path
                        #parse_request_query
                        #parse_request_headers
                        #parse_request_body
                    })
                }
            }

            impl ::futures::future::FutureFrom<::http::Request<::hyper::Body>> for Request {
                type Future = Box<::futures::Future<Item = Self, Error = Self::Error> + Send>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(request: ::http::Request<::hyper::Body>) -> Self::Future {
                    let (parts, body) = request.into_parts();
                    let future = body.from_err().fold(Vec::new(), |mut vec, chunk| {
                        vec.extend(chunk.iter());
                        ::futures::future::ok::<_, Self::Error>(vec)
                    }).and_then(|body| {
                        ::http::Request::from_parts(parts, body)
                            .try_into()
                            .into_future()
                            .from_err()
                    });
                    Box::new(future)
                }
            }

            impl ::std::convert::TryFrom<Request> for ::http::Request<::hyper::Body> {
                type Error = ::ruma_api::Error;

                #[allow(unused_mut, unused_variables)]
                fn try_from(request: Request) -> Result<Self, Self::Error> {
                    let metadata = Endpoint::METADATA;

                    // Use dummy homeserver url which has to be overwritten in
                    // the calling code. Previously (with http::Uri) this was
                    // not required, but Url::parse only accepts absolute urls.
                    let mut url = ::url::Url::parse("http://invalid-host-please-change/").unwrap();

                    { #set_request_path }
                    { #set_request_query }

                    #create_http_request

                    *http_request.method_mut() = ::http::Method::#method;
                    *http_request.uri_mut() = url.into_string().parse().unwrap();

                    { #add_headers_to_request }

                    Ok(http_request)
                }
            }

            #response_types

            impl ::std::convert::TryFrom<Response> for ::http::Response<::hyper::Body> {
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn try_from(response: Response) -> Result<Self, Self::Error> {
                    let response = ::http::Response::builder()
                        .header(::http::header::CONTENT_TYPE, "application/json")
                        #serialize_response_headers
                        #serialize_response_body
                        .unwrap();
                    Ok(response)
                }
            }

            impl ::futures::future::FutureFrom<::http::Response<::hyper::Body>> for Response {
                type Future = Box<::futures::Future<Item = Self, Error = Self::Error> + Send>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(http_response: ::http::Response<::hyper::Body>) -> Self::Future {
                    if http_response.status().is_success() {
                        #extract_response_headers

                        #deserialize_response_body
                        .and_then(move |response_body| {
                            let response = Response {
                                #response_init_fields
                            };

                            Ok(response)
                        });

                        Box::new(future_response)
                    } else {
                        Box::new(::futures::future::err(::ruma_api::Error::StatusCode(http_response.status().clone())))
                    }
                }
            }

            impl ::ruma_api::Endpoint for Endpoint {
                type Request = Request;
                type Response = Response;

                const METADATA: ::ruma_api::Metadata = ::ruma_api::Metadata {
                    description: #description,
                    method: ::http::Method::#method,
                    name: #name,
                    path: #path,
                    rate_limited: #rate_limited,
                    requires_authentication: #requires_authentication,
                };
            }
        };

        api.to_tokens(tokens);
    }
}

mod kw {
    use syn::custom_keyword;

    custom_keyword!(metadata);
    custom_keyword!(request);
    custom_keyword!(response);
}

pub struct RawApi {
    pub metadata: Vec<FieldValue>,
    pub request: Vec<Field>,
    pub response: Vec<Field>,
}

impl Parse for RawApi {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        input.parse::<kw::metadata>()?;
        let metadata;
        braced!(metadata in input);

        input.parse::<kw::request>()?;
        let request;
        braced!(request in input);

        input.parse::<kw::response>()?;
        let response;
        braced!(response in input);

        Ok(RawApi {
            metadata: metadata
                .parse_terminated::<FieldValue, Token![,]>(FieldValue::parse)?
                .into_iter()
                .collect(),
            request: request
                .parse_terminated::<Field, Token![,]>(Field::parse_named)?
                .into_iter()
                .collect(),
            response: response
                .parse_terminated::<Field, Token![,]>(Field::parse_named)?
                .into_iter()
                .collect(),
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>ADD: pub client.request_timeout<commit_after><|endoftext|>


<commit_before><commit_msg>Unneeded import<commit_after><|endoftext|>


<commit_before><commit_msg>Handles representing the channel and chat states, as well as parsing channel IRC into a state representation<commit_after>/*
Tristen Horton
tristen@tristenhorton.com
2017-04-03

Module for basic channel data
Its possible to be in multiple channels at once in Twitch, so we want a simple way
to represent multiple channels at once - we'll be using this module and structure
for that.
*/

use message::Message;
use std::str::Split;

pub struct Channel {
	name: String,
	state: ChannelState
}

impl Channel {
	pub fn name(&self) -> &String {
		&self.name
	}

	pub fn state(&self) -> &ChannelState {
		&self.state
	}
}

pub struct ChannelState {

	r9k_mode: bool,
	sub_only: bool,
	slow_mode: bool,
	emote_only: bool,

	broadcaster_lang: String,
}

impl ChannelState {
	pub fn from(irc: String) -> ChannelState {
		let properties = irc.split_whitespace().nth(0);
		let mut r9k: bool = false;
		let mut sub: bool = false;
		let mut slow: bool = false;
		let mut emote: bool = false;
		let mut lang: String = String::from("");
		let mut channel: String = String::from("");

		macro_rules! parse_from_nth {
			($tag:ident, $e:expr) => ($tag.nth($e).unwrap().parse().unwrap());
		}

		for prop in properties.unwrap().split(";") {
			let mut prop_split = prop.split("=");
			match prop_split.nth(0).unwrap() {

				"broadcaster-lang" => lang = prop_split.nth(1).unwrap().to_string(),

				"emote-only" => emote = bool_from_nth_str(&mut prop_split, 1),
				"r9k" => r9k = bool_from_nth_str(&mut prop_split, 1),
				"slow" => slow = bool_from_nth_str(&mut prop_split, 1),
				"subs-only" => sub = bool_from_nth_str(&mut prop_split, 1),

				_ => println!("[twitch-rs] Unnacounted for irc property: {:?}", prop),
			}
		}

		channel = irc.to_string().split("#").nth(1).unwrap().to_string();

		ChannelState {
			r9k_mode: r9k,
			sub_only: sub,
			slow_mode: slow,
			emote_only: emote,
			broadcaster_lang: lang,
		}
	}
}

fn bool_from_nth_str(split: &mut Split<&str>, nth: usize) -> bool {
	split.nth(nth)
		.unwrap_or("false")
		.parse::<bool>()
		.unwrap_or(false)
}
<|endoftext|>


<commit_before><commit_msg>Fix an error message that reversed the expected and actual number of arguments in a pattern<commit_after><|endoftext|>


<commit_before>use std::iter::repeat;

use ansi_term::Style;

use options::{SizeFormat, TimeType};

#[derive(PartialEq, Debug, Copy)]
pub enum Column {
    Permissions,
    FileSize(SizeFormat),
    Timestamp(TimeType, i64),
    Blocks,
    User,
    Group,
    HardLinks,
    Inode,

    GitStatus,
}

/// Each column can pick its own **Alignment**. Usually, numbers are
/// right-aligned, and text is left-aligned.
#[derive(Copy)]
pub enum Alignment {
    Left, Right,
}

impl Column {

    /// Get the alignment this column should use.
    pub fn alignment(&self) -> Alignment {
        match *self {
            Column::FileSize(_) => Alignment::Right,
            Column::HardLinks   => Alignment::Right,
            Column::Inode       => Alignment::Right,
            Column::Blocks      => Alignment::Right,
            Column::GitStatus   => Alignment::Right,
            _                   => Alignment::Left,
        }
    }

    /// Get the text that should be printed at the top, when the user elects
    /// to have a header row printed.
    pub fn header(&self) -> &'static str {
        match *self {
            Column::Permissions     => "Permissions",
            Column::FileSize(_)     => "Size",
            Column::Timestamp(t, _) => t.header(),
            Column::Blocks          => "Blocks",
            Column::User            => "User",
            Column::Group           => "Group",
            Column::HardLinks       => "Links",
            Column::Inode           => "inode",
            Column::GitStatus       => "Git",
        }
    }
}

/// Pad a string with the given number of spaces.
fn spaces(length: usize) -> String {
    repeat(" ").take(length).collect()
}

impl Alignment {
    /// Pad a string with the given alignment and number of spaces.
    ///
    /// This doesn't take the width the string *should* be, rather the number
    /// of spaces to add: this is because the strings are usually full of
    /// invisible control characters, so getting the displayed width of the
    /// string is not as simple as just getting its length.
    pub fn pad_string(&self, string: &String, padding: usize) -> String {
        match *self {
            Alignment::Left  => format!("{}{}", string, spaces(padding).as_slice()),
            Alignment::Right => format!("{}{}", spaces(padding), string.as_slice()),
        }
    }
}

#[derive(PartialEq, Debug)]
pub struct Cell {
    pub length: usize,
    pub text: String,
}

impl Cell {
    pub fn paint(style: Style, string: &str) -> Cell {
        Cell {
            text: style.paint(string).to_string(),
            length: string.len(),
        }
    }
}
<commit_msg>Count the number of grapheme clusters to determine the cell length.<commit_after>use std::iter::repeat;

use ansi_term::Style;

use options::{SizeFormat, TimeType};

#[derive(PartialEq, Debug, Copy)]
pub enum Column {
    Permissions,
    FileSize(SizeFormat),
    Timestamp(TimeType, i64),
    Blocks,
    User,
    Group,
    HardLinks,
    Inode,

    GitStatus,
}

/// Each column can pick its own **Alignment**. Usually, numbers are
/// right-aligned, and text is left-aligned.
#[derive(Copy)]
pub enum Alignment {
    Left, Right,
}

impl Column {

    /// Get the alignment this column should use.
    pub fn alignment(&self) -> Alignment {
        match *self {
            Column::FileSize(_) => Alignment::Right,
            Column::HardLinks   => Alignment::Right,
            Column::Inode       => Alignment::Right,
            Column::Blocks      => Alignment::Right,
            Column::GitStatus   => Alignment::Right,
            _                   => Alignment::Left,
        }
    }

    /// Get the text that should be printed at the top, when the user elects
    /// to have a header row printed.
    pub fn header(&self) -> &'static str {
        match *self {
            Column::Permissions     => "Permissions",
            Column::FileSize(_)     => "Size",
            Column::Timestamp(t, _) => t.header(),
            Column::Blocks          => "Blocks",
            Column::User            => "User",
            Column::Group           => "Group",
            Column::HardLinks       => "Links",
            Column::Inode           => "inode",
            Column::GitStatus       => "Git",
        }
    }
}

/// Pad a string with the given number of spaces.
fn spaces(length: usize) -> String {
    repeat(" ").take(length).collect()
}

impl Alignment {
    /// Pad a string with the given alignment and number of spaces.
    ///
    /// This doesn't take the width the string *should* be, rather the number
    /// of spaces to add: this is because the strings are usually full of
    /// invisible control characters, so getting the displayed width of the
    /// string is not as simple as just getting its length.
    pub fn pad_string(&self, string: &String, padding: usize) -> String {
        match *self {
            Alignment::Left  => format!("{}{}", string, spaces(padding).as_slice()),
            Alignment::Right => format!("{}{}", spaces(padding), string.as_slice()),
        }
    }
}

#[derive(PartialEq, Debug)]
pub struct Cell {
    pub length: usize,
    pub text: String,
}

impl Cell {
    pub fn paint(style: Style, string: &str) -> Cell {
        Cell {
            text: style.paint(string).to_string(),
            length: string.graphemes(true).count(),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Create an executable that produces the no background image<commit_after>extern crate simple_csv;
extern crate png;

use std::env;
use std::fs::File;
use std::io::{BufWriter, BufReader};
use std::str::FromStr;
use png::HasParameters;
use simple_csv::SimpleCsvReader;

fn main(){
    let f = File::open("../long-cadence.csv").unwrap();
    let buf = BufReader::new(f);
    let mut reader = SimpleCsvReader::new(buf);
    let row = reader.next_row().unwrap().unwrap();
    let mut iter = row.iter();
    iter.next(); // dropping time

    let raw: Vec<f64> = iter
        .map(|s| f64::from_str(s).unwrap())
        .collect();
    let sum = raw
        .iter()
        .fold(0f64, |acc, v| acc+v);
    let average = sum/(raw.len() as f64);
    let maximum = raw
        .iter()
        .fold(std::f64::MIN, |acc, v| acc.max(*v));
    let data: Vec<u8> = raw
        .iter()
        .map(|s| if s >= &average { s*1.0 } else { s*0.0 })
        .map(|s| s/maximum)
        .map(|s| 255.0 * s)
        .map(|s| s.floor() as u8)
        .collect();

    let mut path = env::current_dir().unwrap();
    path.push(format!("assets/trappist-1.{}.nobg.png", 0));

    let file = File::create(path).unwrap();
    let ref mut w = BufWriter::new(file);

    let mut encoder = png::Encoder::new(w, 11, 11);
    encoder.set(png::ColorType::Grayscale).set(png::BitDepth::Eight);
    let mut writer = encoder.write_header().unwrap();

    writer.write_image_data(data.as_slice()).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Add a more descriptive comment for closing brace<commit_after><|endoftext|>


<commit_before><commit_msg>Add a function to delete layers<commit_after><|endoftext|>


<commit_before><commit_msg>Feat(mapping): use correct unit test host name<commit_after><|endoftext|>


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


<commit_before><commit_msg>Expand documentation for IntoInnerError<commit_after><|endoftext|>


<commit_before><commit_msg>extra: Move uuid to libuuid cc #8784<commit_after><|endoftext|>


<commit_before><commit_msg>WIP: server<commit_after><|endoftext|>


<commit_before><commit_msg>Add SEEK_DATA/SEEK_HOLE constants<commit_after><|endoftext|>


<commit_before><commit_msg>Add test bin<commit_after>extern crate wiko;
extern crate diesel;

use self::wiko::*;
use self::wiko::models::*;
use self::diesel::prelude::*;

fn main() {
    use wiko::schema::posts::dsl as posts;
    use wiko::schema::posts_revisions::dsl as posts_revisions;

    let connection = establish_connection();

    let new_post_revision = NewPostRevision {
        post_id: 19,
        title: "Hello world!".to_owned(),
        body: "Lorem ipsum, dolor sit amet.\nThe end".to_owned(),
    };

    let _updated: Post = diesel::update(posts::posts.filter(posts::id.eq(19)))
        .set(posts::title.eq("Good night moon"))
        .get_result(&connection)
        .expect("Error updating post");

    let inserted: PostsRevision = diesel::insert(&new_post_revision)
        .into(posts_revisions::posts_revisions)
        .get_result(&connection)
        .expect("Error creating new post revision");

    println!("{} {} {:?}", inserted.id, inserted.title, inserted.created_at);
    println!("{}", inserted.body);
    println!("----------\n");

    let posts = posts::posts.filter(posts::published.eq(true))
        .limit(5)
        .order(posts::id.asc())
        .load::<(Post)>(&connection)
        .expect("Error loading posts");

    let all_needed_revisions = PostsRevision::belonging_to(&posts)
        .order(posts_revisions::created.desc())
        .limit(5)
        .load::<PostsRevision>(&connection)
        .expect("Error loading revisions");

    let grouped_revisions = all_needed_revisions.grouped_by(&posts);
    let posts_with_revisions = posts.into_iter().zip(grouped_revisions).collect::<Vec<_>>();

    for (post, revisions) in posts_with_revisions {
        println!("{} {}", post.id, post.title);
        println!("{}", post.body);
        println!("{} revisions:", revisions.len());
        for revision in revisions {
            println!("| {} | {} | {}", revision.id, revision.created_at, revision.title);
        }
        println!("----------\n");
    }

    //let posts_to_delete = posts::posts.filter(posts::title.like("Hello world%"));
    //let num_deleted = diesel::delete(posts_to_delete)
    //    .execute(&connection)
    //    .expect(&format!("Error deleting post {}", inserted.id));
    //println!("Deleted {} posts", num_deleted);
}
<|endoftext|>


<commit_before><commit_msg>Refresh the renderer documentation in begin_frame(), and tweak a few other comments<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Implemented Request for IronRequest.<commit_after><|endoftext|>


<commit_before><commit_msg>Disable namespace plugins by default<commit_after><|endoftext|>


<commit_before><commit_msg>Render the missing geometry (fix issue #5)<commit_after><|endoftext|>


<commit_before><commit_msg>Avoid Vulkan Vertex Buffer allocation until the point they are needed<commit_after><|endoftext|>


<commit_before><commit_msg>Add commented code to enable the robustBufferAccess feature<commit_after><|endoftext|>


<commit_before>use orbclient;
use super::super::geometry;

/// Draw a triangle, from 9 floats representing vertice coordinates
#[allow(dead_code)]
pub fn triangle_p(x1: f32, y1: f32, z1: f32,
                  x2: f32, y2: f32, z2: f32,
                  x3: f32, y3: f32, z3: f32,
                  color: orbclient::Color, window: &mut orbclient::window::Window) {
    use super::{perpective, screen};

    // Calculate perspective for points.
    let (x1, y1) = perpective(x1, y1, z1);
    let (x2, y2) = perpective(x2, y2, z2);
    let (x3, y3) = perpective(x3, y3, z3);

    let scr_width  =  window.width() as i32;
    let scr_height = window.height() as i32;

    // Change f32 points into drawable i32, based on screen width,
    let (x1, y1) = screen(x1, y1, scr_width, scr_height);
    let (x2, y2) = screen(x2, y2, scr_width, scr_height);
    let (x3, y3) = screen(x3, y3, scr_width, scr_height);

    window.line(x1, y1, x2, y2, color);
    window.line(x2, y2, x3, y3, color);
    window.line(x3, y3, x1, y1, color);
}

pub fn triangle_s(triangle: geometry::Triangle,
                  color: orbclient::Color, window: &mut orbclient::window::Window) {
    triangle_p(triangle.p1.x, triangle.p1.y, triangle.p1.z,
               triangle.p2.x, triangle.p2.y, triangle.p2.z,
               triangle.p3.x, triangle.p3.y, triangle.p3.z,
               color, window);
}<commit_msg>Fixed lack of reference.<commit_after>use orbclient;
use super::super::geometry;

/// Draw a triangle, from 9 floats representing vertice coordinates
#[allow(dead_code)]
pub fn triangle_p(x1: f32, y1: f32, z1: f32,
                  x2: f32, y2: f32, z2: f32,
                  x3: f32, y3: f32, z3: f32,
                  color: orbclient::Color, window: &mut orbclient::window::Window) {
    use super::{perpective, screen};

    // Calculate perspective for points.
    let (x1, y1) = perpective(x1, y1, z1);
    let (x2, y2) = perpective(x2, y2, z2);
    let (x3, y3) = perpective(x3, y3, z3);

    let scr_width  =  window.width() as i32;
    let scr_height = window.height() as i32;

    // Change f32 points into drawable i32, based on screen width,
    let (x1, y1) = screen(x1, y1, scr_width, scr_height);
    let (x2, y2) = screen(x2, y2, scr_width, scr_height);
    let (x3, y3) = screen(x3, y3, scr_width, scr_height);

    window.line(x1, y1, x2, y2, color);
    window.line(x2, y2, x3, y3, color);
    window.line(x3, y3, x1, y1, color);
}

pub fn triangle_s(triangle: &geometry::Triangle,
                  color: orbclient::Color, window: &mut orbclient::window::Window) {
    triangle_p(triangle.p1.x, triangle.p1.y, triangle.p1.z,
               triangle.p2.x, triangle.p2.y, triangle.p2.z,
               triangle.p3.x, triangle.p3.y, triangle.p3.z,
               color, window);
}<|endoftext|>


<commit_before><commit_msg>Add example for cache parameters.<commit_after>extern crate raw_cpuid;
use raw_cpuid::{CacheType, CpuId};

fn main() {
    let cpuid = CpuId::new();
    cpuid.get_cache_parameters().map_or_else(
        || println!("No cache parameter information available"),
        |cparams| {
            for cache in cparams {
                let size = cache.associativity()
                    * cache.physical_line_partitions()
                    * cache.coherency_line_size()
                    * cache.sets();

                let typ = match cache.cache_type() {
                    CacheType::Data => "Instruction-Cache",
                    CacheType::Instruction => "Data-Cache",
                    CacheType::Unified => "Unified-Cache",
                    _ => "Unknown cache type",
                };

                let associativity = if cache.is_fully_associative() {
                    format!("fully associative")
                } else {
                    format!("{}-way associativity", cache.associativity())
                };

                let size_repr = if size > 1024 * 1024 {
                    format!("{} MiB", size / (1024 * 1024))
                } else {
                    format!("{} KiB", size / 1024)
                };

                let mapping = if cache.has_complex_indexing() {
                    "hash-based-mapping"
                } else {
                    "direct-mapped"
                };

                println!(
                    "L{} {}: ({}, {}, {})",
                    cache.level(),
                    typ,
                    size_repr,
                    associativity,
                    mapping
                );
            }
        },
    );
}
<|endoftext|>