<commit_before>/*
    Copyright 2013 Jesse 'Jeaye' Wilkerson
    See licensing in LICENSE file, or at:
        http://www.opensource.org/licenses/BSD-3-Clause

    File: obj/primitive/sphere.rs
    Author: Jesse 'Jeaye' Wilkerson
    Description:
      An arbitrarily subdivided Icosahedron.
*/

use math::{ Vec3f, BB3 };

#[path = "../../gl/mod.rs"]
mod gl;
#[path = "../../gl/util.rs"]
mod util;
#[macro_escape]
#[path = "../../gl/check.rs"]
mod check;

pub struct Sphere
{
  radius: f32,
  vao: gl::GLuint,
  vbo: gl::GLuint,
  verts: ~[Vec3f],
}

impl Sphere
{
  pub fn new(new_radius: f32, new_subdivides: i32) -> Sphere
  {
    /* Magic numbers place all verts 1.0 from center. */
    let magic_x = 0.525731112119133606f32;
    let magic_z = 0.850650808352039932f32;

    let mut sphere = Sphere
    {
      radius: new_radius,
      vao: 0,
      vbo: 0,
      verts: ~[],
    };

    let root_verts: [Vec3f, ..12] =
    [
      Vec3f::new(-magic_x, 0.0, magic_z),
      Vec3f::new(magic_x, 0.0, magic_z),
      Vec3f::new(-magic_x, 0.0, -magic_z),
      Vec3f::new(magic_x, 0.0, -magic_z),

      Vec3f::new(0.0, magic_z, magic_x),
      Vec3f::new(0.0, magic_z, -magic_x),
      Vec3f::new(0.0, -magic_z, magic_x),
      Vec3f::new(0.0, -magic_z, -magic_x),

      Vec3f::new(magic_z, magic_x, 0.0),
      Vec3f::new(-magic_z, magic_x, 0.0),
      Vec3f::new(magic_z, -magic_x, 0.0),
      Vec3f::new(-magic_z, -magic_x, 0.0),
    ];

    let verts: &[Vec3f] =
    &[
      /* http://www.glprogramming.com/red/chapter02.html#name8 */
      root_verts[0], root_verts[0], root_verts[4], root_verts[0], root_verts[1], root_verts[0], root_verts[0], root_verts[1], root_verts[9], root_verts[1],   root_verts[4],  root_verts[1],
      root_verts[9], root_verts[2], root_verts[5], root_verts[2], root_verts[4], root_verts[2], root_verts[4], root_verts[3], root_verts[5], root_verts[3],   root_verts[8],  root_verts[3],
      root_verts[4], root_verts[4], root_verts[8], root_verts[4], root_verts[1], root_verts[4], root_verts[8], root_verts[5], root_verts[10],root_verts[5],  root_verts[1],  root_verts[5],
      root_verts[8], root_verts[6], root_verts[3], root_verts[6], root_verts[10],root_verts[6], root_verts[5], root_verts[7], root_verts[3], root_verts[7],  root_verts[8],  root_verts[7],
      root_verts[5], root_verts[8], root_verts[2], root_verts[8], root_verts[3], root_verts[8], root_verts[2], root_verts[9], root_verts[7], root_verts[9],   root_verts[3],  root_verts[9],
      root_verts[7], root_verts[1], root_verts[10],root_verts[1], root_verts[3], root_verts[1], root_verts[7], root_verts[2], root_verts[6], root_verts[2],  root_verts[10], root_verts[2],
      root_verts[7], root_verts[3], root_verts[11],root_verts[3], root_verts[6], root_verts[3], root_verts[11],root_verts[4], root_verts[0], root_verts[4], root_verts[6],   root_verts[4],
      root_verts[0], root_verts[5], root_verts[1], root_verts[5], root_verts[6], root_verts[5], root_verts[6], root_verts[6], root_verts[1], root_verts[6],    root_verts[10], root_verts[6],
      root_verts[9], root_verts[7], root_verts[0], root_verts[7], root_verts[11],root_verts[7], root_verts[9], root_verts[8], root_verts[11],root_verts[8], root_verts[2],  root_verts[8],
      root_verts[9], root_verts[9], root_verts[2], root_verts[9], root_verts[5], root_verts[9], root_verts[7], root_verts[0], root_verts[2], root_verts[0],    root_verts[11], root_verts[0],
    ];
    for uint::range_step(0, verts.len(), 6) |x|
    { sphere.subdivide(verts[x], verts[x + 2], verts[x + 4], new_subdivides); }

    sphere.vao = check!(gl::gen_vertex_arrays(1))[0]; /* TODO: Check these. */
    sphere.vbo = check!(gl::gen_buffers(1))[0];
    check!(gl::bind_vertex_array(sphere.vao));
    check!(gl::bind_buffer(gl::ARRAY_BUFFER, sphere.vbo));
    check!(gl::buffer_data(gl::ARRAY_BUFFER, sphere.verts, gl::STATIC_DRAW));

    sphere
  }

  /* Recursive subdivide for a given triangle. */
  priv fn subdivide(&mut self, v1: Vec3f, v2: Vec3f, v3: Vec3f, depth: i32)
  {
    let mut v12 = Vec3f::zero(), v23 = Vec3f::zero(), v31 = Vec3f::zero();

    if depth == 0
    {
      self.verts.push(v1);
      self.verts.push(v1);

      self.verts.push(v2);
      self.verts.push(v1);

      self.verts.push(v3);
      self.verts.push(v1);
      return;
    }

    v12.x = v1.x + v2.x; /* TODO: Lack of clean mutable indexing. */
    v23.x = v2.x + v3.x;
    v31.x = v3.x + v1.x;

    v12.y = v1.y + v2.y;
    v23.y = v2.y + v3.y;
    v31.y = v3.y + v1.y;

    v12.z = v1.z + v2.z;
    v23.z = v2.z + v3.z;
    v31.z = v3.z + v1.z;

    v12.normalize();
    v23.normalize();
    v31.normalize();
    self.subdivide(v1, v12, v31, depth - 1);
    self.subdivide(v2, v23, v12, depth - 1);
    self.subdivide(v3, v31, v23, depth - 1);
    self.subdivide(v12, v23, v31, depth - 1);
  }

  pub fn draw(&self)
  {
    check!(gl::bind_vertex_array(self.vao));
    check!(gl::bind_buffer(gl::ARRAY_BUFFER, self.vbo));

    check!(gl::vertex_attrib_pointer_f32(0, 3, false, (sys::size_of::<Vec3f>() * 2) as i32, 0));
    check!(gl::vertex_attrib_pointer_f32(1, 3, false, (sys::size_of::<Vec3f>() * 2) as i32, sys::size_of::<Vec3f>() as u32));
    check!(gl::enable_vertex_attrib_array(0));
    check!(gl::enable_vertex_attrib_array(1));

    check!(gl::draw_arrays(gl::TRIANGLES, 0, (self.verts.len() as i32) / 2));

    check!(gl::disable_vertex_attrib_array(0));
    check!(gl::disable_vertex_attrib_array(1));
    check!(gl::bind_vertex_array(0));
    check!(gl::bind_buffer(gl::ARRAY_BUFFER, 0));
  }
}

priv fn voxelize(verts: &[Vec3f]) -> ~[Vec3f]
{
  /* Pos -> Col, Pos -> Col, etc */
  let mut new_verts: ~[Vec3f] = ~[];

  /* Bounding box of vert dimensions. */
  /* Calculate, given resolution (how many voxels across), the dimensions of a voxel. */
  /* Create 3D array of voxels. Render wireframe? */
  /* Triangle -> box collision checking to enable voxels. */
  /* Pass back on to sphere for rendering. */

  new_verts
}

<commit_msg> #12 Moved sphere over to Vertex_PC<commit_after>/*
    Copyright 2013 Jesse 'Jeaye' Wilkerson
    See licensing in LICENSE file, or at:
        http://www.opensource.org/licenses/BSD-3-Clause

    File: obj/primitive/sphere.rs
    Author: Jesse 'Jeaye' Wilkerson
    Description:
      An arbitrarily subdivided Icosahedron.
*/

use math::{ Vec3f, BB3 };
use primitive::Vertex_PC;

#[path = "../../gl/mod.rs"]
mod gl;
#[path = "../../gl/util.rs"]
mod util;
#[macro_escape]
#[path = "../../gl/check.rs"]
mod check;

pub struct Sphere
{
  radius: f32,
  vao: gl::GLuint,
  vbo: gl::GLuint,
  verts: ~[Vertex_PC],
}

impl Sphere
{
  pub fn new(new_radius: f32, new_subdivides: i32) -> Sphere
  {
    /* Magic numbers place all verts 1.0 from center. */
    let magic_x = 0.525731112119133606f32;
    let magic_z = 0.850650808352039932f32;

    let mut sphere = Sphere
    {
      radius: new_radius,
      vao: 0,
      vbo: 0,
      verts: ~[],
    };

    let root_verts: [Vec3f, ..12] =
    [
      Vec3f::new(-magic_x, 0.0, magic_z),
      Vec3f::new(magic_x, 0.0, magic_z),
      Vec3f::new(-magic_x, 0.0, -magic_z),
      Vec3f::new(magic_x, 0.0, -magic_z),

      Vec3f::new(0.0, magic_z, magic_x),
      Vec3f::new(0.0, magic_z, -magic_x),
      Vec3f::new(0.0, -magic_z, magic_x),
      Vec3f::new(0.0, -magic_z, -magic_x),

      Vec3f::new(magic_z, magic_x, 0.0),
      Vec3f::new(-magic_z, magic_x, 0.0),
      Vec3f::new(magic_z, -magic_x, 0.0),
      Vec3f::new(-magic_z, -magic_x, 0.0),
    ];

    let verts: &[Vertex_PC] =
    &[
      /* http://www.glprogramming.com/red/chapter02.html#name8 */
      Vertex_PC::new(root_verts[0], root_verts[0]), Vertex_PC::new(root_verts[4], root_verts[0]), Vertex_PC::new(root_verts[1], root_verts[0]), Vertex_PC::new(root_verts[0], root_verts[1]), Vertex_PC::new(root_verts[9], root_verts[1]),   Vertex_PC::new(root_verts[4],  root_verts[1]),
      Vertex_PC::new(root_verts[9], root_verts[2]), Vertex_PC::new(root_verts[5], root_verts[2]), Vertex_PC::new(root_verts[4], root_verts[2]), Vertex_PC::new(root_verts[4], root_verts[3]), Vertex_PC::new(root_verts[5], root_verts[3]),   Vertex_PC::new(root_verts[8],  root_verts[3]),
      Vertex_PC::new(root_verts[4], root_verts[4]), Vertex_PC::new(root_verts[8], root_verts[4]), Vertex_PC::new(root_verts[1], root_verts[4]), Vertex_PC::new(root_verts[8], root_verts[5]), Vertex_PC::new(root_verts[10],root_verts[5]),  Vertex_PC::new(root_verts[1],  root_verts[5]),
      Vertex_PC::new(root_verts[8], root_verts[6]), Vertex_PC::new(root_verts[3], root_verts[6]), Vertex_PC::new(root_verts[10],root_verts[6]), Vertex_PC::new(root_verts[5], root_verts[7]), Vertex_PC::new(root_verts[3], root_verts[7]),  Vertex_PC::new(root_verts[8],  root_verts[7]),
      Vertex_PC::new(root_verts[5], root_verts[8]), Vertex_PC::new(root_verts[2], root_verts[8]), Vertex_PC::new(root_verts[3], root_verts[8]), Vertex_PC::new(root_verts[2], root_verts[9]), Vertex_PC::new(root_verts[7], root_verts[9]),   Vertex_PC::new(root_verts[3],  root_verts[9]),
      Vertex_PC::new(root_verts[7], root_verts[1]), Vertex_PC::new(root_verts[10],root_verts[1]), Vertex_PC::new(root_verts[3], root_verts[1]), Vertex_PC::new(root_verts[7], root_verts[2]), Vertex_PC::new(root_verts[6], root_verts[2]),  Vertex_PC::new(root_verts[10], root_verts[2]),
      Vertex_PC::new(root_verts[7], root_verts[3]), Vertex_PC::new(root_verts[11],root_verts[3]), Vertex_PC::new(root_verts[6], root_verts[3]), Vertex_PC::new(root_verts[11],root_verts[4]), Vertex_PC::new(root_verts[0], root_verts[4]), Vertex_PC::new(root_verts[6],   root_verts[4]),
      Vertex_PC::new(root_verts[0], root_verts[5]), Vertex_PC::new(root_verts[1], root_verts[5]), Vertex_PC::new(root_verts[6], root_verts[5]), Vertex_PC::new(root_verts[6], root_verts[6]), Vertex_PC::new(root_verts[1], root_verts[6]),    Vertex_PC::new(root_verts[10], root_verts[6]),
      Vertex_PC::new(root_verts[9], root_verts[7]), Vertex_PC::new(root_verts[0], root_verts[7]), Vertex_PC::new(root_verts[11],root_verts[7]), Vertex_PC::new(root_verts[9], root_verts[8]), Vertex_PC::new(root_verts[11],root_verts[8]), Vertex_PC::new(root_verts[2],  root_verts[8]),
      Vertex_PC::new(root_verts[9], root_verts[9]), Vertex_PC::new(root_verts[2], root_verts[9]), Vertex_PC::new(root_verts[5], root_verts[9]), Vertex_PC::new(root_verts[7], root_verts[0]), Vertex_PC::new(root_verts[2], root_verts[0]),    Vertex_PC::new(root_verts[11], root_verts[0]),
    ];
    for uint::range_step(0, verts.len(), 3) |x|
    { sphere.subdivide(verts[x], verts[x + 1], verts[x + 2], new_subdivides); }
    //sphere.verts = voxelize(sphere.verts);

    sphere.vao = check!(gl::gen_vertex_arrays(1))[0]; /* TODO: Check these. */
    sphere.vbo = check!(gl::gen_buffers(1))[0];
    check!(gl::bind_vertex_array(sphere.vao));
    check!(gl::bind_buffer(gl::ARRAY_BUFFER, sphere.vbo));
    check!(gl::buffer_data(gl::ARRAY_BUFFER, sphere.verts, gl::STATIC_DRAW));

    sphere
  }

