<commit_before>#![allow(dead_code,
         non_camel_case_types,
         non_upper_case_globals,
         non_snake_case)]

use core::mem;
use core::ops::{Deref, DerefMut};
use core::convert::TryFrom;

use mouros_rust_bindings::CVoid;
use mouros_rust_bindings::mailbox::Mailbox;

#[repr(C)]
pub struct message {
    pub msg_type: u32,
    transaction_id: u32,
    pub data: *mut CVoid,
}

#[repr(C)]
pub struct message_handler {
    pub message_name: *const u8,
    pub parsing_func:
        Option<unsafe extern "C" fn(msg_ptr: *mut message, save_ptr: *mut i8) -> bool>,
    pub serialization_func: Option<
        unsafe extern "C" fn(msg_ptr: *const message,
                             output_str: *mut i8,
                             output_str_max_len: u32)
                             -> isize,
    >,
}

#[repr(C)]
pub struct subsystem_message_conf {
    pub subsystem_name: *const i8,
    pub message_handlers: *mut message_handler,
    pub num_message_types: u32,
    pub incoming_msg_queue: *mut Mailbox<*mut message>,
    pub outgoing_msg_queue: *mut Mailbox<*mut message>,
    pub outgoing_err_queue: *mut Mailbox<i32>,
    pub alloc_message: Option<unsafe extern "C" fn(msg_type_id: u32) -> *mut message>,
    pub free_message: Option<unsafe extern "C" fn(msg: *mut message)>,
}

extern "C" {
    pub fn dispatcher_register_subsystem(conf: *mut subsystem_message_conf) -> bool;
}

pub struct MessageWrapper<T: Wrappable> {
    raw_msg_ref: *mut message,
    msg: T,
}

pub trait MemManagement {
    fn alloc(msg_type: u32) -> *mut message;
    fn free(msg_ptr: *mut message);
}

pub trait Wrappable: MemManagement + TryFrom<*mut message, Error = ()> {}
impl<T> Wrappable for T
where
    T: MemManagement + TryFrom<*mut message, Error = ()>,
{
}

impl<T> Drop for MessageWrapper<T>
where
    T: Wrappable,
{
    fn drop(&mut self) {
        T::free(self.raw_msg_ref);
    }
}

impl<T> Deref for MessageWrapper<T>
where
    T: Wrappable,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.msg
    }
}

impl<T> DerefMut for MessageWrapper<T>
where
    T: Wrappable,
{
    fn deref_mut(&mut self) -> &mut T {
        &mut self.msg
    }
}

impl<T> Into<*mut message> for MessageWrapper<T>
where
    T: Wrappable,
{
    fn into(self) -> *mut message {
        let raw_msg_ptr = self.raw_msg_ref;

        // It's the caller's duty ot deallocate the message now.
        mem::forget(self);

        raw_msg_ptr
    }
}

impl<T> TryFrom<*mut message> for MessageWrapper<T>
where
    T: Wrappable,
{
    type Error = ();

    fn try_from(raw_msg_ptr: *mut message) -> Result<Self, Self::Error> {
        unsafe {
            if raw_msg_ptr.is_null() || (*raw_msg_ptr).data.is_null() {
                return Err(());
            }
        };

        Ok(MessageWrapper {
            msg: T::try_from(raw_msg_ptr)?,
            raw_msg_ref: raw_msg_ptr,
        })
    }
}

impl<T> MessageWrapper<T>
where
    T: Wrappable,
{
    pub fn new(trans_id: u32, msg_type: u32) -> Result<MessageWrapper<T>, ()> {

        if let Ok(msg_wrapper) = MessageWrapper::try_from(T::alloc(msg_type)) {
            unsafe {
                (*msg_wrapper.raw_msg_ref).transaction_id = trans_id;
            }

            Ok(msg_wrapper)
        } else {
            Err(())
        }
    }

    pub fn get_transaction_id(&self) -> u32 {
        unsafe { (*self.raw_msg_ref).transaction_id }
    }
}
<commit_msg>Switched to raw mailboxes and added SyncMemory struct<commit_after>#![allow(dead_code,
         non_camel_case_types,
         non_upper_case_globals,
         non_snake_case)]

use core::mem;
use core::ops::{Deref, DerefMut};
use core::convert::TryFrom;

use mouros_rust_bindings::CVoid;
use mouros_rust_bindings::mailbox::MailboxRaw;

#[repr(C)]
pub struct message {
    pub msg_type: u32,
    transaction_id: u32,
    pub data: *mut CVoid,
}

#[repr(C)]
pub struct message_handler {
    pub message_name: *const u8,
    pub parsing_func:
        Option<unsafe extern "C" fn(msg_ptr: *mut message, save_ptr: *mut i8) -> bool>,
    pub serialization_func: Option<
        unsafe extern "C" fn(msg_ptr: *const message,
                             output_str: *mut i8,
                             output_str_max_len: u32)
                             -> isize,
    >,
}

#[repr(C)]
pub struct subsystem_message_conf {
    pub subsystem_name: *const u8,
    pub message_handlers: *const message_handler,
    pub num_message_types: u32,
    pub incoming_msg_queue: *mut MailboxRaw,
    pub outgoing_msg_queue: *mut MailboxRaw,
    pub outgoing_err_queue: *mut MailboxRaw,
    pub alloc_message: Option<unsafe extern "C" fn(msg_type_id: u32) -> *mut message>,
    pub free_message: Option<unsafe extern "C" fn(msg: *mut message)>,
}

extern "C" {
    pub fn dispatcher_register_subsystem(conf: *mut subsystem_message_conf) -> bool;
}

pub struct MessageWrapper<T: Wrappable> {
    raw_msg_ref: *mut message,
    msg: T,
}

pub trait MemManagement {
    fn alloc(msg_type: u32) -> *mut message;
    fn free(msg_ptr: *mut message);
}

pub trait Wrappable: MemManagement + TryFrom<*mut message, Error = ()> {}
impl<T> Wrappable for T
where
    T: MemManagement + TryFrom<*mut message, Error = ()>,
{
}

impl<T> Drop for MessageWrapper<T>
where
    T: Wrappable,
{
    fn drop(&mut self) {
        T::free(self.raw_msg_ref);
    }
}

impl<T> Deref for MessageWrapper<T>
where
    T: Wrappable,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.msg
    }
}

impl<T> DerefMut for MessageWrapper<T>
where
    T: Wrappable,
{
    fn deref_mut(&mut self) -> &mut T {
        &mut self.msg
    }
}

impl<T> Into<*mut message> for MessageWrapper<T>
where
    T: Wrappable,
{
    fn into(self) -> *mut message {
        let raw_msg_ptr = self.raw_msg_ref;

        // It's the caller's duty ot deallocate the message now.
        mem::forget(self);

        raw_msg_ptr
    }
}

impl<T> TryFrom<*mut message> for MessageWrapper<T>
where
    T: Wrappable,
{
    type Error = ();

    fn try_from(raw_msg_ptr: *mut message) -> Result<Self, Self::Error> {
        unsafe {
            if raw_msg_ptr.is_null() || (*raw_msg_ptr).data.is_null() {
                return Err(());
            }
        };

        Ok(MessageWrapper {
            msg: T::try_from(raw_msg_ptr)?,
            raw_msg_ref: raw_msg_ptr,
        })
    }
}

impl<T> MessageWrapper<T>
where
    T: Wrappable,
{
    pub fn new(trans_id: u32, msg_type: u32) -> Result<MessageWrapper<T>, ()> {

        if let Ok(msg_wrapper) = MessageWrapper::try_from(T::alloc(msg_type)) {
            unsafe {
                (*msg_wrapper.raw_msg_ref).transaction_id = trans_id;
            }

            Ok(msg_wrapper)
        } else {
            Err(())
        }
    }

    pub fn get_transaction_id(&self) -> u32 {
        unsafe { (*self.raw_msg_ref).transaction_id }
    }
}

pub struct SyncMemory<T>(T);
unsafe impl<T> Sync for SyncMemory<T> {}

impl<T> SyncMemory<T> {
    pub fn new(item: T) -> SyncMemory<T> {
        SyncMemory(item)
    }
}

impl<T> AsRef<T> for SyncMemory<T> {
    fn as_ref(&self) -> &T {
        &self.0
    }
}

impl<T> AsMut<T> for SyncMemory<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.0
    }
}
<|endoftext|>


<commit_before>extern crate turtle;

use turtle::Turtle;

const SIZE: f64 = 1.0;
const FIRST_COLOR: [f64; 4] = [62.0, 114.0, 29.0, 1.0];
const SECOND_COLOR: [f64; 4] = [119.0, 178.0, 85.0, 1.0];
const EYE_COLOR: &str = "black";

