<commit_before>use std::collections::HashMap;
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use std::hash::{Hash, Hasher};

use std::collections::vec_deque::VecDeque;
use std::collections::BTreeMap;

use super::{Result, LuaError};

pub type Scope = Rc<BTreeMap<String, LuaValue>>;

#[derive(Debug)]
pub struct LuaState {
     last_id: Cell<usize>,
     global: LuaTable,
     scope_stack: VecDeque<Scope>,
}

impl LuaState {
    pub fn new() -> LuaState {

        let mut ret =  LuaState {
            last_id: Cell::new(0),
            global: LuaTable::new(0),
            scope_stack: VecDeque::new()
        };

        ret.push_scope();
        let table = LuaValue::Table(ret.global.clone());
        Rc::get_mut(ret.get_mutable_local_scope().unwrap()).unwrap().insert("_ENV".to_owned(), table);
        return ret;
    }

    pub fn get_ref_id(&self) -> usize {
        self.last_id.set(self.last_id.get()+1);
        return self.last_id.get();
    }

    pub fn resolve_name(&self, name: &String) -> Option<&Scope> {
        for scope in self.scope_stack.iter() {
            if scope.contains_key(name) {
                return Some(scope)
            }
        }
        return None
    }

    pub fn get_local_scope(&self) -> Option<&Scope> {
        self.scope_stack.front()
    }

    pub fn get_mutable_local_scope(&mut self) -> Option<&mut Scope> {
        self.scope_stack.front_mut()
    }

    pub fn push_scope(&mut self) {
        self.scope_stack.push_front(Rc::new(BTreeMap::new()));
    }

    pub fn pop_scope(&mut self) {
        if self.scope_stack.is_empty() {
            panic!("No scope to pop!")
        }
        self.scope_stack.pop_front();
    }
}

#[derive(Debug,Eq)]
struct CoreTable {
    pub ref_id: usize,
        pub map: RefCell<HashMap<LuaValue, LuaValue>>,
        pub vector: RefCell<Vec<LuaValue>>,
}

impl CoreTable {
}

impl PartialEq for CoreTable {
    fn eq(&self, other: &CoreTable) -> bool {
        return self.ref_id == other.ref_id
    }
}

impl Hash for CoreTable {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ref_id.hash(state);
    }
}

#[derive(Debug,PartialEq,Eq,Hash,Clone)]
pub struct LuaTable {
content: Rc<CoreTable>
}

impl LuaTable {
    pub fn new(id: usize) -> LuaTable {
        LuaTable {
             content: Rc::new(
                 CoreTable {
                      ref_id: id,
                      map: RefCell::new(HashMap::new()),
                      vector: RefCell::new(Vec::new()) }) }
    }

    pub fn with_capacity(id: usize, capacity: usize) -> LuaTable {
        LuaTable {
            content: Rc::new(
                CoreTable {
                    ref_id: id,
                    map: RefCell::new(HashMap::new()),
                    vector: RefCell::new(Vec::with_capacity(capacity))
                    })
        }
    }

    pub fn sequence_border(&self) -> usize {
        return self.content.vector.borrow().len();
    }

    pub fn set(&self, key: &LuaValue, value: &LuaValue) -> Result<()> {
        match *key {
            LuaValue::Nil => Err(LuaError::IndexError("Using nil as a table index".to_owned())),
                LuaValue::Float(f) => {
                    if f.is_nan() {
                        Err(LuaError::IndexError("Using NaN as a table index".to_owned()))
                    } else {
                        let round = f.round();
                        if round == f {
                            self.set(&LuaValue::Integer(round as isize), value)?
                        } else {
                            self.map_set(key, value)
                        };
                        Ok(())
                    }
                },
                LuaValue::Integer(i) => {
                    if i < 1 || (i as usize) > self.content.vector.borrow().len()+1 {
                        self.map_set(key, value);
                    } else {
                        self.sequence_set(i, value);
                    }
                    Ok(())
                }
            _ => {
                self.map_set(key, value);
                Ok(())
            }
        }
    }

    fn map_set(&self, key: &LuaValue, value: &LuaValue) {
        let mut map = self.content.map.borrow_mut();
        match *value {
            LuaValue::Nil => {map.remove(key); () },
                _ =>{ map.insert(key.clone(), value.clone()); () }
        }
    }

    fn sequence_set(&self, idx: isize, value: &LuaValue) {
        let mut seq = self.content.vector.borrow_mut();
        assert!(idx >= 1);

        let idx = (idx-1) as usize;
        if idx == seq.len() {
            seq.push(value.clone());
        }
    }
}

#[derive(Debug,PartialEq,Clone)]
pub enum LuaValue {
    Nil,
        Integer(isize),
        Float(f64),
        Boolean(bool),
        Str(String),
        Table(LuaTable)
}

// This trait is there to say that the equality is symmetric, reflexive and transitive,
// which isn't the case for floats (NaN != NaN). However, for now these properties are
// only used in the table hashmap, and the specs say that a Lua table won't ever have NaN
// as an index, so...
// WARNING: This is gonna bite me in the rear.
impl Eq for LuaValue { }

impl Hash for LuaValue {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            &LuaValue::Nil => 0.hash(state),
                &LuaValue::Integer(ref i) => i.hash(state),
                &LuaValue::Float(ref f) => f.to_bits().hash(state),
                &LuaValue::Boolean(ref b) => b.hash(state),
                &LuaValue::Str(ref s) => s.hash(state),
                &LuaValue::Table(ref t) => t.hash(state),
        }
    }
}
<commit_msg>Add a recolve_name_mut method to LuaState<commit_after>use std::collections::HashMap;
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use std::hash::{Hash, Hasher};

use std::collections::vec_deque::VecDeque;
use std::collections::BTreeMap;

use super::{Result, LuaError};

pub type Scope = Rc<BTreeMap<String, LuaValue>>;

#[derive(Debug)]
pub struct LuaState {
     last_id: Cell<usize>,
     global: LuaTable,
     scope_stack: VecDeque<Scope>,
}

impl LuaState {
    pub fn new() -> LuaState {

        let mut ret =  LuaState {
            last_id: Cell::new(0),
            global: LuaTable::new(0),
            scope_stack: VecDeque::new()
        };

        ret.push_scope();
        let table = LuaValue::Table(ret.global.clone());
        Rc::get_mut(ret.get_mutable_local_scope().unwrap()).unwrap().insert("_ENV".to_owned(), table);
        return ret;
    }

    pub fn get_ref_id(&self) -> usize {
        self.last_id.set(self.last_id.get()+1);
        return self.last_id.get();
    }

    pub fn resolve_name(&self, name: &String) -> Option<&Scope> {
        for scope in self.scope_stack.iter() {
            if scope.contains_key(name) {
                return Some(scope)
            }
        }
        return None
    }

    pub fn resolve_name_mut(&mut self, name: &String) -> Option<&mut Scope> {
        for scope in self.scope_stack.iter_mut() {
            if scope.contains_key(name) {
                return Some(scope)
            }
        }
        return None
    }

    pub fn get_local_scope(&self) -> Option<&Scope> {
        self.scope_stack.front()
    }

    pub fn get_mutable_local_scope(&mut self) -> Option<&mut Scope> {
        self.scope_stack.front_mut()
    }

    pub fn push_scope(&mut self) {
        self.scope_stack.push_front(Rc::new(BTreeMap::new()));
    }

    pub fn pop_scope(&mut self) {
        if self.scope_stack.is_empty() {
            panic!("No scope to pop!")
        }
        self.scope_stack.pop_front();
    }
}

#[derive(Debug,Eq)]
struct CoreTable {
    pub ref_id: usize,
        pub map: RefCell<HashMap<LuaValue, LuaValue>>,
        pub vector: RefCell<Vec<LuaValue>>,
}

impl CoreTable {
}

impl PartialEq for CoreTable {
    fn eq(&self, other: &CoreTable) -> bool {
        return self.ref_id == other.ref_id
    }
}

impl Hash for CoreTable {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ref_id.hash(state);
    }
}

#[derive(Debug,PartialEq,Eq,Hash,Clone)]
pub struct LuaTable {
content: Rc<CoreTable>
}

impl LuaTable {
    pub fn new(id: usize) -> LuaTable {
        LuaTable {
             content: Rc::new(
                 CoreTable {
                      ref_id: id,
                      map: RefCell::new(HashMap::new()),
                      vector: RefCell::new(Vec::new()) }) }
    }

    pub fn with_capacity(id: usize, capacity: usize) -> LuaTable {
        LuaTable {
            content: Rc::new(
                CoreTable {
                    ref_id: id,
                    map: RefCell::new(HashMap::new()),
                    vector: RefCell::new(Vec::with_capacity(capacity))
                    })
        }
    }

    pub fn sequence_border(&self) -> usize {
        return self.content.vector.borrow().len();
    }

    pub fn set(&self, key: &LuaValue, value: &LuaValue) -> Result<()> {
        match *key {
            LuaValue::Nil => Err(LuaError::IndexError("Using nil as a table index".to_owned())),
                LuaValue::Float(f) => {
                    if f.is_nan() {
                        Err(LuaError::IndexError("Using NaN as a table index".to_owned()))
                    } else {
                        let round = f.round();
                        if round == f {
                            self.set(&LuaValue::Integer(round as isize), value)?
                        } else {
                            self.map_set(key, value)
                        };
                        Ok(())
                    }
                },
                LuaValue::Integer(i) => {
                    if i < 1 || (i as usize) > self.content.vector.borrow().len()+1 {
                        self.map_set(key, value);
                    } else {
                        self.sequence_set(i, value);
                    }
                    Ok(())
                }
            _ => {
                self.map_set(key, value);
                Ok(())
            }
        }
    }

