<commit_before>//! indicatif is a library for Rust that helps you build command line
//! interfaces that report progress to users.  It comes with various
//! tools and utilities for formatting anything that indicates progress.
//!
//! Platform support:
//!
//! * Linux
//! * OS X
//! * Windows (colors require Windows 10)
//!
//! # Progress Bars and Spinners
//!
//! indicatif comes with a `ProgressBar` type that support both bounded
//! progress bar uses as well as unbounded "spinner" type progress reports.
//! Progress bars are `Sync` and `Send` objects which means that they are
//! internally locked and can be passed from thread to thread.
//!
//! Additionally a `MultiProgress` utility is provided that can manage
//! rendering multiple progress bars at once (eg: for instance from
//! multiple threads).
//!
//! Progress bars are manually advanced and by default draw to stdout.
//! When you are done the progress bar can be finished either visibly
//! (eg: the progress bar stays on the screen) or cleared (the progress
//! bar will be removed).
//!
//! ```rust
//! use indicatif::ProgressBar;
//!
//! let bar = ProgressBar::new(1000);
//! for _ in 0..1000 {
//!     bar.inc(1);
//!     // ...
//! }
//! bar.finish();
//! ```
//!
//! # Templates
//!
//! Progress bars can be styled with simple format strings similar to the
//! ones in Rust itself.  The format for a placeholder is `{key:options}`
//! where the `options` part is optional.  If provided the format is this:
//!
//! ```text
//! [<^>]           for an optional alignment specification
//! WIDTH           an optional width as positive integer
//! !               an optional exclamation mark to enable truncation
//! .STYLE          an optional dot separated style string
//! /STYLE          an optional dot separated alternative style string
//! ```
//!
//! For the style component see `Styled::from_dotted_str` for more
//! information.
//!
//! Some examples for templates:
//!
//! ```text
//! [{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}
//! ```
//!
//! This sets a progress bar that is 40 characters wide and has cyan
//! as primary style color and blue as alternative style color.
//! Alternative styles are currently only used for progress bars.
//!
//! The following keys exist:
//!
//! * `bar`: renders a progress bar. By default 20 characters wide.  The
//!   style string is used to color the elapsed part, the alternative
//!   style is used for the bar that is yet to render.
//! * `wide_bar`: like `bar` but always fills the remaining space.
//! * `spinner`: renders the spinner (current tick char)
//! * `msg`: renders the currently set message on the progress bar.
//! * `pos`: renders the current position of the bar as integer
//! * `len`: renders the total length of the bar as integer
//! * `bytes`: renders the current position of the bar as bytes.
//! * `total_bytes`: renders the total length of the bar as bytes.
//! * `elapsed_precise`: renders the elapsed time as `HH:MM:SS`.
//! * `elapased`: renders the elapsed time as `42s`, `1m` etc.
//! * `eta_precise`: the remaining time (like `elapsed_precise`).
//! * `eta`: the remaining time (like `elapsed`).
//!
//! The design of the progress bar can be altered with the integrated
//! template functionality.  The template can be set by changing a
//! `ProgressStyle` and attaching it to the progress bar.
//!
//! # Terminal Access
//!
//! The library provides a basic abstraction over working with terminals
//! through the `Term` object.  For instance you can use it to move
//! cursors or clear contents.
//!
//! # Colors and Styles
//!
//! `indicatif` uses `clicolors-control` to control colors.  It also
//! provides higher level wrappers for styling text and other things
//! that can be displayed with the `style` function.
//!
//! Example usage:
//!
//! ```
//! use indicatif::style;
//!
//! println!("This is {} neat", style("fo").cyan());
//! ```
//!
//! # Human Readable Formatting
//!
//! There are some formatting wrappers for showing elapsed time and
//! file sizes for human users:
//!
//! ```ignore
//! use std::time::Instant;
//! use indicatif::{HumanDuration, HumanBytes};
//!
//! let started = Instant::now();
//! println!("The file is {} large", HumanBytes(file.size));
//! println!("The script took {}", HumanDuration(started.elapsed()));
//! ```
#[cfg(unix)] extern crate libc;
#[cfg(windows)] extern crate winapi;
#[cfg(windows)] extern crate kernel32;
extern crate parking_lot;
extern crate regex;
#[macro_use] extern crate lazy_static;
extern crate unicode_width;
extern crate clicolors_control;

mod term;
mod progress;
mod utils;
mod ansistyle;
mod format;

pub use progress::{ProgressBar, MultiProgress, ProgressState, DrawState,
                   DrawTarget, ProgressStyle};
pub use term::Term;
pub use ansistyle::{style, Styled, Color, Style,
                    strip_ansi_codes, measure_text_width,
                    colors_enabled, set_colors_enabled};
pub use format::{HumanDuration, FormattedDuration, HumanBytes};
<commit_msg>Some smaller doc updates<commit_after>//! indicatif is a library for Rust that helps you build command line
//! interfaces that report progress to users.  It comes with various
//! tools and utilities for formatting anything that indicates progress.
//!
//! Platform support:
//!
//! * Linux
//! * OS X
//! * Windows (colors require Windows 10)
//!
//! # Progress Bars and Spinners
//!
//! indicatif comes with a `ProgressBar` type that support both bounded
//! progress bar uses as well as unbounded "spinner" type progress reports.
//! Progress bars are `Sync` and `Send` objects which means that they are
//! internally locked and can be passed from thread to thread.
//!
//! Additionally a `MultiProgress` utility is provided that can manage
//! rendering multiple progress bars at once (eg: for instance from
//! multiple threads).
//!
//! Progress bars are manually advanced and by default draw to stdout.
//! When you are done the progress bar can be finished either visibly
//! (eg: the progress bar stays on the screen) or cleared (the progress
//! bar will be removed).
//!
//! ```rust
//! use indicatif::ProgressBar;
//!
//! let bar = ProgressBar::new(1000);
//! for _ in 0..1000 {
//!     bar.inc(1);
//!     // ...
//! }
//! bar.finish();
//! ```
//!
//! General progress bar behaviors:
//!
//! * if a non terminal is detected the progress bar will be completely
//!   hidden.  This makes piping programs to logfiles make sense out of
//!   the box.
//! * progress bars should be explicitly finished to reset the rendering
//!   for others.  Either by also clearing them or by replacing them with
//!   a new message / retaining the current message.
//! * the default template renders neither message nor prefix.
//!
//! # Templates
//!
//! Progress bars can be styled with simple format strings similar to the
//! ones in Rust itself.  The format for a placeholder is `{key:options}`
//! where the `options` part is optional.  If provided the format is this:
//!
//! ```text
//! [<^>]           for an optional alignment specification
//! WIDTH           an optional width as positive integer
//! !               an optional exclamation mark to enable truncation
//! .STYLE          an optional dot separated style string
//! /STYLE          an optional dot separated alternative style string
//! ```
//!
//! For the style component see `Styled::from_dotted_str` for more
//! information.
//!
//! Some examples for templates:
//!
//! ```text
//! [{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}
//! ```
//!
//! This sets a progress bar that is 40 characters wide and has cyan
//! as primary style color and blue as alternative style color.
//! Alternative styles are currently only used for progress bars.
//!
//! The following keys exist:
//!
//! * `bar`: renders a progress bar. By default 20 characters wide.  The
//!   style string is used to color the elapsed part, the alternative
//!   style is used for the bar that is yet to render.
//! * `wide_bar`: like `bar` but always fills the remaining space.
//! * `spinner`: renders the spinner (current tick char)
//! * `prefix`: renders the prefix set on the progress bar.
//! * `msg`: renders the currently set message on the progress bar.
//! * `pos`: renders the current position of the bar as integer
//! * `len`: renders the total length of the bar as integer
//! * `bytes`: renders the current position of the bar as bytes.
//! * `total_bytes`: renders the total length of the bar as bytes.
//! * `elapsed_precise`: renders the elapsed time as `HH:MM:SS`.
//! * `elapased`: renders the elapsed time as `42s`, `1m` etc.
//! * `eta_precise`: the remaining time (like `elapsed_precise`).
//! * `eta`: the remaining time (like `elapsed`).
//!
//! The design of the progress bar can be altered with the integrated
//! template functionality.  The template can be set by changing a
//! `ProgressStyle` and attaching it to the progress bar.
//!
//! # Terminal Access
//!
//! The library provides a basic abstraction over working with terminals
//! through the `Term` object.  For instance you can use it to move
//! cursors or clear contents.
//!
//! # Colors and Styles
//!
//! `indicatif` uses `clicolors-control` to control colors.  It also
//! provides higher level wrappers for styling text and other things
//! that can be displayed with the `style` function.
//!
//! Example usage:
//!
//! ```
//! use indicatif::style;
//!
//! println!("This is {} neat", style("fo").cyan());
//! ```
//!
//! # Human Readable Formatting
//!
//! There are some formatting wrappers for showing elapsed time and
//! file sizes for human users:
//!
//! ```ignore
//! use std::time::Instant;
//! use indicatif::{HumanDuration, HumanBytes};
//!
//! let started = Instant::now();
//! println!("The file is {} large", HumanBytes(file.size));
//! println!("The script took {}", HumanDuration(started.elapsed()));
//! ```
#[cfg(unix)] extern crate libc;
#[cfg(windows)] extern crate winapi;
#[cfg(windows)] extern crate kernel32;
extern crate parking_lot;
extern crate regex;
#[macro_use] extern crate lazy_static;
extern crate unicode_width;
extern crate clicolors_control;

mod term;
mod progress;
mod utils;
mod ansistyle;
mod format;

pub use progress::{ProgressBar, MultiProgress, ProgressState, DrawState,
                   DrawTarget, ProgressStyle};
pub use term::Term;
pub use ansistyle::{style, Styled, Color, Style,
                    strip_ansi_codes, measure_text_width,
                    colors_enabled, set_colors_enabled};
pub use format::{HumanDuration, FormattedDuration, HumanBytes};
<|endoftext|>


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

use crate::args::Args;

pub fn init(args: &Args) {
    let mut logger = MultiLog::new();
    if args.log_to_stdout {
        logger.push(WriterLog::new(std::io::stdout()));
    }
    if let Some(ref path) = args.log_to_file {
        let file = std::fs::OpenOptions::new()
            .append(true)
            .open(path)
            .expect("failed to open the log file");

        logger.push(WriterLog::new(file));
    }

    log::set_boxed_logger(Box::new(logger))
        .expect("failed to initialize logger");

    log::set_max_level(args.verbosity);
}