fn main() {
    let mut turtle = Turtle::new();
    turtle.set_speed(8);

    turtle.pen_up();
    turtle.set_x(-280.0);
    turtle.set_y(-90.0);

    draw_panther(&mut turtle);

    draw_tail(&mut turtle);

    turtle.pen_up();
    turtle.right(55.0);
    turtle.forward(SIZE * 10.0);
    turtle.right(55.0);

    // Back leg
    draw_leg(&mut turtle);

    turtle.right(86.5);
    turtle.forward(SIZE * 55.0);
    turtle.right(86.0);

    // Front leg
    draw_leg(&mut turtle);

    turtle.right(54.5);
    turtle.forward(SIZE * 8.0);

    draw_neck(&mut turtle);

    turtle.right(172.6);
    turtle.forward(SIZE * 40.0);
    turtle.right(110.0);

    draw_head(&mut turtle);

    turtle.left(128.0);
    turtle.forward(SIZE * 15.0);

    draw_eye(&mut turtle);

    turtle.set_fill_color(SECOND_COLOR);

    turtle.left(175.0);
    turtle.forward(SIZE * 43.0);

    draw_right_highlight(&mut turtle);

    turtle.right(18.0);
    turtle.forward(SIZE * 37.0);
    turtle.set_heading(180.0);

    draw_middle_highlight(&mut turtle);

    turtle.left(24.0);
    turtle.forward(SIZE * 36.0);
    turtle.set_heading(180.0);

    draw_left_highlight(&mut turtle);
}

fn draw_panther(turtle: &mut Turtle) {
    turtle.set_fill_color(FIRST_COLOR);
    turtle.begin_fill();

    for _ in 0..180 {
        turtle.forward(SIZE);
        turtle.right(1.0);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 3.0);
        turtle.right(1.0);
    }

    turtle.set_speed(5);
    let d = SIZE * 360.0 / std::f64::consts::PI;
    turtle.forward(d - d / 3.0);
    turtle.set_speed(10);

    for _ in 0..90 {
        turtle.forward(SIZE / 3.0);
        turtle.right(1.0);
    }

    turtle.end_fill();
}

fn draw_tail(turtle: &mut Turtle) {
    turtle.set_fill_color(SECOND_COLOR);
    turtle.begin_fill();

    turtle.left(90.0);
    turtle.forward(SIZE);

    for _ in 0..45 {
        turtle.forward(SIZE / 3.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 3.0);

    for _ in 0..25 {
        turtle.forward(SIZE / 3.0);
        turtle.left(6.0);
    }

    turtle.forward(SIZE * 9.0);
    turtle.right(6.0);
    turtle.forward(SIZE * 8.0);

    turtle.end_fill();
}

fn draw_leg(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..15 {
        turtle.forward(SIZE);
        turtle.left(0.5);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 6.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 3.0);

    for _ in 0..90 {
        turtle.forward(SIZE / 6.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 14.5);

    turtle.end_fill();
}

fn draw_neck(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..15 {
        turtle.forward(SIZE * 3.0);
        turtle.left(1.5);
    }

    turtle.end_fill();
    turtle.begin_fill();

    turtle.left(100.0);
    turtle.forward(SIZE * 20.0);
    turtle.left(80.0);

    for _ in 0..4 {
        turtle.forward(SIZE * 3.7);
        turtle.left(1.5);
    }

    turtle.left(30.0);

    for _ in 0..27 {
        turtle.forward(SIZE);
        turtle.right(1.0);
    }

    turtle.end_fill();
}

fn draw_head(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..20 {
        turtle.forward(SIZE * 1.2);
        turtle.left(1.0);
    }

    for _ in 0..10 {
        turtle.forward(SIZE * 1.2);
        turtle.left(4.0);
    }

    for _ in 0..10 {
        turtle.forward(SIZE / 1.5);
        turtle.left(7.0);
    }

    for _ in 0..10 {
        turtle.forward(SIZE);
        turtle.left(2.0);
    }

    for _ in 0..50 {
        turtle.forward(SIZE / 2.5);
        turtle.left(1.0);
    }

    for _ in 0..30 {
        turtle.forward(SIZE / 3.0);
        turtle.left(1.8);
    }

    for _ in 0..10 {
        turtle.forward(SIZE / 1.5);
        turtle.left(1.8);
    }

    turtle.end_fill();
}

fn draw_eye(turtle: &mut Turtle) {
    turtle.set_fill_color(EYE_COLOR);
    turtle.begin_fill();
    for _ in 0..90 {
        turtle.forward(SIZE / 3.0);
        turtle.right(4.0);
    }
    turtle.end_fill();
}

fn draw_right_highlight(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..39 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    turtle.forward(SIZE * 36.0);

    for _ in 0..90 {
        turtle.forward(SIZE / 2.5);
        turtle.left(2.0);
    }

    for _ in 0..42 {
        turtle.forward(SIZE);
        turtle.left(0.9);
    }

    for _ in 0..26 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    turtle.end_fill();
}

fn draw_middle_highlight(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..40 {
        turtle.forward(SIZE / 4.0);
        turtle.left(2.0);
    }

    turtle.forward(SIZE * 47.0);
    turtle.left(8.5);

    for _ in 0..90 {
        turtle.forward(SIZE / 2.0);
        turtle.left(2.0);
    }
    turtle.forward(SIZE / 2.0);

    turtle.left(8.5);
    turtle.forward(SIZE * 47.0);

    for _ in 0..40 {
        turtle.left(2.0);
        turtle.forward(SIZE / 4.0);
    }

    turtle.end_fill();
}

fn draw_left_highlight(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..26 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    for _ in 0..42 {
        turtle.forward(SIZE);
        turtle.left(0.9);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 2.5);
        turtle.left(2.0);
    }

    turtle.forward(SIZE * 36.0);

    for _ in 0..39 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    turtle.end_fill();
}
<commit_msg>Update draw_turtle.rs<commit_after>//! https://arkada38.github.io/2018/01/14/creating-a-turtle/
//!
//! Inspired by child's drawing of turtle we are going to draw and paint figures
//! which consists of arcs and straight lines.
//! To draw arcs we need to use the loops which are determine tilt angle and the length.
//! The more sophisticated the figure is the more loops it requires to make.
extern crate turtle;

use turtle::{Turtle, Color, color};

const SIZE: f64 = 1.0;
const SHELL_COLOR: Color = Color {red: 62.0, green: 114.0, blue: 29.0, alpha: 1.0};
const BODY_COLOR: Color = Color {red: 119.0, green: 178.0, blue: 85.0, alpha: 1.0};
const EYE_COLOR: Color = color::BLACK;

fn main() {
    let mut turtle = Turtle::new();
    turtle.set_speed(8);

    turtle.pen_up();
    turtle.set_x(-280.0);
    turtle.set_y(-90.0);

    draw_shell(&mut turtle);

    draw_tail(&mut turtle);

    turtle.pen_up();
    turtle.right(55.0);
    turtle.forward(SIZE * 10.0);
    turtle.right(55.0);

    // Back leg
    draw_leg(&mut turtle);

    turtle.right(86.5);
    turtle.forward(SIZE * 55.0);
    turtle.right(86.0);

    // Front leg
    draw_leg(&mut turtle);

    turtle.right(54.5);
    turtle.forward(SIZE * 8.0);

    draw_neck(&mut turtle);

    turtle.right(172.6);
    turtle.forward(SIZE * 40.0);
    turtle.right(110.0);

    draw_head(&mut turtle);

    turtle.left(128.0);
    turtle.forward(SIZE * 15.0);

    draw_eye(&mut turtle);

    turtle.set_fill_color(BODY_COLOR);

    turtle.left(175.0);
    turtle.forward(SIZE * 43.0);

    draw_right_highlight(&mut turtle);

    turtle.right(18.0);
    turtle.forward(SIZE * 37.0);
    turtle.set_heading(180.0);

    draw_middle_highlight(&mut turtle);

    turtle.left(24.0);
    turtle.forward(SIZE * 36.0);
    turtle.set_heading(180.0);

    draw_left_highlight(&mut turtle);/**/
}

fn draw_shell(turtle: &mut Turtle) {
    turtle.set_fill_color(SHELL_COLOR);
    turtle.begin_fill();

    for _ in 0..180 {
        turtle.forward(SIZE);
        turtle.right(1.0);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 3.0);
        turtle.right(1.0);
    }

    turtle.set_speed(5);
    let d = SIZE * 360.0 / std::f64::consts::PI;
    turtle.forward(d - d / 3.0);
    turtle.set_speed(10);

    for _ in 0..90 {
        turtle.forward(SIZE / 3.0);
        turtle.right(1.0);
    }

    turtle.end_fill();
}