  /* Recursive subdivide for a given triangle. */
  priv fn subdivide(&mut self, v1: Vertex_PC, v2: Vertex_PC, v3: Vertex_PC, depth: i32)
  {
    if depth == 0
    {
      self.verts.push(v1);
      self.verts.push(v2);
      self.verts.push(v3);
      return;
    }

    let mut v12 = Vertex_PC::zero(), v23 = Vertex_PC::zero(), v31 = Vertex_PC::zero();
    v12.color = v1.color;
    v23.color = v1.color;
    v31.color = v1.color;

    v12.position.x = v1.position.x + v2.position.x; /* TODO: Lack of clean mutable indexing. */
    v23.position.x = v2.position.x + v3.position.x;
    v31.position.x = v3.position.x + v1.position.x;

    v12.position.y = v1.position.y + v2.position.y;
    v23.position.y = v2.position.y + v3.position.y;
    v31.position.y = v3.position.y + v1.position.y;

    v12.position.z = v1.position.z + v2.position.z;
    v23.position.z = v2.position.z + v3.position.z;
    v31.position.z = v3.position.z + v1.position.z;

    v12.position.normalize();
    v23.position.normalize();
    v31.position.normalize();
    self.subdivide(v1, v12, v31, depth - 1);
    self.subdivide(v2, v23, v12, depth - 1);
    self.subdivide(v3, v31, v23, depth - 1);
    self.subdivide(v12, v23, v31, depth - 1);
  }

  pub fn draw(&self)
  {
    check!(gl::bind_vertex_array(self.vao));
    check!(gl::bind_buffer(gl::ARRAY_BUFFER, self.vbo));

    check!(gl::vertex_attrib_pointer_f32(0, 3, false, (sys::size_of::<Vertex_PC>()) as i32, 0));
    check!(gl::vertex_attrib_pointer_f32(1, 3, false, (sys::size_of::<Vertex_PC>()) as i32, sys::size_of::<Vec3f>() as u32));
    check!(gl::enable_vertex_attrib_array(0));
    check!(gl::enable_vertex_attrib_array(1));

    check!(gl::draw_arrays(gl::TRIANGLES, 0, (self.verts.len() as i32)));

    check!(gl::disable_vertex_attrib_array(0));
    check!(gl::disable_vertex_attrib_array(1));
    check!(gl::bind_vertex_array(0));
    check!(gl::bind_buffer(gl::ARRAY_BUFFER, 0));
  }
}

priv fn voxelize(verts: &[Vertex_PC]) -> ~[Vertex_PC]
{
  /* Require at least one triangle. */
  assert!(verts.len() >= 3);

  let mut new_verts: ~[Vertex_PC] = ~[];

  /* Bounding box of vert dimensions. */
  let mut min = BB3::zero(), max = BB3::zero();
  for verts.each |x|
  {
  }

  /* Calculate, given resolution (how many voxels across), the dimensions of a voxel. */
  /* Create 3D array of voxels. Render wireframe? */
  /* Triangle -> box collision checking to enable voxels. */
  /* Pass back on to sphere for rendering. */

  new_verts
}

<|endoftext|>


<commit_before>use std::process::Command;
use std::collections::HashMap;
use librespot::playback::player::PlayerEvent;

fn run_program(program: &str, env_vars: HashMap<&str, String>) {
    let mut v: Vec<&str> = program.split_whitespace().collect();
    info!("Running {:?}", v);
    let status = Command::new(&v.remove(0))
        .args(&v)
        .envs(env_vars.iter())
        .status()
        .expect("program failed to start");
    info!("Exit status: {}", status);
}

pub fn run_program_on_events(event: PlayerEvent, onevent: &str) {
    let mut env_vars = HashMap::new();
    match event {
        PlayerEvent::Changed { old_track_id, new_track_id } => {
            env_vars.insert("PLAYER_EVENT", "change".to_string());
            env_vars.insert("OLD_TRACK_ID", old_track_id.to_base16());
            env_vars.insert("TRACK_ID", new_track_id.to_base16());
        },
        PlayerEvent::Started { track_id } => {
            env_vars.insert("PLAYER_EVENT", "start".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base16());
        }
        PlayerEvent::Stopped { track_id } =>  {
            env_vars.insert("PLAYER_EVENT", "stop".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base16());
        }
    }
    run_program(onevent, env_vars);
}
<commit_msg>Just spawn event handlers, don't wait for exit code.<commit_after>use std::process::Command;
use std::collections::HashMap;
use librespot::playback::player::PlayerEvent;

fn run_program(program: &str, env_vars: HashMap<&str, String>) {
    let mut v: Vec<&str> = program.split_whitespace().collect();
    info!("Running {:?} with environment variables {:?}", v, env_vars);
    Command::new(&v.remove(0))
        .args(&v)
        .envs(env_vars.iter())
        .spawn()
        .expect("program failed to start");
}

pub fn run_program_on_events(event: PlayerEvent, onevent: &str) {
    let mut env_vars = HashMap::new();
    match event {
        PlayerEvent::Changed { old_track_id, new_track_id } => {
            env_vars.insert("PLAYER_EVENT", "change".to_string());
            env_vars.insert("OLD_TRACK_ID", old_track_id.to_base16());
            env_vars.insert("TRACK_ID", new_track_id.to_base16());
        },
        PlayerEvent::Started { track_id } => {
            env_vars.insert("PLAYER_EVENT", "start".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base16());
        }
        PlayerEvent::Stopped { track_id } =>  {
            env_vars.insert("PLAYER_EVENT", "stop".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base16());
        }
    }
    run_program(onevent, env_vars);
}
<|endoftext|>


<commit_before>use librespot::playback::player::PlayerEvent;
use tokio_process::{Child, CommandExt};
use std::collections::HashMap;
use std::io;
use std::process::Command;

fn run_program(program: &str, env_vars: HashMap<&str, String>) -> io::Result<Child> {
    let mut v: Vec<&str> = program.split_whitespace().collect();
    info!("Running {:?} with environment variables {:?}", v, env_vars);
    Command::new(&v.remove(0))
        .args(&v)
        .envs(env_vars.iter())
        .spawn_async()
}

pub fn run_program_on_events(event: PlayerEvent, onevent: &str) -> io::Result<Child> {
    let mut env_vars = HashMap::new();
    match event {
        PlayerEvent::Changed {
            old_track_id,
            new_track_id,
        } => {
            env_vars.insert("PLAYER_EVENT", "change".to_string());
            env_vars.insert("OLD_TRACK_ID", old_track_id.to_base16());
            env_vars.insert("TRACK_ID", new_track_id.to_base16());
        }
        PlayerEvent::Started { track_id } => {
            env_vars.insert("PLAYER_EVENT", "start".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base16());
        }
        PlayerEvent::Stopped { track_id } => {
            env_vars.insert("PLAYER_EVENT", "stop".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base16());
        }
    }
    run_program(onevent, env_vars)
}
<commit_msg>Changed TRACK_ID from base16 to base62 so that it is equal with the official Spotify app<commit_after>use librespot::playback::player::PlayerEvent;
use tokio_process::{Child, CommandExt};
use std::collections::HashMap;
use std::io;
use std::process::Command;

fn run_program(program: &str, env_vars: HashMap<&str, String>) -> io::Result<Child> {
    let mut v: Vec<&str> = program.split_whitespace().collect();
    info!("Running {:?} with environment variables {:?}", v, env_vars);
    Command::new(&v.remove(0))
        .args(&v)
        .envs(env_vars.iter())
        .spawn_async()
}

pub fn run_program_on_events(event: PlayerEvent, onevent: &str) -> io::Result<Child> {
    let mut env_vars = HashMap::new();
    match event {
        PlayerEvent::Changed {
            old_track_id,
            new_track_id,
        } => {
            env_vars.insert("PLAYER_EVENT", "change".to_string());
            env_vars.insert("OLD_TRACK_ID", old_track_id.to_base62());
            env_vars.insert("TRACK_ID", new_track_id.to_base62());
        }
        PlayerEvent::Started { track_id } => {
            env_vars.insert("PLAYER_EVENT", "start".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base62());
        }
        PlayerEvent::Stopped { track_id } => {
            env_vars.insert("PLAYER_EVENT", "stop".to_string());
            env_vars.insert("TRACK_ID", track_id.to_base62());
        }
    }
    run_program(onevent, env_vars)
}
<|endoftext|>


<commit_before>extern crate core;
extern crate libc;
extern crate minifb;
extern crate prodbg_api;
extern crate bgfx_rs;
extern crate imgui_sys;

pub mod windows;
mod docking;
mod backend_plugin;

use docking::DockingPlugin;
//use prodbg_api::ui::Ui;
use bgfx_rs::Bgfx;
//use imgui_sys::Imgui;

use core::session::Sessions;
use windows::Windows;
use core::{DynamicReload, Search};
use core::view_plugins::{ViewPlugins};
use std::cell::RefCell;
use std::rc::Rc;

use core::plugins::*;

/*
fn add_view(index: usize, sessions: &mut Sessions, windows: &mut Windows, view_plugins: &mut ViewPlugins) {
    let session = sessions.get_current();
    let window = windows.get_current();
    let ui = Imgui::create_ui_instance();

    // TODO: Mask out index for plugin
    view_plugins.create_instance_from_index(ui, index).map(|handle| {
        window.add_view(handle);
        session.add_view(handle);
    });
}
*/

fn main() {
    let bgfx = Bgfx::new();
    let mut sessions = Sessions::new();
    let mut windows = Windows::new();

    let mut lib_handler = DynamicReload::new(None, Some("t2-output"), Search::Backwards);
    let mut plugins = Plugins::new();

    //let menus = create_menus();

    // Would be nice to nat have it this way
    let view_plugins = Rc::new(RefCell::new(ViewPlugins::new()));
    let docking_plugin = Rc::new(RefCell::new(DockingPlugin::new()));
    //let backend_plugins = Rc::new(RefCell::new(BackendPlugins::new()));

    sessions.create_instance();

    plugins.add_handler(&view_plugins);
    plugins.add_handler(&docking_plugin);
    //plugins.add_handler(&backend_plugins);

    plugins.add_plugin(&mut lib_handler, "bitmap_memory");
    plugins.add_plugin(&mut lib_handler, "i3_docking");

    windows.create_default();

    //add_view(0, &mut sessions, &mut windows, &mut view_plugins.borrow_mut());

    loop {
        bgfx.pre_update();

        plugins.update(&mut lib_handler);
        sessions.update();
        windows.update(&mut sessions, &mut view_plugins.borrow_mut());

        if windows.should_exit() {
            break;
        }

        bgfx.post_update();
    }
}

// dummy
#[no_mangle]
pub fn init_plugin() {
}<commit_msg>Added some more plugins<commit_after>extern crate core;
extern crate libc;
extern crate minifb;
extern crate prodbg_api;
extern crate bgfx_rs;
extern crate imgui_sys;

pub mod windows;
mod docking;
mod backend_plugin;

use docking::DockingPlugin;
//use prodbg_api::ui::Ui;
use bgfx_rs::Bgfx;
//use imgui_sys::Imgui;

use core::session::Sessions;
use windows::Windows;
use core::{DynamicReload, Search};
use core::view_plugins::{ViewPlugins};
use std::cell::RefCell;
use std::rc::Rc;

use core::plugins::*;

/*
fn add_view(index: usize, sessions: &mut Sessions, windows: &mut Windows, view_plugins: &mut ViewPlugins) {
    let session = sessions.get_current();
    let window = windows.get_current();
    let ui = Imgui::create_ui_instance();

    // TODO: Mask out index for plugin
    view_plugins.create_instance_from_index(ui, index).map(|handle| {
        window.add_view(handle);
        session.add_view(handle);
    });
}
*/