struct MultiLog {
    loggers: Vec<Box<dyn log::Log>>,
}

impl MultiLog {

    fn new() -> MultiLog {
        MultiLog {
            loggers: Vec::new(),
        }
    }

    fn push<L: log::Log + 'static>(&mut self, logger: L) {
        self.loggers.push(Box::new(logger));
    }
}

impl log::Log for MultiLog {

    fn enabled(&self, metadata: &log::Metadata) -> bool {
        self.loggers.iter().any(|logger| logger.enabled(metadata))
    }

    fn log(&self, record: &log::Record) {
        for log in &self.loggers {
            log.log(record);
        }
    }

    fn flush(&self) {
        for logger in &self.loggers {
            logger.flush();
        }
    }
}

struct WriterLog<W: Write + Send + Sync> {
    writer: std::sync::Mutex<W>,
}

impl<W: Write + Send + Sync> WriterLog<W> {

    fn new(writer: W) -> WriterLog<W> {
        WriterLog { writer: std::sync::Mutex::new(writer) }
    }
}

impl<W: Write + Send + Sync> log::Log for WriterLog<W> {

    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &log::Record) {
        if !self.enabled(record.metadata()) {
            return;
        }

        let now = std::time::SystemTime::now();

        // We consider failures to write to the log stream critical. Otherwise,
        // if there is some other issue with the system it is not possible to
        // properly communicate it. Thus, we panic on all write errors.
        let mut writer = self.writer.lock()
            .expect("failed to acquire log output stream lock");

        || -> Result<(), std::io::Error> {
            write! {
                writer,
                "[{level} {timestamp} ",
                level = record.level(),
                timestamp = humantime::format_rfc3339_nanos(now)
            }?;
            match record.file() {
                Some(file) => write!(writer, "{file}")?,
                None => write!(writer, "<unknown>")?,
            }
            match record.line() {
                Some(line) => write!(writer, ":{line}]")?,
                None => write!(writer, ":<unknown>]")?,
            }

            write!(writer, " {}\n", record.args())?;

            Ok(())
        }().expect("failed to write to the log output stream")
    }

    fn flush(&self) {
        // Similarly to write errors, we also panic on flush errors as there is
        // nothing we can do otherwise.
        self.writer
            .lock()
            .expect("failed to acquire log output stream lock")
            .flush()
            .expect("failed to flush the log output stream");
    }
}
<commit_msg>Remove top-level imports in the `log` module.<commit_after>pub fn init(args: &crate::args::Args) {
    let mut logger = MultiLog::new();
    if args.log_to_stdout {
        logger.push(WriterLog::new(std::io::stdout()));
    }
    if let Some(ref path) = args.log_to_file {
        let file = std::fs::OpenOptions::new()
            .append(true)
            .open(path)
            .expect("failed to open the log file");

        logger.push(WriterLog::new(file));
    }

    log::set_boxed_logger(Box::new(logger))
        .expect("failed to initialize logger");

    log::set_max_level(args.verbosity);
}

struct MultiLog {
    loggers: Vec<Box<dyn log::Log>>,
}

impl MultiLog {

    fn new() -> MultiLog {
        MultiLog {
            loggers: Vec::new(),
        }
    }

    fn push<L: log::Log + 'static>(&mut self, logger: L) {
        self.loggers.push(Box::new(logger));
    }
}

impl log::Log for MultiLog {

    fn enabled(&self, metadata: &log::Metadata) -> bool {
        self.loggers.iter().any(|logger| logger.enabled(metadata))
    }

    fn log(&self, record: &log::Record) {
        for log in &self.loggers {
            log.log(record);
        }
    }

    fn flush(&self) {
        for logger in &self.loggers {
            logger.flush();
        }
    }
}

struct WriterLog<W: std::io::Write + Send + Sync> {
    writer: std::sync::Mutex<W>,
}

impl<W: std::io::Write + Send + Sync> WriterLog<W> {

    fn new(writer: W) -> WriterLog<W> {
        WriterLog { writer: std::sync::Mutex::new(writer) }
    }
}

impl<W: std::io::Write + Send + Sync> log::Log for WriterLog<W> {

    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &log::Record) {
        if !self.enabled(record.metadata()) {
            return;
        }

        let now = std::time::SystemTime::now();

        // We consider failures to write to the log stream critical. Otherwise,
        // if there is some other issue with the system it is not possible to
        // properly communicate it. Thus, we panic on all write errors.
        let mut writer = self.writer.lock()
            .expect("failed to acquire log output stream lock");

        || -> Result<(), std::io::Error> {
            write! {
                writer,
                "[{level} {timestamp} ",
                level = record.level(),
                timestamp = humantime::format_rfc3339_nanos(now)
            }?;
            match record.file() {
                Some(file) => write!(writer, "{file}")?,
                None => write!(writer, "<unknown>")?,
            }
            match record.line() {
                Some(line) => write!(writer, ":{line}]")?,
                None => write!(writer, ":<unknown>]")?,
            }

            write!(writer, " {}\n", record.args())?;

            Ok(())
        }().expect("failed to write to the log output stream")
    }

    fn flush(&self) {
        // Similarly to write errors, we also panic on flush errors as there is
        // nothing we can do otherwise.
        self.writer
            .lock()
            .expect("failed to acquire log output stream lock")
            .flush()
            .expect("failed to flush the log output stream");
    }
}
<|endoftext|>


<commit_before>//! Netlink module
//!
//! The netlink module contains the netlink-based management capabilities of
//! the socketcan crate. Quoth wikipedia:
//!
//!
//! > Netlink socket family is a Linux kernel interface used for inter-process
//! > communication (IPC) between both the kernel and userspace processes, and
//! > between different userspace processes, in a way similar to the Unix
//! > domain sockets.
//!
//!
//! The netlink module currently relies on the
//! [netlink-rs](https://crates.io/crates/netlink-rs), which has some
//! deficiencies. If those are not fixed, a reimplmentation of netlink-rs'
//! functionality might be required.

use byte_conv::As as AsBytes;
use libc::{self, c_char, c_ushort, c_int, c_uint};
use netlink_rs::socket::{Msg as NetlinkMessage, Socket as NetlinkSocket, NetlinkAddr,
                         Payload as NetlinkPayload, NlMsgHeader};
use netlink_rs::Protocol as NetlinkProtocol;
use nix;
use nix::net::if_::if_nametoindex;
use std::{mem, io};

// linux/rtnetlink.h
const RTM_NEWLINK: u16 = 16;

// linux/socket.h
const AF_UNSPEC: c_char = 0;

// linux/if.h; netdevice(7)
const IFF_UP: c_uint = 1;

/// Mirrors the `struct ifinfomsg` (see rtnetlink(7))
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct IfInfoMsg {
    /// Address family, should always be `AF_UNSPEC`
    family: c_char,

    /// Padding bytes, should be set to 0.
    _pad: c_char, // must be 0

    /// Device type (FIXME: ?)
    dev_type: c_ushort,

    /// The interface index, can be retrieved using `if_nametoindex` from the
    /// `nix` crate.
    index: c_int,

    /// Device flags (FIXME: ?)
    flags: c_uint,

    /// Change mask
    change: c_uint,
}

impl IfInfoMsg {
    fn new(if_index: i32, flags: c_uint, change: c_uint) -> IfInfoMsg {
        IfInfoMsg {
            family: AF_UNSPEC,
            _pad: 0,

            // dev_type: ARPHRD_CAN,
            dev_type: 0,
            index: if_index,
            flags: flags,

            change: change,
        }
    }
}

/// Sends a netlink message down a netlink socket, and checks if an ACK was
/// properly received.
fn send_and_read_ack(sock: &mut NetlinkSocket,
                     msg: NetlinkMessage,
                     dest: &NetlinkAddr)
                     -> io::Result<()> {

    let msg_len = msg.header().msg_length() as usize;
    let bytes_sent = sock.send(msg, dest)?;
    if bytes_sent != msg_len {
        return Err(io::Error::new(io::ErrorKind::Other, "Incomplete write"));
    }

    // receive all pending messages
    let (addr, msgs) = sock.recv()?;

    match msgs.into_iter().nth(0) {
        Some(msg) => {
            println!("Received Address: {:?}", addr);
            println!("Received Message: {:?}", msg);
            match *msg.payload() {
                NetlinkPayload::Ack(_) => (),
                NetlinkPayload::Err(errno, _) => {
                    return Err(io::Error::from_raw_os_error(-errno));
                }
                _ => panic!("Message received is not an ACK"),
            }
        }
        None => panic!("Expect ACK, but no ACK received"),
    }

    Ok(())

}

/// Opens a new netlink socket, bound to this process' PID
fn open_nl_route_socket() -> io::Result<NetlinkSocket> {
    let sock = NetlinkSocket::new(NetlinkProtocol::Route)?;

    // retrieve PID
    let pid = unsafe { libc::getpid() } as u32;
    let pid = 0;  // FIXME: is this necessary?

    // after opening the socket, bind it to be able to receive messages back
    // groups is set to 0, because we want no notifications
    let bind_addr = NetlinkAddr::new(pid, 0);
    sock.bind(bind_addr)?;

    Ok(sock)
}

/// Brings down a CAN interface
fn bring_down(if_index: c_uint) -> io::Result<()> {
    let mut nl = open_nl_route_socket()?;

    // prepare message
    let mut header = NlMsgHeader::user_defined(RTM_NEWLINK, mem::size_of::<IfInfoMsg>() as u32);
    header.ack();

    let info = IfInfoMsg::new(if_index as i32, 0, IFF_UP);
    let msg = NetlinkMessage::new(header, NetlinkPayload::Data(info.as_bytes()));

    let kernel_addr = NetlinkAddr::new(0, 0);

    // send the message
    send_and_read_ack(&mut nl, msg, &kernel_addr)
}

/// SocketCAN interface
///
/// Controlled through the kernel's netlink interface, CAN devices can be
/// brought up or down or configured through this.
pub struct CanInterface {
    if_index: c_uint,
}

impl CanInterface {
    /// Open CAN interface by name
    ///
    /// Similar to `open_if`, but looks up the device by name instead
    pub fn open(ifname: &str) -> Result<CanInterface, nix::Error> {
        let if_index = if_nametoindex(ifname)?;
        Ok(CanInterface::open_if(if_index))
    }