fn draw_tail(turtle: &mut Turtle) {
    turtle.set_fill_color(BODY_COLOR);
    turtle.begin_fill();

    turtle.left(90.0);
    turtle.forward(SIZE);

    for _ in 0..45 {
        turtle.forward(SIZE / 3.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 3.0);

    for _ in 0..25 {
        turtle.forward(SIZE / 3.0);
        turtle.left(6.0);
    }

    turtle.forward(SIZE * 9.0);
    turtle.right(6.0);
    turtle.forward(SIZE * 8.0);

    turtle.end_fill();
}

fn draw_leg(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..15 {
        turtle.forward(SIZE);
        turtle.left(0.5);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 6.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 3.0);

    for _ in 0..90 {
        turtle.forward(SIZE / 6.0);
        turtle.left(1.0);
    }

    turtle.forward(SIZE * 14.5);

    turtle.end_fill();
}

fn draw_neck(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..15 {
        turtle.forward(SIZE * 3.0);
        turtle.left(1.5);
    }

    turtle.end_fill();
    turtle.begin_fill();

    turtle.left(100.0);
    turtle.forward(SIZE * 20.0);
    turtle.left(80.0);

    for _ in 0..4 {
        turtle.forward(SIZE * 3.7);
        turtle.left(1.5);
    }

    turtle.left(30.0);

    for _ in 0..27 {
        turtle.forward(SIZE);
        turtle.right(1.0);
    }

    turtle.end_fill();
}

// In our case the most difficult part of the turtle is head. It requires six loops to draw.
// There was a way to draw it as one circle but
// I've decided to make it look a like a real turtle's head.
fn draw_head(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..20 {
        turtle.forward(SIZE * 1.2);
        turtle.left(1.0);
    }

    for _ in 0..10 {
        turtle.forward(SIZE * 1.2);
        turtle.left(4.0);
    }

    for _ in 0..10 {
        turtle.forward(SIZE / 1.5);
        turtle.left(7.0);
    }

    for _ in 0..10 {
        turtle.forward(SIZE);
        turtle.left(2.0);
    }

    for _ in 0..50 {
        turtle.forward(SIZE / 2.5);
        turtle.left(1.0);
    }

    for _ in 0..30 {
        turtle.forward(SIZE / 3.0);
        turtle.left(1.8);
    }

    for _ in 0..10 {
        turtle.forward(SIZE / 1.5);
        turtle.left(1.8);
    }

    turtle.end_fill();
}

fn draw_eye(turtle: &mut Turtle) {
    turtle.set_fill_color(EYE_COLOR);
    turtle.begin_fill();
    for _ in 0..90 {
        turtle.forward(SIZE / 3.0);
        turtle.right(4.0);
    }
    turtle.end_fill();
}

fn draw_right_highlight(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..39 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    turtle.forward(SIZE * 36.0);

    for _ in 0..90 {
        turtle.forward(SIZE / 2.5);
        turtle.left(2.0);
    }

    for _ in 0..42 {
        turtle.forward(SIZE);
        turtle.left(0.9);
    }

    for _ in 0..26 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    turtle.end_fill();
}

fn draw_middle_highlight(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..40 {
        turtle.forward(SIZE / 4.0);
        turtle.left(2.0);
    }

    turtle.forward(SIZE * 47.0);
    turtle.left(8.5);

    for _ in 0..90 {
        turtle.forward(SIZE / 2.0);
        turtle.left(2.0);
    }
    turtle.forward(SIZE / 2.0);

    turtle.left(8.5);
    turtle.forward(SIZE * 47.0);

    for _ in 0..40 {
        turtle.left(2.0);
        turtle.forward(SIZE / 4.0);
    }

    turtle.end_fill();
}

fn draw_left_highlight(turtle: &mut Turtle) {
    turtle.begin_fill();

    for _ in 0..26 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    for _ in 0..42 {
        turtle.forward(SIZE);
        turtle.left(0.9);
    }

    for _ in 0..90 {
        turtle.forward(SIZE / 2.5);
        turtle.left(2.0);
    }

    turtle.forward(SIZE * 36.0);

    for _ in 0..39 {
        turtle.forward(SIZE / 5.0);
        turtle.left(2.0);
    }

    turtle.end_fill();
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::iterator::Iterator;
use std::ascii::to_ascii_lower;
use cssparser::*;
use selectors;
use properties;
use errors::{ErrorLoggerIterator, log_css_error};
use namespaces::{NamespaceMap, parse_namespace_rule};
use media_queries::{MediaRule, parse_media_rule};
use media_queries;

pub struct Stylesheet {
    rules: ~[CSSRule],
    namespaces: NamespaceMap,
}

pub enum CSSRule {
    CSSStyleRule(StyleRule),
    CSSMediaRule(MediaRule),
}

pub struct StyleRule {
    selectors: ~[selectors::Selector],
    declarations: ~[properties::PropertyDeclaration],
}

fn parse_stylesheet(css: &str) -> Stylesheet {
    static STATE_CHARSET: uint = 1;
    static STATE_IMPORTS: uint = 2;
    static STATE_NAMESPACES: uint = 3;
    static STATE_BODY: uint = 4;
    let mut state: uint = STATE_CHARSET;

    let mut rules = ~[];
    let mut namespaces = NamespaceMap::new();

    for rule in ErrorLoggerIterator(parse_stylesheet_rules(tokenize(css))) {
        let next_state;  // Unitialized to force each branch to set it.
        match rule {
            QualifiedRule(rule) => {
                next_state = STATE_BODY;
                parse_style_rule(rule, &mut rules, &namespaces)
            },
            AtRule(rule) => {
                let lower_name: &str = to_ascii_lower(rule.name);
                match lower_name {
                    "charset" => {
                        if state > STATE_CHARSET {
                            log_css_error(rule.location, "@charset must be the first rule")
                        }
                        // Valid @charset rules are just ignored
                        next_state = state;
                    },
                    "import" => {
                        if state > STATE_IMPORTS {
                            next_state = state;
                            log_css_error(rule.location,
                                          "@import must be before any rule but @charset")
                        } else {
                            next_state = STATE_IMPORTS;
                            log_css_error(rule.location, "@import is not supported yet")  // TODO
                        }
                    },
                    "namespace" => {
                        if state > STATE_NAMESPACES {
                            next_state = state;
                            log_css_error(
                                rule.location,
                                "@namespace must be before any rule but @charset and @import"
                            )
                        } else {
                            next_state = STATE_NAMESPACES;
                            parse_namespace_rule(rule, &mut namespaces)
                        }
                    },
                    _ => {
                        next_state = STATE_BODY;
                        parse_nested_at_rule(lower_name, rule, &mut rules, &namespaces)
                    },
                }
            },
        }
        state = next_state;
    }
    Stylesheet{ rules: rules, namespaces: namespaces }
}

pub fn parse_style_rule(rule: QualifiedRule, parent_rules: &mut ~[CSSRule],
                        namespaces: &NamespaceMap) {
    let QualifiedRule{location: location, prelude: prelude, block: block} = rule;
    match selectors::parse_selector_list(prelude, namespaces) {
        Some(selectors) => parent_rules.push(CSSStyleRule(StyleRule{
            selectors: selectors,
            declarations: properties::parse_property_declaration_list(block)
        })),
        None => log_css_error(location, "Unsupported CSS selector."),
    }
}

// lower_name is passed explicitly to avoid computing it twice.
pub fn parse_nested_at_rule(lower_name: &str, rule: AtRule,
                            parent_rules: &mut ~[CSSRule], namespaces: &NamespaceMap) {
    match lower_name {
        "media" => parse_media_rule(rule, parent_rules, namespaces),
        _ => log_css_error(rule.location, fmt!("Unsupported at-rule: @%s", lower_name))
    }
}

impl Stylesheet {
    fn iter_style_rules<'a>(&'a self, device: media_queries::Device) -> StyleRuleIterator<'a> {
        StyleRuleIterator { device: device, stack: ~[(self.rules.as_slice(), 0)] }
    }
}

struct StyleRuleIterator<'self> {
    device: media_queries::Device,
    // FIXME: I couldn’t get this to borrow-check with a stack of VecIterator
    stack: ~[(&'self [CSSRule], uint)],
}

impl<'self> Iterator<&'self StyleRule> for StyleRuleIterator<'self> {
    fn next(&mut self) -> Option<&'self StyleRule> {
        loop {
            match self.stack.pop_opt() {
                None => return None,
                Some((rule_list, i)) => {
                    if i + 1 < rule_list.len() {
                        self.stack.push((rule_list, i + 1))
                    }
                    match rule_list[i] {
                        CSSStyleRule(ref rule) => return Some(rule),
                        CSSMediaRule(ref rule) => {
                            if rule.media_queries.evaluate(&self.device) {
                                self.stack.push((rule.rules.as_slice(), 0))
                            }
                        }
                    }
                }
            }
        }
    }
}
<commit_msg>Use a borrowed "device" for Media Queries matching.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::iterator::Iterator;
use std::ascii::to_ascii_lower;
use cssparser::*;
use selectors;
use properties;
use errors::{ErrorLoggerIterator, log_css_error};
use namespaces::{NamespaceMap, parse_namespace_rule};
use media_queries::{MediaRule, parse_media_rule};
use media_queries;

pub struct Stylesheet {
    rules: ~[CSSRule],
    namespaces: NamespaceMap,
}

pub enum CSSRule {
    CSSStyleRule(StyleRule),
    CSSMediaRule(MediaRule),
}

pub struct StyleRule {
    selectors: ~[selectors::Selector],
    declarations: ~[properties::PropertyDeclaration],
}