fn main() {
    let bgfx = Bgfx::new();
    let mut sessions = Sessions::new();
    let mut windows = Windows::new();

    let mut lib_handler = DynamicReload::new(None, Some("t2-output"), Search::Backwards);
    let mut plugins = Plugins::new();

    //let menus = create_menus();

    // Would be nice to nat have it this way
    let view_plugins = Rc::new(RefCell::new(ViewPlugins::new()));
    let docking_plugin = Rc::new(RefCell::new(DockingPlugin::new()));
    //let backend_plugins = Rc::new(RefCell::new(BackendPlugins::new()));

    sessions.create_instance();

    plugins.add_handler(&view_plugins);
    plugins.add_handler(&docking_plugin);
    //plugins.add_handler(&backend_plugins);

    plugins.add_plugin(&mut lib_handler, "bitmap_memory");
    plugins.add_plugin(&mut lib_handler, "registers_plugin");
    plugins.add_plugin(&mut lib_handler, "hex_memory_plugin");

    windows.create_default();

    //add_view(0, &mut sessions, &mut windows, &mut view_plugins.borrow_mut());

    loop {
        bgfx.pre_update();

        plugins.update(&mut lib_handler);
        sessions.update();
        windows.update(&mut sessions, &mut view_plugins.borrow_mut());

        if windows.should_exit() {
            break;
        }

        bgfx.post_update();
    }
}

// dummy
#[no_mangle]
pub fn init_plugin() {
}
<|endoftext|>


<commit_before>extern crate pkg_config;

use pkg_config::{Config, Error};
use std::env;
use std::io::prelude::*;
use std::io;
use std::process;

fn main() {
    if let Err(s) = find() {
        let _ = writeln!(io::stderr(), "{}", s);
        process::exit(1);
    }
}

fn find() -> Result<(), Error> {
    let package_name = "cairo";
    let shared_libs = ["cairo"];
    let version = if cfg!(feature = "1.14") {
        "1.14"
    } else if cfg!(feature = "1.12") {
        "1.12"
    } else {
        "1.10"
    };

    if let Ok(lib_dir) = env::var("GTK_LIB_DIR") {
        for lib_ in shared_libs.iter() {
            println!("cargo:rustc-link-lib=dylib={}", lib_);
        }
        println!("cargo:rustc-link-search=native={}", lib_dir);
        return Ok(())
    }

    let target = env::var("TARGET").unwrap();
    let hardcode_shared_libs = target.contains("windows");

    let mut config = Config::new();
    config.atleast_version(version);
    if hardcode_shared_libs {
        config.cargo_metadata(false);
    }
    match config.probe(package_name) {
        Ok(library) => {
            if hardcode_shared_libs {
                for lib_ in shared_libs.iter() {
                    println!("cargo:rustc-link-lib=dylib={}", lib_);
                }
                for path in library.link_paths.iter() {
                    println!("cargo:rustc-link-search=native={}", path.to_str().unwrap());
                }
            }
            Ok(())
        }
        Err(Error::EnvNoPkgConfig(_)) | Err(Error::Command { .. }) => {
            for lib_ in shared_libs.iter() {
                println!("cargo:rustc-link-lib=dylib={}", lib_);
            }
            Ok(())
        }
        Err(err) => Err(err),
    }
}

<commit_msg>cairo-sys-rs: Don't leak system library path information<commit_after>extern crate pkg_config;

use pkg_config::{Config, Error};
use std::env;
use std::io;
use std::io::prelude::*;
use std::process;

fn main() {
    if let Err(s) = find() {
        let _ = writeln!(io::stderr(), "{}", s);
        process::exit(1);
    }
}

fn find() -> Result<(), Error> {
    let package_name = "cairo";
    let shared_libs = ["cairo"];
    let version = if cfg!(feature = "1.14") {
        "1.14"
    } else if cfg!(feature = "1.12") {
        "1.12"
    } else {
        "1.10"
    };

    if let Ok(lib_dir) = env::var("GTK_LIB_DIR") {
        for lib_ in shared_libs.iter() {
            println!("cargo:rustc-link-lib=dylib={}", lib_);
        }
        println!("cargo:rustc-link-search=native={}", lib_dir);
        return Ok(());
    }

    let target = env::var("TARGET").unwrap();
    let hardcode_shared_libs = target.contains("windows");

    let mut config = Config::new();
    config.atleast_version(version);
    config.print_system_libs(false);

    if hardcode_shared_libs {
        config.cargo_metadata(false);
    }
    match config.probe(package_name) {
        Ok(library) => {
            if hardcode_shared_libs {
                for lib_ in shared_libs.iter() {
                    println!("cargo:rustc-link-lib=dylib={}", lib_);
                }
                for path in library.link_paths.iter() {
                    println!("cargo:rustc-link-search=native={}", path.to_str().unwrap());
                }
            }
            Ok(())
        }
        Err(Error::EnvNoPkgConfig(_)) | Err(Error::Command { .. }) => {
            for lib_ in shared_libs.iter() {
                println!("cargo:rustc-link-lib=dylib={}", lib_);
            }
            Ok(())
        }
        Err(err) => Err(err),
    }
}
<|endoftext|>


<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

//! Log directory as specified by user arguments.

use log::error;
use std::collections::HashMap;
use std::io::{self, Read};
use std::path::PathBuf;

use crate::disk_logdir::DiskLogdir;
use crate::gcs;
use crate::logdir::{EventFileBuf, Logdir};
use crate::types::Run;

/// A logdir dynamically dispatched over supported implementations.
pub enum DynLogdir {
    Disk(DiskLogdir),
    Gcs(gcs::Logdir),
}