    /// Open CAN interface
    ///
    /// Creates a new `CanInterface` instance. No actual "opening" is necessary
    /// or performed when calling this function.
    pub fn open_if(if_index: c_uint) -> CanInterface {
        CanInterface { if_index: if_index }
    }
}
<commit_msg>`send_and_read_ack` properly reports errors.<commit_after>//! Netlink module
//!
//! The netlink module contains the netlink-based management capabilities of
//! the socketcan crate. Quoth wikipedia:
//!
//!
//! > Netlink socket family is a Linux kernel interface used for inter-process
//! > communication (IPC) between both the kernel and userspace processes, and
//! > between different userspace processes, in a way similar to the Unix
//! > domain sockets.
//!
//!
//! The netlink module currently relies on the
//! [netlink-rs](https://crates.io/crates/netlink-rs), which has some
//! deficiencies. If those are not fixed, a reimplmentation of netlink-rs'
//! functionality might be required.

use byte_conv::As as AsBytes;
use libc::{self, c_char, c_ushort, c_int, c_uint};
use netlink_rs::socket::{Msg as NetlinkMessage, Socket as NetlinkSocket, NetlinkAddr,
                         Payload as NetlinkPayload, NlMsgHeader};
use netlink_rs::Protocol as NetlinkProtocol;
use nix;
use nix::net::if_::if_nametoindex;
use std::{mem, io};

// linux/rtnetlink.h
const RTM_NEWLINK: u16 = 16;

// linux/socket.h
const AF_UNSPEC: c_char = 0;

// linux/if.h; netdevice(7)
const IFF_UP: c_uint = 1;

/// Mirrors the `struct ifinfomsg` (see rtnetlink(7))
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct IfInfoMsg {
    /// Address family, should always be `AF_UNSPEC`
    family: c_char,

    /// Padding bytes, should be set to 0.
    _pad: c_char, // must be 0

    /// Device type (FIXME: ?)
    dev_type: c_ushort,

    /// The interface index, can be retrieved using `if_nametoindex` from the
    /// `nix` crate.
    index: c_int,

    /// Device flags (FIXME: ?)
    flags: c_uint,

    /// Change mask
    change: c_uint,
}

impl IfInfoMsg {
    fn new(if_index: i32, flags: c_uint, change: c_uint) -> IfInfoMsg {
        IfInfoMsg {
            family: AF_UNSPEC,
            _pad: 0,

            // dev_type: ARPHRD_CAN,
            dev_type: 0,
            index: if_index,
            flags: flags,

            change: change,
        }
    }
}

/// Sends a netlink message down a netlink socket, and checks if an ACK was
/// properly received.
fn send_and_read_ack(sock: &mut NetlinkSocket,
                     msg: NetlinkMessage,
                     dest: &NetlinkAddr)
                     -> io::Result<()> {

    let msg_len = msg.header().msg_length() as usize;
    let bytes_sent = sock.send(msg, dest)?;
    if bytes_sent != msg_len {
        return Err(io::Error::new(io::ErrorKind::Other, "Incomplete write"));
    }

    // receive all pending messages
    let (addr, msgs) = sock.recv()?;

    match msgs.into_iter().nth(0) {
        Some(msg) => {
            println!("Received Address: {:?}", addr);
            println!("Received Message: {:?}", msg);
            match *msg.payload() {
                NetlinkPayload::Ack(_) => (),
                NetlinkPayload::Err(errno, _) => {
                    return Err(io::Error::from_raw_os_error(-errno));
                }
                NetlinkPayload::None => {
                    return Err(io::Error::new(io::ErrorKind::InvalidData,
                                              "Received no payload when
                                              expecting an ACK"));

                }
                NetlinkPayload::Data(_) => {
                    return Err(io::Error::new(io::ErrorKind::InvalidData,
                                              "Received data when expecting an ACK"));
                }
            }
        }
        None => {
            return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
                                      "ACK expected, but got nothing instead"))
        }
    }

    Ok(())

}

/// Opens a new netlink socket, bound to this process' PID
fn open_nl_route_socket() -> io::Result<NetlinkSocket> {
    let sock = NetlinkSocket::new(NetlinkProtocol::Route)?;

    // retrieve PID
    let pid = unsafe { libc::getpid() } as u32;
    let pid = 0;  // FIXME: is this necessary?

    // after opening the socket, bind it to be able to receive messages back
    // groups is set to 0, because we want no notifications
    let bind_addr = NetlinkAddr::new(pid, 0);
    sock.bind(bind_addr)?;

    Ok(sock)
}

/// Brings down a CAN interface
fn bring_down(if_index: c_uint) -> io::Result<()> {
    let mut nl = open_nl_route_socket()?;

    // prepare message
    let mut header = NlMsgHeader::user_defined(RTM_NEWLINK, mem::size_of::<IfInfoMsg>() as u32);
    header.ack();

    let info = IfInfoMsg::new(if_index as i32, 0, IFF_UP);
    let msg = NetlinkMessage::new(header, NetlinkPayload::Data(info.as_bytes()));

    let kernel_addr = NetlinkAddr::new(0, 0);

    // send the message
    send_and_read_ack(&mut nl, msg, &kernel_addr)
}

/// SocketCAN interface
///
/// Controlled through the kernel's netlink interface, CAN devices can be
/// brought up or down or configured through this.
pub struct CanInterface {
    if_index: c_uint,
}

impl CanInterface {
    /// Open CAN interface by name
    ///
    /// Similar to `open_if`, but looks up the device by name instead
    pub fn open(ifname: &str) -> Result<CanInterface, nix::Error> {
        let if_index = if_nametoindex(ifname)?;
        Ok(CanInterface::open_if(if_index))
    }

    /// Open CAN interface
    ///
    /// Creates a new `CanInterface` instance. No actual "opening" is necessary
    /// or performed when calling this function.
    pub fn open_if(if_index: c_uint) -> CanInterface {
        CanInterface { if_index: if_index }
    }
}
<|endoftext|>


<commit_before>#![allow(non_snake_case)]

use std::fmt;
use std::slice;
use std::mem;
use approx;
use channel::{PosFreeChannel, FreeChannel, FreeChannelScalar, ChannelFormatCast, ChannelCast,
              ColorChannel};
use color::{Color, Bounded, Lerp, Flatten, FromTuple};

pub struct LuvTag;

#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Luv<T> {
    pub L: PosFreeChannel<T>,
    pub u: FreeChannel<T>,
    pub v: FreeChannel<T>,
}

impl<T> Luv<T>
    where T: FreeChannelScalar
{
    pub fn from_channels(L: T, u: T, v: T) -> Self {
        Luv {
            L: PosFreeChannel::new(L),
            u: FreeChannel::new(u),
            v: FreeChannel::new(v),
        }
    }

    impl_color_color_cast_square!(Luv {L, u, v}, chan_traits={FreeChannelScalar});

    pub fn L(&self) -> T {
        self.L.0.clone()
    }
    pub fn u(&self) -> T {
        self.u.0.clone()
    }
    pub fn v(&self) -> T {
        self.v.0.clone()
    }
    pub fn L_mut(&mut self) -> &mut T {
        &mut self.L.0
    }
    pub fn u_mut(&mut self) -> &mut T {
        &mut self.u.0
    }
    pub fn v_mut(&mut self) -> &mut T {
        &mut self.v.0
    }
    pub fn set_L(&mut self, val: T) {
        self.L.0 = val;
    }
    pub fn set_u(&mut self, val: T) {
        self.u.0 = val;
    }
    pub fn set_v(&mut self, val: T) {
        self.v.0 = val;
    }
}

impl<T> Color for Luv<T>
    where T: FreeChannelScalar
{
    type Tag = LuvTag;
    type ChannelsTuple = (T, T, T);

    #[inline]
    fn num_channels() -> u32 {
        3
    }
    fn to_tuple(self) -> Self::ChannelsTuple {
        (self.L.0, self.u.0, self.v.0)
    }
}

impl<T> FromTuple for Luv<T>
    where T: FreeChannelScalar
{
    fn from_tuple(values: (T, T, T)) -> Self {
        Luv::from_channels(values.0, values.1, values.2)
    }
}

impl<T> Bounded for Luv<T>
    where T: FreeChannelScalar
{
    fn normalize(self) -> Self {
        Luv::from_channels(self.L.normalize().0, self.u(), self.v())
    }
    fn is_normalized(&self) -> bool {
        self.L.is_normalized()
    }
}

impl<T> Lerp for Luv<T>
    where T: FreeChannelScalar + Lerp
{
    type Position = <FreeChannel<T> as Lerp>::Position;
    impl_color_lerp_square!(Luv {L, u, v});
}

impl<T> Flatten for Luv<T>
    where T: FreeChannelScalar
{
    type ScalarFormat = T;

    impl_color_as_slice!(T);
    impl_color_from_slice_square!(Luv<T> {L:PosFreeChannel - 0, u:FreeChannel - 1,
        v:FreeChannel - 2});
}

impl<T> approx::ApproxEq for Luv<T>
    where T: FreeChannelScalar + approx::ApproxEq,
          T::Epsilon: Clone
{
    impl_approx_eq!({L, u, v});
}

impl<T> Default for Luv<T>
    where T: FreeChannelScalar
{
    impl_color_default!(Luv {L:PosFreeChannel, u:FreeChannel, v:FreeChannel});
}

impl<T> fmt::Display for Luv<T>
    where T: FreeChannelScalar + fmt::Display
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "L*u*v*({}, {}, {})", self.L, self.u, self.v)
    }
}
<commit_msg>Implemented Xyz -> Luv and back.<commit_after>#![allow(non_snake_case)]

use std::fmt;
use std::slice;
use std::mem;
use num;
use approx;
use channel::{PosFreeChannel, FreeChannel, FreeChannelScalar, ChannelFormatCast, ChannelCast,
              ColorChannel};
use color::{Color, Bounded, Lerp, Flatten, FromTuple};
use xyz::Xyz;

pub struct LuvTag;

#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Luv<T> {
    pub L: PosFreeChannel<T>,
    pub u: FreeChannel<T>,
    pub v: FreeChannel<T>,
}