fn parse_stylesheet(css: &str) -> Stylesheet {
    static STATE_CHARSET: uint = 1;
    static STATE_IMPORTS: uint = 2;
    static STATE_NAMESPACES: uint = 3;
    static STATE_BODY: uint = 4;
    let mut state: uint = STATE_CHARSET;

    let mut rules = ~[];
    let mut namespaces = NamespaceMap::new();

    for rule in ErrorLoggerIterator(parse_stylesheet_rules(tokenize(css))) {
        let next_state;  // Unitialized to force each branch to set it.
        match rule {
            QualifiedRule(rule) => {
                next_state = STATE_BODY;
                parse_style_rule(rule, &mut rules, &namespaces)
            },
            AtRule(rule) => {
                let lower_name: &str = to_ascii_lower(rule.name);
                match lower_name {
                    "charset" => {
                        if state > STATE_CHARSET {
                            log_css_error(rule.location, "@charset must be the first rule")
                        }
                        // Valid @charset rules are just ignored
                        next_state = state;
                    },
                    "import" => {
                        if state > STATE_IMPORTS {
                            next_state = state;
                            log_css_error(rule.location,
                                          "@import must be before any rule but @charset")
                        } else {
                            next_state = STATE_IMPORTS;
                            log_css_error(rule.location, "@import is not supported yet")  // TODO
                        }
                    },
                    "namespace" => {
                        if state > STATE_NAMESPACES {
                            next_state = state;
                            log_css_error(
                                rule.location,
                                "@namespace must be before any rule but @charset and @import"
                            )
                        } else {
                            next_state = STATE_NAMESPACES;
                            parse_namespace_rule(rule, &mut namespaces)
                        }
                    },
                    _ => {
                        next_state = STATE_BODY;
                        parse_nested_at_rule(lower_name, rule, &mut rules, &namespaces)
                    },
                }
            },
        }
        state = next_state;
    }
    Stylesheet{ rules: rules, namespaces: namespaces }
}

pub fn parse_style_rule(rule: QualifiedRule, parent_rules: &mut ~[CSSRule],
                        namespaces: &NamespaceMap) {
    let QualifiedRule{location: location, prelude: prelude, block: block} = rule;
    match selectors::parse_selector_list(prelude, namespaces) {
        Some(selectors) => parent_rules.push(CSSStyleRule(StyleRule{
            selectors: selectors,
            declarations: properties::parse_property_declaration_list(block)
        })),
        None => log_css_error(location, "Unsupported CSS selector."),
    }
}

// lower_name is passed explicitly to avoid computing it twice.
pub fn parse_nested_at_rule(lower_name: &str, rule: AtRule,
                            parent_rules: &mut ~[CSSRule], namespaces: &NamespaceMap) {
    match lower_name {
        "media" => parse_media_rule(rule, parent_rules, namespaces),
        _ => log_css_error(rule.location, fmt!("Unsupported at-rule: @%s", lower_name))
    }
}

impl Stylesheet {
    fn iter_style_rules<'a>(&'a self, device: &'a media_queries::Device) -> StyleRuleIterator<'a> {
        StyleRuleIterator { device: device, stack: ~[(self.rules.as_slice(), 0)] }
    }
}