    fn map_set(&self, key: &LuaValue, value: &LuaValue) {
        let mut map = self.content.map.borrow_mut();
        match *value {
            LuaValue::Nil => {map.remove(key); () },
                _ =>{ map.insert(key.clone(), value.clone()); () }
        }
    }

    fn sequence_set(&self, idx: isize, value: &LuaValue) {
        let mut seq = self.content.vector.borrow_mut();
        assert!(idx >= 1);

        let idx = (idx-1) as usize;
        if idx == seq.len() {
            seq.push(value.clone());
        }
    }
}

#[derive(Debug,PartialEq,Clone)]
pub enum LuaValue {
    Nil,
        Integer(isize),
        Float(f64),
        Boolean(bool),
        Str(String),
        Table(LuaTable)
}

// This trait is there to say that the equality is symmetric, reflexive and transitive,
// which isn't the case for floats (NaN != NaN). However, for now these properties are
// only used in the table hashmap, and the specs say that a Lua table won't ever have NaN
// as an index, so...
// WARNING: This is gonna bite me in the rear.
impl Eq for LuaValue { }

impl Hash for LuaValue {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            &LuaValue::Nil => 0.hash(state),
                &LuaValue::Integer(ref i) => i.hash(state),
                &LuaValue::Float(ref f) => f.to_bits().hash(state),
                &LuaValue::Boolean(ref b) => b.hash(state),
                &LuaValue::Str(ref s) => s.hash(state),
                &LuaValue::Table(ref t) => t.hash(state),
        }
    }
}
<|endoftext|>


<commit_before>
#![feature(globs)]

extern crate piston;
extern crate graphics;
extern crate sdl2_game_window;
extern crate opengl_graphics;

use std::rc::Rc;

use piston::{
    AssetStore,
    EventIterator,
    EventSettings,
    WindowSettings,
    Render,
};
use piston::sprite::*;
use piston::event::{
    Action,
    Sequence,
    Wait,
    WaitForever,
    While,
};

use graphics::*;

use sdl2_game_window::WindowSDL2;
use opengl_graphics::{
    Gl,
    Texture,
};