impl<T> Luv<T>
    where T: FreeChannelScalar
{
    pub fn from_channels(L: T, u: T, v: T) -> Self {
        Luv {
            L: PosFreeChannel::new(L),
            u: FreeChannel::new(u),
            v: FreeChannel::new(v),
        }
    }

    impl_color_color_cast_square!(Luv {L, u, v}, chan_traits={FreeChannelScalar});

    pub fn L(&self) -> T {
        self.L.0.clone()
    }
    pub fn u(&self) -> T {
        self.u.0.clone()
    }
    pub fn v(&self) -> T {
        self.v.0.clone()
    }
    pub fn L_mut(&mut self) -> &mut T {
        &mut self.L.0
    }
    pub fn u_mut(&mut self) -> &mut T {
        &mut self.u.0
    }
    pub fn v_mut(&mut self) -> &mut T {
        &mut self.v.0
    }
    pub fn set_L(&mut self, val: T) {
        self.L.0 = val;
    }
    pub fn set_u(&mut self, val: T) {
        self.u.0 = val;
    }
    pub fn set_v(&mut self, val: T) {
        self.v.0 = val;
    }
}

impl<T> Color for Luv<T>
    where T: FreeChannelScalar
{
    type Tag = LuvTag;
    type ChannelsTuple = (T, T, T);

    #[inline]
    fn num_channels() -> u32 {
        3
    }
    fn to_tuple(self) -> Self::ChannelsTuple {
        (self.L.0, self.u.0, self.v.0)
    }
}

impl<T> FromTuple for Luv<T>
    where T: FreeChannelScalar
{
    fn from_tuple(values: (T, T, T)) -> Self {
        Luv::from_channels(values.0, values.1, values.2)
    }
}

impl<T> Bounded for Luv<T>
    where T: FreeChannelScalar
{
    fn normalize(self) -> Self {
        Luv::from_channels(self.L.normalize().0, self.u(), self.v())
    }
    fn is_normalized(&self) -> bool {
        self.L.is_normalized()
    }
}

impl<T> Lerp for Luv<T>
    where T: FreeChannelScalar + Lerp
{
    type Position = <FreeChannel<T> as Lerp>::Position;
    impl_color_lerp_square!(Luv {L, u, v});
}

impl<T> Flatten for Luv<T>
    where T: FreeChannelScalar
{
    type ScalarFormat = T;

    impl_color_as_slice!(T);
    impl_color_from_slice_square!(Luv<T> {L:PosFreeChannel - 0, u:FreeChannel - 1,
        v:FreeChannel - 2});
}

impl<T> approx::ApproxEq for Luv<T>
    where T: FreeChannelScalar + approx::ApproxEq,
          T::Epsilon: Clone
{
    impl_approx_eq!({L, u, v});
}

impl<T> Default for Luv<T>
    where T: FreeChannelScalar
{
    impl_color_default!(Luv {L:PosFreeChannel, u:FreeChannel, v:FreeChannel});
}

impl<T> fmt::Display for Luv<T>
    where T: FreeChannelScalar + fmt::Display
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "L*u*v*({}, {}, {})", self.L, self.u, self.v)
    }
}