struct StyleRuleIterator<'self> {
    device: &'self media_queries::Device,
    // FIXME: I couldn’t get this to borrow-check with a stack of VecIterator
    stack: ~[(&'self [CSSRule], uint)],
}

impl<'self> Iterator<&'self StyleRule> for StyleRuleIterator<'self> {
    fn next(&mut self) -> Option<&'self StyleRule> {
        loop {
            match self.stack.pop_opt() {
                None => return None,
                Some((rule_list, i)) => {
                    if i + 1 < rule_list.len() {
                        self.stack.push((rule_list, i + 1))
                    }
                    match rule_list[i] {
                        CSSStyleRule(ref rule) => return Some(rule),
                        CSSMediaRule(ref rule) => {
                            if rule.media_queries.evaluate(self.device) {
                                self.stack.push((rule.rules.as_slice(), 0))
                            }
                        }
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_operator_body {
    (
        notation = $notation:ident,
        struct_name = $name:ident,
        operator = $operator:expr,
        return_ty = $return_ty:ty,
        ty_params = ($($ty_param:ident,)+),
        field_names = ($($field_name:ident,)+),
        backend_ty_params = ($($backend_ty_param:ident,)*),
        backend_ty = $backend_ty:ty,
    ) => {
        #[derive(Debug, Clone, Copy)]
        pub struct $name<$($ty_param,)+> {
            $($field_name: $ty_param,)+
        }

        impl<$($ty_param,)+> $name<$($ty_param,)+> {
            pub fn new($($field_name: $ty_param,)+) -> Self {
                $name { $($field_name,)+ }
            }
        }

        impl_query_id!($name<$($ty_param),+>);
        impl_selectable_expression!($name<$($ty_param),+>);

        impl<$($ty_param,)+> $crate::expression::Expression for $name<$($ty_param,)+> where
            $($ty_param: $crate::expression::Expression,)+
        {
            type SqlType = $return_ty;
        }

        impl<$($ty_param,)+> $crate::expression::NonAggregate for $name<$($ty_param,)+> where
            $($ty_param: $crate::expression::NonAggregate,)+
        {
        }

        impl<$($ty_param,)+ $($backend_ty_param,)*> $crate::query_builder::QueryFragment<$backend_ty>
            for $name<$($ty_param,)+> where
                $($ty_param: $crate::query_builder::QueryFragment<$backend_ty>,)+
                $($backend_ty_param: $crate::backend::Backend,)*
        {
            fn walk_ast(&self, mut out: $crate::query_builder::AstPass<$backend_ty>) -> $crate::result::QueryResult<()> {
                __diesel_operator_to_sql!(
                    notation = $notation,
                    operator_expr = out.push_sql($operator),
                    field_exprs = ($(self.$field_name.walk_ast(out.reborrow())?),+),
                );
                Ok(())
            }
        }

        __diesel_operator_debug_query_fragment_if_needed!(
            backend_ty_params = ($($backend_ty_param,)*),
            notation = $notation,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = ($($ty_param,)+),
            field_names = ($($field_name,)+),
        );
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_operator_to_sql {
    (
        notation = infix,
        operator_expr = $op:expr,
        field_exprs = ($left:expr, $right:expr),
    ) => {
        $left;
        $op;
        $right;
    };

    (
        notation = postfix,
        operator_expr = $op:expr,
        field_exprs = ($expr:expr),
    ) => {
        $expr;
        $op;
    };

    (
        notation = prefix,
        operator_expr = $op:expr,
        field_exprs = ($expr:expr),
    ) => {
        $op;
        $expr;
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_operator_debug_query_fragment_if_needed {
    // backend_ty_params is empty. This means that we generated `QueryFragment`
    // for a specific backend. We need to generate it for `Debug` as well.
    (
        backend_ty_params = (),
        notation = $notation:ident,
        struct_name = $name:ident,
        operator = $operator:expr,
        return_ty = $return_ty:ty,
        ty_params = ($($ty_param:ident,)+),
        field_names = ($($field_name:ident,)+),
    ) => {
        impl<$($ty_param,)+> $crate::query_builder::QueryFragment<$crate::backend::Debug>
            for $name<$($ty_param,)+> where
                $($ty_param: $crate::query_builder::QueryFragment<$crate::backend::Debug>,)+
        {
            fn walk_ast(&self, mut out: $crate::query_builder::AstPass<$crate::backend::Debug>) -> $crate::result::QueryResult<()> {
                __diesel_operator_to_sql!(
                    notation = $notation,
                    operator_expr = out.push_sql($operator),
                    field_exprs = ($(self.$field_name.walk_ast(out.reborrow())?),+),
                );
                Ok(())
            }
        }
    };

    // At least one backend_ty_param was given. We generated a generic impl
    // which will cover `Debug`.
    (backend_ty_params = ($($backend_ty_params:ident,)+), $($rest:tt)*) => {};
}

/// Useful for libraries adding support for new SQL types. Apps should never
/// need to call this
///
/// This will create a new type with the given name. It will implement all
/// methods needed to be used as an expression in Diesel, placing the given
/// SQL between the two elements. The third argument specifies the SQL type
/// that the operator returns. If it is not given, the type will be assumed
/// to be `Bool`.
///
/// If the operator is specific to a single backend, you can specify this by
/// adding `backend: Pg` or similar as the last argument.
///
/// It should be noted that the generated impls will not constrain the SQL
/// types of the arguments. You should ensure that they are of the right
/// type in your function which constructs the operator.
///
/// Typically you would not expose the type that this generates directly. You'd
/// expose a function (or trait) used to construct the expression, and a helper
/// type which represents the return type of that function. See the
/// `diesel::expression::expression_methods` and
/// `diesel::expression::helper_types` modules for real world examples of this.
///
/// # Examples
///
/// # Possible invocations
///
/// ```ignore
/// // The SQL type will be boolean. The backend will not be constrained
/// diesel_infix_operator!(Matches, " @@ ");
///
/// // Queries which try to execute `Contains` on a backend other than Pg
/// // will fail to compile
/// diesel_infix_operator!(Contains, " @> ", backend: Pg);
///
/// // The type of `Concat` will be `TsVector` rather than Bool
/// diesel_infix_operator!(Concat, " || ", TsVector);
///
/// // It is perfectly fine to have multiple operators with the same SQL.
/// // Diesel will ensure that the queries are always unambiguous in which
/// // operator applies
/// diesel_infix_operator!(Or, " || ", TsQuery);
///
/// // Specifying both the return types and the backend
/// diesel_infix_operator!(And, " && ", TsQuery, backend: Pg);
/// ```
///
/// ## Example usage
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// diesel_infix_operator!(MyEq, " = ");
///
/// use diesel::expression::AsExpression;
///
/// // Normally you would put this on a trait instead
/// fn my_eq<T, U>(left: T, right: U) -> MyEq<T, U::Expression> where
///     T: Expression,
///     U: AsExpression<T::SqlType>,
/// {
///     MyEq::new(left, right.as_expression())
/// }
///
/// let users_with_name = users.select(id).filter(my_eq(name, "Sean"));
///
/// assert_eq!(Ok(1), users_with_name.first(&connection));
/// # }
/// ```
#[macro_export]
macro_rules! diesel_infix_operator {
    ($name:ident, $operator:expr) => {
        diesel_infix_operator!($name, $operator, $crate::types::Bool);
    };

    ($name:ident, $operator:expr, backend: $backend:ty) => {
        diesel_infix_operator!($name, $operator, $crate::types::Bool, backend: $backend);
    };

    ($name:ident, $operator:expr, $return_ty:ty) => {
        __diesel_operator_body!(
            notation = infix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (T, U,),
            field_names = (left, right,),
            backend_ty_params = (DB,),
            backend_ty = DB,
        );
    };

    ($name:ident, $operator:expr, $return_ty:ty, backend: $backend:ty) => {
        __diesel_operator_body!(
            notation = infix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (T, U,),
            field_names = (left, right,),
            backend_ty_params = (),
            backend_ty = $backend,
        );
    };
}

/// Useful for libraries adding support for new SQL types. Apps should never
/// need to call this
///
/// Similar to [`diesel_infix_operator!`], but the generated type will only take
/// a single argument rather than two. The operator SQL will be placed after
/// the single argument. See [`diesel_infix_operator!`] for example usage.
///
/// [`diesel_infix_operator!`]: macro.diesel_infix_operator.html
#[macro_export]
macro_rules! diesel_postfix_operator {
    ($name:ident, $operator:expr) => {
        diesel_postfix_operator!($name, $operator, $crate::types::Bool);
    };

    ($name:ident, $operator:expr, backend: $backend:ty) => {
        diesel_postfix_operator!($name, $operator, $crate::types::Bool, backend: $backend);
    };

    ($name:ident, $operator:expr, $return_ty:ty) => {
        __diesel_operator_body!(
            notation = postfix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (DB,),
            backend_ty = DB,
        );
    };

    ($name:ident, $operator:expr, $return_ty:ty, backend: $backend:ty) => {
        __diesel_operator_body!(
            notation = postfix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (),
            backend_ty = $backend,
        );
    };
}

/// Useful for libraries adding support for new SQL types. Apps should never
/// need to call this
///
/// Similar to [`diesel_infix_operator!`], but the generated type will only take
/// a single argument rather than two. The operator SQL will be placed before
/// the single argument. See [`diesel_infix_operator!`] for example usage.
///
/// [`diesel_infix_operator!`]: macro.diesel_infix_operator.html
#[macro_export]
macro_rules! diesel_prefix_operator {
    ($name:ident, $operator:expr) => {
        diesel_prefix_operator!($name, $operator, $crate::types::Bool);
    };

    ($name:ident, $operator:expr, backend: $backend:ty) => {
        diesel_prefix_operator!($name, $operator, $crate::types::Bool, backend: $backend);
    };

    ($name:ident, $operator:expr, $return_ty:ty) => {
        __diesel_operator_body!(
            notation = prefix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (DB,),
            backend_ty = DB,
        );
    };

    ($name:ident, $operator:expr, $return_ty:ty, backend: $backend:ty) => {
        __diesel_operator_body!(
            notation = prefix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (),
            backend_ty = $backend,
        );
    };
}

diesel_infix_operator!(Concat, " || ", ::types::Text);
diesel_infix_operator!(And, " AND ");
diesel_infix_operator!(Between, " BETWEEN ");
diesel_infix_operator!(Escape, " ESCAPE ");
diesel_infix_operator!(Eq, " = ");
diesel_infix_operator!(Gt, " > ");
diesel_infix_operator!(GtEq, " >= ");
diesel_infix_operator!(Like, " LIKE ");
diesel_infix_operator!(Lt, " < ");
diesel_infix_operator!(LtEq, " <= ");
diesel_infix_operator!(NotBetween, " NOT BETWEEN ");
diesel_infix_operator!(NotEq, " != ");
diesel_infix_operator!(NotLike, " NOT LIKE ");
diesel_infix_operator!(Or, " OR ");

diesel_postfix_operator!(IsNull, " IS NULL");
diesel_postfix_operator!(IsNotNull, " IS NOT NULL");
diesel_postfix_operator!(Asc, " ASC", ());
diesel_postfix_operator!(Desc, " DESC", ());

diesel_prefix_operator!(Not, "NOT ");

use backend::Backend;
use query_source::Column;
use query_builder::*;
use result::QueryResult;
use super::AppearsOnTable;

impl<T, U, DB> Changeset<DB> for Eq<T, U> where
    DB: Backend,
    T: Column,
    U: AppearsOnTable<T::Table> + QueryFragment<DB>,
{
    fn is_noop(&self) -> bool {
        false
    }

    fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
        try!(out.push_identifier(T::name()));
        out.push_sql(" = ");
        QueryFragment::walk_ast(&self.right, out)
    }
}

impl<T, U> AsChangeset for Eq<T, U> where
    T: Column,
    U: AppearsOnTable<T::Table>,
{
    type Target = T::Table;
    type Changeset = Self;

    fn as_changeset(self) -> Self {
        self
    }
}
<commit_msg>Apps should never need to call this. Period.<commit_after>#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_operator_body {
    (
        notation = $notation:ident,
        struct_name = $name:ident,
        operator = $operator:expr,
        return_ty = $return_ty:ty,
        ty_params = ($($ty_param:ident,)+),
        field_names = ($($field_name:ident,)+),
        backend_ty_params = ($($backend_ty_param:ident,)*),
        backend_ty = $backend_ty:ty,
    ) => {
        #[derive(Debug, Clone, Copy)]
        pub struct $name<$($ty_param,)+> {
            $($field_name: $ty_param,)+
        }

        impl<$($ty_param,)+> $name<$($ty_param,)+> {
            pub fn new($($field_name: $ty_param,)+) -> Self {
                $name { $($field_name,)+ }
            }
        }

        impl_query_id!($name<$($ty_param),+>);
        impl_selectable_expression!($name<$($ty_param),+>);

        impl<$($ty_param,)+> $crate::expression::Expression for $name<$($ty_param,)+> where
            $($ty_param: $crate::expression::Expression,)+
        {
            type SqlType = $return_ty;
        }

        impl<$($ty_param,)+> $crate::expression::NonAggregate for $name<$($ty_param,)+> where
            $($ty_param: $crate::expression::NonAggregate,)+
        {
        }

        impl<$($ty_param,)+ $($backend_ty_param,)*> $crate::query_builder::QueryFragment<$backend_ty>
            for $name<$($ty_param,)+> where
                $($ty_param: $crate::query_builder::QueryFragment<$backend_ty>,)+
                $($backend_ty_param: $crate::backend::Backend,)*
        {
            fn walk_ast(&self, mut out: $crate::query_builder::AstPass<$backend_ty>) -> $crate::result::QueryResult<()> {
                __diesel_operator_to_sql!(
                    notation = $notation,
                    operator_expr = out.push_sql($operator),
                    field_exprs = ($(self.$field_name.walk_ast(out.reborrow())?),+),
                );
                Ok(())
            }
        }

        __diesel_operator_debug_query_fragment_if_needed!(
            backend_ty_params = ($($backend_ty_param,)*),
            notation = $notation,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = ($($ty_param,)+),
            field_names = ($($field_name,)+),
        );
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_operator_to_sql {
    (
        notation = infix,
        operator_expr = $op:expr,
        field_exprs = ($left:expr, $right:expr),
    ) => {
        $left;
        $op;
        $right;
    };

    (
        notation = postfix,
        operator_expr = $op:expr,
        field_exprs = ($expr:expr),
    ) => {
        $expr;
        $op;
    };

    (
        notation = prefix,
        operator_expr = $op:expr,
        field_exprs = ($expr:expr),
    ) => {
        $op;
        $expr;
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_operator_debug_query_fragment_if_needed {
    // backend_ty_params is empty. This means that we generated `QueryFragment`
    // for a specific backend. We need to generate it for `Debug` as well.
    (
        backend_ty_params = (),
        notation = $notation:ident,
        struct_name = $name:ident,
        operator = $operator:expr,
        return_ty = $return_ty:ty,
        ty_params = ($($ty_param:ident,)+),
        field_names = ($($field_name:ident,)+),
    ) => {
        impl<$($ty_param,)+> $crate::query_builder::QueryFragment<$crate::backend::Debug>
            for $name<$($ty_param,)+> where
                $($ty_param: $crate::query_builder::QueryFragment<$crate::backend::Debug>,)+
        {
            fn walk_ast(&self, mut out: $crate::query_builder::AstPass<$crate::backend::Debug>) -> $crate::result::QueryResult<()> {
                __diesel_operator_to_sql!(
                    notation = $notation,
                    operator_expr = out.push_sql($operator),
                    field_exprs = ($(self.$field_name.walk_ast(out.reborrow())?),+),
                );
                Ok(())
            }
        }
    };

    // At least one backend_ty_param was given. We generated a generic impl
    // which will cover `Debug`.
    (backend_ty_params = ($($backend_ty_params:ident,)+), $($rest:tt)*) => {};
}

/// Useful for libraries adding support for new SQL types. Apps should never
/// need to call this.
///
/// This will create a new type with the given name. It will implement all
/// methods needed to be used as an expression in Diesel, placing the given
/// SQL between the two elements. The third argument specifies the SQL type
/// that the operator returns. If it is not given, the type will be assumed
/// to be `Bool`.
///
/// If the operator is specific to a single backend, you can specify this by
/// adding `backend: Pg` or similar as the last argument.
///
/// It should be noted that the generated impls will not constrain the SQL
/// types of the arguments. You should ensure that they are of the right
/// type in your function which constructs the operator.
///
/// Typically you would not expose the type that this generates directly. You'd
/// expose a function (or trait) used to construct the expression, and a helper
/// type which represents the return type of that function. See the source of
/// `diesel::expression::expression_methods` and
/// `diesel::expression::helper_types` for real world examples of this.
///
/// # Examples
///
/// # Possible invocations
///
/// ```ignore
/// // The SQL type will be boolean. The backend will not be constrained
/// diesel_infix_operator!(Matches, " @@ ");
///
/// // Queries which try to execute `Contains` on a backend other than Pg
/// // will fail to compile
/// diesel_infix_operator!(Contains, " @> ", backend: Pg);
///
/// // The type of `Concat` will be `TsVector` rather than Bool
/// diesel_infix_operator!(Concat, " || ", TsVector);
///
/// // It is perfectly fine to have multiple operators with the same SQL.
/// // Diesel will ensure that the queries are always unambiguous in which
/// // operator applies
/// diesel_infix_operator!(Or, " || ", TsQuery);
///
/// // Specifying both the return types and the backend
/// diesel_infix_operator!(And, " && ", TsQuery, backend: Pg);
/// ```
///
/// ## Example usage
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// #     users {
/// #         id -> Integer,
/// #         name -> VarChar,
/// #     }
/// # }
/// #
/// # fn main() {
/// #     use self::users::dsl::*;
/// #     let connection = establish_connection();
/// diesel_infix_operator!(MyEq, " = ");
///
/// use diesel::expression::AsExpression;
///
/// // Normally you would put this on a trait instead
/// fn my_eq<T, U>(left: T, right: U) -> MyEq<T, U::Expression> where
///     T: Expression,
///     U: AsExpression<T::SqlType>,
/// {
///     MyEq::new(left, right.as_expression())
/// }
///
/// let users_with_name = users.select(id).filter(my_eq(name, "Sean"));
///
/// assert_eq!(Ok(1), users_with_name.first(&connection));
/// # }
/// ```
#[macro_export]
macro_rules! diesel_infix_operator {
    ($name:ident, $operator:expr) => {
        diesel_infix_operator!($name, $operator, $crate::types::Bool);
    };

    ($name:ident, $operator:expr, backend: $backend:ty) => {
        diesel_infix_operator!($name, $operator, $crate::types::Bool, backend: $backend);
    };

    ($name:ident, $operator:expr, $return_ty:ty) => {
        __diesel_operator_body!(
            notation = infix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (T, U,),
            field_names = (left, right,),
            backend_ty_params = (DB,),
            backend_ty = DB,
        );
    };

    ($name:ident, $operator:expr, $return_ty:ty, backend: $backend:ty) => {
        __diesel_operator_body!(
            notation = infix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (T, U,),
            field_names = (left, right,),
            backend_ty_params = (),
            backend_ty = $backend,
        );
    };
}

/// Useful for libraries adding support for new SQL types. Apps should never
/// need to call this.
///
/// Similar to [`diesel_infix_operator!`], but the generated type will only take
/// a single argument rather than two. The operator SQL will be placed after
/// the single argument. See [`diesel_infix_operator!`] for example usage.
///
/// [`diesel_infix_operator!`]: macro.diesel_infix_operator.html
#[macro_export]
macro_rules! diesel_postfix_operator {
    ($name:ident, $operator:expr) => {
        diesel_postfix_operator!($name, $operator, $crate::types::Bool);
    };

    ($name:ident, $operator:expr, backend: $backend:ty) => {
        diesel_postfix_operator!($name, $operator, $crate::types::Bool, backend: $backend);
    };

    ($name:ident, $operator:expr, $return_ty:ty) => {
        __diesel_operator_body!(
            notation = postfix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (DB,),
            backend_ty = DB,
        );
    };

    ($name:ident, $operator:expr, $return_ty:ty, backend: $backend:ty) => {
        __diesel_operator_body!(
            notation = postfix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (),
            backend_ty = $backend,
        );
    };
}

/// Useful for libraries adding support for new SQL types. Apps should never
/// need to call this.
///
/// Similar to [`diesel_infix_operator!`], but the generated type will only take
/// a single argument rather than two. The operator SQL will be placed before
/// the single argument. See [`diesel_infix_operator!`] for example usage.
///
/// [`diesel_infix_operator!`]: macro.diesel_infix_operator.html
#[macro_export]
macro_rules! diesel_prefix_operator {
    ($name:ident, $operator:expr) => {
        diesel_prefix_operator!($name, $operator, $crate::types::Bool);
    };

    ($name:ident, $operator:expr, backend: $backend:ty) => {
        diesel_prefix_operator!($name, $operator, $crate::types::Bool, backend: $backend);
    };

    ($name:ident, $operator:expr, $return_ty:ty) => {
        __diesel_operator_body!(
            notation = prefix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (DB,),
            backend_ty = DB,
        );
    };

    ($name:ident, $operator:expr, $return_ty:ty, backend: $backend:ty) => {
        __diesel_operator_body!(
            notation = prefix,
            struct_name = $name,
            operator = $operator,
            return_ty = $return_ty,
            ty_params = (Expr,),
            field_names = (expr,),
            backend_ty_params = (),
            backend_ty = $backend,
        );
    };
}

diesel_infix_operator!(Concat, " || ", ::types::Text);
diesel_infix_operator!(And, " AND ");
diesel_infix_operator!(Between, " BETWEEN ");
diesel_infix_operator!(Escape, " ESCAPE ");
diesel_infix_operator!(Eq, " = ");
diesel_infix_operator!(Gt, " > ");
diesel_infix_operator!(GtEq, " >= ");
diesel_infix_operator!(Like, " LIKE ");
diesel_infix_operator!(Lt, " < ");
diesel_infix_operator!(LtEq, " <= ");
diesel_infix_operator!(NotBetween, " NOT BETWEEN ");
diesel_infix_operator!(NotEq, " != ");
diesel_infix_operator!(NotLike, " NOT LIKE ");
diesel_infix_operator!(Or, " OR ");

diesel_postfix_operator!(IsNull, " IS NULL");
diesel_postfix_operator!(IsNotNull, " IS NOT NULL");
diesel_postfix_operator!(Asc, " ASC", ());
diesel_postfix_operator!(Desc, " DESC", ());

diesel_prefix_operator!(Not, "NOT ");

use backend::Backend;
use query_source::Column;
use query_builder::*;
use result::QueryResult;
use super::AppearsOnTable;

impl<T, U, DB> Changeset<DB> for Eq<T, U> where
    DB: Backend,
    T: Column,
    U: AppearsOnTable<T::Table> + QueryFragment<DB>,
{
    fn is_noop(&self) -> bool {
        false
    }

    fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
        try!(out.push_identifier(T::name()));
        out.push_sql(" = ");
        QueryFragment::walk_ast(&self.right, out)
    }
}

impl<T, U> AsChangeset for Eq<T, U> where
    T: Column,
    U: AppearsOnTable<T::Table>,
{
    type Target = T::Table;
    type Changeset = Self;

    fn as_changeset(self) -> Self {
        self
    }
}
<|endoftext|>


<commit_before>// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

#[doc(hidden)]
#[macro_export]
macro_rules! consumes_to {
    ( $tokens:expr, [] ) => ();
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr ) ] ) => {
        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };
    };
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr ),
                      $( $names:ident $calls:tt ),* $(,)* ] ) => {

        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $names $calls ),* ]);
    };
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr,
                      [ $( $names:ident $calls:tt ),* $(,)* ] ) ] ) => {
        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $names $calls ),* ]);

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };
    };
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr,
                      [ $( $nested_names:ident $nested_calls:tt ),* $(,)* ] ),
      $( $names:ident $calls:tt ),* ] ) => {

        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $nested_names $nested_calls ),* ]);

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $names $calls ),* ]);
    };
}