fn main() {
    let (width, height) = (300, 300);
    let opengl = piston::shader_version::opengl::OpenGL_3_2;
    let mut window = WindowSDL2::new(
        opengl,
        WindowSettings {
            title: "Sprite".to_string(),
            size: [width, height],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let asset_store = AssetStore::from_folder("../");
    let mut scene = Scene::new();

    let tex = Rc::new(Texture::from_path(&asset_store.path("rust-logo.png").unwrap()).unwrap());
    let mut sprite = Sprite::from_texture(tex.clone());
    sprite.set_position(width as f64 / 2.0, height as f64 / 2.0);

    let id = scene.add_child(sprite);

    // Run a sequence actions
    scene.run_action(id, Sequence(vec![
        Action(Ease(EaseCubicOut, box ScaleTo(2.0, 0.5, 0.5))),
        Action(Ease(EaseBounceOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Ease(EaseElasticOut, box MoveBy(2.0, 0.0, -100.0))),
        Action(Ease(EaseBackInOut, box MoveBy(1.0, 0.0, -100.0))),
        Wait(0.5),
        Action(Ease(EaseExponentialInOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Blink(1.0, 5)),
        While(box WaitForever, vec![
            Action(Ease(EaseQuadraticIn, box FadeOut(1.0))),
            Action(Ease(EaseQuadraticOut, box FadeIn(1.0))),
        ]),
    ]));

    // This action and above one can run in parallel
    scene.run_action(id, Action(Ease(EaseExponentialInOut, box RotateTo(2.0, 360.0))));

    let event_settings = EventSettings {
        updates_per_second: 120,
        max_frames_per_second: 60,
    };
    let ref mut gl = Gl::new(opengl);
    for e in EventIterator::new(&mut window, &event_settings) {
        scene.update(&e);

        match e {
            Render(args) => {
                gl.viewport(0, 0, args.width as i32, args.height as i32);

                let c = Context::abs(args.width as f64, args.width as f64);
                c.rgb(1.0, 1.0, 1.0).draw(gl);

                scene.draw(&c, gl);
            },
            _ => {},
        }
    }
}
<commit_msg>Upgraded to latest sprite<commit_after>
#![feature(globs)]

extern crate piston;
extern crate graphics;
extern crate sdl2_game_window;
extern crate opengl_graphics;

use std::rc::Rc;

use piston::{
    AssetStore,
    EventIterator,
    EventSettings,
    WindowSettings,
    Render,
    Input,
};
use piston::sprite::*;
use piston::event::{
    Action,
    Sequence,
    Wait,
    WaitForever,
    While,
};

use graphics::*;

use sdl2_game_window::WindowSDL2;
use opengl_graphics::{
    Gl,
    Texture,
};

fn main() {
    let (width, height) = (300, 300);
    let opengl = piston::shader_version::opengl::OpenGL_3_2;
    let mut window = WindowSDL2::new(
        opengl,
        WindowSettings {
            title: "Sprite".to_string(),
            size: [width, height],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let asset_store = AssetStore::from_folder("../");
    let mut scene = Scene::new();

    let tex = Rc::new(Texture::from_path(&asset_store.path("rust-logo.png").unwrap()).unwrap());
    let mut sprite = Sprite::from_texture(tex.clone());
    sprite.set_position(width as f64 / 2.0, height as f64 / 2.0);

    let id = scene.add_child(sprite);

    // Run a sequence actions
    let seq_action = Sequence(vec![
        Action(Ease(EaseCubicOut, box ScaleTo(2.0, 0.5, 0.5))),
        Action(Ease(EaseBounceOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Ease(EaseElasticOut, box MoveBy(2.0, 0.0, -100.0))),
        Action(Ease(EaseBackInOut, box MoveBy(1.0, 0.0, -100.0))),
        Wait(0.5),
        Action(Ease(EaseExponentialInOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Blink(1.0, 5)),
        While(box WaitForever, vec![
            Action(Ease(EaseQuadraticIn, box FadeOut(1.0))),
            Action(Ease(EaseQuadraticOut, box FadeIn(1.0))),
        ]),
    ]);
    scene.run_action(id, &seq_action);

    // This action and above one can run in parallel
    let rotate_action = Action(Ease(EaseExponentialInOut, box RotateTo(2.0, 360.0)));
    scene.run_action(id, &rotate_action);

    println!("Press any key to pause/resume the animation!");

    let event_settings = EventSettings {
        updates_per_second: 120,
        max_frames_per_second: 60,
    };
    let ref mut gl = Gl::new(opengl);
    for e in EventIterator::new(&mut window, &event_settings) {
        scene.update(&e);

        match e {
            Render(args) => {
                gl.viewport(0, 0, args.width as i32, args.height as i32);

                let c = Context::abs(args.width as f64, args.width as f64);
                c.rgb(1.0, 1.0, 1.0).draw(gl);

                scene.draw(&c, gl);
            },
            Input(piston::input::Press(_)) => {
                scene.toggle_action(id, &seq_action);
                scene.toggle_action(id, &rotate_action);
            },
            _ => {},
        }
    }
}
<|endoftext|>


<commit_before>extern crate serde_json;

use serde_json::Value;
use error::{Result, Error};

pub fn hue_result(v: Value) -> Result<Value> {
	if let Some(val) = v.get(0).and_then(|v| v.get("success")) {
        return Ok(val.to_owned());
	}
	if let Some(err) = v.get(0).and_then(|v| v.get("error")) {
		let desc = err["description"].as_str().unwrap_or("Hue error")
            .to_owned();
		return Err(Error::Hue(desc));
	}
    Err(Error::Other("Hue Bridge sent back bad data"))
}
<commit_msg>Change to_owned to clone<commit_after>extern crate serde_json;

use serde_json::Value;
use error::{Result, Error};

pub fn hue_result(v: Value) -> Result<Value> {
    if let Some(val) = v.get(0).and_then(|v| v.get("success")) {
        return Ok(val.clone());
    }
    if let Some(err) = v.get(0).and_then(|v| v.get("error")) {
        let desc = err["description"].as_str().unwrap_or("Hue error")
            .to_owned();
        return Err(Error::Hue(desc));
    }
    Err(Error::Other("Hue Bridge sent back bad data"))
}
<|endoftext|>


<commit_before>/// The default target to pass to cargo, to workaround issue #11.
#[cfg(target_os = "macos")]
pub fn default_target() -> &'static str {
    "x86_64-apple-darwin"
}

/// The default target to pass to cargo, to workaround issue #11.
#[cfg(not(target_os = "macos"))]
pub fn default_target() -> &'static str {
    "x86_64-unknown-linux-gnu"
}
<commit_msg>Add support for aarch64-apple-darwin.<commit_after>/// The default target to pass to cargo, to workaround issue #11.
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub fn default_target() -> &'static str {
    "aarch64-apple-darwin"
}

#[cfg(all(not(target_arch = "aarch64"), target_os = "macos"))]
pub fn default_target() -> &'static str {
    "x86_64-apple-darwin"
}

/// The default target to pass to cargo, to workaround issue #11.
#[cfg(not(target_os = "macos"))]
pub fn default_target() -> &'static str {
    "x86_64-unknown-linux-gnu"
}
<|endoftext|>


<commit_before>use std::fmt;
use std::time::Duration;
use chrono::{NaiveDate, NaiveTime};

#[derive(Default, Debug, PartialEq, Eq)]
pub struct GameRecord {
    pub black_player: Option<String>,
    pub white_player: Option<String>,
    pub event: Option<String>,
    pub site: Option<String>,
    pub start_time: Option<Time>,
    pub end_time: Option<Time>,
    pub time_limit: Option<TimeLimit>,
    pub opening: Option<String>,
    pub start_pos: Position,
    pub moves: Vec<MoveRecord>,
}

impl fmt::Display for GameRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "V2.2")?;

        // Metadata
        let metadata = [
            ("N+", self.black_player.as_ref().map(|x| x.to_string())),
            ("N-", self.white_player.as_ref().map(|x| x.to_string())),
            ("$EVENT:", self.event.as_ref().map(|x| x.to_string())),
            ("$SITE:", self.site.as_ref().map(|x| x.to_string())),
            (
                "$START_TIME:",
                self.start_time.as_ref().map(|x| x.to_string()),
            ),
            ("$END_TIME:", self.end_time.as_ref().map(|x| x.to_string())),
            (
                "$TIME_LIMIT:",
                self.time_limit.as_ref().map(|x| x.to_string()),
            ),
            ("$OPENING:", self.opening.as_ref().map(|x| x.to_string())),
        ];
        for &(ref key, ref value) in &metadata {
            if let Some(ref value) = *value {
                writeln!(f, "{}{}", key, value)?;
            }
        }

        // Position
        write!(f, "{}", self.start_pos)?;

        // Move records
        for record in &self.moves {
            write!(f, "{}", record)?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Time {
    pub date: NaiveDate,
    pub time: Option<NaiveTime>,
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.date.format("%Y/%m/%d"))?;
        if let Some(time) = self.time {
            write!(f, " {}", time.format("%H:%M:%S"))?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TimeLimit {
    pub main_time: Duration,
    pub byoyomi: Duration,
}

impl fmt::Display for TimeLimit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let secs = self.main_time.as_secs();
        let hours = secs / 3600;
        let minutes = (secs % 3600) / 60;

        write!(
            f,
            "{:02}:{:02}+{:02}",
            hours,
            minutes,
            self.byoyomi.as_secs()
        )
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq)]
pub enum GameAttribute {
    Time(Time),
    TimeLimit(TimeLimit),
    Str(String),
}

impl fmt::Display for GameAttribute {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GameAttribute::Time(ref time) => write!(f, "{}", time),
            GameAttribute::TimeLimit(ref time_limit) => write!(f, "{}", time_limit),
            GameAttribute::Str(ref s) => write!(f, "{}", s),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Color {
    Black,
    White,
}

impl Default for Color {
    fn default() -> Self {
        Color::Black
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Color::Black => write!(f, "+"),
            Color::White => write!(f, "-"),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Square {
    pub file: u8,
    pub rank: u8,
}

impl Square {
    pub fn new(file: u8, rank: u8) -> Square {
        Square { file, rank }
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}", self.file, self.rank)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum PieceType {
    Pawn,
    Lance,
    Knight,
    Silver,
    Gold,
    Bishop,
    Rook,
    King,
    ProPawn,
    ProLance,
    ProKnight,
    ProSilver,
    Horse,
    Dragon,
    All,
}

impl fmt::Display for PieceType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let pt = match *self {
            PieceType::Pawn => "FU",
            PieceType::Lance => "KY",
            PieceType::Knight => "KE",
            PieceType::Silver => "GI",
            PieceType::Gold => "KI",
            PieceType::Bishop => "KA",
            PieceType::Rook => "HI",
            PieceType::King => "OU",
            PieceType::ProPawn => "TO",
            PieceType::ProLance => "NY",
            PieceType::ProKnight => "NK",
            PieceType::ProSilver => "NG",
            PieceType::Horse => "UM",
            PieceType::Dragon => "RY",
            PieceType::All => "AL",
        };
        write!(f, "{}", pt)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Position {
    pub drop_pieces: Vec<(Square, PieceType)>,
    pub bulk: Option<[[Option<(Color, PieceType)>; 9]; 9]>,
    pub add_pieces: Vec<(Color, Square, PieceType)>,
    pub side_to_move: Color,
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref bulk) = self.bulk {
            for (i, ref row) in bulk.iter().enumerate() {
                write!(f, "P{}", i + 1)?;

                for pc in row.iter() {
                    match *pc {
                        Some((ref color, ref pt)) => write!(f, "{}{}", color, pt)?,
                        None => write!(f, " * ")?,
                    }
                }

                writeln!(f, "")?;
            }
        } else {
            write!(f, "PI")?;
            for &(ref sq, ref pt) in &self.drop_pieces {
                write!(f, "{}{}", sq, pt)?;
            }
            writeln!(f, "")?;
        }

        for &(ref color, ref sq, ref pt) in &self.add_pieces {
            writeln!(f, "P{}{}{}", color, sq, pt)?;
        }

        writeln!(f, "{}", self.side_to_move)?;

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Action {
    Move(Color, Square, Square, PieceType),
    Toryo,
    Chudan,
    Sennichite,
    TimeUp,
    IllegalMove,
    IllegalAction(Color),
    Jishogi,
    Kachi,
    Hikiwake,
    Matta,
    Tsumi,
    Fuzumi,
    Error,
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Action::Move(ref color, ref from, ref to, ref pt) => {
                write!(f, "{}{}{}{}", color, from, to, pt)
            }
            Action::Toryo => write!(f, "%TORYO"),
            Action::Chudan => write!(f, "%CHUDAN"),
            Action::Sennichite => write!(f, "SENNICHITE"),
            Action::TimeUp => write!(f, "%TIME_UP"),
            Action::IllegalMove => write!(f, "%ILLEGAL_MOVE"),
            Action::IllegalAction(ref color) => write!(f, "%{}ILLEGAL_ACTION", color),
            Action::Jishogi => write!(f, "%JISHOGI"),
            Action::Kachi => write!(f, "%KACHI"),
            Action::Hikiwake => write!(f, "%HIKIWAKE"),
            Action::Matta => write!(f, "%MATTA"),
            Action::Tsumi => write!(f, "%TSUMI"),
            Action::Fuzumi => write!(f, "%FUZUMI"),
            Action::Error => write!(f, "%ERROR"),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq)]
pub struct MoveRecord {
    pub action: Action,
    pub time: Option<Duration>,
}

impl fmt::Display for MoveRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", self.action)?;

        if let Some(ref time) = self.time {
            writeln!(f, "T{}", time.as_secs())?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut g = GameRecord::default();
        g.black_player = Some("black".to_string());
        g.white_player = Some("white".to_string());
        g.event = Some("event".to_string());
        g.site = Some("site".to_string());
        g.opening = Some("Yagura".to_string());
        g.moves.push(MoveRecord {
            action: Action::Move(
                Color::Black,
                Square::new(8, 7),
                Square::new(8, 6),
                PieceType::Pawn,
            ),
            time: Some(Duration::from_secs(5)),
        });
        g.moves.push(MoveRecord {
            action: Action::Toryo,
            time: None,
        });

        let csa = "\
V2.2
N+black
N-white
$EVENT:event
$SITE:site
$OPENING:Yagura
PI
+
+8786FU
T5
%TORYO
";

        assert_eq!(csa, g.to_string());
    }
}
<commit_msg>test: add tests for serializing datetimes<commit_after>use std::fmt;
use std::time::Duration;
use chrono::{NaiveDate, NaiveTime};

#[derive(Default, Debug, PartialEq, Eq)]
pub struct GameRecord {
    pub black_player: Option<String>,
    pub white_player: Option<String>,
    pub event: Option<String>,
    pub site: Option<String>,
    pub start_time: Option<Time>,
    pub end_time: Option<Time>,
    pub time_limit: Option<TimeLimit>,
    pub opening: Option<String>,
    pub start_pos: Position,
    pub moves: Vec<MoveRecord>,
}

impl fmt::Display for GameRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "V2.2")?;

        // Metadata
        let metadata = [
            ("N+", self.black_player.as_ref().map(|x| x.to_string())),
            ("N-", self.white_player.as_ref().map(|x| x.to_string())),
            ("$EVENT:", self.event.as_ref().map(|x| x.to_string())),
            ("$SITE:", self.site.as_ref().map(|x| x.to_string())),
            (
                "$START_TIME:",
                self.start_time.as_ref().map(|x| x.to_string()),
            ),
            ("$END_TIME:", self.end_time.as_ref().map(|x| x.to_string())),
            (
                "$TIME_LIMIT:",
                self.time_limit.as_ref().map(|x| x.to_string()),
            ),
            ("$OPENING:", self.opening.as_ref().map(|x| x.to_string())),
        ];
        for &(ref key, ref value) in &metadata {
            if let Some(ref value) = *value {
                writeln!(f, "{}{}", key, value)?;
            }
        }

        // Position
        write!(f, "{}", self.start_pos)?;

        // Move records
        for record in &self.moves {
            write!(f, "{}", record)?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Time {
    pub date: NaiveDate,
    pub time: Option<NaiveTime>,
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.date.format("%Y/%m/%d"))?;
        if let Some(time) = self.time {
            write!(f, " {}", time.format("%H:%M:%S"))?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TimeLimit {
    pub main_time: Duration,
    pub byoyomi: Duration,
}

impl fmt::Display for TimeLimit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let secs = self.main_time.as_secs();
        let hours = secs / 3600;
        let minutes = (secs % 3600) / 60;

        write!(
            f,
            "{:02}:{:02}+{:02}",
            hours,
            minutes,
            self.byoyomi.as_secs()
        )
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq)]
pub enum GameAttribute {
    Time(Time),
    TimeLimit(TimeLimit),
    Str(String),
}

impl fmt::Display for GameAttribute {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GameAttribute::Time(ref time) => write!(f, "{}", time),
            GameAttribute::TimeLimit(ref time_limit) => write!(f, "{}", time_limit),
            GameAttribute::Str(ref s) => write!(f, "{}", s),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Color {
    Black,
    White,
}

impl Default for Color {
    fn default() -> Self {
        Color::Black
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Color::Black => write!(f, "+"),
            Color::White => write!(f, "-"),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Square {
    pub file: u8,
    pub rank: u8,
}

impl Square {
    pub fn new(file: u8, rank: u8) -> Square {
        Square { file, rank }
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}", self.file, self.rank)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum PieceType {
    Pawn,
    Lance,
    Knight,
    Silver,
    Gold,
    Bishop,
    Rook,
    King,
    ProPawn,
    ProLance,
    ProKnight,
    ProSilver,
    Horse,
    Dragon,
    All,
}

impl fmt::Display for PieceType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let pt = match *self {
            PieceType::Pawn => "FU",
            PieceType::Lance => "KY",
            PieceType::Knight => "KE",
            PieceType::Silver => "GI",
            PieceType::Gold => "KI",
            PieceType::Bishop => "KA",
            PieceType::Rook => "HI",
            PieceType::King => "OU",
            PieceType::ProPawn => "TO",
            PieceType::ProLance => "NY",
            PieceType::ProKnight => "NK",
            PieceType::ProSilver => "NG",
            PieceType::Horse => "UM",
            PieceType::Dragon => "RY",
            PieceType::All => "AL",
        };
        write!(f, "{}", pt)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Position {
    pub drop_pieces: Vec<(Square, PieceType)>,
    pub bulk: Option<[[Option<(Color, PieceType)>; 9]; 9]>,
    pub add_pieces: Vec<(Color, Square, PieceType)>,
    pub side_to_move: Color,
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref bulk) = self.bulk {
            for (i, ref row) in bulk.iter().enumerate() {
                write!(f, "P{}", i + 1)?;

                for pc in row.iter() {
                    match *pc {
                        Some((ref color, ref pt)) => write!(f, "{}{}", color, pt)?,
                        None => write!(f, " * ")?,
                    }
                }

                writeln!(f, "")?;
            }
        } else {
            write!(f, "PI")?;
            for &(ref sq, ref pt) in &self.drop_pieces {
                write!(f, "{}{}", sq, pt)?;
            }
            writeln!(f, "")?;
        }

        for &(ref color, ref sq, ref pt) in &self.add_pieces {
            writeln!(f, "P{}{}{}", color, sq, pt)?;
        }

        writeln!(f, "{}", self.side_to_move)?;

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Action {
    Move(Color, Square, Square, PieceType),
    Toryo,
    Chudan,
    Sennichite,
    TimeUp,
    IllegalMove,
    IllegalAction(Color),
    Jishogi,
    Kachi,
    Hikiwake,
    Matta,
    Tsumi,
    Fuzumi,
    Error,
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Action::Move(ref color, ref from, ref to, ref pt) => {
                write!(f, "{}{}{}{}", color, from, to, pt)
            }
            Action::Toryo => write!(f, "%TORYO"),
            Action::Chudan => write!(f, "%CHUDAN"),
            Action::Sennichite => write!(f, "SENNICHITE"),
            Action::TimeUp => write!(f, "%TIME_UP"),
            Action::IllegalMove => write!(f, "%ILLEGAL_MOVE"),
            Action::IllegalAction(ref color) => write!(f, "%{}ILLEGAL_ACTION", color),
            Action::Jishogi => write!(f, "%JISHOGI"),
            Action::Kachi => write!(f, "%KACHI"),
            Action::Hikiwake => write!(f, "%HIKIWAKE"),
            Action::Matta => write!(f, "%MATTA"),
            Action::Tsumi => write!(f, "%TSUMI"),
            Action::Fuzumi => write!(f, "%FUZUMI"),
            Action::Error => write!(f, "%ERROR"),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq)]
pub struct MoveRecord {
    pub action: Action,
    pub time: Option<Duration>,
}

impl fmt::Display for MoveRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", self.action)?;

        if let Some(ref time) = self.time {
            writeln!(f, "T{}", time.as_secs())?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut g = GameRecord::default();
        g.black_player = Some("NAKAHARA".to_string());
        g.white_player = Some("YONENAGA".to_string());
        g.event = Some("13th World Computer Shogi Championship".to_string());
        g.site = Some("KAZUSA ARC".to_string());
        g.start_time = Some(Time {
            date: NaiveDate::from_ymd(2003, 5, 3),
            time: Some(NaiveTime::from_hms(10, 30, 0)),
        });
        g.end_time = Some(Time {
            date: NaiveDate::from_ymd(2003, 5, 3),
            time: Some(NaiveTime::from_hms(11, 11, 5)),
        });
        g.time_limit = Some(TimeLimit {
            main_time: Duration::from_secs(1500),
            byoyomi: Duration::from_secs(0),
        });
        g.opening = Some("YAGURA".to_string());
        g.moves.push(MoveRecord {
            action: Action::Move(
                Color::Black,
                Square::new(8, 7),
                Square::new(8, 6),
                PieceType::Pawn,
            ),
            time: Some(Duration::from_secs(5)),
        });
        g.moves.push(MoveRecord {
            action: Action::Toryo,
            time: None,
        });

        let csa = "\
V2.2
N+NAKAHARA
N-YONENAGA
$EVENT:13th World Computer Shogi Championship
$SITE:KAZUSA ARC
$START_TIME:2003/05/03 10:30:00
$END_TIME:2003/05/03 11:11:05
$TIME_LIMIT:00:25+00
$OPENING:YAGURA
PI
+
+8786FU
T5
%TORYO
";

        assert_eq!(csa, g.to_string());
    }
}
<|endoftext|>


<commit_before>/// # Value extension
///
/// Extension trait for the toml::Value type
///

use toml::Value;

use read::TomlValueReadExt;
use set::TomlValueSetExt;
use delete::TomlValueDeleteExt;
use insert::TomlValueInsertExt;
use error::Result;

/// Conveniance trait over
///
///  * TomlValueReadExt
///  * TomlValueSetExt
///
/// for ease of use.
///
/// The very same goal can be achieved by importing each trait seperately.
pub trait TomlValueExt<'doc> :
    TomlValueReadExt<'doc> + TomlValueSetExt + TomlValueDeleteExt + TomlValueInsertExt
{

    //
    // READ functionality
    //

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read_with_seperator(&'doc self, query: &String, sep: char) -> Result<&'doc Value> {
        TomlValueReadExt::read_with_seperator(self, query, sep)
    }

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read_mut_with_seperator(&'doc mut self, query: &String, sep: char) -> Result<&'doc mut Value> {
        TomlValueReadExt::read_mut_with_seperator(self, query, sep)
    }

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read(&'doc self, query: &String) -> Result<&'doc Value> {
        TomlValueReadExt::read_with_seperator(self, query, '.')
    }

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read_mut(&'doc mut self, query: &String) -> Result<&'doc mut Value> {
        TomlValueReadExt::read_mut_with_seperator(self, query, '.')
    }

    //
    // SET functionality
    //

    /// See documentation of `TomlValueSetExt`
    #[inline]
    fn set_with_seperator(&mut self, query: &String, sep: char, value: Value) -> Result<Option<Value>> {
        TomlValueSetExt::set_with_seperator(self, query, sep, value)
    }

    /// See documentation of `TomlValueSetExt`
    #[inline]
    fn set(&mut self, query: &String, value: Value) -> Result<Option<Value>> {
        TomlValueSetExt::set_with_seperator(self, query, '.', value)
    }

    //
    // DELETE functionality
    //

    /// See documentation of `TomlValueDeleteExt`
    #[inline]
    fn delete_with_seperator(&mut self, query: &String, sep: char) -> Result<Option<Value>> {
        TomlValueDeleteExt::delete_with_seperator(self, query, sep)
    }

    /// See documentation of `TomlValueDeleteExt`
    #[inline]
    fn delete(&mut self, query: &String) -> Result<Option<Value>> {
        TomlValueDeleteExt::delete(self, query)
    }

    //
    // INSERT functionality
    //

    /// See documentation of `TomlValueInsertExt`
    #[inline]
    fn insert_with_seperator(&mut self, query: &String, sep: char, value: Value) -> Result<Option<Value>> {
        TomlValueInsertExt::insert_with_seperator(self, query, sep, value)
    }

    /// See documentation of `TomlValueInsertExt`
    #[inline]
    fn insert(&mut self, query: &String, value: Value) -> Result<Option<Value>> {
        TomlValueInsertExt::insert(self, query, value)
    }
}

<commit_msg>Implement TomlValueExt for Value<commit_after>/// # Value extension
///
/// Extension trait for the toml::Value type
///

use toml::Value;

use read::TomlValueReadExt;
use set::TomlValueSetExt;
use delete::TomlValueDeleteExt;
use insert::TomlValueInsertExt;
use error::Result;

/// Conveniance trait over
///
///  * TomlValueReadExt
///  * TomlValueSetExt
///
/// for ease of use.
///
/// The very same goal can be achieved by importing each trait seperately.
pub trait TomlValueExt<'doc> :
    TomlValueReadExt<'doc> + TomlValueSetExt + TomlValueDeleteExt + TomlValueInsertExt
{

    //
    // READ functionality
    //

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read_with_seperator(&'doc self, query: &String, sep: char) -> Result<&'doc Value> {
        TomlValueReadExt::read_with_seperator(self, query, sep)
    }

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read_mut_with_seperator(&'doc mut self, query: &String, sep: char) -> Result<&'doc mut Value> {
        TomlValueReadExt::read_mut_with_seperator(self, query, sep)
    }

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read(&'doc self, query: &String) -> Result<&'doc Value> {
        TomlValueReadExt::read_with_seperator(self, query, '.')
    }

    /// See documentation of `TomlValueReadExt`
    #[inline]
    fn read_mut(&'doc mut self, query: &String) -> Result<&'doc mut Value> {
        TomlValueReadExt::read_mut_with_seperator(self, query, '.')
    }

    //
    // SET functionality
    //

    /// See documentation of `TomlValueSetExt`
    #[inline]
    fn set_with_seperator(&mut self, query: &String, sep: char, value: Value) -> Result<Option<Value>> {
        TomlValueSetExt::set_with_seperator(self, query, sep, value)
    }

    /// See documentation of `TomlValueSetExt`
    #[inline]
    fn set(&mut self, query: &String, value: Value) -> Result<Option<Value>> {
        TomlValueSetExt::set_with_seperator(self, query, '.', value)
    }

    //
    // DELETE functionality
    //

    /// See documentation of `TomlValueDeleteExt`
    #[inline]
    fn delete_with_seperator(&mut self, query: &String, sep: char) -> Result<Option<Value>> {
        TomlValueDeleteExt::delete_with_seperator(self, query, sep)
    }

    /// See documentation of `TomlValueDeleteExt`
    #[inline]
    fn delete(&mut self, query: &String) -> Result<Option<Value>> {
        TomlValueDeleteExt::delete(self, query)
    }

    //
    // INSERT functionality
    //

    /// See documentation of `TomlValueInsertExt`
    #[inline]
    fn insert_with_seperator(&mut self, query: &String, sep: char, value: Value) -> Result<Option<Value>> {
        TomlValueInsertExt::insert_with_seperator(self, query, sep, value)
    }

    /// See documentation of `TomlValueInsertExt`
    #[inline]
    fn insert(&mut self, query: &String, value: Value) -> Result<Option<Value>> {
        TomlValueInsertExt::insert(self, query, value)
    }
}

impl<'doc> TomlValueExt<'doc> for Value { }

<|endoftext|>


<commit_before>use serde_bytes::{Bytes, ByteBuf};

fn _bytes_eq_slice(bytes: &Bytes, slice: &[u8]) -> bool {
    bytes == slice
}

fn _bytebuf_eq_vec(bytebuf: ByteBuf, vec: Vec<u8>) -> bool {
    bytebuf == vec
}

fn _bytes_eq_bytestring(bytes: &Bytes) -> bool {
    bytes == b"..."
}
<commit_msg>Format with rustfmt 2020-04-14<commit_after>use serde_bytes::{ByteBuf, Bytes};

fn _bytes_eq_slice(bytes: &Bytes, slice: &[u8]) -> bool {
    bytes == slice
}

fn _bytebuf_eq_vec(bytebuf: ByteBuf, vec: Vec<u8>) -> bool {
    bytebuf == vec
}

fn _bytes_eq_bytestring(bytes: &Bytes) -> bool {
    bytes == b"..."
}
<|endoftext|>


<commit_before>use expression::Expression;
use helper_types::Select;
use query_dsl::SelectDsl;
use super::delete_statement::DeleteStatement;
use super::insert_statement::Insert;
use super::{IntoUpdateTarget, IncompleteUpdateStatement, IncompleteInsertStatement, SelectStatement, IncompleteDefaultInsertStatement};

/// Creates an update statement. Helpers for updating a single row can be
/// generated by deriving [`AsChangeset`](query_builder/trait.AsChangeset.html)
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # #[cfg(feature = "postgres")]
/// # fn main() {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// let updated_row = diesel::update(users.filter(id.eq(1)))
///     .set(name.eq("James"))
///     .get_result(&connection);
/// // On backends that support it, you can call `get_result` instead of `execute`
/// // to have `RETURNING *` automatically appended to the query. Alternatively, you
/// // can explicitly return an expression by using the `returning` method before
/// // getting the result.
/// assert_eq!(Ok((1, "James".to_string())), updated_row);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # fn main() {}
/// ```
///
/// To update multiple columns, give `set` a tuple argument:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #         surname -> VarChar,
/// #     }
/// # }
/// #
/// # #[cfg(feature = "postgres")]
/// # fn main() {
/// # use users::dsl::*;
/// # let connection = establish_connection();
/// # connection.execute("DROP TABLE users").unwrap();
/// # connection.execute("CREATE TABLE users (
/// #     id SERIAL PRIMARY KEY,
/// #     name VARCHAR,
/// #     surname VARCHAR)").unwrap();
/// # connection.execute("INSERT INTO users(name, surname) VALUES('Sean', 'Griffin')").unwrap();
///
/// let updated_row = diesel::update(users.filter(id.eq(1)))
///     .set((name.eq("James"), surname.eq("Bond")))
///     .get_result(&connection);
///
/// assert_eq!(Ok((1, "James".to_string(), "Bond".to_string())), updated_row);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # fn main() {}
/// ```
pub fn update<T: IntoUpdateTarget>(source: T) -> IncompleteUpdateStatement<T::Table, T::WhereClause> {
    IncompleteUpdateStatement::new(source.into_update_target())
}

/// Creates a delete statement. Will delete the records in the given set.
/// Because this function has a very generic name, it is not exported by
/// default.
///
/// # Examples
///
/// ### Deleting a single record:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     delete();
/// # }
/// #
/// # fn delete() -> QueryResult<()> {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// #     let get_count = || users.count().first::<i64>(&connection);
/// let old_count = get_count();
/// try!(diesel::delete(users.filter(id.eq(1))).execute(&connection));
/// assert_eq!(old_count.map(|count| count - 1), get_count());
/// # Ok(())
/// # }
/// ```
///
/// ### Deleting a whole table:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     delete();
/// # }
/// #
/// # fn delete() -> QueryResult<()> {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// #     let get_count = || users.count().first::<i64>(&connection);
/// try!(diesel::delete(users).execute(&connection));
/// assert_eq!(Ok(0), get_count());
/// # Ok(())
/// # }
/// ```
pub fn delete<T: IntoUpdateTarget>(source: T) -> DeleteStatement<T::Table, T::WhereClause> {
    let target = source.into_update_target();
    DeleteStatement::new(target.table, target.where_clause)
}

/// Creates an insert statement. Will add the given data to a table. This
/// function is not exported by default. As with other commands, the resulting
/// query can return the inserted rows if you choose.
pub fn insert<T: ?Sized>(records: &T) -> IncompleteInsertStatement<&T, Insert> {
    IncompleteInsertStatement::new(records, Insert)
}

/// Creates a bare select statement, with no from clause. Primarily used for
/// testing diesel itself, but likely useful for third party crates as well. The
/// given expressions must be selectable from anywhere.
pub fn select<T>(expression: T) -> Select<SelectStatement<()>, T> where
    T: Expression,
    SelectStatement<()>: SelectDsl<T>,
{
    SelectStatement::simple(()).select(expression)
}

/// Creates an insert statement with default values.
///
/// This function is not exported by default. As with other commands, the resulting
/// query can return the inserted rows if you choose.
pub fn insert_default_values() -> IncompleteDefaultInsertStatement {
    IncompleteDefaultInsertStatement::new()
}
<commit_msg>Example usage for insert (#1098)<commit_after>use expression::Expression;
use helper_types::Select;
use query_dsl::SelectDsl;
use super::delete_statement::DeleteStatement;
use super::insert_statement::Insert;
use super::{IntoUpdateTarget, IncompleteUpdateStatement, IncompleteInsertStatement, SelectStatement, IncompleteDefaultInsertStatement};

/// Creates an update statement. Helpers for updating a single row can be
/// generated by deriving [`AsChangeset`](query_builder/trait.AsChangeset.html)
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # #[cfg(feature = "postgres")]
/// # fn main() {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// let updated_row = diesel::update(users.filter(id.eq(1)))
///     .set(name.eq("James"))
///     .get_result(&connection);
/// // On backends that support it, you can call `get_result` instead of `execute`
/// // to have `RETURNING *` automatically appended to the query. Alternatively, you
/// // can explicitly return an expression by using the `returning` method before
/// // getting the result.
/// assert_eq!(Ok((1, "James".to_string())), updated_row);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # fn main() {}
/// ```
///
/// To update multiple columns, give `set` a tuple argument:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #         surname -> VarChar,
/// #     }
/// # }
/// #
/// # #[cfg(feature = "postgres")]
/// # fn main() {
/// # use users::dsl::*;
/// # let connection = establish_connection();
/// # connection.execute("DROP TABLE users").unwrap();
/// # connection.execute("CREATE TABLE users (
/// #     id SERIAL PRIMARY KEY,
/// #     name VARCHAR,
/// #     surname VARCHAR)").unwrap();
/// # connection.execute("INSERT INTO users(name, surname) VALUES('Sean', 'Griffin')").unwrap();
///
/// let updated_row = diesel::update(users.filter(id.eq(1)))
///     .set((name.eq("James"), surname.eq("Bond")))
///     .get_result(&connection);
///
/// assert_eq!(Ok((1, "James".to_string(), "Bond".to_string())), updated_row);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # fn main() {}
/// ```
pub fn update<T: IntoUpdateTarget>(source: T) -> IncompleteUpdateStatement<T::Table, T::WhereClause> {
    IncompleteUpdateStatement::new(source.into_update_target())
}

/// Creates a delete statement. Will delete the records in the given set.
/// Because this function has a very generic name, it is not exported by
/// default.
///
/// # Examples
///
/// ### Deleting a single record:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     delete();
/// # }
/// #
/// # fn delete() -> QueryResult<()> {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// #     let get_count = || users.count().first::<i64>(&connection);
/// let old_count = get_count();
/// try!(diesel::delete(users.filter(id.eq(1))).execute(&connection));
/// assert_eq!(old_count.map(|count| count - 1), get_count());
/// # Ok(())
/// # }
/// ```
///
/// ### Deleting a whole table:
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     delete();
/// # }
/// #
/// # fn delete() -> QueryResult<()> {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// #     let get_count = || users.count().first::<i64>(&connection);
/// try!(diesel::delete(users).execute(&connection));
/// assert_eq!(Ok(0), get_count());
/// # Ok(())
/// # }
/// ```
pub fn delete<T: IntoUpdateTarget>(source: T) -> DeleteStatement<T::Table, T::WhereClause> {
    let target = source.into_update_target();
    DeleteStatement::new(target.table, target.where_clause)
}

/// Creates an insert statement. Will add the given data to a table. This
/// function is not exported by default. As with other commands, the resulting
/// query can return the inserted rows if you choose.
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> Text,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// // Insert one record at a time
///
/// let new_user = NewUser { name: "Ruby Rhod".to_string() };
///
/// diesel::insert(&new_user)
///     .into(users)
///     .execute(&connection)
///     .unwrap();
///
/// // Insert many records
///
/// let new_users = vec![
///     NewUser { name: "Leeloo Multipass".to_string(), },
///     NewUser { name: "Korben Dallas".to_string(), },
/// ];
///
/// let inserted_names = diesel::insert(&new_users)
///     .into(users)
///     .execute(&connection)
///     .unwrap();
/// # }
/// ```
///
/// ### With return value
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> Text,
/// #     }
/// # }
/// #
/// # #[cfg(feature = "postgres")]
/// # fn main() {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// // postgres only
/// let new_users = vec![
///     NewUser { name: "Diva Plavalaguna".to_string(), },
///     NewUser { name: "Father Vito Cornelius".to_string(), },
/// ];
///
/// let inserted_names = diesel::insert(&new_users)
///     .into(users)
///     .returning(name)
///     .get_results(&connection);
/// assert_eq!(Ok(vec!["Diva Plavalaguna".to_string(), "Father Vito Cornelius".to_string()]), inserted_names);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # fn main() {}
/// ```
pub fn insert<T: ?Sized>(records: &T) -> IncompleteInsertStatement<&T, Insert> {
    IncompleteInsertStatement::new(records, Insert)
}

/// Creates a bare select statement, with no from clause. Primarily used for
/// testing diesel itself, but likely useful for third party crates as well. The
/// given expressions must be selectable from anywhere.
pub fn select<T>(expression: T) -> Select<SelectStatement<()>, T> where
    T: Expression,
    SelectStatement<()>: SelectDsl<T>,
{
    SelectStatement::simple(()).select(expression)
}

/// Creates an insert statement with default values.
///
/// This function is not exported by default. As with other commands, the resulting
/// query can return the inserted rows if you choose.
pub fn insert_default_values() -> IncompleteDefaultInsertStatement {
    IncompleteDefaultInsertStatement::new()
}
<|endoftext|>


<commit_before>use cargo_test_support::{basic_lib_manifest, project};

#[cargo_test]
fn inherits_on_release() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release]
            inherits = "dev"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  An 'inherits' must not specified root profile 'release'
",
        )
        .run();
}

#[cargo_test]
fn missing_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  An 'inherits' directive is needed for all profiles that are not 'dev' or 'release'. Here it is missing from 'release-lto'",
        )
        .run();
}

#[cargo_test]
fn non_existent_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
            inherits = "non-existent"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Profile 'non-existent' not found in Cargo.toml",
        )
        .run();
}

#[cargo_test]
fn self_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
            inherits = "release-lto"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Inheritance loop of profiles cycles with profile 'release-lto'",
        )
        .run();
}

#[cargo_test]
fn inherits_loop() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
            inherits = "release-lto2"

            [profile.release-lto2]
            codegen-units = 7
            inherits = "release-lto"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Inheritance loop of profiles cycles with profile 'release-lto'",
        )
        .run();
}

#[cargo_test]
fn overrides_with_custom() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["profile-overrides", "named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies]
            xxx = {path = "xxx"}
            yyy = {path = "yyy"}

            [profile.dev]
            codegen-units = 7

            [profile.dev.overrides.xxx]
            codegen-units = 5
            [profile.dev.overrides.yyy]
            codegen-units = 3

            [profile.other]
            inherits = "dev"
            codegen-units = 2

            [profile.other.overrides.yyy]
            codegen-units = 6
        "#,
        )
        .file("src/lib.rs", "")
        .file("xxx/Cargo.toml", &basic_lib_manifest("xxx"))
        .file("xxx/src/lib.rs", "")
        .file("yyy/Cargo.toml", &basic_lib_manifest("yyy"))
        .file("yyy/src/lib.rs", "")
        .build();

    // profile overrides are inherited between profiles using inherits and have a
    // higher priority than profile options provided by custom profiles
    p.cargo("build -v")
        .masquerade_as_nightly_cargo()
        .with_stderr_unordered(
            "\
[COMPILING] xxx [..]
[COMPILING] yyy [..]
[COMPILING] foo [..]
[RUNNING] `rustc --crate-name xxx [..] -C codegen-units=5 [..]`
[RUNNING] `rustc --crate-name yyy [..] -C codegen-units=3 [..]`
[RUNNING] `rustc --crate-name foo [..] -C codegen-units=7 [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();

    // This also verifies that the custom profile names appears in the finished line.
    p.cargo("build --profile=other -Z unstable-options -v")
        .masquerade_as_nightly_cargo()
        .with_stderr_unordered(
            "\
[COMPILING] xxx [..]
[COMPILING] yyy [..]
[COMPILING] foo [..]
[RUNNING] `rustc --crate-name xxx [..] -C codegen-units=5 [..]`
[RUNNING] `rustc --crate-name yyy [..] -C codegen-units=6 [..]`
[RUNNING] `rustc --crate-name foo [..] -C codegen-units=2 [..]`
[FINISHED] other [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn conflicting_usage() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build -Z unstable-options --profile=dev --release")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr_unordered("error: Conflicting usage of --profile and --release")
        .run();

    p.cargo("install -Z unstable-options --profile=release --debug")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr_unordered("error: Conflicting usage of --profile and --debug")
        .run();
}

#[cargo_test]
fn clean_custom_dirname() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.other]
            inherits = "release"
        "#,
        )
        .file("src/main.rs", "fn main() {}")
        .build();

    p.cargo("build --release")
        .masquerade_as_nightly_cargo()
        .with_stdout("")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] release [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("clean -p foo").masquerade_as_nightly_cargo().run();

    p.cargo("build --release")
        .masquerade_as_nightly_cargo()
        .with_stdout("")
        .with_stderr(
            "\
[FINISHED] release [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("clean -p foo --release")
        .masquerade_as_nightly_cargo()
        .run();

    p.cargo("build --release")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] release [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_stdout("")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();

    p.cargo("build -Z unstable-options --profile=other")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] other [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("clean")
        .arg("--release")
        .masquerade_as_nightly_cargo()
        .run();

    // Make sure that 'other' was not cleaned
    assert!(p.build_dir().is_dir());
    assert!(p.build_dir().join("debug").is_dir());
    assert!(p.build_dir().join("other").is_dir());
    assert!(!p.build_dir().join("release").is_dir());

    // This should clean 'other'
    p.cargo("clean -Z unstable-options --profile=other")
        .masquerade_as_nightly_cargo()
        .with_stderr("")
        .run();
    assert!(p.build_dir().join("debug").is_dir());
    assert!(!p.build_dir().join("other").is_dir());
}
<commit_msg>tests: profile_custom - add name validation tests<commit_after>use cargo_test_support::{basic_lib_manifest, project};

#[cargo_test]
fn inherits_on_release() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release]
            inherits = "dev"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  An 'inherits' must not specified root profile 'release'
",
        )
        .run();
}

#[cargo_test]
fn missing_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  An 'inherits' directive is needed for all profiles that are not 'dev' or 'release'. Here it is missing from 'release-lto'",
        )
        .run();
}

#[cargo_test]
fn invalid_profile_name() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.'.release-lto']
            inherits = "release"
            codegen-units = 7
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Invalid character `.` in profile name: `.release-lto`",
        )
        .run();
}

#[cargo_test]
fn invalid_dir_name() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.'release-lto']
            inherits = "release"
            dir-name = ".subdir"
            codegen-units = 7
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Invalid character `.` in dir-name: `.subdir`",
        )
        .run();
}

#[cargo_test]
fn invalid_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.'release-lto']
            inherits = ".release"
            codegen-units = 7
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Invalid character `.` in inherits: `.release`",
        )
        .run();
}

#[cargo_test]
fn non_existent_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
            inherits = "non-existent"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Profile 'non-existent' not found in Cargo.toml",
        )
        .run();
}

#[cargo_test]
fn self_inherits() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
            inherits = "release-lto"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Inheritance loop of profiles cycles with profile 'release-lto'",
        )
        .run();
}

#[cargo_test]
fn inherits_loop() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.release-lto]
            codegen-units = 7
            inherits = "release-lto2"

            [profile.release-lto2]
            codegen-units = 7
            inherits = "release-lto"
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
[ERROR] failed to parse manifest at [..]

Caused by:
  Inheritance loop of profiles cycles with profile 'release-lto'",
        )
        .run();
}

#[cargo_test]
fn overrides_with_custom() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["profile-overrides", "named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies]
            xxx = {path = "xxx"}
            yyy = {path = "yyy"}

            [profile.dev]
            codegen-units = 7

            [profile.dev.overrides.xxx]
            codegen-units = 5
            [profile.dev.overrides.yyy]
            codegen-units = 3

            [profile.other]
            inherits = "dev"
            codegen-units = 2

            [profile.other.overrides.yyy]
            codegen-units = 6
        "#,
        )
        .file("src/lib.rs", "")
        .file("xxx/Cargo.toml", &basic_lib_manifest("xxx"))
        .file("xxx/src/lib.rs", "")
        .file("yyy/Cargo.toml", &basic_lib_manifest("yyy"))
        .file("yyy/src/lib.rs", "")
        .build();

    // profile overrides are inherited between profiles using inherits and have a
    // higher priority than profile options provided by custom profiles
    p.cargo("build -v")
        .masquerade_as_nightly_cargo()
        .with_stderr_unordered(
            "\
[COMPILING] xxx [..]
[COMPILING] yyy [..]
[COMPILING] foo [..]
[RUNNING] `rustc --crate-name xxx [..] -C codegen-units=5 [..]`
[RUNNING] `rustc --crate-name yyy [..] -C codegen-units=3 [..]`
[RUNNING] `rustc --crate-name foo [..] -C codegen-units=7 [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();

    // This also verifies that the custom profile names appears in the finished line.
    p.cargo("build --profile=other -Z unstable-options -v")
        .masquerade_as_nightly_cargo()
        .with_stderr_unordered(
            "\
[COMPILING] xxx [..]
[COMPILING] yyy [..]
[COMPILING] foo [..]
[RUNNING] `rustc --crate-name xxx [..] -C codegen-units=5 [..]`
[RUNNING] `rustc --crate-name yyy [..] -C codegen-units=6 [..]`
[RUNNING] `rustc --crate-name foo [..] -C codegen-units=2 [..]`
[FINISHED] other [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn conflicting_usage() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build -Z unstable-options --profile=dev --release")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr_unordered("error: Conflicting usage of --profile and --release")
        .run();

    p.cargo("install -Z unstable-options --profile=release --debug")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr_unordered("error: Conflicting usage of --profile and --debug")
        .run();
}

#[cargo_test]
fn clean_custom_dirname() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["named-profiles"]

            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [profile.other]
            inherits = "release"
        "#,
        )
        .file("src/main.rs", "fn main() {}")
        .build();

    p.cargo("build --release")
        .masquerade_as_nightly_cargo()
        .with_stdout("")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] release [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("clean -p foo").masquerade_as_nightly_cargo().run();

    p.cargo("build --release")
        .masquerade_as_nightly_cargo()
        .with_stdout("")
        .with_stderr(
            "\
[FINISHED] release [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("clean -p foo --release")
        .masquerade_as_nightly_cargo()
        .run();

    p.cargo("build --release")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] release [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("build")
        .masquerade_as_nightly_cargo()
        .with_stdout("")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();

    p.cargo("build -Z unstable-options --profile=other")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] other [optimized] target(s) in [..]
",
        )
        .run();

    p.cargo("clean")
        .arg("--release")
        .masquerade_as_nightly_cargo()
        .run();

    // Make sure that 'other' was not cleaned
    assert!(p.build_dir().is_dir());
    assert!(p.build_dir().join("debug").is_dir());
    assert!(p.build_dir().join("other").is_dir());
    assert!(!p.build_dir().join("release").is_dir());

    // This should clean 'other'
    p.cargo("clean -Z unstable-options --profile=other")
        .masquerade_as_nightly_cargo()
        .with_stderr("")
        .run();
    assert!(p.build_dir().join("debug").is_dir());
    assert!(!p.build_dir().join("other").is_dir());
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016-2017 Boucher, Antoni <bouanto@zoho.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

//! Web extension for the titanium web browser.
//! It provides an ad blocker, scrolling support, hints, navigation and login credentials load/save.

#![warn(
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_results,
)]