impl<T> Luv<T>
    where T: FreeChannelScalar + fmt::Display
{
    pub fn from_xyz(from: &Xyz<T>, wp: &Xyz<T>) -> Self {
        let epsilon: T = num::cast(1e-8).unwrap();
        let four: T = num::cast(4.0).unwrap();
        let fifteen: T = num::cast(15.0).unwrap();
        let three: T = num::cast(3.0).unwrap();
        let nine: T = num::cast(9.0).unwrap();

        let yr = from.y() / wp.y();
        let L = Self::compute_L(yr);

        let denom = from.x() + fifteen * from.y() + three * from.z() + epsilon;
        let r_denom = wp.x() + fifteen * wp.y() + three * wp.z() + epsilon;
        let u_prime = (four * from.x()) / denom;
        let v_prime = (nine * from.y()) / denom;
        let ur_prime = (four * wp.x()) / r_denom;
        let vr_prime = (nine * wp.y()) / r_denom;

        let u = num::cast::<_, T>(13.0).unwrap() * L * (u_prime - ur_prime);
        let v = num::cast::<_, T>(13.0).unwrap() * L * (v_prime - vr_prime);

        Luv::from_channels(L, u, v)
    }

    pub fn to_xyz(&self, wp: &Xyz<T>) -> Xyz<T> {
        let epsilon: T = num::cast(1e-8).unwrap();
        let four: T = num::cast(4.0).unwrap();
        let fifteen: T = num::cast(15.0).unwrap();
        let three: T = num::cast(3.0).unwrap();
        let nine: T = num::cast(9.0).unwrap();

        let r_denom = wp.x() + fifteen * wp.y() + three * wp.z();
        let u0 = (four * wp.x()) / r_denom;
        let v0 = (nine * wp.y()) / r_denom;

        let Y = Self::compute_Y(self.L());

        let a = num::cast::<_, T>(1.0 / 3.0).unwrap() *
                ((num::cast::<_, T>(52.0).unwrap() * self.L()) /
                 (self.u() + num::cast::<_, T>(13.0).unwrap() * self.L() * u0 + epsilon) -
                 num::cast(1.0).unwrap());

        let b = num::cast::<_, T>(-5.0).unwrap() * Y;
        let c: T = num::cast(-1.0 / 3.0).unwrap();
        let d = Y *
                ((num::cast::<_, T>(39.0).unwrap() * self.L()) /
                 (self.v() + num::cast::<_, T>(13.0).unwrap() * self.L() * v0 + epsilon) -
                 num::cast::<_, T>(5.0).unwrap());

        println!("{} {} {} {}", a, b, c, d);
        let X;
        if a != c {
            X = (d - b) / (a - c);
        } else {
            X = num::cast(0.0).unwrap();
        }

        let Z = X * a + b;

        Xyz::from_channels(X, Y, Z)

    }

    fn compute_Y(L: T) -> T {
        if L > Self::kappa() * Self::epsilon() {
            let val = (L + num::cast::<_, T>(16.0).unwrap()) / num::cast::<_, T>(116.0).unwrap();
            val * val * val
        } else {
            L / Self::kappa()
        }
    }

    fn compute_L(yr: T) -> T {
        if yr > Self::epsilon() {
            num::cast::<_, T>(116.0).unwrap() * yr.cbrt() - num::cast(16.0).unwrap()
        } else {
            Self::kappa() * yr
        }
    }

    #[inline]
    pub fn epsilon() -> T {
        num::cast(0.008856451679035631).unwrap()
    }
    #[inline]
    pub fn kappa() -> T {
        num::cast(903.2962962963).unwrap()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use xyz::Xyz;
    use white_point::*;

    #[test]
    fn test_from_xyz() {
        let c1 = Xyz::from_channels(0.5, 0.5, 0.5);
        let t1 = Luv::from_xyz(&c1, &D65::get_xyz());
        assert_relative_eq!(t1, Luv::from_channels(76.0693, 12.5457, 5.2885), epsilon=1e-4);
        assert_relative_eq!(t1.to_xyz(&D65::get_xyz()), c1, epsilon=1e-4);

        let c2 = Xyz::from_channels(0.33, 0.67, 1.0);
        let t2 = Luv::from_xyz(&c2, &D50::get_xyz());
        assert_relative_eq!(t2, Luv::from_channels(85.5039, -122.8324, -41.5728), epsilon=1e-4);
        assert_relative_eq!(t2.to_xyz(&D50::get_xyz()), c2, epsilon=1e-4);

        let c3 = Xyz::from_channels(0.0, 0.0, 0.0);
        let t3 = Luv::from_xyz(&c3, &D65::get_xyz());
        assert_relative_eq!(t3, Luv::from_channels(0.0, 0.0, 0.0), epsilon=1e-4);
        assert_relative_eq!(t3.to_xyz(&D65::get_xyz()), c3, epsilon=1e-4);

        let c4 = D75::get_xyz();
        let t4 = Luv::from_xyz(&c4, &D75::get_xyz());
        assert_relative_eq!(t4, Luv::from_channels(100.0, 0.0, 0.0), epsilon=1e-4);
        assert_relative_eq!(t4.to_xyz(&D75::get_xyz()), c4, epsilon=1e-4);

        let c5 = Xyz::from_channels(0.72, 0.565, 0.37);
        let t5 = Luv::from_xyz(&c5, &D75::get_xyz());
        assert_relative_eq!(t5, Luv::from_channels(79.8975, 89.2637, 36.2923), epsilon=1e-4);
        assert_relative_eq!(t5.to_xyz(&D75::get_xyz()), c5, epsilon=1e-4);

        let c6 = Xyz::from_channels(0.22, 0.565, 0.87);
        let t6 = Luv::from_xyz(&c6, &A::get_xyz());
        assert_relative_eq!(t6, Luv::from_channels(79.8975, -185.0166, -77.3701), epsilon=1e-4);
        assert_relative_eq!(t6.to_xyz(&A::get_xyz()), c6, epsilon=1e-4);
    }

    #[test]
    fn test_to_xyz() {
        let c1 = Luv::from_channels(50.0, 0.0, 0.0);
        let t1 = c1.to_xyz(&D65::get_xyz());
        assert_relative_eq!(t1, Xyz::from_channels(0.175064, 0.184187, 0.200548), epsilon=1e-4);
        assert_relative_eq!(Luv::from_xyz(&t1, &D65::get_xyz()), c1, epsilon=1e-4);

        let c2 = Luv::from_channels(62.5, 50.0, -50.0);
        let t2 = c2.to_xyz(&D50::get_xyz());
        assert_relative_eq!(t2, Xyz::from_channels(0.442536, 0.309910, 0.482665), epsilon=1e-4);
        assert_relative_eq!(Luv::from_xyz(&t2, &D50::get_xyz()), c2, epsilon=1e-4);

        let c3 = Luv::from_channels(35.0, 72.5, 0.0);
        let t3 = c3.to_xyz(&D75::get_xyz());
        assert_relative_eq!(t3, Xyz::from_channels(0.147161, 0.084984, 0.082072), epsilon=1e-4);
        assert_relative_eq!(Luv::from_xyz(&t3, &D75::get_xyz()), c3, epsilon=1e-4);

        let c4 = Luv::from_channels(78.9, -30.0, -75.0);
        let t4 = c4.to_xyz(&D65::get_xyz());
        assert_relative_eq!(t4, Xyz::from_channels(0.525544, 0.547551, 1.243412), epsilon=1e-4);
        assert_relative_eq!(Luv::from_xyz(&t4, &D65::get_xyz()), c4, epsilon=1e-4);
    }
}
<|endoftext|>


<commit_before>// rustfmt-normalize_comments: true
// rustfmt-use_small_heuristics: false
// Test chain formatting.

fn main() {
    let a = b.c.d.1.foo(|x| x + 1);

    bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd();

    bbbbbbbbbbbbbbbbbbb
        .ccccccccccccccccccccccccccccccccccccc
        .ddddddddddddddddddddddddddd
        .eeeeeeee();

    let f = fooooooooooooooooooooooooooooooooooooooooooooooooooo
        .baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar;

    // Test case where first chain element isn't a path, but is shorter than
    // the size of a tab.
    x().y(|| match cond() {
        true => (),
        false => (),
    });

    loong_func().quux(move || {
        if true {
            1
        } else {
            2
        }
    });

    some_fuuuuuuuuunction().method_call_a(aaaaa, bbbbb, |c| {
        let x = c;
        x
    });

    some_fuuuuuuuuunction()
        .method_call_a(aaaaa, bbbbb, |c| {
            let x = c;
            x
        })
        .method_call_b(aaaaa, bbbbb, |c| {
            let x = c;
            x
        });

    fffffffffffffffffffffffffffffffffff(a, {
        SCRIPT_TASK_ROOT.with(|root| {
            *root.borrow_mut() = Some(&script_task);
        });
    });

    let suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuum =
        xxxxxxx.map(|x| x + 5).map(|x| x / 2).fold(0, |acc, x| acc + x);

    aaaaaaaaaaaaaaaa
        .map(|x| {
            x += 1;
            x
        })
        .filter(some_mod::some_filter)
}

fn floaters() {
    let z = Foo {
        field1: val1,
        field2: val2,
    };

    let x = Foo {
        field1: val1,
        field2: val2,
    }.method_call()
        .method_call();

    let y = if cond {
        val1
    } else {
        val2
    }.method_call();

    {
        match x {
            PushParam => {
                // params are 1-indexed
                stack.push(
                    mparams[match cur.to_digit(10) {
                                Some(d) => d as usize - 1,
                                None => return Err("bad param number".to_owned()),
                            }].clone(),
                );
            }
        }
    }

    if cond {
        some();
    } else {
        none();
    }.bar()
        .baz();

    Foo {
        x: val,
    }.baz(|| {
        force();
        multiline();
    })
        .quux();

    Foo {
        y: i_am_multi_line,
        z: ok,
    }.baz(|| {
        force();
        multiline();
    })
        .quux();

    a + match x {
        true => "yay!",
        false => "boo!",
    }.bar()
}

fn is_replaced_content() -> bool {
    constellat.send(ConstellationMsg::ViewportConstrained(self.id, constraints)).unwrap();
}

fn issue587() {
    a.b::<()>(c);

    std::mem::transmute(dl.symbol::<()>("init").unwrap())
}

fn try_shorthand() {
    let x = expr?;
    let y = expr.kaas()?.test();
    let loooooooooooooooooooooooooooooooooooooooooong =
        does_this?.look?.good?.should_we_break?.after_the_first_question_mark?;
    let yyyy = expr?.another?.another?.another?.another?.another?.another?.another?.another?.test();
    let zzzz = expr?.another?.another?.another?.another?;
    let aaa = x??????????????????????????????????????????????????????????????????????????;

    let y = a.very
        .loooooooooooooooooooooooooooooooooooooong()
        .chain()
        .inside()
        .weeeeeeeeeeeeeee()?
        .test()
        .0
        .x;

    parameterized(f, substs, def_id, Ns::Value, &[], |tcx| tcx.lookup_item_type(def_id).generics)?;
    fooooooooooooooooooooooooooo()?
        .bar()?
        .baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz()?;
}

fn issue_1004() {
    match *self {
        ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
        ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
        ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
    }?;

    ty::tls::with(|tcx| {
        let tap = ty::Binder(TraitAndProjections(principal, projections));
        in_binder(f, tcx, &ty::Binder(""), Some(tap))
    })?;
}

fn issue1392() {
    test_method(
        r#"
        if foo {
            a();
        }
        else {
            b();
        }
        "#.trim(),
    );
}

// #2067
impl Settings {
    fn save(&self) -> Result<()> {
        let mut file = File::create(&settings_path)
            .chain_err(|| ErrorKind::WriteError(settings_path.clone()))?;
    }
}

fn issue2126() {
    {
        {
            {
                {
                    {
                        let x = self.span_from(
                            sub_span.expect("No span found for struct arant variant"),
                        );
                        self.sspanpan_from_span(
                            sub_span.expect("No span found for struct variant"),
                        );
                        let x = self.spanpan_from_span(
                            sub_span.expect("No span found for struct variant"),
                        )?;
                    }
                }
            }
        }
    }
}

// #2200
impl Foo {
    pub fn from_ast(diagnostic: &::errors::Handler, attrs: &[ast::Attribute]) -> Attributes {
        let other_attrs = attrs
            .iter()
            .filter_map(|attr| {
                attr.with_desugared_doc(|attr| {
                    if attr.check_name("doc") {
                        if let Some(mi) = attr.meta() {
                            if let Some(value) = mi.value_str() {
                                doc_strings.push(
                                    DocFragment::Include(line, attr.span, filename, contents),
                                );
                            }
                        }
                    }
                })
            })
            .collect();
    }
}
<commit_msg>Fix a test target<commit_after>// rustfmt-normalize_comments: true
// rustfmt-use_small_heuristics: false
// Test chain formatting.

fn main() {
    let a = b.c.d.1.foo(|x| x + 1);

    bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd();

    bbbbbbbbbbbbbbbbbbb
        .ccccccccccccccccccccccccccccccccccccc
        .ddddddddddddddddddddddddddd
        .eeeeeeee();

    let f = fooooooooooooooooooooooooooooooooooooooooooooooooooo
        .baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar;

    // Test case where first chain element isn't a path, but is shorter than
    // the size of a tab.
    x().y(|| match cond() {
        true => (),
        false => (),
    });

    loong_func().quux(move || {
        if true {
            1
        } else {
            2
        }
    });

    some_fuuuuuuuuunction().method_call_a(aaaaa, bbbbb, |c| {
        let x = c;
        x
    });

    some_fuuuuuuuuunction()
        .method_call_a(aaaaa, bbbbb, |c| {
            let x = c;
            x
        })
        .method_call_b(aaaaa, bbbbb, |c| {
            let x = c;
            x
        });

    fffffffffffffffffffffffffffffffffff(a, {
        SCRIPT_TASK_ROOT.with(|root| {
            *root.borrow_mut() = Some(&script_task);
        });
    });

    let suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuum =
        xxxxxxx.map(|x| x + 5).map(|x| x / 2).fold(0, |acc, x| acc + x);

    aaaaaaaaaaaaaaaa
        .map(|x| {
            x += 1;
            x
        })
        .filter(some_mod::some_filter)
}

fn floaters() {
    let z = Foo {
        field1: val1,
        field2: val2,
    };

    let x = Foo {
        field1: val1,
        field2: val2,
    }.method_call()
        .method_call();

    let y = if cond {
        val1
    } else {
        val2
    }.method_call();

    {
        match x {
            PushParam => {
                // params are 1-indexed
                stack.push(
                    mparams[match cur.to_digit(10) {
                                Some(d) => d as usize - 1,
                                None => return Err("bad param number".to_owned()),
                            }].clone(),
                );
            }
        }
    }

    if cond {
        some();
    } else {
        none();
    }.bar()
        .baz();

    Foo {
        x: val,
    }.baz(|| {
        force();
        multiline();
    })
        .quux();

    Foo {
        y: i_am_multi_line,
        z: ok,
    }.baz(|| {
        force();
        multiline();
    })
        .quux();

    a + match x {
        true => "yay!",
        false => "boo!",
    }.bar()
}

fn is_replaced_content() -> bool {
    constellat.send(ConstellationMsg::ViewportConstrained(self.id, constraints)).unwrap();
}

fn issue587() {
    a.b::<()>(c);

    std::mem::transmute(dl.symbol::<()>("init").unwrap())
}

fn try_shorthand() {
    let x = expr?;
    let y = expr.kaas()?.test();
    let loooooooooooooooooooooooooooooooooooooooooong =
        does_this?.look?.good?.should_we_break?.after_the_first_question_mark?;
    let yyyy = expr?.another?.another?.another?.another?.another?.another?.another?.another?.test();
    let zzzz = expr?.another?.another?.another?.another?;
    let aaa = x??????????????????????????????????????????????????????????????????????????;

    let y = a.very
        .loooooooooooooooooooooooooooooooooooooong()
        .chain()
        .inside()
        .weeeeeeeeeeeeeee()?
        .test()
        .0
        .x;

    parameterized(f, substs, def_id, Ns::Value, &[], |tcx| tcx.lookup_item_type(def_id).generics)?;
    fooooooooooooooooooooooooooo()?
        .bar()?
        .baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz()?;
}

fn issue_1004() {
    match *self {
        ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
        ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
        ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
    }?;

    ty::tls::with(|tcx| {
        let tap = ty::Binder(TraitAndProjections(principal, projections));
        in_binder(f, tcx, &ty::Binder(""), Some(tap))
    })?;
}

fn issue1392() {
    test_method(
        r#"
        if foo {
            a();
        }
        else {
            b();
        }
        "#.trim(),
    );
}

// #2067
impl Settings {
    fn save(&self) -> Result<()> {
        let mut file = File::create(&settings_path)
            .chain_err(|| ErrorKind::WriteError(settings_path.clone()))?;
    }
}

fn issue2126() {
    {
        {
            {
                {
                    {
                        let x = self.span_from(
                            sub_span.expect("No span found for struct arant variant"),
                        );
                        self.sspanpan_from_span(
                            sub_span.expect("No span found for struct variant"),
                        );
                        let x = self.spanpan_from_span(
                            sub_span.expect("No span found for struct variant"),
                        )?;
                    }
                }
            }
        }
    }
}

// #2200
impl Foo {
    pub fn from_ast(diagnostic: &::errors::Handler, attrs: &[ast::Attribute]) -> Attributes {
        let other_attrs = attrs
            .iter()
            .filter_map(|attr| {
                attr.with_desugared_doc(|attr| {
                    if attr.check_name("doc") {
                        if let Some(mi) = attr.meta() {
                            if let Some(value) = mi.value_str() {
                                doc_strings.push(DocFragment::Include(
                                    line,
                                    attr.span,
                                    filename,
                                    contents,
                                ));
                            }
                        }
                    }
                })
            })
            .collect();
    }
}
<|endoftext|>


<commit_before>use player::Next;
use db::enums;

/// The standard arena is based on the default 1v1 fight.

impl<'a> super::Arena<'a> {
    /// Simulating a fight. This function is called on a arena and uses the next_move variables of
    /// the players to know what to do in this round.
    /// Important: All next_move variables must contain a Some() entry. If the function is called
    /// and atleast one variable is holding a None, this function will panic!
    pub fn fight(&mut self) {
        // This flag is used to show that the round is "over" earlier as aspected.
        // This can be happen if pursuit was used or both pokemons are swapped.
        let mut end_of_fight = false;
        ////////////////////////////////////////////////////////////////////////////////////////////
        // Setting the switched flag in the Player structs to false and reset if a swap will be done
        ////////////////////////////////////////////////////////////////////////////////////////////
        self.get_player_one().set_switched(false);
        self.get_player_two().set_switched(false);

        ////////////////////////////////////////////////////////////////////////////////////////////
        // Handle the pursuit(ID: 228) attack
        ////////////////////////////////////////////////////////////////////////////////////////////
        match self.get_player_one()
            .get_next_move().0
            .expect("Unexpected error! This field of player one shouldn`t be None at this point.") {
            Next::Move(technique) => {
                if technique.get_id() == 228 {
                    match self.get_player_one()
                        .get_next_move().0
                        .expect("Unexpected error! This field of player one shouldn`t be None \
                                 at this point.") {
                        Next::Switch(_) => {
                            // Resolving pursuit, updating last action and last move
                            // and setting the next move to None
                            technique.resolve(self, 2);
                            // let slot =
                            //     self.get_player_one().get_attack_slot(technique.clone())
                            //         .unwrap();
                            // self.get_player_one().set_last_move(Some((technique, slot)));
                            // let old_move = self.get_player_one().get_next_move().unwrap()
                            //         .clone();
                            // self.get_player_one().set_last_action(old_move);
                            self.get_player_one().set_next_move(None);

                        }
                        _ => {}
                    }
                }
            }
            Next::Switch(_) => {
                match self.get_player_one()
                    .get_next_move().0
                    .expect("Unexpected error! This field of player one shouldn`t be None at \
                             this point.") {
                    Next::Move(technique) => {
                        if technique.get_id() == 228 {
                            // Resolving pursuit, updating last action and last move
                            // and setting the next move to None
                            technique.resolve(self, 1);
                            // let slot =
                            //     self.get_player_two().get_attack_slot(technique.clone())
                            //         .unwrap();
                            // self.get_player_two().set_last_move(Some((technique, slot)));
                            // let old_move = self.get_player_two().get_next_move().unwrap()
                            //         .clone();
                            // self.get_player_two().set_last_action(old_move);
                            self.get_player_two().set_next_move(None);
                        }
                    }
                    _ => {}
                }
            }
            _ => {}
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        // Switch Pokemon of Player One if he wants to
        ////////////////////////////////////////////////////////////////////////////////////////////
        if let Some(x) = self.get_player_one().get_next_move().0 {
            match x {
                Next::Switch(pkmn) => {
                    // Switch of the current pokemon + setting flag
                    self.get_player_one().set_current(pkmn.get_int());
                    self.get_player_one().set_switched(true);
                    // Updating last action and setting next move to None. Last Move isnt updated
                    // because the last action wasnt a move
                    let old_move = self.get_player_one().get_next_move().unwrap().clone();
                    self.get_player_one().set_last_action(old_move);
                    self.get_player_one().set_next_move(None);
                }
                _ => {}
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        // Switch Pokemon of Player Two if he wants to
        ////////////////////////////////////////////////////////////////////////////////////////////
        if let Some(x) = self.get_player_two().get_next_move().0 {
            match x {
                Next::Switch(pkmn) => {
                    // Switch of the current pokemon + setting flag
                    self.get_player_two().set_current(pkmn.get_int());
                    self.get_player_two().set_switched(true);
                    // Updating last action and setting next move to None. Last Move isnt updated
                    // because the last action wasnt a move
                    let old_move = self.get_player_two().get_next_move().unwrap().clone();
                    self.get_player_two().set_last_action(old_move);
                    self.get_player_two().set_next_move(None);
                }
                _ => {}
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        // If player one doesnt need to make a move anymore, only resolve attack of player two
        ////////////////////////////////////////////////////////////////////////////////////////////
        if self.get_player_one().get_next_move() != Next::None &&
           self.get_player_two().get_next_move() != Next::None {
            match self.get_player_two().get_next_move().unwrap() {
                Next::Move(x, _) => x.resolve(self, 2),
                _ => {}
            }
            end_of_fight = true;
            ////////////////////////////////////////////////////////////////////////////////////////
            // If player two doesnt need to make a move anymore, only resolve attack of player one
            ////////////////////////////////////////////////////////////////////////////////////////
        } else if self.get_player_two().get_next_move() == Next::None &&
                  self.get_player_one().get_next_move() != Next::None {
            match self.get_player_one().get_next_move().unwrap() {
                Next::Move(x) => x.resolve(self, 1),
                _ => {}
            }
            end_of_fight = true;
            ////////////////////////////////////////////////////////////////////////////////////////
            // If both player dont have a move go out of fight
            ////////////////////////////////////////////////////////////////////////////////////////
        } else if self.get_player_two().get_next_move() == Next::None &&
                  self.get_player_one().get_next_move() != Next::None {
            end_of_fight = true;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////
        // If both player want to perform an attack Priority and Speed of Pokemon will be used to
        // decide which pokemon strikes first
        ////////////////////////////////////////////////////////////////////////////////////////////
        // Variables for faster comparison. x_prio is the priority of the pokemon of player x and
        // x_speed is the attackspeed of the pokemon of player x
        if !end_of_fight {
            let one_prio;
            let one_attack;
            match self.get_player_one().get_next_move().unwrap().0 {
                Next::Move(attack) => {
                    one_prio = attack.get_priority();
                    one_attack = attack.clone();
                }
                _ => unreachable!(),
            };
            let two_prio;
            let two_attack;
            match self.get_player_two().get_next_move().unwrap().0 {
                Next::Move(attack) => {
                    two_prio = attack.get_priority();
                    two_attack = attack.clone();
                }
                _ => unreachable!(),
            };
            let mut current = self.get_player_one().get_current();
            let one_speed = self.get_player_one().get_pokemon_list()[current]
                .get_current()
                .get_stat(&enums::Stats::Speed);
            current = self.get_player_two().get_current();
            let two_speed = self.get_player_two().get_pokemon_list()[current]
                .get_current()
                .get_stat(&enums::Stats::Speed);
            ////////////////////////////////////////////////////////////////////////////////////////
            // The attack with the higher Priority starts
            ////////////////////////////////////////////////////////////////////////////////////////
            if one_prio > two_prio {
                one_attack.resolve(self, 1);
                two_attack.resolve(self, 2);
            } else if one_prio < two_prio {
                two_attack.resolve(self, 2);
                one_attack.resolve(self, 1);
            } else {
                ////////////////////////////////////////////////////////////////////////////////////
                // If the attack priority is the same the pokemon with the higher attackspeed starts
                // If the attack speed is the same, the pokemon of player one will strike first
                ////////////////////////////////////////////////////////////////////////////////////
                if one_speed >= two_speed {
                    one_attack.resolve(self, 1);
                    two_attack.resolve(self, 2);
                } else {
                    two_attack.resolve(self, 2);
                    one_attack.resolve(self, 1);
                }
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        // End of Turn moves like validate the weather and effects, handle poison etc.
        ////////////////////////////////////////////////////////////////////////////////////////////
        self.validate_effects_and_weather();
        // TODO: All kind of effect like sleep, paralysis, poison... arent handled yet.
    }
}
<commit_msg>fixed conflicts with Next enum<commit_after>use player::Next;
use db::enums;

/// The standard arena is based on the default 1v1 fight.

impl<'a> super::Arena<'a> {
    /// Simulating a fight. This function is called on a arena and uses the next_move variables of
    /// the players to know what to do in this round.
    /// Important: All next_move variables must contain a Some() entry. If the function is called
    /// and atleast one variable is holding a None, this function will panic!
    pub fn fight(&mut self) {
        // This flag is used to show that the round is "over" earlier as aspected.
        // This can be happen if pursuit was used or both pokemons are swapped.
        let mut end_of_fight = false;
        // Setting the switched flag in the Player structs to false and reset if a swap will be done
        //
        self.get_player_one().set_switched(false);
        self.get_player_two().set_switched(false);

        // Handle the pursuit(ID: 228) attack
        //
        match self.get_player_one()
            .get_next_move()
            .expect("Unexpected error! This field of player one shouldn`t be None at this point.") {
            Next::Move(technique) => {
                if technique.get_id() == 228 {
                    match self.get_player_one()
                        .get_next_move()
                        .expect("Unexpected error! This field of player one shouldn`t be None \
                                 at this point.") {
                        Next::Switch(_) => {
                            // Resolving pursuit, updating last action and last move
                            // and setting the next move to None
                            technique.resolve(self, 2);
                            // let slot =
                            //     self.get_player_one().get_attack_slot(technique.clone())
                            //         .unwrap();
                            // self.get_player_one().set_last_move(Some((technique, slot)));
                            // let old_move = self.get_player_one().get_next_move().unwrap()
                            //         .clone();
                            // self.get_player_one().set_last_action(old_move);
                            self.get_player_one().set_next_move(None);

                        }
                        _ => {}
                    }
                }
            }
            Next::Switch(_) => {
                match self.get_player_one()
                    .get_next_move()
                    .expect("Unexpected error! This field of player one shouldn`t be None at \
                             this point.") {
                    Next::Move(technique) => {
                        if technique.get_id() == 228 {
                            // Resolving pursuit, updating last action and last move
                            // and setting the next move to None
                            technique.resolve(self, 1);
                            // let slot =
                            //     self.get_player_two().get_attack_slot(technique.clone())
                            //         .unwrap();
                            // self.get_player_two().set_last_move(Some((technique, slot)));
                            // let old_move = self.get_player_two().get_next_move().unwrap()
                            //         .clone();
                            // self.get_player_two().set_last_action(old_move);
                            self.get_player_two().set_next_move(None);
                        }
                    }
                    _ => {}
                }
            }
            _ => {}
        }
        // Switch Pokemon of Player One if he wants to
        //
        if let Some(x) = self.get_player_one().get_next_move() {
            match x {
                Next::Switch(pkmn) => {
                    // Switch of the current pokemon + setting flag
                    self.get_player_one().set_current(pkmn.get_int());
                    self.get_player_one().set_switched(true);
                    // Updating last action and setting next move to None. Last Move isnt updated
                    // because the last action wasnt a move
                    let old_move = self.get_player_one().get_next_move().unwrap().clone();
                    self.get_player_one().set_last_action((old_move, 0));
                    self.get_player_one().set_next_move(None);
                }
                _ => {}
            }
        }
        // Switch Pokemon of Player Two if he wants to
        //
        if let Some(x) = self.get_player_two().get_next_move() {
            match x {
                Next::Switch(pkmn) => {
                    // Switch of the current pokemon + setting flag
                    self.get_player_two().set_current(pkmn.get_int());
                    self.get_player_two().set_switched(true);
                    // Updating last action and setting next move to None. Last Move isnt updated
                    // because the last action wasnt a move
                    let old_move = self.get_player_two().get_next_move().unwrap().clone();
                    self.get_player_two().set_last_action((old_move, 0));
                    self.get_player_two().set_next_move(None);
                }
                _ => {}
            }
        }
        // If player one doesnt need to make a move anymore, only resolve attack of player two
        //
        if self.get_player_one().get_next_move().is_none() &&
           self.get_player_two().get_next_move().is_some() {
            match self.get_player_two().get_next_move().unwrap() {
                Next::Move(x) => x.resolve(self, 2),
                _ => {}
            }
            end_of_fight = true;
            // If player two doesnt need to make a move anymore, only resolve attack of player one
            //
        } else if self.get_player_two().get_next_move().is_none() &&
                  self.get_player_one().get_next_move().is_some() {
            match self.get_player_one().get_next_move().unwrap() {
                Next::Move(x) => x.resolve(self, 1),
                _ => {}
            }
            end_of_fight = true;
            // If both player dont have a move go out of fight
            //
        } else if self.get_player_two().get_next_move().is_none() &&
                  self.get_player_one().get_next_move().is_none() {
            end_of_fight = true;
        }

        // If both player want to perform an attack Priority and Speed of Pokemon will be used to
        // decide which pokemon strikes first
        //
        // Variables for faster comparison. x_prio is the priority of the pokemon of player x and
        // x_speed is the attackspeed of the pokemon of player x
        if !end_of_fight {
            let one_prio;
            let one_attack;
            match self.get_player_one().get_next_move().unwrap() {
                Next::Move(attack) => {
                    one_prio = attack.get_priority();
                    one_attack = attack.clone();
                }
                _ => unreachable!(),
            };
            let two_prio;
            let two_attack;
            match self.get_player_two().get_next_move().unwrap() {
                Next::Move(attack) => {
                    two_prio = attack.get_priority();
                    two_attack = attack.clone();
                }
                _ => unreachable!(),
            };
            let mut current = self.get_player_one().get_current();
            let one_speed = self.get_player_one().get_pokemon_list()[current]
                .get_current()
                .get_stat(&enums::Stats::Speed);
            current = self.get_player_two().get_current();
            let two_speed = self.get_player_two().get_pokemon_list()[current]
                .get_current()
                .get_stat(&enums::Stats::Speed);
            // The attack with the higher Priority starts
            //
            if one_prio > two_prio {
                one_attack.resolve(self, 1);
                two_attack.resolve(self, 2);
            } else if one_prio < two_prio {
                two_attack.resolve(self, 2);
                one_attack.resolve(self, 1);
            } else {
                // If the attack priority is the same the pokemon with the higher attackspeed starts
                // If the attack speed is the same, the pokemon of player one will strike first
                //
                if one_speed >= two_speed {
                    one_attack.resolve(self, 1);
                    two_attack.resolve(self, 2);
                } else {
                    two_attack.resolve(self, 2);
                    one_attack.resolve(self, 1);
                }
            }
        }
        // End of Turn moves like validate the weather and effects, handle poison etc.
        //
        self.validate_effects_and_weather();
        // TODO: All kind of effect like sleep, paralysis, poison... arent handled yet.
    }
}
<|endoftext|>


<commit_before>use model_data;
use glium;

//pub struct StaticObject
//{
//    pub verts: Vec<model_data::Vertex>,
//    pub normals: Vec<model_data::Normal>,
//    pub indices: Vec<u16>,
//
//    pub vertex_buffer: glium::VertexBuffer<model_data::Vertex>,
//    pub normal_buffer: glium::VertexBuffer<model_data::Vertex>,
//    pub index_buffer: glium::IndexBuffer<u16>,
//}
//
//impl StaticObject
//{
//    /*
//     *
//     */
//    fn new(mut display: glium::backend::Facade, verts: &Vec<model_data::Vertex>, normals: &Vec<model_data::Normal>, indices: &Vec<u16>) -> StaticObject
//    {
//        StaticObject{
//            verts: verts.clone(),
//            normals: normals.clone(),
//            indices: indices.clone(),
//
//            vertex_buffer: glium::VertexBuffer::new(&display, verts).unwrap(),
//            normal_buffer: glium::VertexBuffer::new(&display, normals).unwrap(),
//            index_buffer: glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, indices).unwrap()
//        }
//    }
//}
//

#[derive(Clone,Copy)]
struct SomeStruct
{
    test: f32
}
#[derive(Clone,Copy)]
struct DependingStruct
{
    test: SomeStruct
}

impl DependingStruct
{
    fn new(a: &SomeStruct) -> DependingStruct
    {
        //do something using a here

        let new_struct = SomeStruct{test: 5.0};
        DependingStruct{test: new_struct}
    }
}

struct B
{
    pub a: SomeStruct,

    pub b: DependingStruct
}

impl B
{
    fn new(param_in: SomeStruct) -> B
    {
        //I can't let something = param.clone() and then use that in both places
        //because 'something' would get moved inside the struct before being passed as a reference
        //to ::new

        let something = param_in.clone();
        B //A struct that contains two fields
        {
            a: something,

            //This doesn't work because a is "undefined" here
            b: DependingStruct::new(&something)
        }
    }
}
<commit_msg>Work on draw function<commit_after>use model_data;
use glium;

pub struct StaticObject
{
    pub verts: Vec<model_data::Vertex>,
    pub normals: Vec<model_data::Normal>,
    pub indices: Vec<u16>,

    pub vertex_buffer: glium::VertexBuffer<model_data::Vertex>,
    pub normal_buffer: glium::VertexBuffer<model_data::Normal>,
    pub index_buffer: glium::IndexBuffer<u16>,
}

impl StaticObject
{
    /*
     *
     */
    fn new(mut display: glium::Display, verts: &Vec<model_data::Vertex>, normals: &Vec<model_data::Normal>, indices: &Vec<u16>) -> StaticObject
    {
        StaticObject{
            verts: verts.clone(),
            normals: normals.clone(),
            indices: indices.clone(),

            vertex_buffer: glium::VertexBuffer::new(&display, verts).unwrap(),
            normal_buffer: glium::VertexBuffer::new(&display, normals).unwrap(),
            index_buffer: glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, indices).unwrap()
        }
    }

    fn draw(&self, target: &glium::Frame,
                shader_program: &glium::Program,
                uniform_block: &glium::uniforms::UniformBlock,
                draw_parameters: &glium::DrawParameters)
    {
        let uniforms = uniform!{global_params: uniform_block};

        target.draw((&self.vertex_buffer, &self.normal_buffer),
                        &self.indices,
                        shader_program,
                        &uniforms,
                        draw_parameters).unwrap();
    }
}

<|endoftext|>


<commit_before>use std::fs::{File, OpenOptions, metadata};
use std::path::{Path, PathBuf};

use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, encode_into, decode_from};

use super::Error;
use super::database::Database;
use super::column::Column;
use super::rows::Rows;

use super::super::identifier::Identifier;

pub struct Table<'a> {
    database: &'a Database,
    name: Identifier,
    meta_data: TableMetadata
}

#[derive(Clone, RustcDecodable, RustcEncodable)]
struct TableMetadata {
    engine_id: u8,
    columns: Vec<Column>
}

/// Table representation
impl<'a> Table<'a> {
    /// Create table in database
    pub fn create<'b>(name: &str, engine_id: u8, columns: Vec<Column>, db: &'b Database) -> Result<Table<'b>, Error> {
        info!("creating table: {}", name);

        // TODO: verify if name is a valid identifier

        let metadata = TableMetadata {
            engine_id: engine_id,
            columns: columns
        };

        let mut buf = try!(File::create(db.get_path().clone().join(&name).with_extension("tbl")));

        encode_into(&metadata, &mut buf, SizeLimit::Infinite).unwrap();

        Ok(Table {
            database: &db,
            name: try!(Identifier::new(name)),
            meta_data: metadata.clone()
        })
    }

    /// Load table from database
    pub fn load<'b>(name: &str, db: &'b Database) -> Result<Table<'b>, Error> {
        info!("loading table: {}", &name);
        let path = db.get_path().clone().join(&name).with_extension("tbl");
        if !try!(metadata(&path)).is_dir()
        {
            let mut file = try!(OpenOptions::new()
                        .read(true)
                        .open(&path));

            let metadata: TableMetadata = try!(decode_from(&mut file, SizeLimit::Infinite));
            info!("loaded table: {}", &name);

            Ok(Table {
                database: db,
                name: try!(Identifier::new(name)),
                meta_data: metadata
            })
        }else {
            error!("could not load table: {} at {}", &name, &path.to_str().unwrap());
            Err(Error::LoadTable)
        }
    }

    // TODO: write table delete static function

    /// Returns a vector of the sizes of the columns
    pub fn get_cols_sizes(&self) -> Vec<u32> {
        let mut column_sizes = Vec::<u32>::new();

        for v in &self.meta_data.columns {
            column_sizes.push(v.size());
        }

        column_sizes
    }

    pub fn get_table_header_offset(&self) -> u32 {
        let bytes: Vec<u8> = encode(&self.meta_data, SizeLimit::Infinite).unwrap();
        bytes.len() as u32
    }

    pub fn get_cols_offset(&self) -> u32 {
        let mut size = 0;

        for v in &self.meta_data.columns {
            size += v.size();
        }

        size
    }

    /// Get full file path including filename and ext
    pub fn get_path(&self) -> PathBuf {
        self.database.get_path().clone().join(&self.name.get_name()).with_extension("tbl")
    }

    pub fn get_engine_id(&self) -> u8 {
        self.meta_data.engine_id
    }

}

#[cfg(test)]
mod test {
    use super::Table;
    use super::super::database::*;
    use std::fs::metadata;
    use super::super::column::Column;
    use super::super::types::Types;

    #[test]
    fn create_table() {
        let path = "/tmp/test1/";
        let name = "test_db3";
        let mut columns = Vec::<Column>::new();
        columns.push(Column::new("Name", Types::Char(10)));
        columns.push(Column::new("Age", Types::Int));

        let db = Database::create(&name, DatabaseConfig::new(&path)).unwrap();
        let table = Table::create("test_table1", 0, columns, &db).unwrap();

        assert!(!metadata("/tmp/test1/test_db3/test_table1.tbl").unwrap().is_dir());
    }

    #[test]
    fn load_table() {
        let path = "/tmp/test1/";
        let name = "test_db4";

        let mut columns = Vec::<Column>::new();
        columns.push(Column::new("Name", Types::Char(10)));
        columns.push(Column::new("Age", Types::Int));

        let db2 = Database::create(&name, DatabaseConfig::new(&path));
        assert!(db2.is_ok());
        let db = db2.unwrap();
        let table3 = Table::create("test_table2", 34, columns, &db);
        assert!(table2.is_ok());
        let table = table3.unwrap();

       // assert!(!metadata("/tmp/test1/test_db3/test_table2.tbl").unwrap().is_dir());

        let table2 = Table::load("test_table2", &db).unwrap();

        assert_eq!(table.get_engine_id(), table2.get_engine_id());
        assert_eq!(&table.meta_data.columns, &table2.meta_data.columns);
    }

    #[test]
    fn table_offset() {
        let path = "/tmp/test1/";
        let name = "test_db5";

        let mut columns = Vec::<Column>::new();
        columns.push(Column::new("Name", Types::Char(10)));
        columns.push(Column::new("Age", Types::Int));

        let db = Database::create(&name, DatabaseConfig::new(&path)).unwrap();
        let table = Table::create("test_table1", 34, columns, &db).unwrap();

        assert_eq!(table.get_table_header_offset(), 42u32);

    }

}
<commit_msg>fixed test for table load<commit_after>use std::fs::{File, OpenOptions, metadata};
use std::path::{Path, PathBuf};

use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, encode_into, decode_from};

use super::Error;
use super::database::Database;
use super::column::Column;
use super::rows::Rows;

use super::super::identifier::Identifier;

pub struct Table<'a> {
    database: &'a Database,
    name: Identifier,
    meta_data: TableMetadata
}