#[macro_export]
macro_rules! parses_to {
    ( parser: $parser:expr, input: $string:expr, rule: $rule:expr,
      tokens: [ $( $names:ident $calls:tt ),* $(,)* ] ) => {

        #[allow(unused_mut)]
        {
            let vm = $parser;
            let mut tokens = vm.parse($rule, $string).unwrap().tokens();

            consumes_to!(&mut tokens, [ $( $names $calls ),* ]);

            let rest: Vec<_> = tokens.collect();

            match rest.len() {
                0 => (),
                2 => {
                    let (first, second) = (&rest[0], &rest[1]);

                    match (first, second) {
                        (
                            &::pest::Token::Start { rule: ref first_rule, .. },
                            &::pest::Token::End { rule: ref second_rule, .. }
                        ) => {
                            assert!(
                                format!("{:?}", first_rule) == "eoi",
                                format!("expected end of input, but found {:?}", rest)
                            );
                            assert!(
                                format!("{:?}", second_rule) == "eoi",
                                format!("expected end of input, but found {:?}", rest)
                            );
                        }
                        _ => panic!("expected end of input, but found {:?}", rest)
                    }
                }
                _ => panic!("expected end of input, but found {:?}", rest)
            };
        }
    };
}

#[macro_export]
macro_rules! fails_with {
    ( parser: $parser:expr, input: $string:expr, rule: $rule:expr,
      positives: $positives:expr, negatives: $negatives:expr, pos: $pos:expr ) => {

        #[allow(unused_mut)]
        #[allow(dead_code)]
        {
            let vm = $parser;
            let error = vm.parse($rule, $string).unwrap_err();

            match error {
                ::pest::Error::ParsingError { positives, negatives, pos } => {
                    let positives: Vec<&str> = $positives;
                    let negatives: Vec<&str> = $negatives;

                    assert_eq!(positives, positives);
                    assert_eq!(negatives, negatives);
                    assert_eq!(pos.pos(), $pos);
                }
                _ => unreachable!()
            };
        }
    };
}
<commit_msg>Fixed warnings.<commit_after>// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