extern crate fg_uds;
extern crate futures;
extern crate futures_glib;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate simplelog;
#[macro_use]
extern crate relm_state;
#[macro_use]
extern crate relm_derive_state;
extern crate titanium_common;
extern crate tokio_io;
extern crate tokio_serde_bincode;
extern crate url;
extern crate xdg;
#[macro_use]
extern crate webkit2gtk_webextension;

macro_rules! check_err {
    ($e:expr) => {
        if let Err(error) = $e {
            error!("check_err: {}", error);
            return;
        }
    };
}

macro_rules! check_err_opt {
    ($e:expr) => {
        if $e.is_none() {
            error!("{} is None", stringify!($e));
            return None;
        }
    };
}

macro_rules! unwrap_opt_or_ret {
    ($e:expr, $default:expr) => {
        match $e {
            Some(expr) => expr,
            None => return $default,
        }
    };
}

macro_rules! unwrap_or_ret {
    ($e:expr, $default:expr) => {
        match $e {
            Ok(expr) => expr,
            Err(error) => {
                error!("unwrap_or_ret: {}", error);
                return $default;
            },
        }
    };
}

macro_rules! wtry {
    ($e:expr) => {
        match $e {
            Ok(expr) => expr,
            Err(error) => {
                error!("wtry: {}", error);
                return;
            },
        }
    };
}