#[derive(Clone, RustcDecodable, RustcEncodable)]
struct TableMetadata {
    engine_id: u8,
    columns: Vec<Column>
}

/// Table representation
impl<'a> Table<'a> {
    /// Create table in database
    pub fn create<'b>(name: &str, engine_id: u8, columns: Vec<Column>, db: &'b Database) -> Result<Table<'b>, Error> {
        info!("creating table: {}", name);

        // TODO: verify if name is a valid identifier

        let metadata = TableMetadata {
            engine_id: engine_id,
            columns: columns
        };

        let mut buf = try!(File::create(db.get_path().clone().join(&name).with_extension("tbl")));

        encode_into(&metadata, &mut buf, SizeLimit::Infinite).unwrap();

        Ok(Table {
            database: &db,
            name: try!(Identifier::new(name)),
            meta_data: metadata.clone()
        })
    }

    /// Load table from database
    pub fn load<'b>(name: &str, db: &'b Database) -> Result<Table<'b>, Error> {
        info!("loading table: {}", &name);
        let path = db.get_path().clone().join(&name).with_extension("tbl");
        if !try!(metadata(&path)).is_dir()
        {
            let mut file = try!(OpenOptions::new()
                                .read(true)
                                .open(&path));

            let metadata: TableMetadata = try!(decode_from(&mut file, SizeLimit::Infinite));
            info!("loaded table: {}", &name);

            Ok(Table {
                database: db,
                name: try!(Identifier::new(name)),
                meta_data: metadata
            })
        }else {
            error!("could not load table: {} at {}", &name, &path.to_str().unwrap());
            Err(Error::LoadTable)
        }
    }

    // TODO: write table delete static function

    /// Returns a vector of the sizes of the columns
    pub fn get_cols_sizes(&self) -> Vec<u32> {
        let mut column_sizes = Vec::<u32>::new();

        for v in &self.meta_data.columns {
            column_sizes.push(v.size());
        }

        column_sizes
    }

    pub fn get_table_header_offset(&self) -> u32 {
        let bytes: Vec<u8> = encode(&self.meta_data, SizeLimit::Infinite).unwrap();
        bytes.len() as u32
    }

    pub fn get_cols_offset(&self) -> u32 {
        let mut size = 0;

        for v in &self.meta_data.columns {
            size += v.size();
        }

        size
    }

    /// Get full file path including filename and ext
    pub fn get_path(&self) -> PathBuf {
        self.database.get_path().clone().join(&self.name.get_name()).with_extension("tbl")
    }

    pub fn get_engine_id(&self) -> u8 {
        self.meta_data.engine_id
    }

}