#[doc(hidden)]
#[macro_export]
macro_rules! consumes_to {
    ( $tokens:expr, [] ) => ();
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr ) ] ) => {
        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };
    };
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr ),
                      $( $names:ident $calls:tt ),* $(,)* ] ) => {

        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $names $calls ),* ]);
    };
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr,
                      [ $( $names:ident $calls:tt ),* $(,)* ] ) ] ) => {
        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $names $calls ),* ]);

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };
    };
    ( $tokens:expr, [ $name:ident ( $start:expr, $end:expr,
                      [ $( $nested_names:ident $nested_calls:tt ),* $(,)* ] ),
      $( $names:ident $calls:tt ),* ] ) => {

        let expected = format!("expected Start {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $start);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::Start { rule, pos } => {
                let message = format!("{} but found Start {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $start {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $nested_names $nested_calls ),* ]);

        let expected = format!("expected End {{ rule: {}, pos: Position {{ pos: {} }} }}",
                               stringify!($name), $end);
        match $tokens.next().expect(&format!("{} but found nothing", expected)) {
            ::pest::Token::End { rule, pos } => {
                let message = format!("{} but found End {{ rule: {}, pos: Position {{ {} }} }}",
                                      expected, rule, pos.pos());

                if rule != stringify!($name) || pos.pos() != $end {
                    panic!("{}", message);
                }
            },
            token => panic!("{}", format!("{} but found {:?}", expected, token))
        };

        consumes_to!($tokens, [ $( $names $calls ),* ]);
    };
}

#[macro_export]
macro_rules! parses_to {
    ( parser: $parser:expr, input: $string:expr, rule: $rule:expr,
      tokens: [ $( $names:ident $calls:tt ),* $(,)* ] ) => {

        #[allow(unused_mut)]
        {
            let vm = $parser;
            let mut tokens = vm.parse($rule, $string).unwrap().tokens();

            consumes_to!(&mut tokens, [ $( $names $calls ),* ]);

            let rest: Vec<_> = tokens.collect();

            match rest.len() {
                0 => (),
                2 => {
                    let (first, second) = (&rest[0], &rest[1]);

                    match (first, second) {
                        (
                            &::pest::Token::Start { rule: ref first_rule, .. },
                            &::pest::Token::End { rule: ref second_rule, .. }
                        ) => {
                            assert!(
                                format!("{:?}", first_rule) == "eoi",
                                format!("expected end of input, but found {:?}", rest)
                            );
                            assert!(
                                format!("{:?}", second_rule) == "eoi",
                                format!("expected end of input, but found {:?}", rest)
                            );
                        }
                        _ => panic!("expected end of input, but found {:?}", rest)
                    }
                }
                _ => panic!("expected end of input, but found {:?}", rest)
            };
        }
    };
}

#[macro_export]
macro_rules! fails_with {
    ( parser: $parser:expr, input: $string:expr, rule: $rule:expr,
      positives: $positives:expr, negatives: $negatives:expr, pos: $pos:expr ) => {

        #[allow(unused_mut)]
        #[allow(unused_variables)]
        {
            let vm = $parser;
            let error = vm.parse($rule, $string).unwrap_err();

            match error {
                ::pest::Error::ParsingError { positives, negatives, pos } => {
                    let positives: Vec<&str> = $positives;
                    let negatives: Vec<&str> = $negatives;

                    assert_eq!(positives, positives);
                    assert_eq!(negatives, negatives);
                    assert_eq!(pos.pos(), $pos);
                }
                _ => unreachable!()
            };
        }
    };
}
<|endoftext|>


<commit_before>use std::ops::{ Index, IndexMut };

struct GenericPixmap<T> {
    w: usize,
    h: usize,

    data: Vec<T>
}

impl<T> GenericPixmap<T>
    where T: Copy + Clone
{
    fn new(w: usize, h: usize, fill_value: T) -> GenericPixmap<T> {
        GenericPixmap {
            w: w,
            h: h,
            data: vec![fill_value; w*h]
        }
    }
}

impl<T> Index<usize> for  GenericPixmap<T>
    where T: Copy + Clone
{
    type Output = [T];

    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        let from = i*self.w;
        let to = from+self.w;
        &self.data[from..to]
    }
}
impl<T> IndexMut<usize> for GenericPixmap<T>
    where T: Copy + Clone
{
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Self::Output {
        let from = i*self.w;
        let to = from+self.w;
        &mut self.data[from..to]
    }
}

type Pixmap = GenericPixmap<u32>;

trait Canvas
{
    fn set_pixel(&mut self, x: usize, y:usize, color:u32);
}

impl Canvas for Pixmap
{
    fn set_pixel(&mut self, x: usize, y:usize, color:u32)
    {
        self[x][y] = color;
    }
}

struct Vec3 {
    x: i32,
    y: i32,
    z: i32
}

impl Index<usize> for Vec3
{
    type Output = i32;

    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        match i {
            0   => &self.x,
            1   => &self.y,
            2   => &self.z,
            _   => panic!("Wrong index"),
        }
    }
}
impl IndexMut<usize> for Vec3
{
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Self::Output {
        match i {
            0   => &mut self.x,
            1   => &mut self.y,
            2   => &mut self.z,
            _   => panic!("Wrong index"),
        }
    }
}

fn main() {
    let canvas = Pixmap::new(300, 300, 0);
}
<commit_msg>LineRasterizer for Rust<commit_after>use std::ops::{ Index, IndexMut };

struct GenericPixmap<T> {
    w: usize,
    h: usize,

    data: Vec<T>
}

impl<T> GenericPixmap<T>
    where T: Copy + Clone
{
    fn new(w: usize, h: usize, fill_value: T) -> GenericPixmap<T> {
        GenericPixmap {
            w: w,
            h: h,
            data: vec![fill_value; w*h]
        }
    }
}

impl<T> Index<usize> for  GenericPixmap<T>
    where T: Copy + Clone
{
    type Output = [T];

    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        let from = i*self.w;
        let to = from+self.w;
        &self.data[from..to]
    }
}
impl<T> IndexMut<usize> for GenericPixmap<T>
    where T: Copy + Clone
{
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Self::Output {
        let from = i*self.w;
        let to = from+self.w;
        &mut self.data[from..to]
    }
}

type Pixmap = GenericPixmap<u32>;

trait Canvas
{
    fn set_pixel(&mut self, x: usize, y:usize, color:u32);
}

impl Canvas for Pixmap
{
    fn set_pixel(&mut self, x: usize, y:usize, color:u32)
    {
        self[x][y] = color;
    }
}

#[derive(Copy, Clone, PartialEq)]
struct Vec3 {
    x: i32,
    y: i32,
    z: i32
}