/// A file from any one of [`DynLogdir`]'s underlying implementations.
pub enum DynFile {
    Disk(<DiskLogdir as Logdir>::File),
    Gcs(<gcs::Logdir as Logdir>::File),
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("empty --logdir")]
    EmptyLogdir,
    #[error("unknown protocol {:?} in logdir {}", .protocol, .full_logdir.display())]
    UnknownProtocol {
        protocol: String,
        full_logdir: PathBuf,
    },
    #[error(transparent)]
    GcsCredentialsError(#[from] gcs::CredentialsError),
    #[error(transparent)]
    GcsClientError(#[from] gcs::ClientError),
}

/// A `--logdir` flag value after parsing but before any impure operations like reading
/// credentials or opening an HTTP client.
#[derive(Debug, PartialEq, Eq)]
enum ParsedLogdir {
    Disk(PathBuf),
    Gcs { bucket: String, prefix: String },
}

impl ParsedLogdir {
    pub fn from_path(path: PathBuf) -> Result<Self, Error> {
        let path_str = path.to_string_lossy();
        if path_str.is_empty() {
            return Err(Error::EmptyLogdir);
        }

        let protocol_parts: Vec<&str> = path_str.splitn(2, "://").collect();
        if protocol_parts.len() < 2 || !is_protocol(protocol_parts[0]) {
            // Interpret as path on disk.
            return Ok(ParsedLogdir::Disk(path));
        }

        let (protocol, subpath) = (protocol_parts[0], protocol_parts[1]);
        match protocol {
            "gs" => Ok(Self::parse_gcs(subpath)),
            _ => Err(Error::UnknownProtocol {
                protocol: protocol.to_string(),
                full_logdir: path,
            }),
        }
    }

    fn parse_gcs(gcs_path: &str) -> Self {
        let mut parts = gcs_path.splitn(2, '/');
        let bucket = parts.next().unwrap().to_string(); // splitn always yields at least one element
        let prefix = parts.next().unwrap_or("").to_string();
        ParsedLogdir::Gcs { bucket, prefix }
    }
}

impl DynLogdir {
    /// Parses a `DynLogdir` from a user-supplied path.
    ///
    /// This succeeds unless the path represents a GCS logdir and no HTTP client can be opened. In
    /// case of failure, errors will be logged to the active logger.
    ///
    /// This constructor is heavyweight; it may construct an HTTP client and read a GCS credentials
    /// file from disk.
    ///
    /// # Panics
    ///
    /// May panic in debug mode if called from a thread with an active Tokio runtime; see
    /// [seanmonstar/reqwest#1017].
    ///
    /// [seanmonstar/reqwest#1017]: https://github.com/seanmonstar/reqwest/issues/1017
    pub fn new(path: PathBuf) -> Result<Self, Error> {
        match ParsedLogdir::from_path(path)? {
            ParsedLogdir::Disk(path) => Ok(DynLogdir::Disk(DiskLogdir::new(path))),
            ParsedLogdir::Gcs { bucket, prefix } => {
                let client = gcs::Client::new(gcs::Credentials::from_disk()?)?;
                Ok(DynLogdir::Gcs(gcs::Logdir::new(client, bucket, prefix)))
            }
        }
    }
}

/// [RFC 3986, section 3.1][rfc] specifies:
///
/// ```text
/// scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
/// ```
///
/// [rfc]: https://tools.ietf.org/html/rfc3986#section-3.1
fn is_protocol(s: &str) -> bool {
    if !s.chars().next().map_or(false, |c| c.is_ascii_alphabetic()) {
        return false;
    }
    s.chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
}

impl crate::logdir::Logdir for DynLogdir {
    type File = DynFile;

    fn discover(&self) -> io::Result<HashMap<Run, Vec<EventFileBuf>>> {
        match self {
            Self::Disk(x) => x.discover(),
            Self::Gcs(x) => x.discover(),
        }
    }

    fn open(&self, path: &EventFileBuf) -> io::Result<Self::File> {
        match self {
            Self::Disk(x) => x.open(path).map(DynFile::Disk),
            Self::Gcs(x) => x.open(path).map(DynFile::Gcs),
        }
    }
}

impl Read for DynFile {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Disk(x) => x.read(buf),
            Self::Gcs(x) => x.read(buf),
        }
    }
}

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

    #[test]
    fn test_parse_disk_absolute() {
        let p = PathBuf::from("/path/to/data");
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_disk_relative() {
        let p = PathBuf::from("path/to/data");
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_disk_unc() {
        let p = PathBuf::from(r#"C:\path\to\data"#);
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_colonslashslash_but_not_protocol() {
        let p = PathBuf::from("protocols_cant_have_underscores://hmm");
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_gcs_no_prefix() {
        let p = PathBuf::from("gs://tensorboard-bench-logs");
        assert_eq!(
            ParsedLogdir::from_path(p).unwrap(),
            ParsedLogdir::Gcs {
                bucket: "tensorboard-bench-logs".to_string(),
                prefix: "".to_string(),
            },
        );
    }

    #[test]
    fn test_parse_gcs_empty_prefix() {
        let p = PathBuf::from("gs://tensorboard-bench-logs/");
        assert_eq!(
            ParsedLogdir::from_path(p).unwrap(),
            ParsedLogdir::Gcs {
                bucket: "tensorboard-bench-logs".to_string(),
                prefix: "".to_string(),
            },
        );
    }

    #[test]
    fn test_parse_gcs_with_prefix() {
        let p = PathBuf::from("gs://tensorboard-bench-logs/mnist");
        assert_eq!(
            ParsedLogdir::from_path(p).unwrap(),
            ParsedLogdir::Gcs {
                bucket: "tensorboard-bench-logs".to_string(),
                prefix: "mnist".to_string(),
            },
        );
    }

    #[test]
    fn test_parse_empty() {
        match ParsedLogdir::from_path(PathBuf::new()) {
            Err(Error::EmptyLogdir) => (),
            other => panic!("{:?}", other),
        }
    }

    #[test]
    fn test_parse_unknown_protocol() {
        match ParsedLogdir::from_path(PathBuf::from("wat://wot")) {
            Err(Error::UnknownProtocol {
                protocol,
                full_logdir,
            }) if protocol == "wat" && full_logdir == PathBuf::from("wat://wot") => (),
            other => panic!("{:?}", other),
        }
    }
}
<commit_msg>rust: use `split_once` where appropriate (#4950)<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

//! Log directory as specified by user arguments.

use log::error;
use std::collections::HashMap;
use std::io::{self, Read};
use std::path::PathBuf;

use crate::disk_logdir::DiskLogdir;
use crate::gcs;
use crate::logdir::{EventFileBuf, Logdir};
use crate::types::Run;

/// A logdir dynamically dispatched over supported implementations.
pub enum DynLogdir {
    Disk(DiskLogdir),
    Gcs(gcs::Logdir),
}

/// A file from any one of [`DynLogdir`]'s underlying implementations.
pub enum DynFile {
    Disk(<DiskLogdir as Logdir>::File),
    Gcs(<gcs::Logdir as Logdir>::File),
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("empty --logdir")]
    EmptyLogdir,
    #[error("unknown protocol {:?} in logdir {}", .protocol, .full_logdir.display())]
    UnknownProtocol {
        protocol: String,
        full_logdir: PathBuf,
    },
    #[error(transparent)]
    GcsCredentialsError(#[from] gcs::CredentialsError),
    #[error(transparent)]
    GcsClientError(#[from] gcs::ClientError),
}

/// A `--logdir` flag value after parsing but before any impure operations like reading
/// credentials or opening an HTTP client.
#[derive(Debug, PartialEq, Eq)]
enum ParsedLogdir {
    Disk(PathBuf),
    Gcs { bucket: String, prefix: String },
}

impl ParsedLogdir {
    pub fn from_path(path: PathBuf) -> Result<Self, Error> {
        let path_str = path.to_string_lossy();
        if path_str.is_empty() {
            return Err(Error::EmptyLogdir);
        }

        let (protocol, subpath) = match path_str.split_once("://") {
            Some((p, s)) if is_protocol(p) => (p, s),
            // Otherwise, interpret as path on disk.
            _ => return Ok(ParsedLogdir::Disk(path)),
        };
        match protocol {
            "gs" => {
                let (bucket, prefix) = subpath.split_once('/').unwrap_or((subpath, ""));
                let (bucket, prefix) = (bucket.to_string(), prefix.to_string());
                Ok(ParsedLogdir::Gcs { bucket, prefix })
            }
            _ => Err(Error::UnknownProtocol {
                protocol: protocol.to_string(),
                full_logdir: path,
            }),
        }
    }
}

impl DynLogdir {
    /// Parses a `DynLogdir` from a user-supplied path.
    ///
    /// This succeeds unless the path represents a GCS logdir and no HTTP client can be opened. In
    /// case of failure, errors will be logged to the active logger.
    ///
    /// This constructor is heavyweight; it may construct an HTTP client and read a GCS credentials
    /// file from disk.
    ///
    /// # Panics
    ///
    /// May panic in debug mode if called from a thread with an active Tokio runtime; see
    /// [seanmonstar/reqwest#1017].
    ///
    /// [seanmonstar/reqwest#1017]: https://github.com/seanmonstar/reqwest/issues/1017
    pub fn new(path: PathBuf) -> Result<Self, Error> {
        match ParsedLogdir::from_path(path)? {
            ParsedLogdir::Disk(path) => Ok(DynLogdir::Disk(DiskLogdir::new(path))),
            ParsedLogdir::Gcs { bucket, prefix } => {
                let client = gcs::Client::new(gcs::Credentials::from_disk()?)?;
                Ok(DynLogdir::Gcs(gcs::Logdir::new(client, bucket, prefix)))
            }
        }
    }
}

/// [RFC 3986, section 3.1][rfc] specifies:
///
/// ```text
/// scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
/// ```
///
/// [rfc]: https://tools.ietf.org/html/rfc3986#section-3.1
fn is_protocol(s: &str) -> bool {
    if !s.chars().next().map_or(false, |c| c.is_ascii_alphabetic()) {
        return false;
    }
    s.chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
}

impl crate::logdir::Logdir for DynLogdir {
    type File = DynFile;

    fn discover(&self) -> io::Result<HashMap<Run, Vec<EventFileBuf>>> {
        match self {
            Self::Disk(x) => x.discover(),
            Self::Gcs(x) => x.discover(),
        }
    }

    fn open(&self, path: &EventFileBuf) -> io::Result<Self::File> {
        match self {
            Self::Disk(x) => x.open(path).map(DynFile::Disk),
            Self::Gcs(x) => x.open(path).map(DynFile::Gcs),
        }
    }
}

impl Read for DynFile {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Disk(x) => x.read(buf),
            Self::Gcs(x) => x.read(buf),
        }
    }
}

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

    #[test]
    fn test_parse_disk_absolute() {
        let p = PathBuf::from("/path/to/data");
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_disk_relative() {
        let p = PathBuf::from("path/to/data");
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_disk_unc() {
        let p = PathBuf::from(r#"C:\path\to\data"#);
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_colonslashslash_but_not_protocol() {
        let p = PathBuf::from("protocols_cant_have_underscores://hmm");
        assert_eq!(
            ParsedLogdir::from_path(p.clone()).unwrap(),
            ParsedLogdir::Disk(p),
        );
    }

    #[test]
    fn test_parse_gcs_no_prefix() {
        let p = PathBuf::from("gs://tensorboard-bench-logs");
        assert_eq!(
            ParsedLogdir::from_path(p).unwrap(),
            ParsedLogdir::Gcs {
                bucket: "tensorboard-bench-logs".to_string(),
                prefix: "".to_string(),
            },
        );
    }

    #[test]
    fn test_parse_gcs_empty_prefix() {
        let p = PathBuf::from("gs://tensorboard-bench-logs/");
        assert_eq!(
            ParsedLogdir::from_path(p).unwrap(),
            ParsedLogdir::Gcs {
                bucket: "tensorboard-bench-logs".to_string(),
                prefix: "".to_string(),
            },
        );
    }

    #[test]
    fn test_parse_gcs_with_prefix() {
        let p = PathBuf::from("gs://tensorboard-bench-logs/mnist");
        assert_eq!(
            ParsedLogdir::from_path(p).unwrap(),
            ParsedLogdir::Gcs {
                bucket: "tensorboard-bench-logs".to_string(),
                prefix: "mnist".to_string(),
            },
        );
    }

    #[test]
    fn test_parse_empty() {
        match ParsedLogdir::from_path(PathBuf::new()) {
            Err(Error::EmptyLogdir) => (),
            other => panic!("{:?}", other),
        }
    }

    #[test]
    fn test_parse_unknown_protocol() {
        match ParsedLogdir::from_path(PathBuf::from("wat://wot")) {
            Err(Error::UnknownProtocol {
                protocol,
                full_logdir,
            }) if protocol == "wat" && full_logdir == PathBuf::from("wat://wot") => (),
            other => panic!("{:?}", other),
        }
    }
}
<|endoftext|>


<commit_before>//! [Mocktopus](https://docs.rs/mocktopus) procedural macros making items mockable
#![doc(html_logo_url = "https://raw.githubusercontent.com/CodeSandwich/mocktopus/master/logo.png",
    html_favicon_url = "https://raw.githubusercontent.com/CodeSandwich/mocktopus/master/logo.png")]

#![feature(iterator_for_each, proc_macro)]

extern crate proc_macro;
extern crate proc_macro2;
extern crate syn;
extern crate quote;

mod display_delegate;
mod item_injector;
mod header_builder;
mod lifetime_remover;

use proc_macro::{Diagnostic, Level, Span, TokenStream};
use quote::ToTokens;

/// Procedural macro, makes items and their sub-items mockable
///
/// # Valid to annotate
/// - module definitions (makes all its valid to annotate items annotated, even if stored in another file)
///
/// ```
/// #[mockable]
/// mod module {
///     mod nested {
///         fn mockable() { ... }
///     }
/// }
/// ```
/// - standalone functions
///
/// ```
/// #[mockable]
/// fn mockable() { ... }
/// ```
/// - struct impl blocks (makes all functions inside mockable)
///
/// ```
/// #[mockable]
/// impl Structure {
///     fn mockable() { ... }
/// }
/// ```
/// - trait impl blocks (makes all functions inside mockable)
///
/// ```
/// #[mockable]
/// impl Trait for Structure {
///     fn mockable() { ... }
/// }
/// ```
/// - traits (makes all default functions inside mockable)
///
/// ```
/// #[mockable]
/// trait Trait {
///     fn mockable() { ... }
/// }
/// ```
/// # Invalid to annotate **(WILL FAIL TO COMPILE OR BREAK MOCKING!)**
///
/// - single functions in struct impls
///
/// ```
/// impl Structure {
///     #[mockable] //INVALID USAGE!
///     fn mockable() { ... }
/// }
/// ```
/// - single functions in trait impls
///
/// ```
/// impl Trait for Structure {
///     #[mockable] //INVALID USAGE!
///     fn mockable() { ... }
/// }
/// ```
/// - single default functions in traits
///
/// ```
/// trait Trait {
///     #[mockable] //INVALID USAGE!
///     fn mockable() { ... }
/// }
/// ```
///
/// # Indifferent to annotate
/// - already mockable items (inside annotated modules)
/// - const functions (they are impossible to mock)
/// - unsafe functions (they are impossible to mock)
/// - any macro generated items (they are impossible to mock)
/// - any other items
#[proc_macro_attribute]
pub fn mockable(_: TokenStream, token_stream: TokenStream) -> TokenStream {
    let mut item: syn::Item = match syn::parse(token_stream.clone()) {
        Ok(item) => item,
        Err(err) => {
            Span::call_site()
                .warning("Failed to make code mockable")
                .error(format!("Failed to parse: {}", err))
                .emit();
            return token_stream;
        }
    };
    item_injector::inject_item(&mut item);
    item.into_tokens().into()
}

/// Procedural macro, guards items from being made mockable by enclosing item.
///
/// # Valid to annotate
/// - module definitions
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     mod nested {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - standalone functions
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
/// - struct impl blocks
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     impl Struct {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - trait impl blocks
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     impl Trait for Struct {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - traits
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     trait Trait {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - single functions in struct impls
///
/// ```
/// #[mockable]
/// impl Struct {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
/// - single functions in trait impls
///
/// ```
/// #[mockable]
/// impl Trait for Struct {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
/// - single default functions in traits
///
/// ```
/// #[mockable]
/// trait Trait {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
///
/// # Indifferent to annotate
/// - items not made mockable by enclosing item
/// - any other items
#[proc_macro_attribute]
pub fn not_mockable(_: TokenStream, token_stream: TokenStream) -> TokenStream {
    token_stream
}

<commit_msg>Clean up unused imports in macros<commit_after>//! [Mocktopus](https://docs.rs/mocktopus) procedural macros making items mockable
#![doc(html_logo_url = "https://raw.githubusercontent.com/CodeSandwich/mocktopus/master/logo.png",
    html_favicon_url = "https://raw.githubusercontent.com/CodeSandwich/mocktopus/master/logo.png")]

#![feature(iterator_for_each, proc_macro)]

extern crate proc_macro;
extern crate proc_macro2;
extern crate syn;
extern crate quote;

mod display_delegate;
mod item_injector;
mod header_builder;
mod lifetime_remover;

use proc_macro::{Span, TokenStream};
use quote::ToTokens;

/// Procedural macro, makes items and their sub-items mockable
///
/// # Valid to annotate
/// - module definitions (makes all its valid to annotate items annotated, even if stored in another file)
///
/// ```
/// #[mockable]
/// mod module {
///     mod nested {
///         fn mockable() { ... }
///     }
/// }
/// ```
/// - standalone functions
///
/// ```
/// #[mockable]
/// fn mockable() { ... }
/// ```
/// - struct impl blocks (makes all functions inside mockable)
///
/// ```
/// #[mockable]
/// impl Structure {
///     fn mockable() { ... }
/// }
/// ```
/// - trait impl blocks (makes all functions inside mockable)
///
/// ```
/// #[mockable]
/// impl Trait for Structure {
///     fn mockable() { ... }
/// }
/// ```
/// - traits (makes all default functions inside mockable)
///
/// ```
/// #[mockable]
/// trait Trait {
///     fn mockable() { ... }
/// }
/// ```
/// # Invalid to annotate **(WILL FAIL TO COMPILE OR BREAK MOCKING!)**
///
/// - single functions in struct impls
///
/// ```
/// impl Structure {
///     #[mockable] //INVALID USAGE!
///     fn mockable() { ... }
/// }
/// ```
/// - single functions in trait impls
///
/// ```
/// impl Trait for Structure {
///     #[mockable] //INVALID USAGE!
///     fn mockable() { ... }
/// }
/// ```
/// - single default functions in traits
///
/// ```
/// trait Trait {
///     #[mockable] //INVALID USAGE!
///     fn mockable() { ... }
/// }
/// ```
///
/// # Indifferent to annotate
/// - already mockable items (inside annotated modules)
/// - const functions (they are impossible to mock)
/// - unsafe functions (they are impossible to mock)
/// - any macro generated items (they are impossible to mock)
/// - any other items
#[proc_macro_attribute]
pub fn mockable(_: TokenStream, token_stream: TokenStream) -> TokenStream {
    let mut item: syn::Item = match syn::parse(token_stream.clone()) {
        Ok(item) => item,
        Err(err) => {
            Span::call_site()
                .warning("Failed to make code mockable")
                .error(format!("Failed to parse: {}", err))
                .emit();
            return token_stream;
        }
    };
    item_injector::inject_item(&mut item);
    item.into_tokens().into()
}

/// Procedural macro, guards items from being made mockable by enclosing item.
///
/// # Valid to annotate
/// - module definitions
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     mod nested {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - standalone functions
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
/// - struct impl blocks
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     impl Struct {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - trait impl blocks
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     impl Trait for Struct {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - traits
///
/// ```
/// #[mockable]
/// mod module {
///     #[not_mockable]
///     trait Trait {
///         fn not_mockable() { ... }
///     }
/// }
/// ```
/// - single functions in struct impls
///
/// ```
/// #[mockable]
/// impl Struct {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
/// - single functions in trait impls
///
/// ```
/// #[mockable]
/// impl Trait for Struct {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
/// - single default functions in traits
///
/// ```
/// #[mockable]
/// trait Trait {
///     #[not_mockable]
///     fn not_mockable() { ... }
/// }
/// ```
///
/// # Indifferent to annotate
/// - items not made mockable by enclosing item
/// - any other items
#[proc_macro_attribute]
pub fn not_mockable(_: TokenStream, token_stream: TokenStream) -> TokenStream {
    token_stream
}

<|endoftext|>


<commit_before>#![feature(plugin_registrar, rustc_private)]

//! `#[derive(..)]` attributes for POD and binary encodable types.
//!
//! # Attributes
//!
//! ## `#[derive(Pod)]`
//!
//! Marks a struct as `pod::Pod`. It must only contain other `Pod` members, and
//! the type must be packed.
//!
//! ### `#[derive(PodPacked)]`
//!
//! Marks a struct as `pod::Pod`, and also applies the `#[repr(packed)]`
//! attribute to the type.
//!
//! ### Example
//!
//! ```
//! #![feature(plugin, custom_derive, custom_attribute)]
//! #![plugin(nue_macros)]
//!
//! extern crate pod;
//! use pod::{Encode, PodExt};
//!
//! # fn main() {
//! #[derive(Pod)]
//! #[repr(packed)]
//! struct Data(u8);
//!
//! assert_eq!(Data(5).as_slice(), &[5]);
//! # }
//! ```
//!
//! ## `#[derive(NueEncode, NueDecode)]`
//!
//! Implements `pod::Encode` and `pod::Decode` on the struct.
//! All fields must also implement `Encode` / `Decode` (or be skipped by a `nue` attribute).
//!
//! ### `#[nue(...)]`, `#[nue_enc(...)]`, `#[nue_dec(...)]`
//!
//! Additional coding options may be provided per field using the `nue` attributes.
//! They will affect how the parent type is encoded or decoded. The attributes accept
//! arbitrary Rust expressions. Member variables may be accessed through `self`.
//!
//! `nue_enc` only applies to encoding, `nue_dec` applies to decoding, and `nue` applies to both.
//! The order of the attributes doesn't usually matter, though `align` and `skip` interact
//! differently depending on which is defined first.
//!
//! #### `assert`
//!
//! Asserts that some property is true before continuing with the operation.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//!
//! # fn main() {
//! #[derive(NueDecode)]
//! struct Data(
//!     #[nue(assert = "self.0 == 0")]
//! 	u8
//! );
//!
//! let data = &[1];
//! assert!(&Data::decode_slice(data).is_err());
//! # }
//! ```
//!
//! #### `align`
//!
//! Aligns the field to an offset of the given multiple.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Encode;
//!
//! # fn main() {
//! #[derive(NueEncode)]
//! struct Data(
//! 	u8,
//! 	#[nue(align = "self.0 as u64 + 1")]
//! 	&'static str
//! );
//!
//! let data = Data(2, "hi");
//! let cmp = &[2, 0, 0, b'h', b'i'];
//! assert_eq!(&data.encode_vec().unwrap(), cmp);
//! # }
//! ```
//!
//! #### `skip`
//!
//! Discards the provided amount of bytes before encoding/decoding the value.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Encode;
//!
//! # fn main() {
//! #[derive(NueEncode)]
//! struct Data(
//! 	u8,
//! 	#[nue(skip = "1")]
//! 	&'static str
//! );
//!
//! let data = Data(2, "hi");
//! let cmp = &[2, 0, b'h', b'i'];
//! assert_eq!(&data.encode_vec().unwrap(), cmp);
//! # }
//! ```
//!
//! #### `cond`
//!
//! Conditionally encodes or decodes the field. If the condition is not met,
//! `Default::default()` will be used.
//! `false` is a static guarantee that the field will be ignored.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Encode;
//!
//! # fn main() {
//! #[derive(NueEncode)]
//! struct Data<'a>(
//! 	u8,
//! 	#[nue(cond = "false")]
//! 	&'a () // Note that this type does not implement `Encode`
//! );
//!
//! let u = ();
//! let data = Data(2, &u);
//! let cmp = &[2];
//! assert_eq!(&data.encode_vec().unwrap(), cmp);
//! # }
//! ```
//!
//! #### `default`
//!
//! Determines the default value to be used if `cond` evaluates to false.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//!
//! # fn main() {
//! #[derive(NueDecode, PartialEq, Debug)]
//! struct Data(
//! 	u8,
//! 	#[nue(cond = "self.0 == 1", default = "5")]
//! 	u8
//! );
//!
//! let data = &[2];
//! assert_eq!(&Data::decode_slice(data).unwrap(), &Data(2, 5));
//!
//! let data = &[1, 2];
//! assert_eq!(&Data::decode_slice(data).unwrap(), &Data(1, 2));
//! # }
//! ```
//!
//! #### `limit`
//!
//! Limits the amount of bytes that can be consumed or written during coding.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//!
//! # fn main() {
//! #[derive(NueDecode)]
//! struct Data(
//! 	#[nue(limit = "4")]
//! 	String,
//! );
//!
//! let data = b"hello";
//! assert_eq!(&Data::decode_slice(data).unwrap().0, "hell");
//! # }
//! ```
//!
//! #### `consume`
//!
//! When set, uses all of `limit` even if the type did not encode or decode the entire byte region.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//! use std::ffi::CString;
//!
//! # fn main() {
//! #[derive(NueDecode)]
//! struct Data(
//! 	#[nue(limit = "8", consume = "true")]
//! 	CString,
//! 	u8
//! );
//!
//! let data = b"hello\0\0\0\x05";
//! let data = Data::decode_slice(data).unwrap();
//! assert_eq!(data.0.to_bytes(), b"hello");
//! assert_eq!(data.1, 5);
//! # }
//! ```

extern crate rustc;
extern crate nue_codegen;

#[plugin_registrar]
#[doc(hidden)]
pub fn register(reg: &mut rustc::plugin::Registry) {
    nue_codegen::register(reg);
}
<commit_msg>Add an extra assertion in the assert example<commit_after>#![feature(plugin_registrar, rustc_private)]

//! `#[derive(..)]` attributes for POD and binary encodable types.
//!
//! # Attributes
//!
//! ## `#[derive(Pod)]`
//!
//! Marks a struct as `pod::Pod`. It must only contain other `Pod` members, and
//! the type must be packed.
//!
//! ### `#[derive(PodPacked)]`
//!
//! Marks a struct as `pod::Pod`, and also applies the `#[repr(packed)]`
//! attribute to the type.
//!
//! ### Example
//!
//! ```
//! #![feature(plugin, custom_derive, custom_attribute)]
//! #![plugin(nue_macros)]
//!
//! extern crate pod;
//! use pod::{Encode, PodExt};
//!
//! # fn main() {
//! #[derive(Pod)]
//! #[repr(packed)]
//! struct Data(u8);
//!
//! assert_eq!(Data(5).as_slice(), &[5]);
//! # }
//! ```
//!
//! ## `#[derive(NueEncode, NueDecode)]`
//!
//! Implements `pod::Encode` and `pod::Decode` on the struct.
//! All fields must also implement `Encode` / `Decode` (or be skipped by a `nue` attribute).
//!
//! ### `#[nue(...)]`, `#[nue_enc(...)]`, `#[nue_dec(...)]`
//!
//! Additional coding options may be provided per field using the `nue` attributes.
//! They will affect how the parent type is encoded or decoded. The attributes accept
//! arbitrary Rust expressions. Member variables may be accessed through `self`.
//!
//! `nue_enc` only applies to encoding, `nue_dec` applies to decoding, and `nue` applies to both.
//! The order of the attributes doesn't usually matter, though `align` and `skip` interact
//! differently depending on which is defined first.
//!
//! #### `assert`
//!
//! Asserts that some property is true before continuing with the operation.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//!
//! # fn main() {
//! #[derive(NueDecode)]
//! struct Data(
//!     #[nue(assert = "self.0 == 0")]
//! 	u8
//! );
//!
//! let data = &[1];
//! assert!(&Data::decode_slice(data).is_err());
//!
//! let data = &[0];
//! assert!(&Data::decode_slice(data).is_ok());
//! # }
//! ```
//!
//! #### `align`
//!
//! Aligns the field to an offset of the given multiple.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Encode;
//!
//! # fn main() {
//! #[derive(NueEncode)]
//! struct Data(
//! 	u8,
//! 	#[nue(align = "self.0 as u64 + 1")]
//! 	&'static str
//! );
//!
//! let data = Data(2, "hi");
//! let cmp = &[2, 0, 0, b'h', b'i'];
//! assert_eq!(&data.encode_vec().unwrap(), cmp);
//! # }
//! ```
//!
//! #### `skip`
//!
//! Discards the provided amount of bytes before encoding/decoding the value.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Encode;
//!
//! # fn main() {
//! #[derive(NueEncode)]
//! struct Data(
//! 	u8,
//! 	#[nue(skip = "1")]
//! 	&'static str
//! );
//!
//! let data = Data(2, "hi");
//! let cmp = &[2, 0, b'h', b'i'];
//! assert_eq!(&data.encode_vec().unwrap(), cmp);
//! # }
//! ```
//!
//! #### `cond`
//!
//! Conditionally encodes or decodes the field. If the condition is not met,
//! `Default::default()` will be used.
//! `false` is a static guarantee that the field will be ignored.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Encode;
//!
//! # fn main() {
//! #[derive(NueEncode)]
//! struct Data<'a>(
//! 	u8,
//! 	#[nue(cond = "false")]
//! 	&'a () // Note that this type does not implement `Encode`
//! );
//!
//! let u = ();
//! let data = Data(2, &u);
//! let cmp = &[2];
//! assert_eq!(&data.encode_vec().unwrap(), cmp);
//! # }
//! ```
//!
//! #### `default`
//!
//! Determines the default value to be used if `cond` evaluates to false.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//!
//! # fn main() {
//! #[derive(NueDecode, PartialEq, Debug)]
//! struct Data(
//! 	u8,
//! 	#[nue(cond = "self.0 == 1", default = "5")]
//! 	u8
//! );
//!
//! let data = &[2];
//! assert_eq!(&Data::decode_slice(data).unwrap(), &Data(2, 5));
//!
//! let data = &[1, 2];
//! assert_eq!(&Data::decode_slice(data).unwrap(), &Data(1, 2));
//! # }
//! ```
//!
//! #### `limit`
//!
//! Limits the amount of bytes that can be consumed or written during coding.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//!
//! # fn main() {
//! #[derive(NueDecode)]
//! struct Data(
//! 	#[nue(limit = "4")]
//! 	String,
//! );
//!
//! let data = b"hello";
//! assert_eq!(&Data::decode_slice(data).unwrap().0, "hell");
//! # }
//! ```
//!
//! #### `consume`
//!
//! When set, uses all of `limit` even if the type did not encode or decode the entire byte region.
//!
//! ```
//! # #![feature(plugin, custom_derive, custom_attribute)] #![plugin(nue_macros)]
//! # extern crate pod; extern crate nue_io;
//! use pod::Decode;
//! use std::ffi::CString;
//!
//! # fn main() {
//! #[derive(NueDecode)]
//! struct Data(
//! 	#[nue(limit = "8", consume = "true")]
//! 	CString,
//! 	u8
//! );
//!
//! let data = b"hello\0\0\0\x05";
//! let data = Data::decode_slice(data).unwrap();
//! assert_eq!(data.0.to_bytes(), b"hello");
//! assert_eq!(data.1, 5);
//! # }
//! ```

extern crate rustc;
extern crate nue_codegen;

#[plugin_registrar]
#[doc(hidden)]
pub fn register(reg: &mut rustc::plugin::Registry) {
    nue_codegen::register(reg);
}
<|endoftext|>


<commit_before>endogenous ewma epinfma  zcapf rkf kf pkf cf invef yf labf wf rrf mc zcap rk k pk c inve y lab pinf w r a
b g qs ms  spinf sw kpf kp

endogenous labobs robs pinfobs dy dc dinve dw

exogenous ea eb eg  eqs  em  epinf ew

parameters curvw cgy curvp constelab constepinf constebeta cmaw cmap calfa
czcap csadjcost ctou csigma chabb cfc
cindw cprobw cindp cprobp csigl clandaw  crpi crdy cry crr
crhoa crhoas crhob crhog crhols crhoqs crhoms crhopinf crhow
ctrend cg, sig_a, sig_b,sig_w,sig_pinf,sig_m,sig_qs,sig_g

model(linear)

		# cpie=1+constepinf/100;
		# cgamma=1+ctrend/100 ;
		# cbeta=1/(1+constebeta/100);
		# clandap=cfc;
		# cbetabar=cbeta*cgamma^(-csigma);
		# cr=cpie/(cbeta*cgamma^(-csigma));
		# crk=(cbeta^(-1))*(cgamma^csigma) - (1-ctou);
		# cw = (calfa^calfa*(1-calfa)^(1-calfa)/(clandap*crk^calfa))^(1/(1-calfa));
		# cikbar=(1-(1-ctou)/cgamma);
		# cik=(1-(1-ctou)/cgamma)*cgamma;
		# clk=((1-calfa)/calfa)*(crk/cw);
		# cky=cfc*(clk)^(calfa-1);
		# ciy=cik*cky;
		# ccy=1-cg-cik*cky;
		# crkky=crk*cky;
		# cwhlc=(1/clandaw)*(1-calfa)/calfa*crk*cky/ccy;
		# cwly=1-crk*cky;
		# conster=(cr-1)*100;

% flexible economy

	      0*(1-calfa)*a + 1*a =  calfa*rkf+(1-calfa)*(wf)  ;
	      zcapf =  (1/(czcap/(1-czcap)))* rkf  ;
	      rkf =  (wf)+labf-kf ;
	      kf =  kpf(-1)+zcapf ;
	      invef = (1/(1+cbetabar*cgamma))* (  invef(-1) + cbetabar*cgamma*invef(1)+(1/(cgamma^2*csadjcost))*pkf ) +qs ;
          pkf = -rrf-0*b+(1/((1-chabb/cgamma)/(csigma*(1+chabb/cgamma))))*b +(crk/(crk+(1-ctou)))*rkf(1) +  ((1-ctou)/(crk+(1-ctou)))*pkf(1) ;
	      cf = (chabb/cgamma)/(1+chabb/cgamma)*cf(-1) + (1/(1+chabb/cgamma))*cf(+1) +((csigma-1)*cwhlc/(csigma*(1+chabb/cgamma)))*(labf-labf(+1)) - (1-chabb/cgamma)/(csigma*(1+chabb/cgamma))*(rrf+0*b) + b ;
	      yf = ccy*cf+ciy*invef+g  +  crkky*zcapf ;
	      yf = cfc*( calfa*kf+(1-calfa)*labf +a );
	      wf = csigl*labf 	+(1/(1-chabb/cgamma))*cf - (chabb/cgamma)/(1-chabb/cgamma)*cf(-1) ;
	      kpf =  (1-cikbar)*kpf(-1)+(cikbar)*invef + (cikbar)*(cgamma^2*csadjcost)*qs ;

% sticky price - wage economy

	      mc =  calfa*rk+(1-calfa)*(w) - 1*a - 0*(1-calfa)*a ;
	      zcap =  (1/(czcap/(1-czcap)))* rk ;
	      rk =  w+lab-k ;
	      k =  kp(-1)+zcap ;
	      inve = (1/(1+cbetabar*cgamma))* (  inve(-1) + cbetabar*cgamma*inve(1)+(1/(cgamma^2*csadjcost))*pk ) +qs ;
          pk = -r+pinf(1)-0*b +(1/((1-chabb/cgamma)/(csigma*(1+chabb/cgamma))))*b + (crk/(crk+(1-ctou)))*rk(1) +  ((1-ctou)/(crk+(1-ctou)))*pk(1) ;
	      c = (chabb/cgamma)/(1+chabb/cgamma)*c(-1) + (1/(1+chabb/cgamma))*c(+1) +((csigma-1)*cwhlc/(csigma*(1+chabb/cgamma)))*(lab-lab(+1)) - (1-chabb/cgamma)/(csigma*(1+chabb/cgamma))*(r-pinf(+1) + 0*b) +b ;
	      y = ccy*c+ciy*inve+g  +  1*crkky*zcap ;
	      y = cfc*( calfa*k+(1-calfa)*lab +a );
	      pinf =  (1/(1+cbetabar*cgamma*cindp)) * ( cbetabar*cgamma*pinf(1) +cindp*pinf(-1)
               +((1-cprobp)*(1-cbetabar*cgamma*cprobp)/cprobp)/((cfc-1)*curvp+1)*(mc)  )  + spinf ;
	      w =  (1/(1+cbetabar*cgamma))*w(-1)
               +(cbetabar*cgamma/(1+cbetabar*cgamma))*w(1)
               +(cindw/(1+cbetabar*cgamma))*pinf(-1)
               -(1+cbetabar*cgamma*cindw)/(1+cbetabar*cgamma)*pinf
               +(cbetabar*cgamma)/(1+cbetabar*cgamma)*pinf(1)
               +(1-cprobw)*(1-cbetabar*cgamma*cprobw)/((1+cbetabar*cgamma)*cprobw)*(1/((clandaw-1)*curvw+1))*
               (csigl*lab + (1/(1-chabb/cgamma))*c - ((chabb/cgamma)/(1-chabb/cgamma))*c(-1) -w)
               + 1*sw ;
	      r =  crpi*(1-crr)*pinf +cry*(1-crr)*(y-yf)+crdy*(y-yf-y(-1)+yf(-1))+crr*r(-1)+ms  ;
	      a = crhoa*a(-1)  + sig_a*ea;	%
	      b = crhob*b(-1) + sig_b*eb;
	      g = crhog*(g(-1)) + sig_g*eg + cgy*sig_a*ea;
	      qs = crhoqs*qs(-1) + sig_qs*eqs;
	      ms = crhoms*ms(-1) + sig_m*em;
	      spinf = crhopinf*spinf(-1) + epinfma - cmap*epinfma(-1);
	          epinfma=sig_pinf*epinf;
	      sw = crhow*sw(-1) + ewma - cmaw*ewma(-1) ;
	          ewma=sig_w*ew;
	      kp =  (1-cikbar)*kp(-1)+cikbar*inve + cikbar*cgamma^2*csadjcost*qs ;

% measurment equations

		dy=y-y(-1)+ctrend;
		dc=c-c(-1)+ctrend;
		dinve=inve-inve(-1)+ctrend;
		dw=w-w(-1)+ctrend;
		pinfobs = 1*(pinf) + constepinf;
		robs =    1*(r) + conster;
		labobs = lab + constelab;

observables dy dc dinve dw pinfobs robs labobs

parameterization
	% fixed parameters
	crhoas,1; 	 % this parameter does not enter the model
	crhols,    0.9928;  % this parameter does not enter the model
	ctou,.025;
	clandaw,1.5;
	cg,0.18;
	curvp,10;
	curvw,10;

	% estimated parameters initialisation
	sig_a,   0.4618,0.01,2,inv_gamma_pdf(0.9);
	sig_b,   0.18185,0.01,2,inv_gamma_pdf(0.9);
	sig_g,   0.6090,0.01,2,inv_gamma_pdf(0.9);
	sig_qs,  0.46017,0.01,2,inv_gamma_pdf(0.9);
	sig_m,   0.2397,0.01,2,inv_gamma_pdf(0.9);
	sig_pinf,0.1455,0.01,2,inv_gamma_pdf(0.9);
	sig_w,   0.2089,0.01,2,inv_gamma_pdf(0.9);

	calfa,   .24, .2,.4,normal_pdf(.9);
	csigma,   1.5,.75,2.25,normal_pdf(0.9);
	cfc,      1.5, 1, 1.5,normal_pdf(.9);
	cgy,      0.51,.1,1.5,normal_pdf(.9);

	csadjcost, 6.0144,1,7,normal_pdf(0.9);
	chabb,     0.6361,0.3,0.7,beta_pdf(.9);
	cprobw,    0.8087,0.3,0.7,beta_pdf(.9);
	csigl,     1.9423,.5,3.5,normal_pdf(.9);
	cprobp,    0.6,0.3,0.7,beta_pdf(.9);
	cindw,     0.3243,0.3,0.7,beta_pdf(.9);
	cindp,     0.47,0.3,0.7,beta_pdf(.9);
	czcap,     0.2696,0.3,0.7,beta_pdf(.9);
	crpi,      1.488,1,2,normal_pdf(.9);
	crr,       0.8762,0.3,0.7,beta_pdf(.9);
	cry,       0.0593,0.025,0.225,normal_pdf(.9);
	crdy,      0.2347,0.025,0.225,normal_pdf(.9);
	crhoa,     0.9977,0.2,0.8,beta_pdf(.9);
	crhob,     0.5799,0.3,0.7,beta_pdf(.9);
	crhog,     0.9957,0.2,0.8,beta_pdf(.9);
	crhoqs,    0.7165,0.3,0.7,beta_pdf(.9);
	crhoms,    .3,0.3,0.7,beta_pdf(.9);
	crhopinf,  0.8,0.3,0.7,beta_pdf(.9);
	crhow,     0.8,0.3,0.7,beta_pdf(.9);
	cmap ,     0.7,0.3,0.7,beta_pdf(.9);
	cmaw  ,    0.7,0.3,0.7,beta_pdf(.9);
	% derived from steady state
	constebeta, 0.7420,.05,.8,gamma_pdf(.9);

	ctrend,     0.3982,.2,.6,normal_pdf(.9);
	constepinf, .7,.425,.825,gamma_pdf(.9);
	constelab,  1.2918,-4,4,normal_pdf(.9);
<commit_msg>removed old call to linear<commit_after>endogenous ewma epinfma  zcapf rkf kf pkf cf invef yf labf wf rrf mc zcap rk k pk c inve y lab pinf w r a
b g qs ms  spinf sw kpf kp

endogenous labobs robs pinfobs dy dc dinve dw

exogenous ea eb eg  eqs  em  epinf ew

parameters curvw cgy curvp constelab constepinf constebeta cmaw cmap calfa
czcap csadjcost ctou csigma chabb cfc
cindw cprobw cindp cprobp csigl clandaw  crpi crdy cry crr
crhoa crhoas crhob crhog crhols crhoqs crhoms crhopinf crhow
ctrend cg, sig_a, sig_b,sig_w,sig_pinf,sig_m,sig_qs,sig_g

model

		# cpie=1+constepinf/100;
		# cgamma=1+ctrend/100 ;
		# cbeta=1/(1+constebeta/100);
		# clandap=cfc;
		# cbetabar=cbeta*cgamma^(-csigma);
		# cr=cpie/(cbeta*cgamma^(-csigma));
		# crk=(cbeta^(-1))*(cgamma^csigma) - (1-ctou);
		# cw = (calfa^calfa*(1-calfa)^(1-calfa)/(clandap*crk^calfa))^(1/(1-calfa));
		# cikbar=(1-(1-ctou)/cgamma);
		# cik=(1-(1-ctou)/cgamma)*cgamma;
		# clk=((1-calfa)/calfa)*(crk/cw);
		# cky=cfc*(clk)^(calfa-1);
		# ciy=cik*cky;
		# ccy=1-cg-cik*cky;
		# crkky=crk*cky;
		# cwhlc=(1/clandaw)*(1-calfa)/calfa*crk*cky/ccy;
		# cwly=1-crk*cky;
		# conster=(cr-1)*100;

% flexible economy

	      0*(1-calfa)*a + 1*a =  calfa*rkf+(1-calfa)*(wf)  ;
	      zcapf =  (1/(czcap/(1-czcap)))* rkf  ;
	      rkf =  (wf)+labf-kf ;
	      kf =  kpf(-1)+zcapf ;
	      invef = (1/(1+cbetabar*cgamma))* (  invef(-1) + cbetabar*cgamma*invef(1)+(1/(cgamma^2*csadjcost))*pkf ) +qs ;
          pkf = -rrf-0*b+(1/((1-chabb/cgamma)/(csigma*(1+chabb/cgamma))))*b +(crk/(crk+(1-ctou)))*rkf(1) +  ((1-ctou)/(crk+(1-ctou)))*pkf(1) ;
	      cf = (chabb/cgamma)/(1+chabb/cgamma)*cf(-1) + (1/(1+chabb/cgamma))*cf(+1) +((csigma-1)*cwhlc/(csigma*(1+chabb/cgamma)))*(labf-labf(+1)) - (1-chabb/cgamma)/(csigma*(1+chabb/cgamma))*(rrf+0*b) + b ;
	      yf = ccy*cf+ciy*invef+g  +  crkky*zcapf ;
	      yf = cfc*( calfa*kf+(1-calfa)*labf +a );
	      wf = csigl*labf 	+(1/(1-chabb/cgamma))*cf - (chabb/cgamma)/(1-chabb/cgamma)*cf(-1) ;
	      kpf =  (1-cikbar)*kpf(-1)+(cikbar)*invef + (cikbar)*(cgamma^2*csadjcost)*qs ;

% sticky price - wage economy

	      mc =  calfa*rk+(1-calfa)*(w) - 1*a - 0*(1-calfa)*a ;
	      zcap =  (1/(czcap/(1-czcap)))* rk ;
	      rk =  w+lab-k ;
	      k =  kp(-1)+zcap ;
	      inve = (1/(1+cbetabar*cgamma))* (  inve(-1) + cbetabar*cgamma*inve(1)+(1/(cgamma^2*csadjcost))*pk ) +qs ;
          pk = -r+pinf(1)-0*b +(1/((1-chabb/cgamma)/(csigma*(1+chabb/cgamma))))*b + (crk/(crk+(1-ctou)))*rk(1) +  ((1-ctou)/(crk+(1-ctou)))*pk(1) ;
	      c = (chabb/cgamma)/(1+chabb/cgamma)*c(-1) + (1/(1+chabb/cgamma))*c(+1) +((csigma-1)*cwhlc/(csigma*(1+chabb/cgamma)))*(lab-lab(+1)) - (1-chabb/cgamma)/(csigma*(1+chabb/cgamma))*(r-pinf(+1) + 0*b) +b ;
	      y = ccy*c+ciy*inve+g  +  1*crkky*zcap ;
	      y = cfc*( calfa*k+(1-calfa)*lab +a );
	      pinf =  (1/(1+cbetabar*cgamma*cindp)) * ( cbetabar*cgamma*pinf(1) +cindp*pinf(-1)
               +((1-cprobp)*(1-cbetabar*cgamma*cprobp)/cprobp)/((cfc-1)*curvp+1)*(mc)  )  + spinf ;
	      w =  (1/(1+cbetabar*cgamma))*w(-1)
               +(cbetabar*cgamma/(1+cbetabar*cgamma))*w(1)
               +(cindw/(1+cbetabar*cgamma))*pinf(-1)
               -(1+cbetabar*cgamma*cindw)/(1+cbetabar*cgamma)*pinf
               +(cbetabar*cgamma)/(1+cbetabar*cgamma)*pinf(1)
               +(1-cprobw)*(1-cbetabar*cgamma*cprobw)/((1+cbetabar*cgamma)*cprobw)*(1/((clandaw-1)*curvw+1))*
               (csigl*lab + (1/(1-chabb/cgamma))*c - ((chabb/cgamma)/(1-chabb/cgamma))*c(-1) -w)
               + 1*sw ;
	      r =  crpi*(1-crr)*pinf +cry*(1-crr)*(y-yf)+crdy*(y-yf-y(-1)+yf(-1))+crr*r(-1)+ms  ;
	      a = crhoa*a(-1)  + sig_a*ea;	%
	      b = crhob*b(-1) + sig_b*eb;
	      g = crhog*(g(-1)) + sig_g*eg + cgy*sig_a*ea;
	      qs = crhoqs*qs(-1) + sig_qs*eqs;
	      ms = crhoms*ms(-1) + sig_m*em;
	      spinf = crhopinf*spinf(-1) + epinfma - cmap*epinfma(-1);
	          epinfma=sig_pinf*epinf;
	      sw = crhow*sw(-1) + ewma - cmaw*ewma(-1) ;
	          ewma=sig_w*ew;
	      kp =  (1-cikbar)*kp(-1)+cikbar*inve + cikbar*cgamma^2*csadjcost*qs ;

% measurment equations

		dy=y-y(-1)+ctrend;
		dc=c-c(-1)+ctrend;
		dinve=inve-inve(-1)+ctrend;
		dw=w-w(-1)+ctrend;
		pinfobs = 1*(pinf) + constepinf;
		robs =    1*(r) + conster;
		labobs = lab + constelab;

observables dy dc dinve dw pinfobs robs labobs

parameterization
	% fixed parameters
	crhoas,1; 	 % this parameter does not enter the model
	crhols,    0.9928;  % this parameter does not enter the model
	ctou,.025;
	clandaw,1.5;
	cg,0.18;
	curvp,10;
	curvw,10;

	% estimated parameters initialisation
	sig_a,   0.4618,0.01,2,inv_gamma_pdf(0.9);
	sig_b,   0.18185,0.01,2,inv_gamma_pdf(0.9);
	sig_g,   0.6090,0.01,2,inv_gamma_pdf(0.9);
	sig_qs,  0.46017,0.01,2,inv_gamma_pdf(0.9);
	sig_m,   0.2397,0.01,2,inv_gamma_pdf(0.9);
	sig_pinf,0.1455,0.01,2,inv_gamma_pdf(0.9);
	sig_w,   0.2089,0.01,2,inv_gamma_pdf(0.9);

	calfa,   .24, .2,.4,normal_pdf(.9);
	csigma,   1.5,.75,2.25,normal_pdf(0.9);
	cfc,      1.5, 1, 1.5,normal_pdf(.9);
	cgy,      0.51,.1,1.5,normal_pdf(.9);

	csadjcost, 6.0144,1,7,normal_pdf(0.9);
	chabb,     0.6361,0.3,0.7,beta_pdf(.9);
	cprobw,    0.8087,0.3,0.7,beta_pdf(.9);
	csigl,     1.9423,.5,3.5,normal_pdf(.9);
	cprobp,    0.6,0.3,0.7,beta_pdf(.9);
	cindw,     0.3243,0.3,0.7,beta_pdf(.9);
	cindp,     0.47,0.3,0.7,beta_pdf(.9);
	czcap,     0.2696,0.3,0.7,beta_pdf(.9);
	crpi,      1.488,1,2,normal_pdf(.9);
	crr,       0.8762,0.3,0.7,beta_pdf(.9);
	cry,       0.0593,0.025,0.225,normal_pdf(.9);
	crdy,      0.2347,0.025,0.225,normal_pdf(.9);
	crhoa,     0.9977,0.2,0.8,beta_pdf(.9);
	crhob,     0.5799,0.3,0.7,beta_pdf(.9);
	crhog,     0.9957,0.2,0.8,beta_pdf(.9);
	crhoqs,    0.7165,0.3,0.7,beta_pdf(.9);
	crhoms,    .3,0.3,0.7,beta_pdf(.9);
	crhopinf,  0.8,0.3,0.7,beta_pdf(.9);
	crhow,     0.8,0.3,0.7,beta_pdf(.9);
	cmap ,     0.7,0.3,0.7,beta_pdf(.9);
	cmaw  ,    0.7,0.3,0.7,beta_pdf(.9);
	% derived from steady state
	constebeta, 0.7420,.05,.8,gamma_pdf(.9);

	ctrend,     0.3982,.2,.6,normal_pdf(.9);
	constepinf, .7,.425,.825,gamma_pdf(.9);
	constelab,  1.2918,-4,4,normal_pdf(.9);
<|endoftext|>


<commit_before>#[macro_use] extern crate diesel;
#[macro_use] extern crate diesel_codegen;

use std::time::SystemTime;

use diesel::prelude::*;
use diesel::pg::PgConnection;

table! {
    posts {
        id -> BigInt,
        title -> Text,
        body -> Text,
        draft -> Bool,
        publish_at -> Timestamp,
        visit_count -> Integer,
    }
}

#[derive(Queryable, Identifiable, AsChangeset)]
pub struct Post {
    pub id: i64,
    pub title: String,
    pub body: String,
    pub draft: bool,
    pub publish_at: SystemTime,
    pub visit_count: i32,
}

pub fn publish_all_posts(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;

    diesel::update(posts).set(draft.eq(false))
        .execute(conn)
}

#[test]
fn examine_sql_from_publish_all_posts() {
    use posts::dsl::*;

    assert_eq!(
        "UPDATE `posts` SET `draft` = ?".to_string(),
        debug_sql!(diesel::update(posts).set(draft.eq(false)))
    );
}

pub fn publish_pending_posts(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;
    use diesel::expression::dsl::now;

    let target = posts.filter(publish_at.lt(now));
    diesel::update(target).set(draft.eq(false))
        .execute(conn)
}

#[test]
fn examine_sql_from_publish_pending_posts() {
    use posts::dsl::*;
    use diesel::expression::dsl::now;

    let target = posts.filter(publish_at.lt(now));
    assert_eq!(
        "UPDATE `posts` SET `draft` = ? \
        WHERE `posts`.`publish_at` < CURRENT_TIMESTAMP".to_string(),
        debug_sql!(diesel::update(target).set(draft.eq(false)))
    );
}

pub fn publish_post(post: Post, conn: &PgConnection) -> QueryResult<usize> {
    diesel::update(&post).set(posts::draft.eq(false))
        .execute(conn)
}

#[test]
fn examine_sql_from_publish_post() {
    let post = Post {
        id: 1,
        title: "".into(),
        body: "".into(),
        draft: false,
        publish_at: SystemTime::now(),
        visit_count: 0,
    };
    assert_eq!(
        "UPDATE `posts` SET `draft` = ? WHERE `posts`.`id` = ?".to_string(),
        debug_sql!(diesel::update(&post).set(posts::draft.eq(false)))
    );
}

pub fn increment_visit_counts(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;

    diesel::update(posts).set(visit_count.eq(visit_count + 1))
        .execute(conn)
}

#[test]
fn examine_sql_from_increment_visit_counts() {
    use posts::dsl::*;

    assert_eq!(
        "UPDATE `posts` SET `visit_count` = `posts`.`visit_count` + ?".to_string(),
        debug_sql!(diesel::update(posts).set(visit_count.eq(visit_count + 1)))
    );
}

pub fn hide_everything(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;

    diesel::update(posts)
        .set((
            title.eq("[REDACTED]"),
            body.eq("This post has been classified"),
        ))
        .execute(conn)
}

#[test]
fn examine_sql_from_hide_everything() {
    use posts::dsl::*;

    let query = diesel::update(posts).set((
        title.eq("[REDACTED]"),
        body.eq("This post has been classified"),
    ));
    assert_eq!(
        "UPDATE `posts` SET `title` = ?, `body` = ?".to_string(),
        debug_sql!(query)
    );
}

pub fn update_from_post_fields(post: Post, conn: &PgConnection) -> QueryResult<usize> {
    diesel::update(posts::table).set(&post)
        .execute(conn)
}

#[test]
fn examine_sql_from_update_post_fields() {
    let post = Post {
        id: 1,
        title: "".into(),
        body: "".into(),
        draft: false,
        publish_at: SystemTime::now(),
        visit_count: 0,
    };
    assert_eq!(
        "UPDATE `posts` SET \
            `title` = ?, \
            `body` = ?, \
            `draft` = ?, \
            `publish_at` = ?, \
            `visit_count` = ?".to_string(),
        debug_sql!(diesel::update(posts::table).set(&post))
    );
}

pub fn update_with_option(conn: &PgConnection) -> QueryResult<usize> {
    #[derive(AsChangeset)]
    #[table_name="posts"]
    struct PostForm<'a> {
        title: Option<&'a str>,
        body: Option<&'a str>,
    }

    diesel::update(posts::table)
        .set(&PostForm {
            title: None,
            body: Some("My new post"),
        })
        .execute(conn)
}

#[test]
fn examine_sql_from_update_with_option() {
    #[derive(AsChangeset)]
    #[table_name="posts"]
    struct PostForm<'a> {
        title: Option<&'a str>,
        body: Option<&'a str>,
    }

    let post_form = PostForm {
        title: None,
        body: Some("My new post"),
    };
    let query = diesel::update(posts::table)
        .set(&post_form);
    assert_eq!(
        "UPDATE `posts` SET `body` = ?".to_string(),
        debug_sql!(query)
    );
}
<commit_msg>Update the tests in `all_about_updates`<commit_after>#[macro_use] extern crate diesel;
#[macro_use] extern crate diesel_codegen;

use std::time::SystemTime;

use diesel::prelude::*;
use diesel::pg::PgConnection;

table! {
    posts {
        id -> BigInt,
        title -> Text,
        body -> Text,
        draft -> Bool,
        publish_at -> Timestamp,
        visit_count -> Integer,
    }
}

#[derive(Queryable, Identifiable, AsChangeset)]
pub struct Post {
    pub id: i64,
    pub title: String,
    pub body: String,
    pub draft: bool,
    pub publish_at: SystemTime,
    pub visit_count: i32,
}

pub fn publish_all_posts(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;

    diesel::update(posts).set(draft.eq(false))
        .execute(conn)
}

#[test]
fn examine_sql_from_publish_all_posts() {
    use posts::dsl::*;

    assert_eq!(
        "UPDATE \"posts\" SET \"draft\" = $1".to_string(),
        debug_sql!(diesel::update(posts).set(draft.eq(false)))
    );
}

pub fn publish_pending_posts(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;
    use diesel::expression::dsl::now;

    let target = posts.filter(publish_at.lt(now));
    diesel::update(target).set(draft.eq(false))
        .execute(conn)
}

#[test]
fn examine_sql_from_publish_pending_posts() {
    use posts::dsl::*;
    use diesel::expression::dsl::now;

    let target = posts.filter(publish_at.lt(now));
    assert_eq!(
        "UPDATE \"posts\" SET \"draft\" = $1 \
        WHERE \"posts\".\"publish_at\" < CURRENT_TIMESTAMP".to_string(),
        debug_sql!(diesel::update(target).set(draft.eq(false)))
    );
}

pub fn publish_post(post: Post, conn: &PgConnection) -> QueryResult<usize> {
    diesel::update(&post).set(posts::draft.eq(false))
        .execute(conn)
}

#[test]
fn examine_sql_from_publish_post() {
    let post = Post {
        id: 1,
        title: "".into(),
        body: "".into(),
        draft: false,
        publish_at: SystemTime::now(),
        visit_count: 0,
    };
    assert_eq!(
        "UPDATE \"posts\" SET \"draft\" = $1 WHERE \"posts\".\"id\" = $2".to_string(),
        debug_sql!(diesel::update(&post).set(posts::draft.eq(false)))
    );
}

pub fn increment_visit_counts(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;

    diesel::update(posts).set(visit_count.eq(visit_count + 1))
        .execute(conn)
}

#[test]
fn examine_sql_from_increment_visit_counts() {
    use posts::dsl::*;

    assert_eq!(
        "UPDATE \"posts\" SET \"visit_count\" = \"posts\".\"visit_count\" + $1".to_string(),
        debug_sql!(diesel::update(posts).set(visit_count.eq(visit_count + 1)))
    );
}

pub fn hide_everything(conn: &PgConnection) -> QueryResult<usize> {
    use posts::dsl::*;

    diesel::update(posts)
        .set((
            title.eq("[REDACTED]"),
            body.eq("This post has been classified"),
        ))
        .execute(conn)
}

#[test]
fn examine_sql_from_hide_everything() {
    use posts::dsl::*;

    let query = diesel::update(posts).set((
        title.eq("[REDACTED]"),
        body.eq("This post has been classified"),
    ));
    assert_eq!(
        "UPDATE \"posts\" SET \"title\" = $1, \"body\" = $2".to_string(),
        debug_sql!(query)
    );
}

pub fn update_from_post_fields(post: Post, conn: &PgConnection) -> QueryResult<usize> {
    diesel::update(posts::table).set(&post)
        .execute(conn)
}

#[test]
fn examine_sql_from_update_post_fields() {
    let post = Post {
        id: 1,
        title: "".into(),
        body: "".into(),
        draft: false,
        publish_at: SystemTime::now(),
        visit_count: 0,
    };
    assert_eq!(
        "UPDATE \"posts\" SET \
            \"title\" = $1, \
            \"body\" = $2, \
            \"draft\" = $3, \
            \"publish_at\" = $4, \
            \"visit_count\" = $5".to_string(),
        debug_sql!(diesel::update(posts::table).set(&post))
    );
}

pub fn update_with_option(conn: &PgConnection) -> QueryResult<usize> {
    #[derive(AsChangeset)]
    #[table_name="posts"]
    struct PostForm<'a> {
        title: Option<&'a str>,
        body: Option<&'a str>,
    }

    diesel::update(posts::table)
        .set(&PostForm {
            title: None,
            body: Some("My new post"),
        })
        .execute(conn)
}

#[test]
fn examine_sql_from_update_with_option() {
    #[derive(AsChangeset)]
    #[table_name="posts"]
    struct PostForm<'a> {
        title: Option<&'a str>,
        body: Option<&'a str>,
    }

    let post_form = PostForm {
        title: None,
        body: Some("My new post"),
    };
    let query = diesel::update(posts::table)
        .set(&post_form);
    assert_eq!(
        "UPDATE \"posts\" SET \"body\" = $1".to_string(),
        debug_sql!(query)
    );
}
<|endoftext|>


<commit_before>use cairo;
use cssparser::Parser;
use markup5ever::{expanded_name, local_name, namespace_url, ns};

use crate::drawing_ctx::DrawingCtx;
use crate::error::*;
use crate::node::{NodeResult, NodeTrait, RsvgNode};
use crate::parsers::{Parse, ParseValue, ParseValueToParseError};
use crate::property_bag::PropertyBag;
use crate::surface_utils::shared_surface::SharedImageSurface;

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::input::Input;
use super::{FilterEffect, FilterError, PrimitiveWithInput};

/// Enumeration of the possible blending modes.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum Mode {
    Normal,
    Multiply,
    Screen,
    Darken,
    Lighten,
    Overlay,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
    HslHue,
    HslSaturation,
    HslColor,
    HslLuminosity,
}

/// The `feBlend` filter primitive.
pub struct FeBlend {
    base: PrimitiveWithInput,
    in2: Option<Input>,
    mode: Mode,
}

impl Default for FeBlend {
    /// Constructs a new `Blend` with empty properties.
    #[inline]
    fn default() -> FeBlend {
        FeBlend {
            base: PrimitiveWithInput::new::<Self>(),
            in2: None,
            mode: Mode::Normal,
        }
    }
}

impl NodeTrait for FeBlend {
    impl_node_as_filter_effect!();

    fn set_atts(&mut self, parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        self.base.set_atts(parent, pbag)?;

        for (attr, value) in pbag.iter() {
            match attr.expanded() {
                expanded_name!(svg "in2") => {
                    self.in2 = Some(attr.parse_to_parse_error(value)?);
                }
                expanded_name!(svg "mode") => self.mode = attr.parse(value)?,
                _ => (),
            }
        }

        Ok(())
    }
}

impl FilterEffect for FeBlend {
    fn render(
        &self,
        _node: &RsvgNode,
        ctx: &FilterContext,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterResult, FilterError> {
        let input = self.base.get_input(ctx, draw_ctx)?;
        let input_2 = ctx.get_input(draw_ctx, self.in2.as_ref())?;
        let bounds = self
            .base
            .get_bounds(ctx)
            .add_input(&input)
            .add_input(&input_2)
            .into_irect(draw_ctx);

        // If we're combining two alpha-only surfaces, the result is alpha-only. Otherwise the
        // result is whatever the non-alpha-only type we're working on (which can be either sRGB or
        // linear sRGB depending on color-interpolation-filters).
        let surface_type = if input.surface().is_alpha_only() {
            input_2.surface().surface_type()
        } else {
            if !input_2.surface().is_alpha_only() {
                // All surface types should match (this is enforced by get_input()).
                assert_eq!(
                    input_2.surface().surface_type(),
                    input.surface().surface_type()
                );
            }

            input.surface().surface_type()
        };

        let output_surface = input_2.surface().copy_surface(bounds)?;
        {
            let cr = cairo::Context::new(&output_surface);
            let r = cairo::Rectangle::from(bounds);
            cr.rectangle(r.x, r.y, r.width, r.height);
            cr.clip();

            input.surface().set_as_source_surface(&cr, 0f64, 0f64);
            cr.set_operator(self.mode.into());
            cr.paint();
        }

        Ok(FilterResult {
            name: self.base.result.clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface, surface_type)?,
                bounds,
            },
        })
    }

    #[inline]
    fn is_affected_by_color_interpolation_filters(&self) -> bool {
        true
    }
}

impl Parse for Mode {
    fn parse(parser: &mut Parser<'_, '_>) -> Result<Self, ValueErrorKind> {
        parse_identifiers!(
            parser,
            "normal" => Mode::Normal,
            "multiply" => Mode::Multiply,
            "screen" => Mode::Screen,
            "darken" => Mode::Darken,
            "lighten" => Mode::Lighten,
            "overlay" => Mode::Overlay,
            "color-dodge" => Mode::ColorDodge,
            "color-burn" => Mode::ColorBurn,
            "hard-light" => Mode::HardLight,
            "soft-light" => Mode::SoftLight,
            "difference" => Mode::Difference,
            "exclusion" => Mode::Exclusion,
            "hue" => Mode::HslHue,
            "saturation" => Mode::HslSaturation,
            "color" => Mode::HslColor,
            "luminosity" => Mode::HslLuminosity,
        )
        .map_err(|_| ValueErrorKind::parse_error("parse error"))
    }
}

impl From<Mode> for cairo::Operator {
    #[inline]
    fn from(x: Mode) -> Self {
        match x {
            Mode::Normal => cairo::Operator::Over,
            Mode::Multiply => cairo::Operator::Multiply,
            Mode::Screen => cairo::Operator::Screen,
            Mode::Darken => cairo::Operator::Darken,
            Mode::Lighten => cairo::Operator::Lighten,
            Mode::Overlay => cairo::Operator::Overlay,
            Mode::ColorDodge => cairo::Operator::ColorDodge,
            Mode::ColorBurn => cairo::Operator::ColorBurn,
            Mode::HardLight => cairo::Operator::HardLight,
            Mode::SoftLight => cairo::Operator::SoftLight,
            Mode::Difference => cairo::Operator::Difference,
            Mode::Exclusion => cairo::Operator::Exclusion,
            Mode::HslHue => cairo::Operator::HslHue,
            Mode::HslSaturation => cairo::Operator::HslSaturation,
            Mode::HslColor => cairo::Operator::HslColor,
            Mode::HslLuminosity => cairo::Operator::HslLuminosity,
        }
    }
}
<commit_msg>Convert blend::Mode to CssParseError<commit_after>use cairo;
use cssparser::Parser;
use markup5ever::{expanded_name, local_name, namespace_url, ns};

use crate::drawing_ctx::DrawingCtx;
use crate::error::*;
use crate::node::{NodeResult, NodeTrait, RsvgNode};
use crate::parsers::{ParseToParseError, ParseValueToParseError};
use crate::property_bag::PropertyBag;
use crate::surface_utils::shared_surface::SharedImageSurface;

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::input::Input;
use super::{FilterEffect, FilterError, PrimitiveWithInput};

/// Enumeration of the possible blending modes.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum Mode {
    Normal,
    Multiply,
    Screen,
    Darken,
    Lighten,
    Overlay,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
    HslHue,
    HslSaturation,
    HslColor,
    HslLuminosity,
}

/// The `feBlend` filter primitive.
pub struct FeBlend {
    base: PrimitiveWithInput,
    in2: Option<Input>,
    mode: Mode,
}

impl Default for FeBlend {
    /// Constructs a new `Blend` with empty properties.
    #[inline]
    fn default() -> FeBlend {
        FeBlend {
            base: PrimitiveWithInput::new::<Self>(),
            in2: None,
            mode: Mode::Normal,
        }
    }
}

impl NodeTrait for FeBlend {
    impl_node_as_filter_effect!();

    fn set_atts(&mut self, parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        self.base.set_atts(parent, pbag)?;

        for (attr, value) in pbag.iter() {
            match attr.expanded() {
                expanded_name!(svg "in2") => {
                    self.in2 = Some(attr.parse_to_parse_error(value)?);
                }
                expanded_name!(svg "mode") => self.mode = attr.parse_to_parse_error(value)?,
                _ => (),
            }
        }

        Ok(())
    }
}

impl FilterEffect for FeBlend {
    fn render(
        &self,
        _node: &RsvgNode,
        ctx: &FilterContext,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterResult, FilterError> {
        let input = self.base.get_input(ctx, draw_ctx)?;
        let input_2 = ctx.get_input(draw_ctx, self.in2.as_ref())?;
        let bounds = self
            .base
            .get_bounds(ctx)
            .add_input(&input)
            .add_input(&input_2)
            .into_irect(draw_ctx);

        // If we're combining two alpha-only surfaces, the result is alpha-only. Otherwise the
        // result is whatever the non-alpha-only type we're working on (which can be either sRGB or
        // linear sRGB depending on color-interpolation-filters).
        let surface_type = if input.surface().is_alpha_only() {
            input_2.surface().surface_type()
        } else {
            if !input_2.surface().is_alpha_only() {
                // All surface types should match (this is enforced by get_input()).
                assert_eq!(
                    input_2.surface().surface_type(),
                    input.surface().surface_type()
                );
            }

            input.surface().surface_type()
        };

        let output_surface = input_2.surface().copy_surface(bounds)?;
        {
            let cr = cairo::Context::new(&output_surface);
            let r = cairo::Rectangle::from(bounds);
            cr.rectangle(r.x, r.y, r.width, r.height);
            cr.clip();

            input.surface().set_as_source_surface(&cr, 0f64, 0f64);
            cr.set_operator(self.mode.into());
            cr.paint();
        }

        Ok(FilterResult {
            name: self.base.result.clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface, surface_type)?,
                bounds,
            },
        })
    }

    #[inline]
    fn is_affected_by_color_interpolation_filters(&self) -> bool {
        true
    }
}

impl ParseToParseError for Mode {
    fn parse_to_parse_error<'i>(parser: &mut Parser<'i, '_>) -> Result<Self, CssParseError<'i>> {
        Ok(parse_identifiers!(
            parser,
            "normal" => Mode::Normal,
            "multiply" => Mode::Multiply,
            "screen" => Mode::Screen,
            "darken" => Mode::Darken,
            "lighten" => Mode::Lighten,
            "overlay" => Mode::Overlay,
            "color-dodge" => Mode::ColorDodge,
            "color-burn" => Mode::ColorBurn,
            "hard-light" => Mode::HardLight,
            "soft-light" => Mode::SoftLight,
            "difference" => Mode::Difference,
            "exclusion" => Mode::Exclusion,
            "hue" => Mode::HslHue,
            "saturation" => Mode::HslSaturation,
            "color" => Mode::HslColor,
            "luminosity" => Mode::HslLuminosity,
        )?)
    }
}

impl From<Mode> for cairo::Operator {
    #[inline]
    fn from(x: Mode) -> Self {
        match x {
            Mode::Normal => cairo::Operator::Over,
            Mode::Multiply => cairo::Operator::Multiply,
            Mode::Screen => cairo::Operator::Screen,
            Mode::Darken => cairo::Operator::Darken,
            Mode::Lighten => cairo::Operator::Lighten,
            Mode::Overlay => cairo::Operator::Overlay,
            Mode::ColorDodge => cairo::Operator::ColorDodge,
            Mode::ColorBurn => cairo::Operator::ColorBurn,
            Mode::HardLight => cairo::Operator::HardLight,
            Mode::SoftLight => cairo::Operator::SoftLight,
            Mode::Difference => cairo::Operator::Difference,
            Mode::Exclusion => cairo::Operator::Exclusion,
            Mode::HslHue => cairo::Operator::HslHue,
            Mode::HslSaturation => cairo::Operator::HslSaturation,
            Mode::HslColor => cairo::Operator::HslColor,
            Mode::HslLuminosity => cairo::Operator::HslLuminosity,
        }
    }
}
<|endoftext|>