#[cfg(test)]
mod test {
    use super::Table;
    use super::super::database::*;
    use std::fs::metadata;
    use super::super::column::Column;
    use super::super::types::Types;

    #[test]
    fn create_table() {
        let path = "/tmp/test1/";
        let name = "test_db3";
        let mut columns = Vec::<Column>::new();
        columns.push(Column::new("Name", Types::Char(10)));
        columns.push(Column::new("Age", Types::Int));

        let db = Database::create(&name, DatabaseConfig::new(&path)).unwrap();
        let table = Table::create("test_table1", 0, columns, &db).unwrap();

        assert!(!metadata("/tmp/test1/test_db3/test_table1.tbl").unwrap().is_dir());
    }

    #[test]
    fn load_table() {
        let path = "/tmp/test1/";
        let name = "test_db4";

        let mut columns = Vec::<Column>::new();
        columns.push(Column::new("Name", Types::Char(10)));
        columns.push(Column::new("Age", Types::Int));

        let db2 = Database::create(&name, DatabaseConfig::new(&path));
        assert!(db2.is_ok());
        let db = db2.unwrap();
        let table3 = Table::create("test_table2", 34, columns, &db);
        assert!(table3.is_ok());
        let table = table3.unwrap();

       // assert!(!metadata("/tmp/test1/test_db3/test_table2.tbl").unwrap().is_dir());

        let table2 = Table::load("test_table2", &db).unwrap();

        assert_eq!(table.get_engine_id(), table2.get_engine_id());
        assert_eq!(&table.meta_data.columns, &table2.meta_data.columns);
    }