impl Index<usize> for Vec3
{
    type Output = i32;

    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        match i {
            0   => &self.x,
            1   => &self.y,
            2   => &self.z,
            _   => panic!("Wrong index"),
        }
    }
}
impl IndexMut<usize> for Vec3
{
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Self::Output {
        match i {
            0   => &mut self.x,
            1   => &mut self.y,
            2   => &mut self.z,
            _   => panic!("Wrong index"),
        }
    }
}

struct RasterState {
    step: Vec3,
    d: Vec3,
    major_axis: usize,
}

struct LineRasterizer {
    from: Vec3,
    to: Vec3,

    state: Option<RasterState>
}

impl LineRasterizer {

    fn new(from: Vec3, to: Vec3) -> LineRasterizer {
        LineRasterizer {
            from: from,
            to: to,
            state: None
        }
    }

    fn next_point(&mut self) -> Option<Vec3> {
        match self.state {
            None => {
                let mut state = RasterState {
                    step: Vec3 { x: 0, y: 0, z: 0 },
                    d: Vec3 { x: 0, y: 0, z: 0 },
                    major_axis: 0
                };

                let mut max = 0;
                for i in 0..3 {
                    let d = self.to[i] - self.from[i];
                    state.step[i] = if d > 0 { 1 } else { -1 };

                    let d = d.abs();
                    if d > max {
                        max = d;
                        state.major_axis = i as usize;
                    };
                }

                self.state = Some(state);
                Some(self.from)
            },
            Some(ref mut state) => {
                if self.from == self.to {
                    None
                } else {
                    let from = self.from; let to = self.to;
                    let calc_residual_steps = |axis| { (to[axis] - from[axis]).abs() };

                    self.from[state.major_axis] += state.step[state.major_axis];
                    let rs_base = calc_residual_steps(state.major_axis);
                    for i in 0..3 {
                        let rs = calc_residual_steps(i);

                        if rs > 0 && i != state.major_axis {
                            state.d[i] += rs;
                            if state.d[i] >= rs_base {
                                state.d[i] -= rs_base;
                                self.from[i] += state.step[i];
                            }
                        }
                    }

                    Some(self.from)
                }
            },
        }
    }
}

fn main() {
    let mut canvas = Pixmap::new(300, 300, 0);

    let a = Vec3 { x: 0, y:0, z:0 };
    let b = Vec3 { x: 10, y: 5, z: -4 };

    let mut rasterizer = LineRasterizer::new(a, b);
    while let Some(point) = rasterizer.next_point() {
        let color = std::u32::MAX;
        canvas.set_pixel(point.x as usize, point.y as usize, color);
        println!("point: x: {}, y: {}, z: {}, color: #{:X}", point.x, point.y, point.z, color);
    }
}
<|endoftext|>


<commit_before>use std::process::Command;
use std::string::String;

fn main() {
    let icu_libs_output = Command::new("pkg-config")
        .args(&["--libs-only-L", "icu-uc", "icu-io"])
        .output()
        .unwrap_or_else(|e| {
            panic!("Failed to execute: {}", e)
        });
    let icu_libs = &String::from_utf8_lossy(&icu_libs_output.stdout)
        [2 .. icu_libs_output.stdout.len()]
        .to_string();
    println!("cargo:rustc-link-search=native={}", icu_libs);
    println!("cargo:rustc-link-lib=dylib=icui18n");
    println!("cargo:rustc-link-lib=dylib=icuuc");
    println!("cargo:rustc-link-lib=dylib=icudata");
    println!("cargo:rustc-link-lib=dylib=icuio");
}
<commit_msg>Bit of refactoring in the build script<commit_after>use std::process::Command;
use std::string::String;

fn main() {
    println!("cargo:rustc-link-search=native={}", icu_libs_path());
    println!("cargo:rustc-link-lib=dylib=icui18n");
    println!("cargo:rustc-link-lib=dylib=icuuc");
    println!("cargo:rustc-link-lib=dylib=icudata");
    println!("cargo:rustc-link-lib=dylib=icuio");
}

fn icu_libs_path() -> String {
    let icu_libs_output = Command::new("pkg-config")
        .args(&["--libs-only-L", "icu-uc", "icu-io"])
        .output()
        .unwrap_or_else(|e| {
            panic!("Failed to execute: {}", e)
        });
    String::from_utf8_lossy(&icu_libs_output.stdout)
        [2 .. icu_libs_output.stdout.len()]
        .to_string()
}
<|endoftext|>


<commit_before>#![feature(phase)]
#[phase(plugin, link)] extern crate log;
extern crate url;

use std::from_str::from_str;
use std::io::net::tcp::{TcpListener,TcpStream};
use std::io::{Acceptor,Listener,Command};
use std::string::String;
use url::Url;

// Note: Error handling could be improved
fn main() {
	let browserCommand = "firefox";
	let address = "127.0.0.1";
	let port = 7777;

	// Prepare a socket listening on localhost:7777
	let listener = TcpListener::bind(address, port).unwrap();
	let mut acceptor = listener.listen().unwrap();

	// Infinite loop to keep handling new connections.
	loop {
		let tcpStream = acceptor.accept().unwrap();
		debug!("Accepted new connection");
		spawn(proc() {
			handle_client(tcpStream, browserCommand)
		});
	}
}

// Accept a new connection and listen for URLs
fn handle_client(tcpStream: TcpStream, browserCommand: &'static str) {
	debug!("Spawned new task");

	let mut tcpStream = tcpStream;

	// Note that as soon as read_to_str() returns, everything sent
	// to the socket after this point will be discarded as once
	// we're done working with the content we've just read, the
	// tcpStream will be freed.
	let message = tcpStream.read_to_str().unwrap();

	// Iterate over the lines in the received message
	for line in message.as_slice().split('\n') {
		debug!("Current line is: {}", line);

		// This tries to convert the line to a Url struct
		let url = from_str(line);

		// On failure it returns None; on success a valid URL
		match url {
			None     => { info!("No Url found") }
			Some(u)  => {
				debug!("Found Url in: {}", line);
				if check_url(&u) {
					spawn_process(&u, browserCommand)
				}
			}
		}
	}
}

// Check that the URL is actually usable
fn check_url(u: &Url) -> bool {
	(u.scheme == String::from_str("http") ||
	 u.scheme == String::from_str("https"))
		&& !u.host.is_empty()
}

// Spawn a browser to access the URL
fn spawn_process(u: &Url, command: &'static str) {
	debug!("Spawning process: {} {}", command, u.to_str());
	let mut child = match Command::new(command).arg(u.to_str()).spawn() {
		Ok(child) => child,
		Err(e)    => fail!("Failed to spawn process: {}. {}", command, e),
	};
	child.wait().unwrap().success();
}
<commit_msg>Coding-style update<commit_after>#![feature(phase)]
#[phase(plugin, link)] extern crate log;
extern crate url;

use std::from_str::from_str;
use std::io::net::tcp::{TcpListener,TcpStream};
use std::io::{Acceptor,Listener,Command};
use std::string::String;
use url::Url;

// Note: Error handling could be improved
fn main() {
    let browserCommand = "firefox";
    let address = "127.0.0.1";
    let port = 7777;

    // Prepare a socket listening on localhost:7777
    let listener = TcpListener::bind(address, port).unwrap();
    let mut acceptor = listener.listen().unwrap();

    // Infinite loop to keep handling new connections.
    loop {
        let tcpStream = acceptor.accept().unwrap();
        debug!("Accepted new connection");
        spawn(proc() {
            handle_client(tcpStream, browserCommand)
        });
    }
}

// Accept a new connection and listen for URLs
fn handle_client(tcpStream: TcpStream, browserCommand: &'static str) {
    debug!("Spawned new task");

    let mut tcpStream = tcpStream;

    // Note that as soon as read_to_str() returns, everything sent
    // to the socket after this point will be discarded as once
    // we're done working with the content we've just read, the
    // tcpStream will be freed.
    let message = tcpStream.read_to_str().unwrap();

    // Iterate over the lines in the received message
    for line in message.as_slice().split('\n') {
        debug!("Current line is: {}", line);

        // This tries to convert the line to a Url struct
        let url = from_str(line);

        // On failure it returns None; on success a valid URL
        match url {
            None     => { info!("No Url found") }
            Some(u)  => {
                debug!("Found Url in: {}", line);
                if check_url(&u) {
                    spawn_process(&u, browserCommand)
                }
            }
        }
    }
}

// Check that the URL is actually usable
fn check_url(u: &Url) -> bool {
    (u.scheme == String::from_str("http") ||
     u.scheme == String::from_str("https"))
        && !u.host.is_empty()
}

// Spawn a browser to access the URL
fn spawn_process(u: &Url, command: &'static str) {
    debug!("Spawning process: {} {}", command, u.to_str());
    let mut child = match Command::new(command).arg(u.to_str()).spawn() {
        Ok(child) => child,
        Err(e)    => fail!("Failed to spawn process: {}. {}", command, e),
    };
    child.wait().unwrap().success();
}
<|endoftext|>