macro_rules! wtry_no_show {
    ($e:expr) => {
        match $e {
            Ok(expr) => expr,
            Err(_) => {
                error!("Error during this operation: {}", stringify!($e));
                return;
            },
        }
    };
}

macro_rules! wtry_opt {
    ($e:expr) => {
        match $e {
            Some(expr) => expr,
            None => {
                error!("{} returned None", stringify!($e));
                return None;
            },
        }
    };
}

macro_rules! wtry_opt_no_ret {
    ($e:expr) => {
        match $e {
            Some(expr) => expr,
            None => {
                error!("{} returned None", stringify!($e));
                return;
            },
        }
    };
}

mod adblocker;
mod dom;
mod executor;
mod hints;
mod login_form;
mod message_client;
mod option_util;

use std::fs::OpenOptions;
use std::mem::forget;
use std::path::Path;

use log::LogLevel::Error;
use simplelog::{Config, TermLogger, WriteLogger};
use simplelog::LogLevelFilter;
use webkit2gtk_webextension::{WebExtension, WebExtensionExt};

use message_client::MessageClient;
use message_client::Msg::PageCreated;

web_extension_init!();

#[doc(hidden)]
pub const APP_NAME: &'static str = "titanium";

/// Initialize the the logger and the message server.
pub fn web_extension_initialize(extension: &WebExtension) {
    let config = Config {
        time: Some(Error),
        level: Some(Error),
        target: None,
        location: None,
    };

    if let Err(error) = TermLogger::init(LogLevelFilter::Info, config) {
        println!("Cannot initialize the logger: {}", error);
    }

    trace!("Before MessageClient::new()");
    let client = wtry!(MessageClient::new());
    trace!("After MessageClient::new()");

    connect_stream!(extension, connect_page_created(_, page), client, PageCreated(page.clone()));

    // Don't drop the client to keep receiving the messages on the stream.
    forget(client);
}
<commit_msg>cleanup<commit_after>/*
 * Copyright (c) 2016-2017 Boucher, Antoni <bouanto@zoho.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

//! Web extension for the titanium web browser.
//! It provides an ad blocker, scrolling support, hints, navigation and login credentials load/save.

#![warn(
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_results,
)]

extern crate fg_uds;
extern crate futures;
extern crate futures_glib;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate simplelog;
#[macro_use]
extern crate relm_state;
#[macro_use]
extern crate relm_derive_state;
extern crate titanium_common;
extern crate tokio_io;
extern crate tokio_serde_bincode;
extern crate url;
extern crate xdg;
#[macro_use]
extern crate webkit2gtk_webextension;

macro_rules! check_err {
    ($e:expr) => {
        if let Err(error) = $e {
            error!("check_err: {}", error);
            return;
        }
    };
}

macro_rules! check_err_opt {
    ($e:expr) => {
        if $e.is_none() {
            error!("{} is None", stringify!($e));
            return None;
        }
    };
}

macro_rules! unwrap_opt_or_ret {
    ($e:expr, $default:expr) => {
        match $e {
            Some(expr) => expr,
            None => return $default,
        }
    };
}

macro_rules! unwrap_or_ret {
    ($e:expr, $default:expr) => {
        match $e {
            Ok(expr) => expr,
            Err(error) => {
                error!("unwrap_or_ret: {}", error);
                return $default;
            },
        }
    };
}

macro_rules! wtry {
    ($e:expr) => {
        match $e {
            Ok(expr) => expr,
            Err(error) => {
                error!("wtry: {}", error);
                return;
            },
        }
    };
}

macro_rules! wtry_no_show {
    ($e:expr) => {
        match $e {
            Ok(expr) => expr,
            Err(_) => {
                error!("Error during this operation: {}", stringify!($e));
                return;
            },
        }
    };
}

macro_rules! wtry_opt {
    ($e:expr) => {
        match $e {
            Some(expr) => expr,
            None => {
                error!("{} returned None", stringify!($e));
                return None;
            },
        }
    };
}

macro_rules! wtry_opt_no_ret {
    ($e:expr) => {
        match $e {
            Some(expr) => expr,
            None => {
                error!("{} returned None", stringify!($e));
                return;
            },
        }
    };
}

mod adblocker;
mod dom;
mod executor;
mod hints;
mod login_form;
mod message_client;
mod option_util;

use std::fs::OpenOptions;
use std::mem::forget;

use log::LogLevel::Error;
use simplelog::{Config, TermLogger, WriteLogger};
use simplelog::LogLevelFilter;
use webkit2gtk_webextension::{WebExtension, WebExtensionExt};

use message_client::MessageClient;
use message_client::Msg::PageCreated;

web_extension_init!();

#[doc(hidden)]
pub const APP_NAME: &'static str = "titanium";

/// Initialize the the logger and the message server.
pub fn web_extension_initialize(extension: &WebExtension) {
    let config = Config {
        time: Some(Error),
        level: Some(Error),
        target: None,
        location: None,
    };

    if let Err(error) = TermLogger::init(LogLevelFilter::Info, config) {
        println!("Cannot initialize the logger: {}", error);
    }

    trace!("Before MessageClient::new()");
    let client = wtry!(MessageClient::new());
    trace!("After MessageClient::new()");

    connect_stream!(extension, connect_page_created(_, page), client, PageCreated(page.clone()));

    // Don't drop the client to keep receiving the messages on the stream.
    forget(client);
}
<|endoftext|>


<commit_before>use super::{AggregateSignature, AttestationData, Bitfield};
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use test_random_derive::TestRandom;

/// Details an attestation that can be slashable.
///
/// Spec v0.5.0
#[derive(
    Debug,
    Clone,
    PartialEq,
    Serialize,
    Deserialize,
    Encode,
    Decode,
    TreeHash,
    TestRandom,
    SignedRoot,
)]
pub struct Attestation {
    pub aggregation_bitfield: Bitfield,
    pub data: AttestationData,
    pub custody_bitfield: Bitfield,
    pub aggregate_signature: AggregateSignature,
}

impl Attestation {
    /// Are the aggregation bitfields of these attestations disjoint?
    pub fn signers_disjoint_from(&self, other: &Attestation) -> bool {
        self.aggregation_bitfield
            .intersection(&other.aggregation_bitfield)
            .is_zero()
    }

    /// Aggregate another Attestation into this one.
    ///
    /// The aggregation bitfields must be disjoint, and the data must be the same.
    pub fn aggregate(&mut self, other: &Attestation) {
        debug_assert_eq!(self.data, other.data);
        debug_assert!(self.signers_disjoint_from(other));

        self.aggregation_bitfield
            .union_inplace(&other.aggregation_bitfield);
        self.custody_bitfield.union_inplace(&other.custody_bitfield);
        // FIXME: signature aggregation once our BLS library wraps it
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    ssz_tests!(Attestation);
}
<commit_msg>types: aggregate signatures in attestations<commit_after>use super::{AggregateSignature, AttestationData, Bitfield};
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use test_random_derive::TestRandom;

/// Details an attestation that can be slashable.
///
/// Spec v0.5.0
#[derive(
    Debug,
    Clone,
    PartialEq,
    Serialize,
    Deserialize,
    Encode,
    Decode,
    TreeHash,
    TestRandom,
    SignedRoot,
)]
pub struct Attestation {
    pub aggregation_bitfield: Bitfield,
    pub data: AttestationData,
    pub custody_bitfield: Bitfield,
    pub aggregate_signature: AggregateSignature,
}

impl Attestation {
    /// Are the aggregation bitfields of these attestations disjoint?
    pub fn signers_disjoint_from(&self, other: &Attestation) -> bool {
        self.aggregation_bitfield
            .intersection(&other.aggregation_bitfield)
            .is_zero()
    }

    /// Aggregate another Attestation into this one.
    ///
    /// The aggregation bitfields must be disjoint, and the data must be the same.
    pub fn aggregate(&mut self, other: &Attestation) {
        debug_assert_eq!(self.data, other.data);
        debug_assert!(self.signers_disjoint_from(other));

        self.aggregation_bitfield
            .union_inplace(&other.aggregation_bitfield);
        self.custody_bitfield.union_inplace(&other.custody_bitfield);
        self.aggregate_signature
            .add_aggregate(&other.aggregate_signature);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    ssz_tests!(Attestation);
}
<|endoftext|>


<commit_before>use std::io::stdout;
use std::io::Write;

use lister::Lister;
use result::Result;

use libimagstore::store::FileLockEntry;

pub struct PathLister {
    absolute: bool,
}

impl PathLister {

    pub fn new(absolute: bool) -> PathLister {
        PathLister {
            absolute: absolute,
        }
    }

}

impl Lister for PathLister {

    fn list<'a, I: Iterator<Item = FileLockEntry<'a>>>(&self, entries: I) -> Result<()> {
        use error::ListError as LE;
        use error::ListErrorKind as LEK;

        entries.fold(Ok(()), |accu, entry| {
            accu.and_then(|_| Ok(entry.get_location().clone()))
                .and_then(|pb| {
                    if self.absolute {
                        pb.canonicalize().map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                    } else {
                        Ok(pb)
                    }
                })
                .and_then(|pb| {
                    write!(stdout(), "{:?}\n", pb)
                        .map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                })
                .map_err(|e| {
                    if e.err_type() == LEK::FormatError {
                        e
                    } else {
                        LE::new(LEK::FormatError, Some(Box::new(e)))
                    }
                })
            })
    }

}

<commit_msg>Fix libimagentrylist::listers::path<commit_after>use std::io::stdout;
use std::io::Write;

use lister::Lister;
use result::Result;

use libimagstore::store::FileLockEntry;

pub struct PathLister {
    absolute: bool,
}

impl PathLister {

    pub fn new(absolute: bool) -> PathLister {
        PathLister {
            absolute: absolute,
        }
    }

}

impl Lister for PathLister {

    fn list<'a, I: Iterator<Item = FileLockEntry<'a>>>(&self, entries: I) -> Result<()> {
        use error::ListError as LE;
        use error::ListErrorKind as LEK;

        entries.fold(Ok(()), |accu, entry| {
            accu.and_then(|_| Ok(entry.get_location().clone()))
                .and_then(|pb| {
                    if self.absolute {
                        pb.canonicalize().map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                    } else {
                        Ok(pb.into())
                    }
                })
                .and_then(|pb| {
                    write!(stdout(), "{:?}\n", pb)
                        .map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                })
                .map_err(|e| {
                    if e.err_type() == LEK::FormatError {
                        e
                    } else {
                        LE::new(LEK::FormatError, Some(Box::new(e)))
                    }
                })
            })
    }

}

<|endoftext|>


<commit_before>use std::io;
use std::string::String;
use std::io::Write; // Used for flush implicitly?
use std::str;

struct Topping<'a> {
    name: &'a str,
    price: f32
}

struct Pizza<'a> {
//    toppings: Vec<Box<Topping<'a>>>
    toppings: Vec<Topping<'a>>
}

impl <'a> Pizza<'a> {
    pub fn to_string(&self) -> String {
        return format!("Pizza with {} has price {}", self.toppings[0].name, self.toppings[0].price);
    }
}

fn main() {
    let stdin = io::stdin();
    let name  = get_name(stdin);
    println!("Hello {}", name);
    str_topping(get_topping());
    println!("Pizza is {}", get_pizza().to_string());
}

fn get_pizza<'a>() -> Pizza<'a> {
    return Pizza{toppings:vec!(get_topping())}
}

fn get_topping<'a>() -> Topping<'a> {
    return Topping {name: "Salami", price: 0.7}
}

fn str_topping(topping: Topping) {
    println!("{} - {}", topping.name, topping.price)
}

fn get_name(stdin: io::Stdin) -> String {
    print!("Enter name: ");
    io::stdout().flush();
    let mut name = String::new();
    stdin.read_line(&mut name);
    return name;
}
<commit_msg>List processing of toppings<commit_after>use std::io;
use std::string::String;
use std::io::Write; // Used for flush implicitly?
use std::str;

struct Topping<'a> {
    name: &'a str,
    price: f32
}

struct Pizza<'a> {
    toppings: Vec<Topping<'a>>
}

impl<'a> Pizza<'a> {
    pub fn to_string(&self) -> String {
        let total: f32 = self.toppings
            .iter()
            .map(|topping| topping.price)
            .fold(0f32, |left, right| { left + right });
        let topping_list = self.toppings.iter().map(|topping| topping.name).collect::<Vec<String>>().join(", ");
        return format!("Pizza with {} has price {}", topping_list, total);
    }
}

fn main() {
    let stdin = io::stdin();
    let name = get_name(stdin);
    println!("Hello {}", name);
    str_topping(get_topping());
    println!("Pizza is {}", get_pizza().to_string());
}

fn get_pizza<'a>() -> Pizza<'a> {
    return Pizza { toppings: vec!(get_topping(), get_topping()) }
}

fn get_topping<'a>() -> Topping<'a> {
    return Topping { name: "Salami", price: 0.7 }
}

fn str_topping(topping: Topping) {
    println!("{} - {}", topping.name, topping.price)
}

fn get_name(stdin: io::Stdin) -> String {
    print!("Enter name: ");
    io::stdout().flush();
    let mut name = String::new();
    stdin.read_line(&mut name);
    return name;
}
<|endoftext|>