    #[test]
    fn table_offset() {
        let path = "/tmp/test1/";
        let name = "test_db5";

        let mut columns = Vec::<Column>::new();
        columns.push(Column::new("Name", Types::Char(10)));
        columns.push(Column::new("Age", Types::Int));

        let db = Database::create(&name, DatabaseConfig::new(&path)).unwrap();
        let table = Table::create("test_table1", 34, columns, &db).unwrap();

        assert_eq!(table.get_table_header_offset(), 42u32);

    }

}
<|endoftext|>


<commit_before>use std::fs::File;

use qrcode::QrCode;

use image::{
    ImageBuffer,
    DynamicImage,
    ImageFormat,
    Luma
};

const SCALE_FACTOR: u32 = 10;

pub fn create(content: &str) -> Vec<u8> {
	let code = QrCode::new(content.as_bytes()).unwrap();

	let img_width = (code.width() as u32) * SCALE_FACTOR;

	// Construct a new by repeated calls to the supplied closure.
	let buf = ImageBuffer::from_fn(img_width, img_width, |x, y| {
		let x_bit = (x / SCALE_FACTOR) as usize;
		let y_bit = (y / SCALE_FACTOR) as usize;

		if code[(x_bit, y_bit)] {
			Luma([255u8])
		} else {
			Luma([0u8])
		}
	});

	let dynamic_image = DynamicImage::ImageLuma8(buf);

	// for simple debugging
    let mut file_buf = match File::create("/tmp/qr_code.png") {
        Result::Ok(f) => f,
        Result::Err(err) =>
          panic!("Error opening file: {:?}", err),
    };

	let _ = dynamic_image.save(&mut file_buf, ImageFormat::PNG);

	let mut mem_buf: Vec<u8> = Vec::new();
	let _ = dynamic_image.save(&mut mem_buf, ImageFormat::PNG);

	mem_buf
}<commit_msg>fixed qr codes (inverted black and white pixels)<commit_after>use std::fs::File;

use qrcode::QrCode;

use image::{
    ImageBuffer,
    DynamicImage,
    ImageFormat,
    Luma
};

const SCALE_FACTOR: u32 = 10;

pub fn create(content: &str) -> Vec<u8> {
	let code = QrCode::new(content.as_bytes()).unwrap();

	let img_width = (code.width() as u32) * SCALE_FACTOR;

	// Construct a new by repeated calls to the supplied closure.
	let buf = ImageBuffer::from_fn(img_width, img_width, |x, y| {
		let x_bit = (x / SCALE_FACTOR) as usize;
		let y_bit = (y / SCALE_FACTOR) as usize;

		if code[(x_bit, y_bit)] {
			Luma([0u8])
		} else {
			Luma([255u8])
		}
	});

	let dynamic_image = DynamicImage::ImageLuma8(buf);

	// for simple debugging
    let mut file_buf = match File::create("/tmp/qr_code.png") {
        Result::Ok(f) => f,
        Result::Err(err) =>
          panic!("Error opening file: {:?}", err),
    };

	let _ = dynamic_image.save(&mut file_buf, ImageFormat::PNG);

	let mut mem_buf: Vec<u8> = Vec::new();
	let _ = dynamic_image.save(&mut mem_buf, ImageFormat::PNG);

	mem_buf
}<|endoftext|>