<commit_before>use std::str::Chars;
use std::iter::Peekable;
use std::fmt::{Show,Formatter};
use std::fmt;

pub struct TokenValue<'a> {
  token: Token,
  value: &'a str
}

/// Lexer
pub struct Lexer<'a> {
  line: int,
  column: int,
  pos: int,
  iter: Peekable<char, Chars<'a>>,
  curr_ch: Option<char>,
  done: bool
}

/// Lexer tokens.
pub enum Token {
  PLUS,
  MINUS,
  INTEGER, // Any type of integer
  IDEN, // Identifier
  LPAREN,
  RPAREN,
  COLON
}

impl<'a> TokenValue<'a> {
  pub fn new(tok: Token, val: &'a str) -> TokenValue<'a> {
    TokenValue {
      token: tok,
      value: val
    }
  }
}

impl Eq for Token {
  fn eq(&self, other: &Token) -> bool {
    match *self {
      PLUS => match *other { PLUS => true, _ => false },
      MINUS => match *other { MINUS => true, _ => false },
      INTEGER => match *other { INTEGER => true, _ => false },
      IDEN => match *other { IDEN => true, _ => false },
      LPAREN => match *other { LPAREN => true, _ => false },
      RPAREN => match *other { RPAREN => true, _ => false },
      COLON => match *other { COLON => true, _ => false }
    }
  }
}

impl Show for Token {
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    let c = match *self {
      PLUS => &"+",
      MINUS => &"-",
      INTEGER => &"integer",
      IDEN => &"iden",
      LPAREN => &"(",
      RPAREN => &")",
      COLON => ":"
    };

    write!(f.buf, "({})", c)
  }
}

impl<'a> Lexer<'a> {
  pub fn new(input: &'a str) -> Lexer<'a> {
    let it = input.chars().peekable();
    Lexer {
      line: 0,
      column: 0,
      pos: 0,
      iter: it,
      curr_ch: None,
      done: false
    }
  }

  pub fn bump(&mut self) {
    self.curr_ch = self.iter.next();
  }

  pub fn nextch_is(&mut self, ch: char) -> bool {
    self.bump();
    self.curr_ch.unwrap() == ch
  }

  pub fn peekch_is(&mut self, ch: char) -> bool {
    *self.iter.peek().unwrap() == ch
  }

  pub fn next_token(&mut self) -> Option<TokenValue<'a>> {

    for c in self.iter {
      match c {
        '(' => return Some(TokenValue::new(LPAREN, &"(")),
        ')' => return Some(TokenValue::new(RPAREN, &")")),
        '+' => return Some(TokenValue::new(PLUS, &"+")),
        '-' => return Some(TokenValue::new(MINUS, &"-")),
        ':' => return Some(TokenValue::new(COLON, &":")),
        '9' => return Some(TokenValue::new(INTEGER, &"9")),
        '8' => return Some(TokenValue::new(INTEGER, &"8")),
        '7' => return Some(TokenValue::new(INTEGER, &"7")),
        '6' => return Some(TokenValue::new(INTEGER, &"6")),
        '5' => return Some(TokenValue::new(INTEGER, &"5")),
        '4' => return Some(TokenValue::new(INTEGER, &"4")),
        '3' => return Some(TokenValue::new(INTEGER, &"3")),
        '2' => return Some(TokenValue::new(INTEGER, &"2")),
        '1' => return Some(TokenValue::new(INTEGER, &"1")),
        '0' => return Some(TokenValue::new(INTEGER, &"0")),
        _ => return None
      }
    }

    None
  }

}

#[cfg(test)]
mod test {
  use super::Lexer;
  use super::LPAREN;
  use super::TokenValue;

  #[test]
  fn bump() {
    let mut lex = Lexer::new(&"Hello World");
    lex.bump();
    assert_eq!(lex.curr_ch.unwrap(), 'H');
  }

  #[test]
  fn nextch() {
    let mut lex = Lexer::new(&"Woot");
    assert!(lex.nextch_is('W'));
  }

  #[test]
  fn peekable() {
    let mut lex = Lexer::new(&"Haha");
    lex.bump();
    assert!(lex.peekch_is('a'));
  }

  #[test]
  fn next_token() {
    // Should spit out two tokens (LPAREN,RPAREN)
    let mut lex = Lexer::new(&"()");
    assert!(lex.next_token().unwrap().value == &"("); //TokenValue::new(LPAREN, "("));
  }

}<commit_msg>new assert<commit_after>use std::str::Chars;
use std::iter::Peekable;
use std::fmt::{Show,Formatter};
use std::fmt;

pub struct TokenValue<'a> {
  token: Token,
  value: &'a str
}

/// Lexer
pub struct Lexer<'a> {
  line: int,
  column: int,
  pos: int,
  iter: Peekable<char, Chars<'a>>,
  curr_ch: Option<char>,
  done: bool
}

/// Lexer tokens.
pub enum Token {
  PLUS,
  MINUS,
  INTEGER, // Any type of integer
  IDEN, // Identifier
  LPAREN,
  RPAREN,
  COLON
}

impl<'a> TokenValue<'a> {
  pub fn new(tok: Token, val: &'a str) -> TokenValue<'a> {
    TokenValue {
      token: tok,
      value: val
    }
  }
}

impl Eq for Token {
  fn eq(&self, other: &Token) -> bool {
    match *self {
      PLUS => match *other { PLUS => true, _ => false },
      MINUS => match *other { MINUS => true, _ => false },
      INTEGER => match *other { INTEGER => true, _ => false },
      IDEN => match *other { IDEN => true, _ => false },
      LPAREN => match *other { LPAREN => true, _ => false },
      RPAREN => match *other { RPAREN => true, _ => false },
      COLON => match *other { COLON => true, _ => false }
    }
  }
}

impl Show for Token {
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    let c = match *self {
      PLUS => &"+",
      MINUS => &"-",
      INTEGER => &"integer",
      IDEN => &"iden",
      LPAREN => &"(",
      RPAREN => &")",
      COLON => ":"
    };

    write!(f.buf, "({})", c)
  }
}

impl<'a> Lexer<'a> {
  pub fn new(input: &'a str) -> Lexer<'a> {
    let it = input.chars().peekable();
    Lexer {
      line: 0,
      column: 0,
      pos: 0,
      iter: it,
      curr_ch: None,
      done: false
    }
  }

  pub fn bump(&mut self) {
    self.curr_ch = self.iter.next();
  }

  pub fn nextch_is(&mut self, ch: char) -> bool {
    self.bump();
    self.curr_ch.unwrap() == ch
  }

  pub fn peekch_is(&mut self, ch: char) -> bool {
    *self.iter.peek().unwrap() == ch
  }

  pub fn next_token(&mut self) -> Option<TokenValue<'a>> {

    for c in self.iter {
      match c {
        '(' => return Some(TokenValue::new(LPAREN, &"(")),
        ')' => return Some(TokenValue::new(RPAREN, &")")),
        '+' => return Some(TokenValue::new(PLUS, &"+")),
        '-' => return Some(TokenValue::new(MINUS, &"-")),
        ':' => return Some(TokenValue::new(COLON, &":")),
        '9' => return Some(TokenValue::new(INTEGER, &"9")),
        '8' => return Some(TokenValue::new(INTEGER, &"8")),
        '7' => return Some(TokenValue::new(INTEGER, &"7")),
        '6' => return Some(TokenValue::new(INTEGER, &"6")),
        '5' => return Some(TokenValue::new(INTEGER, &"5")),
        '4' => return Some(TokenValue::new(INTEGER, &"4")),
        '3' => return Some(TokenValue::new(INTEGER, &"3")),
        '2' => return Some(TokenValue::new(INTEGER, &"2")),
        '1' => return Some(TokenValue::new(INTEGER, &"1")),
        '0' => return Some(TokenValue::new(INTEGER, &"0")),
        _ => return None
      }
    }

    None
  }

}

#[cfg(test)]
mod test {
  use super::Lexer;
  use super::LPAREN;
  use super::TokenValue;

  #[test]
  fn bump() {
    let mut lex = Lexer::new(&"Hello World");
    lex.bump();
    assert_eq!(lex.curr_ch.unwrap(), 'H');
  }

  #[test]
  fn nextch() {
    let mut lex = Lexer::new(&"Woot");
    assert!(lex.nextch_is('W'));
  }

  #[test]
  fn peekable() {
    let mut lex = Lexer::new(&"Haha");
    lex.bump();
    assert!(lex.peekch_is('a'));
  }

  #[test]
  fn next_token() {
    // Should spit out two tokens (LPAREN,RPAREN)
    let mut lex = Lexer::new(&"()");
    assert!(lex.next_token().unwrap().value == &"("); //TokenValue::new(LPAREN, "("));
    assert!(lex.next_token().unwrap().value == &")");
  }

}<|endoftext|>


<commit_before>use libc;
use glib::translate::*;
use itertools::Itertools;
use std::borrow::Cow;

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum XmlSpace {
    Default,
    Preserve
}

/// Implements `xml:space` handling per the SVG spec
///
/// Normalizes a string as it comes out of the XML parser's handler
/// for character data according to the SVG rules in
/// https://www.w3.org/TR/SVG/text.html#WhiteSpace
pub fn xml_space_normalize(mode: XmlSpace, s: &str) -> String {
    match mode {
        XmlSpace::Default => normalize_default(s),
        XmlSpace::Preserve => normalize_preserve(s)
    }
}

// From https://www.w3.org/TR/SVG/text.html#WhiteSpace
//
// When xml:space="default", the SVG user agent will do the following
// using a copy of the original character data content. First, it will
// remove all newline characters. Then it will convert all tab
// characters into space characters. Then, it will strip off all
// leading and trailing space characters. Then, all contiguous space
// characters will be consolidated.
fn normalize_default<'a, S: Into<Cow<'a, str>>>(s: S) -> String {
    let s = s.into();
    s.replace('\n', "")
        // split at whitespace, also trims whitespace.
        .split_whitespace()
        .join(" ")
}

// From https://www.w3.org/TR/SVG/text.html#WhiteSpace
//
// When xml:space="preserve", the SVG user agent will do the following
// using a copy of the original character data content. It will
// convert all newline and tab characters into space characters. Then,
// it will draw all space characters, including leading, trailing and
// multiple contiguous space characters. Thus, when drawn with
// xml:space="preserve", the string "a   b" (three spaces between "a"
// and "b") will produce a larger separation between "a" and "b" than
// "a b" (one space between "a" and "b").
fn normalize_preserve<'a, S: Into<Cow<'a, str>>>(s: S) -> String {
    let s = s.into();
    let s = s.replace('\n', " ");
    s.replace('\t', " ")
}

#[no_mangle]
pub extern fn rsvg_xml_space_normalize(mode: XmlSpace, s: *const libc::c_char) -> *const libc::c_char {
    let rs = unsafe { String::from_glib_none (s) };

    xml_space_normalize(mode, &rs).to_glib_full()
}

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

    #[test]
    fn xml_space_default() {
        assert_eq!(xml_space_normalize(XmlSpace::Default, "\n    WS example\n    indented lines\n  "),
                   "WS example indented lines");
        assert_eq!(xml_space_normalize(XmlSpace::Default, "\n  \t  \tWS \t\t\texample\n  \t  indented lines\t\t  \n  "),
                   "WS example indented lines");

        assert_eq!(xml_space_normalize(XmlSpace::Default, "\nWS example\nnon-indented lines\n  "),
                   "WS examplenon-indented lines");
    }

    #[test]
    fn xml_space_preserve() {
        assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n    WS example\n    indented lines\n  "),
                   "     WS example     indented lines   ");
        assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n  \t  \tWS \t\t\texample\n  \t  indented lines\t\t  \n  "),
                   "       WS    example      indented lines       ");

    }
}
<commit_msg>Properly revert reggresions this time.<commit_after>use libc;
use glib::translate::*;
use itertools::Itertools;
use std::borrow::Cow;

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum XmlSpace {
    Default,
    Preserve
}

/// Implements `xml:space` handling per the SVG spec
///
/// Normalizes a string as it comes out of the XML parser's handler
/// for character data according to the SVG rules in
/// https://www.w3.org/TR/SVG/text.html#WhiteSpace
pub fn xml_space_normalize(mode: XmlSpace, s: &str) -> String {
    match mode {
        XmlSpace::Default => normalize_default(s),
        XmlSpace::Preserve => normalize_preserve(s)
    }
}

// From https://www.w3.org/TR/SVG/text.html#WhiteSpace
//
// When xml:space="default", the SVG user agent will do the following
// using a copy of the original character data content. First, it will
// remove all newline characters. Then it will convert all tab
// characters into space characters. Then, it will strip off all
// leading and trailing space characters. Then, all contiguous space
// characters will be consolidated.
fn normalize_default<'a, S: Into<Cow<'a, str>>>(s: S) -> String {
    let s = s.into();
    s.chars()
        .filter(|ch| *ch != '\n')
        .collect::<String>()
        // split at whitespace, also trims whitespace.
        .split_whitespace()
        .join(" ")
}

// From https://www.w3.org/TR/SVG/text.html#WhiteSpace
//
// When xml:space="preserve", the SVG user agent will do the following
// using a copy of the original character data content. It will
// convert all newline and tab characters into space characters. Then,
// it will draw all space characters, including leading, trailing and
// multiple contiguous space characters. Thus, when drawn with
// xml:space="preserve", the string "a   b" (three spaces between "a"
// and "b") will produce a larger separation between "a" and "b" than
// "a b" (one space between "a" and "b").
fn normalize_preserve(s: &str) -> String {
    s.chars()
        .map(|ch| {
            match ch {
                '\n' | '\t' => ' ',

                c => c
            }
        })
        .collect()
}

#[no_mangle]
pub extern fn rsvg_xml_space_normalize(mode: XmlSpace, s: *const libc::c_char) -> *const libc::c_char {
    let rs = unsafe { String::from_glib_none (s) };

    xml_space_normalize(mode, &rs).to_glib_full()
}

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

    #[test]
    fn xml_space_default() {
        assert_eq!(xml_space_normalize(XmlSpace::Default, "\n    WS example\n    indented lines\n  "),
                   "WS example indented lines");
        assert_eq!(xml_space_normalize(XmlSpace::Default, "\n  \t  \tWS \t\t\texample\n  \t  indented lines\t\t  \n  "),
                   "WS example indented lines");

        assert_eq!(xml_space_normalize(XmlSpace::Default, "\nWS example\nnon-indented lines\n  "),
                   "WS examplenon-indented lines");
    }

    #[test]
    fn xml_space_preserve() {
        assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n    WS example\n    indented lines\n  "),
                   "     WS example     indented lines   ");
        assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n  \t  \tWS \t\t\texample\n  \t  indented lines\t\t  \n  "),
                   "       WS    example      indented lines       ");

    }
}
<|endoftext|>


<commit_before>//! Core data structures in OpenCV
extern crate libc;
extern crate std;

use std::ffi::CString;
use libc::c_int;
use std::os::raw::c_char;

// Opaque data struct for C bindings
pub enum CMat {}

/// This wraps OpenCV's `Mat` class which is designed for n-dimensional dense
/// array. It's the most widely used data structure in image/video processing
/// since images are often stored as `Mat`.
#[derive(Debug)]
pub struct Mat {
    pub c_mat: *mut CMat,
    pub cols: i32,
    pub rows: i32,
    pub depth: i32,
}

/// A 4-element struct that is widely used to pass pixel values.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Scalar {
    pub v0: i32,
    pub v1: i32,
    pub v2: i32,
    pub v3: i32,
}

impl Scalar {
    pub fn new(v0: i32, v1: i32, v2: i32, v3: i32) -> Self {
        Scalar {
            v0: v0,
            v1: v1,
            v2: v2,
            v3: v3,
        }
    }
}

/// 2D integer points specified by its coordinates `x` and `y`.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Point2i {
    pub x: i32,
    pub y: i32,
}

/// 2D floating points specified by its coordinates `x` and `y`.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Point2f {
    pub x: f32,
    pub y: f32,
}

/// `Size2i` struct is used for specifying the size (`width` and `height` as
/// `i32`) of an image or rectangle.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Size2i {
    pub width: i32,
    pub height: i32,
}

/// `Size2f` struct is used for specifying the size (`width` and `height` as
/// `f32`) of an image or rectangle.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Size2f {
    pub width: f32,
    pub height: f32,
}

#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Rect {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

impl Rect {
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
        Rect {
            x: x,
            y: y,
            width: width,
            height: height,
        }
    }
}

#[repr(C)]
pub struct CVecOfRect {
    array: *mut Rect,
    size: usize,
}

/// This struct represents a vector of rectangles. It can be used as a return
/// value from object detection algorithms (such as face detection) where each
/// detection is a rectangle.
pub struct VecOfRect {
    rects: Vec<Rect>,
    c_vec_of_rect: CVecOfRect,
}

impl VecOfRect {
    /// Helper function to draw all rectangles on the `Mat` (image).
    pub fn draw_on_mat(&self, mat: &mut Mat) {
        self.rects.iter().map(|&r| mat.rectangle(r)).count();
    }

    pub fn get_mut_c_vec_of_rec(&mut self) -> &mut CVecOfRect {
        &mut self.c_vec_of_rect
    }

    /// Creates internal `Vec<Rect>` from the C structs; this is necessary right
    /// now to prepare an idiosyncratic Rust API.
    // TODO(benzh): find ways to simplify this extra function call.
    pub fn populate_rects(&mut self) {
        for i in 0..self.c_vec_of_rect.size {
            let rect =
                unsafe { *(self.c_vec_of_rect.array.offset(i as isize)) };
            self.rects.push(rect);
        }
    }
}

impl Default for VecOfRect {
    fn default() -> Self {
        VecOfRect {
            c_vec_of_rect: CVecOfRect {
                array: std::ptr::null_mut::<Rect>(),
                size: 0,
            },
            rects: Vec::new(),
        }
    }
}

impl std::fmt::Debug for VecOfRect {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, " {:?} ", self.rects)
    }
}

impl Drop for VecOfRect {
    fn drop(&mut self) {
        extern "C" {
            fn opencv_vec_of_rect_drop(_: *mut CVecOfRect);
        }
        unsafe {
            opencv_vec_of_rect_drop(&mut self.c_vec_of_rect);
        }
    }
}

extern "C" {
    pub fn opencv_mat_new() -> *mut CMat;
    fn opencv_mat_new_with_size(rows: i32, cols: i32, t: i32) -> *mut CMat;
    fn opencv_mat_is_valid(mat: *mut CMat) -> bool;
    fn opencv_mat_rows(cmat: *const CMat) -> i32;
    fn opencv_mat_cols(cmat: *const CMat) -> i32;
    fn opencv_mat_depth(cmat: *const CMat) -> i32;
    fn opencv_imread(input: *const c_char, flags: c_int) -> *mut CMat;
    fn opencv_mat_roi(cmat: *const CMat, rect: Rect) -> *mut CMat;
    fn opencv_mat_logic_and(cimage: *mut CMat, cmask: *const CMat);
    fn opencv_mat_flip(src: *mut CMat, code: i32);
    fn opencv_mat_drop(mat: *mut CMat);
}

pub enum FlipCode {
    XAxis,
    YAxis,
    XYAxis,
}

impl Mat {
    #[inline]
    pub fn new_with_cmat(cmat: *mut CMat) -> Mat {
        Mat {
            c_mat: cmat,
            rows: unsafe { opencv_mat_rows(cmat) },
            cols: unsafe { opencv_mat_cols(cmat) },
            depth: unsafe { opencv_mat_depth(cmat) },
        }
    }

    /// Create an empty `Mat` struct.
    pub fn new() -> Mat {
        let m = unsafe { opencv_mat_new() };
        Mat::new_with_cmat(m)
    }

    /// Create an empty `Mat` with specific size (rows, cols and types).
    pub fn with_size(rows: i32, cols: i32, t: i32) -> Self {
        let m = unsafe { opencv_mat_new_with_size(rows, cols, t) };
        Mat::new_with_cmat(m)
    }

    /// Create a `Mat` from reading the image specified by the path.
    pub fn from_path(path: &str, flags: i32) -> Self {
        let s = CString::new(path).unwrap();
        let m = unsafe { opencv_imread((&s).as_ptr(), flags) };
        Mat::new_with_cmat(m)
    }

    /// Check if the `Mat` is valid or not.
    pub fn is_valid(&self) -> bool {
        unsafe { opencv_mat_is_valid(self.c_mat) }
    }

    /// Return a region of interest from a `Mat` specfied by a `Rect`.
    pub fn roi(&self, rect: Rect) -> Mat {
        let cmat = unsafe { opencv_mat_roi(self.c_mat, rect) };
        Mat::new_with_cmat(cmat)
    }

    /// Apply a mask to myself.
    // TODO(benzh): Find the right reference in OpenCV for this one. Provide a
    // shortcut for `image &= mask`
    pub fn logic_and(&mut self, mask: Mat) {
        unsafe {
            opencv_mat_logic_and(self.c_mat, mask.get_cmat());
        }
    }

    /// Flips an image around vertical, horizontal, or both axes.
    pub fn flip(&mut self, code: FlipCode) {
        let code = match code {
            FlipCode::XAxis => 0,
            FlipCode::YAxis => 1,
            FlipCode::XYAxis => -1,
        };
        unsafe { opencv_mat_flip(self.c_mat, code); }
    }

    /// Call out to highgui to show the image, the duration is specified by
    /// `delay`.
    pub fn show(&self, name: &str, delay: i32) {
        extern "C" {
            fn opencv_imshow(name: *const c_char, cmat: *mut CMat);
            fn opencv_wait_key(delay_ms: c_int) -> c_int;
        }

        let s = CString::new(name).unwrap();
        unsafe {
            opencv_imshow((&s).as_ptr(), self.c_mat);
            opencv_wait_key(delay);
        }
    }

    pub fn get_cmat(&self) -> *mut CMat {
        self.c_mat
    }
}

impl Drop for Mat {
    fn drop(&mut self) {
        unsafe {
            opencv_mat_drop(self.c_mat);
        }
    }
}
<commit_msg>add len<commit_after>//! Core data structures in OpenCV
extern crate libc;
extern crate std;

use std::ffi::CString;
use libc::c_int;
use std::os::raw::c_char;

// Opaque data struct for C bindings
pub enum CMat {}

/// This wraps OpenCV's `Mat` class which is designed for n-dimensional dense
/// array. It's the most widely used data structure in image/video processing
/// since images are often stored as `Mat`.
#[derive(Debug)]
pub struct Mat {
    pub c_mat: *mut CMat,
    pub cols: i32,
    pub rows: i32,
    pub depth: i32,
}

/// A 4-element struct that is widely used to pass pixel values.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Scalar {
    pub v0: i32,
    pub v1: i32,
    pub v2: i32,
    pub v3: i32,
}

impl Scalar {
    pub fn new(v0: i32, v1: i32, v2: i32, v3: i32) -> Self {
        Scalar {
            v0: v0,
            v1: v1,
            v2: v2,
            v3: v3,
        }
    }
}

/// 2D integer points specified by its coordinates `x` and `y`.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Point2i {
    pub x: i32,
    pub y: i32,
}

/// 2D floating points specified by its coordinates `x` and `y`.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Point2f {
    pub x: f32,
    pub y: f32,
}

/// `Size2i` struct is used for specifying the size (`width` and `height` as
/// `i32`) of an image or rectangle.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Size2i {
    pub width: i32,
    pub height: i32,
}

/// `Size2f` struct is used for specifying the size (`width` and `height` as
/// `f32`) of an image or rectangle.
#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Size2f {
    pub width: f32,
    pub height: f32,
}

#[derive(Default, Debug, Clone, Copy)]
#[repr(C)]
pub struct Rect {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

impl Rect {
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
        Rect {
            x: x,
            y: y,
            width: width,
            height: height,
        }
    }
}

#[repr(C)]
pub struct CVecOfRect {
    array: *mut Rect,
    size: usize,
}

/// This struct represents a vector of rectangles. It can be used as a return
/// value from object detection algorithms (such as face detection) where each
/// detection is a rectangle.
pub struct VecOfRect {
    rects: Vec<Rect>,
    c_vec_of_rect: CVecOfRect,
}

impl VecOfRect {
    /// Count of detect rectangles
    pub fn len(&self) -> usize {
        self.rects.len()
    }

    /// Helper function to draw all rectangles on the `Mat` (image).
    pub fn draw_on_mat(&self, mat: &mut Mat) {
        self.rects.iter().map(|&r| mat.rectangle(r)).count();
    }

    pub fn get_mut_c_vec_of_rec(&mut self) -> &mut CVecOfRect {
        &mut self.c_vec_of_rect
    }

    /// Creates internal `Vec<Rect>` from the C structs; this is necessary right
    /// now to prepare an idiosyncratic Rust API.
    // TODO(benzh): find ways to simplify this extra function call.
    pub fn populate_rects(&mut self) {
        for i in 0..self.c_vec_of_rect.size {
            let rect =
                unsafe { *(self.c_vec_of_rect.array.offset(i as isize)) };
            self.rects.push(rect);
        }
    }
}

impl Default for VecOfRect {
    fn default() -> Self {
        VecOfRect {
            c_vec_of_rect: CVecOfRect {
                array: std::ptr::null_mut::<Rect>(),
                size: 0,
            },
            rects: Vec::new(),
        }
    }
}

impl std::fmt::Debug for VecOfRect {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, " {:?} ", self.rects)
    }
}

impl Drop for VecOfRect {
    fn drop(&mut self) {
        extern "C" {
            fn opencv_vec_of_rect_drop(_: *mut CVecOfRect);
        }
        unsafe {
            opencv_vec_of_rect_drop(&mut self.c_vec_of_rect);
        }
    }
}

extern "C" {
    pub fn opencv_mat_new() -> *mut CMat;
    fn opencv_mat_new_with_size(rows: i32, cols: i32, t: i32) -> *mut CMat;
    fn opencv_mat_is_valid(mat: *mut CMat) -> bool;
    fn opencv_mat_rows(cmat: *const CMat) -> i32;
    fn opencv_mat_cols(cmat: *const CMat) -> i32;
    fn opencv_mat_depth(cmat: *const CMat) -> i32;
    fn opencv_imread(input: *const c_char, flags: c_int) -> *mut CMat;
    fn opencv_mat_roi(cmat: *const CMat, rect: Rect) -> *mut CMat;
    fn opencv_mat_logic_and(cimage: *mut CMat, cmask: *const CMat);
    fn opencv_mat_flip(src: *mut CMat, code: i32);
    fn opencv_mat_drop(mat: *mut CMat);
}

pub enum FlipCode {
    XAxis,
    YAxis,
    XYAxis,
}

impl Mat {
    #[inline]
    pub fn new_with_cmat(cmat: *mut CMat) -> Mat {
        Mat {
            c_mat: cmat,
            rows: unsafe { opencv_mat_rows(cmat) },
            cols: unsafe { opencv_mat_cols(cmat) },
            depth: unsafe { opencv_mat_depth(cmat) },
        }
    }

    /// Create an empty `Mat` struct.
    pub fn new() -> Mat {
        let m = unsafe { opencv_mat_new() };
        Mat::new_with_cmat(m)
    }

    /// Create an empty `Mat` with specific size (rows, cols and types).
    pub fn with_size(rows: i32, cols: i32, t: i32) -> Self {
        let m = unsafe { opencv_mat_new_with_size(rows, cols, t) };
        Mat::new_with_cmat(m)
    }

    /// Create a `Mat` from reading the image specified by the path.
    pub fn from_path(path: &str, flags: i32) -> Self {
        let s = CString::new(path).unwrap();
        let m = unsafe { opencv_imread((&s).as_ptr(), flags) };
        Mat::new_with_cmat(m)
    }

    /// Check if the `Mat` is valid or not.
    pub fn is_valid(&self) -> bool {
        unsafe { opencv_mat_is_valid(self.c_mat) }
    }

    /// Return a region of interest from a `Mat` specfied by a `Rect`.
    pub fn roi(&self, rect: Rect) -> Mat {
        let cmat = unsafe { opencv_mat_roi(self.c_mat, rect) };
        Mat::new_with_cmat(cmat)
    }

    /// Apply a mask to myself.
    // TODO(benzh): Find the right reference in OpenCV for this one. Provide a
    // shortcut for `image &= mask`
    pub fn logic_and(&mut self, mask: Mat) {
        unsafe {
            opencv_mat_logic_and(self.c_mat, mask.get_cmat());
        }
    }

    /// Flips an image around vertical, horizontal, or both axes.
    pub fn flip(&mut self, code: FlipCode) {
        let code = match code {
            FlipCode::XAxis => 0,
            FlipCode::YAxis => 1,
            FlipCode::XYAxis => -1,
        };
        unsafe { opencv_mat_flip(self.c_mat, code); }
    }

    /// Call out to highgui to show the image, the duration is specified by
    /// `delay`.
    pub fn show(&self, name: &str, delay: i32) {
        extern "C" {
            fn opencv_imshow(name: *const c_char, cmat: *mut CMat);
            fn opencv_wait_key(delay_ms: c_int) -> c_int;
        }

        let s = CString::new(name).unwrap();
        unsafe {
            opencv_imshow((&s).as_ptr(), self.c_mat);
            opencv_wait_key(delay);
        }
    }

    pub fn get_cmat(&self) -> *mut CMat {
        self.c_mat
    }
}

impl Drop for Mat {
    fn drop(&mut self) {
        unsafe {
            opencv_mat_drop(self.c_mat);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>simple_query generate error on unexpected message<commit_after><|endoftext|>


<commit_before>//! `GET /_matrix/federation/*/query/profile`
//!
//! Endpoint to query profile information with a user id and optional field.

pub mod v1 {
    //! `/v1/` ([spec])
    //!
    //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile

    use ruma_common::{api::ruma_api, serde::StringEnum, OwnedMxcUri, UserId};

    use crate::PrivOwnedStr;

    ruma_api! {
        metadata: {
            description: "Get profile information, such as a display name or avatar, for a given user.",
            name: "get_profile_information",
            method: GET,
            stable_path: "/_matrix/federation/v1/query/profile",
            rate_limited: false,
            authentication: ServerSignatures,
            added: 1.0,
        }

        request: {
            /// User ID to query.
            #[ruma_api(query)]
            pub user_id: &'a UserId,

            /// Profile field to query.
            #[serde(skip_serializing_if = "Option::is_none")]
            #[ruma_api(query)]
            pub field: Option<&'a ProfileField>,
        }

        #[derive(Default)]
        response: {
            /// Display name of the user.
            #[serde(skip_serializing_if = "Option::is_none")]
            pub displayname: Option<String>,

            /// Avatar URL for the user's avatar.
            ///
            /// If you activate the `compat` feature, this field being an empty string in JSON will result
            /// in `None` here during deserialization.
            #[serde(skip_serializing_if = "Option::is_none")]
            #[cfg_attr(
                feature = "compat",
                serde(default, deserialize_with = "ruma_common::serde::empty_string_as_none")
            )]
            pub avatar_url: Option<OwnedMxcUri>,

            /// The [BlurHash](https://blurha.sh) for the avatar pointed to by `avatar_url`.
            ///
            /// This uses the unstable prefix in
            /// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
            #[cfg(feature = "unstable-msc2448")]
            #[serde(
                rename = "xyz.amorgan.blurhash",
                alias = "blurhash",
                skip_serializing_if = "Option::is_none"
            )]
            pub blurhash: Option<String>,
        }
    }

    impl<'a> Request<'a> {
        /// Creates a new `Request` with the given user id.
        pub fn new(user_id: &'a UserId) -> Self {
            Self { user_id, field: None }
        }
    }

    impl Response {
        /// Creates an empty `Response`.
        pub fn new() -> Self {
            Default::default()
        }
    }

    /// Profile fields to specify in query.
    ///
    /// This type can hold an arbitrary string. To build this with a custom value, convert it from a
    /// string with `::from() / .into()`. To check for values that are not available as a
    /// documented variant here, use its string representation, obtained through
    /// [`.as_str()`](Self::as_str()).
    #[derive(Clone, Debug, PartialEq, Eq, StringEnum)]
    #[non_exhaustive]
    pub enum ProfileField {
        /// Display name of the user.
        #[ruma_enum(rename = "displayname")]
        DisplayName,

        /// Avatar URL for the user's avatar.
        #[ruma_enum(rename = "avatar_url")]
        AvatarUrl,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }
}
<commit_msg>federation-api: Remove serde aliases for blurhashes<commit_after>//! `GET /_matrix/federation/*/query/profile`
//!
//! Endpoint to query profile information with a user id and optional field.

pub mod v1 {
    //! `/v1/` ([spec])
    //!
    //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile

    use ruma_common::{api::ruma_api, serde::StringEnum, OwnedMxcUri, UserId};

    use crate::PrivOwnedStr;

    ruma_api! {
        metadata: {
            description: "Get profile information, such as a display name or avatar, for a given user.",
            name: "get_profile_information",
            method: GET,
            stable_path: "/_matrix/federation/v1/query/profile",
            rate_limited: false,
            authentication: ServerSignatures,
            added: 1.0,
        }

        request: {
            /// User ID to query.
            #[ruma_api(query)]
            pub user_id: &'a UserId,

            /// Profile field to query.
            #[serde(skip_serializing_if = "Option::is_none")]
            #[ruma_api(query)]
            pub field: Option<&'a ProfileField>,
        }

        #[derive(Default)]
        response: {
            /// Display name of the user.
            #[serde(skip_serializing_if = "Option::is_none")]
            pub displayname: Option<String>,

            /// Avatar URL for the user's avatar.
            ///
            /// If you activate the `compat` feature, this field being an empty string in JSON will result
            /// in `None` here during deserialization.
            #[serde(skip_serializing_if = "Option::is_none")]
            #[cfg_attr(
                feature = "compat",
                serde(default, deserialize_with = "ruma_common::serde::empty_string_as_none")
            )]
            pub avatar_url: Option<OwnedMxcUri>,

            /// The [BlurHash](https://blurha.sh) for the avatar pointed to by `avatar_url`.
            ///
            /// This uses the unstable prefix in
            /// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
            #[cfg(feature = "unstable-msc2448")]
            #[serde(rename = "xyz.amorgan.blurhash", skip_serializing_if = "Option::is_none")]
            pub blurhash: Option<String>,
        }
    }

    impl<'a> Request<'a> {
        /// Creates a new `Request` with the given user id.
        pub fn new(user_id: &'a UserId) -> Self {
            Self { user_id, field: None }
        }
    }

    impl Response {
        /// Creates an empty `Response`.
        pub fn new() -> Self {
            Default::default()
        }
    }

    /// Profile fields to specify in query.
    ///
    /// This type can hold an arbitrary string. To build this with a custom value, convert it from a
    /// string with `::from() / .into()`. To check for values that are not available as a
    /// documented variant here, use its string representation, obtained through
    /// [`.as_str()`](Self::as_str()).
    #[derive(Clone, Debug, PartialEq, Eq, StringEnum)]
    #[non_exhaustive]
    pub enum ProfileField {
        /// Display name of the user.
        #[ruma_enum(rename = "displayname")]
        DisplayName,

        /// Avatar URL for the user's avatar.
        #[ruma_enum(rename = "avatar_url")]
        AvatarUrl,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }
}
<|endoftext|>


<commit_before>pub fn is_leap_year(year: i32) -> bool {
    if year % 400 == 0 {
        true
    } else if year % 100 == 0 {
        false
    } else { year % 4 == 0 }
}
<commit_msg>cargo fmt --all<commit_after>pub fn is_leap_year(year: i32) -> bool {
    if year % 400 == 0 {
        true
    } else if year % 100 == 0 {
        false
    } else {
        year % 4 == 0
    }
}
<|endoftext|>


<commit_before>use libc::c_int;

use super::ffi;

use {SqliteResult, SqliteError, SqliteConnection, SqliteStatement, SqliteRows, SqliteRow,
     str_to_cstring};
use types::ToSql;

impl SqliteConnection {
    /// Convenience method to prepare and execute a single SQL statement with named parameter(s).
    ///
    /// On success, returns the number of rows that were changed or inserted or deleted (via
    /// `sqlite3_changes`).
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// # use rusqlite::{SqliteConnection, SqliteResult};
    /// fn insert(conn: &SqliteConnection) -> SqliteResult<i32> {
    ///     conn.execute_named("INSERT INTO test (name) VALUES (:name)", &[(":name", &"one")])
    /// }
    /// ```
    ///
    /// # Failure
    ///
    /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
    /// underlying SQLite call fails.
    pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> SqliteResult<c_int> {
        self.prepare(sql).and_then(|mut stmt| stmt.execute_named(params))
    }

    /// Convenience method to execute a query with named parameter(s) that is expected to return
    /// a single row.
    ///
    /// If the query returns more than one row, all rows except the first are ignored.
    ///
    /// # Failure
    ///
    /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
    /// underlying SQLite call fails.
    pub fn query_row_named<T, F>(&self,
                                 sql: &str,
                                 params: &[(&str, &ToSql)],
                                 f: F)
                                 -> SqliteResult<T>
        where F: FnOnce(SqliteRow) -> T
    {
        let mut stmt = try!(self.prepare(sql));
        let mut rows = try!(stmt.query_named(params));

        rows.get_expected_row().map(f)
    }
}

impl<'conn> SqliteStatement<'conn> {
    /// Return the index of an SQL parameter given its name.
    ///
    /// # Failure
    ///
    /// Will return Err if `name` is invalid. Will return Ok(None) if the name
    /// is valid but not a bound parameter of this statement.
    pub fn parameter_index(&self, name: &str) -> SqliteResult<Option<i32>> {
        let c_name = try!(str_to_cstring(name));
        let c_index = unsafe { ffi::sqlite3_bind_parameter_index(self.stmt, c_name.as_ptr()) };
        Ok(match c_index {
            0 => None, // A zero is returned if no matching parameter is found.
            n => Some(n),
        })
    }

    /// Execute the prepared statement with named parameter(s).
    ///
    /// On success, returns the number of rows that were changed or inserted or deleted (via
    /// `sqlite3_changes`).
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// # use rusqlite::{SqliteConnection, SqliteResult};
    /// fn insert(conn: &SqliteConnection) -> SqliteResult<i32> {
    ///     let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)"));
    ///     stmt.execute_named(&[(":name", &"one")])
    /// }
    /// ```
    ///
    /// # Failure
    ///
    /// Will return `Err` if binding parameters fails, the executed statement returns rows (in
    /// which case `query` should be used instead), or the underling SQLite call fails.
    pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult<c_int> {
        try!(self.bind_named_parameters(params));
        unsafe {
            self.execute_()
        }
    }

    /// Execute the prepared statement with named parameter(s), returning an iterator over the
    /// resulting rows.
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// # use rusqlite::{SqliteConnection, SqliteResult, SqliteRows};
    /// fn query(conn: &SqliteConnection) -> SqliteResult<()> {
    ///     let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name"));
    ///     let mut rows = try!(stmt.query_named(&[(":name", &"one")]));
    ///     for row in rows {
    ///         // ...
    ///     }
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Failure
    ///
    /// Will return `Err` if binding parameters fails.
    pub fn query_named<'a>(&'a mut self,
                           params: &[(&str, &ToSql)])
                           -> SqliteResult<SqliteRows<'a>> {
        self.reset_if_needed();
        try!(self.bind_named_parameters(params));

        self.needs_reset = true;
        Ok(SqliteRows::new(self))
    }

    fn bind_named_parameters(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult<()> {
        // Always check that the number of parameters is correct.
        assert!(params.len() as c_int == unsafe { ffi::sqlite3_bind_parameter_count(self.stmt) },
                "incorrect number of parameters to query(): expected {}, got {}",
                unsafe { ffi::sqlite3_bind_parameter_count(self.stmt) },
                params.len());

        // In debug, also sanity check that we got distinct parameter names.
        debug_assert!({
                          use std::collections::HashSet;

                          let mut s = HashSet::with_capacity(params.len());
                          for &(name, _) in params {
                              s.insert(name);
                          }

                          s.len() == params.len()
                      },
                      "named parameters must be unique");

        for &(name, value) in params {
            if let Some(i) = try!(self.parameter_index(name)) {
                try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt, i) }));
            } else {
                return Err(SqliteError {
                    code: ffi::SQLITE_MISUSE,
                    message: format!("Invalid parameter name: {}", name),
                });
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use SqliteConnection;

    #[test]
    fn test_execute_named() {
        let db = SqliteConnection::open_in_memory().unwrap();
        db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap();

        assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &1i32)]).unwrap(),
                   1);
        assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &2i32)]).unwrap(),
                   1);

        assert_eq!(3i32,
                   db.query_row_named("SELECT SUM(x) FROM foo WHERE x > :x",
                                      &[(":x", &0i32)],
                                      |r| r.get(0))
                     .unwrap());
    }

    #[test]
    fn test_stmt_execute_named() {
        let db = SqliteConnection::open_in_memory().unwrap();
        let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
                   INTEGER)";
        db.execute_batch(sql).unwrap();

        let mut stmt = db.prepare("INSERT INTO test (name) VALUES (:name)").unwrap();
        stmt.execute_named(&[(":name", &"one")]).unwrap();

        assert_eq!(1i32,
                   db.query_row_named("SELECT COUNT(*) FROM test WHERE name = :name",
                                      &[(":name", &"one")],
                                      |r| r.get(0))
                     .unwrap());
    }

    #[test]
    fn test_query_named() {
        let db = SqliteConnection::open_in_memory().unwrap();
        let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
                   INTEGER)";
        db.execute_batch(sql).unwrap();

        let mut stmt = db.prepare("SELECT * FROM test where name = :name").unwrap();
        stmt.query_named(&[(":name", &"one")]).unwrap();
    }

    #[test]
    #[should_panic]
    fn test_panic_on_incorrect_number_of_parameters() {
        let db = SqliteConnection::open_in_memory().unwrap();

        let mut stmt = db.prepare("SELECT 1 WHERE 1 = :one AND 2 = :two").unwrap();
        let _ = stmt.query_named(&[(":one", &1i32)]);
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn test_debug_panic_on_incorrect_parameter_names() {
        let db = SqliteConnection::open_in_memory().unwrap();

        let mut stmt = db.prepare("SELECT 1 WHERE 1 = :one AND 2 = :two").unwrap();
        let _ = stmt.query_named(&[(":one", &1i32), (":one", &2i32)]);
    }
}
<commit_msg>Rename bind_named_parameters -> bind_parameters_named.<commit_after>use libc::c_int;

use super::ffi;

use {SqliteResult, SqliteError, SqliteConnection, SqliteStatement, SqliteRows, SqliteRow,
     str_to_cstring};
use types::ToSql;

impl SqliteConnection {
    /// Convenience method to prepare and execute a single SQL statement with named parameter(s).
    ///
    /// On success, returns the number of rows that were changed or inserted or deleted (via
    /// `sqlite3_changes`).
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// # use rusqlite::{SqliteConnection, SqliteResult};
    /// fn insert(conn: &SqliteConnection) -> SqliteResult<i32> {
    ///     conn.execute_named("INSERT INTO test (name) VALUES (:name)", &[(":name", &"one")])
    /// }
    /// ```
    ///
    /// # Failure
    ///
    /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
    /// underlying SQLite call fails.
    pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> SqliteResult<c_int> {
        self.prepare(sql).and_then(|mut stmt| stmt.execute_named(params))
    }

    /// Convenience method to execute a query with named parameter(s) that is expected to return
    /// a single row.
    ///
    /// If the query returns more than one row, all rows except the first are ignored.
    ///
    /// # Failure
    ///
    /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
    /// underlying SQLite call fails.
    pub fn query_row_named<T, F>(&self,
                                 sql: &str,
                                 params: &[(&str, &ToSql)],
                                 f: F)
                                 -> SqliteResult<T>
        where F: FnOnce(SqliteRow) -> T
    {
        let mut stmt = try!(self.prepare(sql));
        let mut rows = try!(stmt.query_named(params));

        rows.get_expected_row().map(f)
    }
}

impl<'conn> SqliteStatement<'conn> {
    /// Return the index of an SQL parameter given its name.
    ///
    /// # Failure
    ///
    /// Will return Err if `name` is invalid. Will return Ok(None) if the name
    /// is valid but not a bound parameter of this statement.
    pub fn parameter_index(&self, name: &str) -> SqliteResult<Option<i32>> {
        let c_name = try!(str_to_cstring(name));
        let c_index = unsafe { ffi::sqlite3_bind_parameter_index(self.stmt, c_name.as_ptr()) };
        Ok(match c_index {
            0 => None, // A zero is returned if no matching parameter is found.
            n => Some(n),
        })
    }

    /// Execute the prepared statement with named parameter(s).
    ///
    /// On success, returns the number of rows that were changed or inserted or deleted (via
    /// `sqlite3_changes`).
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// # use rusqlite::{SqliteConnection, SqliteResult};
    /// fn insert(conn: &SqliteConnection) -> SqliteResult<i32> {
    ///     let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)"));
    ///     stmt.execute_named(&[(":name", &"one")])
    /// }
    /// ```
    ///
    /// # Failure
    ///
    /// Will return `Err` if binding parameters fails, the executed statement returns rows (in
    /// which case `query` should be used instead), or the underling SQLite call fails.
    pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult<c_int> {
        try!(self.bind_parameters_named(params));
        unsafe {
            self.execute_()
        }
    }

    /// Execute the prepared statement with named parameter(s), returning an iterator over the
    /// resulting rows.
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// # use rusqlite::{SqliteConnection, SqliteResult, SqliteRows};
    /// fn query(conn: &SqliteConnection) -> SqliteResult<()> {
    ///     let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name"));
    ///     let mut rows = try!(stmt.query_named(&[(":name", &"one")]));
    ///     for row in rows {
    ///         // ...
    ///     }
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Failure
    ///
    /// Will return `Err` if binding parameters fails.
    pub fn query_named<'a>(&'a mut self,
                           params: &[(&str, &ToSql)])
                           -> SqliteResult<SqliteRows<'a>> {
        self.reset_if_needed();
        try!(self.bind_parameters_named(params));

        self.needs_reset = true;
        Ok(SqliteRows::new(self))
    }

    fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult<()> {
        // Always check that the number of parameters is correct.
        assert!(params.len() as c_int == unsafe { ffi::sqlite3_bind_parameter_count(self.stmt) },
                "incorrect number of parameters to query(): expected {}, got {}",
                unsafe { ffi::sqlite3_bind_parameter_count(self.stmt) },
                params.len());

        // In debug, also sanity check that we got distinct parameter names.
        debug_assert!({
                          use std::collections::HashSet;

                          let mut s = HashSet::with_capacity(params.len());
                          for &(name, _) in params {
                              s.insert(name);
                          }

                          s.len() == params.len()
                      },
                      "named parameters must be unique");

        for &(name, value) in params {
            if let Some(i) = try!(self.parameter_index(name)) {
                try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt, i) }));
            } else {
                return Err(SqliteError {
                    code: ffi::SQLITE_MISUSE,
                    message: format!("Invalid parameter name: {}", name),
                });
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use SqliteConnection;

    #[test]
    fn test_execute_named() {
        let db = SqliteConnection::open_in_memory().unwrap();
        db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap();

        assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &1i32)]).unwrap(),
                   1);
        assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &2i32)]).unwrap(),
                   1);

        assert_eq!(3i32,
                   db.query_row_named("SELECT SUM(x) FROM foo WHERE x > :x",
                                      &[(":x", &0i32)],
                                      |r| r.get(0))
                     .unwrap());
    }

    #[test]
    fn test_stmt_execute_named() {
        let db = SqliteConnection::open_in_memory().unwrap();
        let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
                   INTEGER)";
        db.execute_batch(sql).unwrap();

        let mut stmt = db.prepare("INSERT INTO test (name) VALUES (:name)").unwrap();
        stmt.execute_named(&[(":name", &"one")]).unwrap();

        assert_eq!(1i32,
                   db.query_row_named("SELECT COUNT(*) FROM test WHERE name = :name",
                                      &[(":name", &"one")],
                                      |r| r.get(0))
                     .unwrap());
    }

    #[test]
    fn test_query_named() {
        let db = SqliteConnection::open_in_memory().unwrap();
        let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
                   INTEGER)";
        db.execute_batch(sql).unwrap();

        let mut stmt = db.prepare("SELECT * FROM test where name = :name").unwrap();
        stmt.query_named(&[(":name", &"one")]).unwrap();
    }

    #[test]
    #[should_panic]
    fn test_panic_on_incorrect_number_of_parameters() {
        let db = SqliteConnection::open_in_memory().unwrap();

        let mut stmt = db.prepare("SELECT 1 WHERE 1 = :one AND 2 = :two").unwrap();
        let _ = stmt.query_named(&[(":one", &1i32)]);
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn test_debug_panic_on_incorrect_parameter_names() {
        let db = SqliteConnection::open_in_memory().unwrap();

        let mut stmt = db.prepare("SELECT 1 WHERE 1 = :one AND 2 = :two").unwrap();
        let _ = stmt.query_named(&[(":one", &1i32), (":one", &2i32)]);
    }
}
<|endoftext|>


<commit_before>#![cfg(feature = "std")]

#[macro_use]
extern crate criterion;
#[macro_use]
extern crate combine;

use std::fmt;

use {
    combine::{
        many, many1,
        parser::range::{range, take_while1},
        stream::easy,
        token, ParseError, Parser, RangeStream,
    },
    criterion::{black_box, Bencher, Criterion},
};

#[derive(Debug)]
struct Request<'a> {
    method: &'a [u8],
    uri: &'a [u8],
    version: &'a [u8],
}

#[derive(Debug)]
struct Header<'a> {
    name: &'a [u8],
    value: Vec<&'a [u8]>,
}

fn is_token(c: u8) -> bool {
    !matches!(
        c,
        128..=255
        | 0..=31
        | b'('
        | b')'
        | b'<'
        | b'>'
        | b'@'
        | b','
        | b';'
        | b':'
        | b'\\'
        | b'"'
        | b'/'
        | b'['
        | b']'
        | b'?'
        | b'='
        | b'{'
        | b'}'
        | b' '
    )
}

fn is_horizontal_space(c: u8) -> bool {
    c == b' ' || c == b'\t'
}
fn is_space(c: u8) -> bool {
    c == b' '
}
fn is_not_space(c: u8) -> bool {
    c != b' '
}
fn is_http_version(c: u8) -> bool {
    (b'0'..=b'9').contains(&c) || c == b'.'
}

fn end_of_line<'a, Input>() -> impl Parser<Input, Output = u8>
where
    Input: RangeStream<Token = u8, Range = &'a [u8]>,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
    (token(b'\r'), token(b'\n')).map(|_| b'\r').or(token(b'\n'))
}

fn message_header<'a, Input>() -> impl Parser<Input, Output = Header<'a>>
where
    Input: RangeStream<Token = u8, Range = &'a [u8]>,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
    let message_header_line = (
        take_while1(is_horizontal_space),
        take_while1(|c| c != b'\r' && c != b'\n'),
        end_of_line(),
    )
        .map(|(_, line, _)| line);

    struct_parser!(Header {
        name: take_while1(is_token),
        _: token(b':'),
        value: many1(message_header_line),
    })
}

type HttpRequest<'a> = (Request<'a>, Vec<Header<'a>>);

fn parse_http_request<'a, Input>(input: Input) -> Result<(HttpRequest<'a>, Input), Input::Error>
where
    Input: RangeStream<Token = u8, Range = &'a [u8]>,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
    let http_version = range(&b"HTTP/"[..]).with(take_while1(is_http_version));

    let request_line = struct_parser!(Request {
        method: take_while1(is_token),
        _: take_while1(is_space),
        uri: take_while1(is_not_space),
        _: take_while1(is_space),
        version: http_version,
    });

    let mut request = (
        request_line,
        end_of_line(),
        many(message_header()),
        end_of_line(),
    )
        .map(|(request, _, headers, _)| (request, headers));

    request.parse(input)
}

static REQUESTS: &[u8] = include_bytes!("http-requests.txt");

fn http_requests_small(b: &mut Bencher<'_>) {
    http_requests_bench(b, easy::Stream(REQUESTS))
}

fn http_requests_large(b: &mut Bencher<'_>) {
    use std::iter;

    let mut buffer = Vec::with_capacity(REQUESTS.len() * 5);
    for buf in iter::repeat(REQUESTS).take(5) {
        buffer.extend_from_slice(buf);
    }
    http_requests_bench(b, easy::Stream(&buffer[..]))
}

fn http_requests_large_cheap_error(b: &mut Bencher<'_>) {
    use std::iter;

    let mut buffer = Vec::with_capacity(REQUESTS.len() * 5);
    for buf in iter::repeat(REQUESTS).take(5) {
        buffer.extend_from_slice(buf);
    }
    http_requests_bench(b, &buffer[..])
}

fn http_requests_bench<'a, Input>(b: &mut Bencher<'_>, buffer: Input)
where
    Input: RangeStream<Token = u8, Range = &'a [u8]> + Clone,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position> + fmt::Debug,
{
    b.iter(|| {
        let mut buf = black_box(buffer.clone());

        while buf.clone().uncons().is_ok() {
            match parse_http_request(buf) {
                Ok(((_, _), b)) => {
                    buf = b;
                }
                Err(err) => panic!("{:?}", err),
            }
        }
    });
}

fn http_requests(c: &mut Criterion) {
    c.bench_function("http_requests_small", http_requests_small);
    c.bench_function("http_requests_large", http_requests_large);
    c.bench_function(
        "http_requests_large_cheap_error",
        http_requests_large_cheap_error,
    );
}

criterion_group!(http, http_requests,);
criterion_main!(http);
<commit_msg>Fix some warnings in benchmark code<commit_after>#![cfg(feature = "std")]

#[macro_use]
extern crate criterion;
#[macro_use]
extern crate combine;

use std::fmt;

use {
    combine::{
        many, many1,
        parser::range::{range, take_while1},
        stream::easy,
        token, ParseError, Parser, RangeStream,
    },
    criterion::{black_box, Bencher, Criterion},
};

#[allow(dead_code)]
#[derive(Debug)]
struct Request<'a> {
    method: &'a [u8],
    uri: &'a [u8],
    version: &'a [u8],
}

#[allow(dead_code)]
#[derive(Debug)]
struct Header<'a> {
    name: &'a [u8],
    value: Vec<&'a [u8]>,
}

fn is_token(c: u8) -> bool {
    !matches!(
        c,
        128..=255
        | 0..=31
        | b'('
        | b')'
        | b'<'
        | b'>'
        | b'@'
        | b','
        | b';'
        | b':'
        | b'\\'
        | b'"'
        | b'/'
        | b'['
        | b']'
        | b'?'
        | b'='
        | b'{'
        | b'}'
        | b' '
    )
}

fn is_horizontal_space(c: u8) -> bool {
    c == b' ' || c == b'\t'
}
fn is_space(c: u8) -> bool {
    c == b' '
}
fn is_not_space(c: u8) -> bool {
    c != b' '
}
fn is_http_version(c: u8) -> bool {
    (b'0'..=b'9').contains(&c) || c == b'.'
}

fn end_of_line<'a, Input>() -> impl Parser<Input, Output = u8>
where
    Input: RangeStream<Token = u8, Range = &'a [u8]>,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
    (token(b'\r'), token(b'\n')).map(|_| b'\r').or(token(b'\n'))
}

fn message_header<'a, Input>() -> impl Parser<Input, Output = Header<'a>>
where
    Input: RangeStream<Token = u8, Range = &'a [u8]>,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
    let message_header_line = (
        take_while1(is_horizontal_space),
        take_while1(|c| c != b'\r' && c != b'\n'),
        end_of_line(),
    )
        .map(|(_, line, _)| line);

    struct_parser!(Header {
        name: take_while1(is_token),
        _: token(b':'),
        value: many1(message_header_line),
    })
}

type HttpRequest<'a> = (Request<'a>, Vec<Header<'a>>);

fn parse_http_request<'a, Input>(input: Input) -> Result<(HttpRequest<'a>, Input), Input::Error>
where
    Input: RangeStream<Token = u8, Range = &'a [u8]>,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
    let http_version = range(&b"HTTP/"[..]).with(take_while1(is_http_version));

    let request_line = struct_parser!(Request {
        method: take_while1(is_token),
        _: take_while1(is_space),
        uri: take_while1(is_not_space),
        _: take_while1(is_space),
        version: http_version,
    });

    let mut request = (
        request_line,
        end_of_line(),
        many(message_header()),
        end_of_line(),
    )
        .map(|(request, _, headers, _)| (request, headers));

    request.parse(input)
}

static REQUESTS: &[u8] = include_bytes!("http-requests.txt");

fn http_requests_small(b: &mut Bencher<'_>) {
    http_requests_bench(b, easy::Stream(REQUESTS))
}

fn http_requests_large(b: &mut Bencher<'_>) {
    use std::iter;

    let mut buffer = Vec::with_capacity(REQUESTS.len() * 5);
    for buf in iter::repeat(REQUESTS).take(5) {
        buffer.extend_from_slice(buf);
    }
    http_requests_bench(b, easy::Stream(&buffer[..]))
}

fn http_requests_large_cheap_error(b: &mut Bencher<'_>) {
    use std::iter;

    let mut buffer = Vec::with_capacity(REQUESTS.len() * 5);
    for buf in iter::repeat(REQUESTS).take(5) {
        buffer.extend_from_slice(buf);
    }
    http_requests_bench(b, &buffer[..])
}

fn http_requests_bench<'a, Input>(b: &mut Bencher<'_>, buffer: Input)
where
    Input: RangeStream<Token = u8, Range = &'a [u8]> + Clone,
    Input::Error: ParseError<Input::Token, Input::Range, Input::Position> + fmt::Debug,
{
    b.iter(|| {
        let mut buf = black_box(buffer.clone());

        while buf.clone().uncons().is_ok() {
            match parse_http_request(buf) {
                Ok(((_, _), b)) => {
                    buf = b;
                }
                Err(err) => panic!("{:?}", err),
            }
        }
    });
}

fn http_requests(c: &mut Criterion) {
    c.bench_function("http_requests_small", http_requests_small);
    c.bench_function("http_requests_large", http_requests_large);
    c.bench_function(
        "http_requests_large_cheap_error",
        http_requests_large_cheap_error,
    );
}

criterion_group!(http, http_requests,);
criterion_main!(http);
<|endoftext|>


<commit_before>use krate::Crate;
use schema::badges;
use util::CargoResult;

use diesel::pg::{Pg, PgConnection};
use diesel::prelude::*;
use serde_json;
use std::collections::HashMap;

#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")]
pub enum Badge {
    TravisCi {
        repository: String,
        branch: Option<String>,
    },
    Appveyor {
        repository: String,
        branch: Option<String>,
        service: Option<String>,
    },
    #[serde(rename = "gitlab")]
    GitLab {
        repository: String,
        branch: Option<String>,
    },
    CircleCi {
        repository: String,
        branch: Option<String>,
    },
    IsItMaintainedIssueResolution { repository: String },
    IsItMaintainedOpenIssues { repository: String },
    Codecov {
        repository: String,
        branch: Option<String>,
        service: Option<String>,
    },
    Coveralls {
        repository: String,
        branch: Option<String>,
        service: Option<String>,
    },
    Maintenance { value: MaintenanceValue },
}

#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub enum MaintenanceValue {
    #[serde(rename = "actively-developed")]
    ActivelyDeveloped,

    #[serde(rename = "passively-maintained")]
    PassivelyMaintained,

    #[serde(rename = "as-is")]
    AsIs,

    #[serde(rename = "none")]
    None,

    #[serde(rename = "experimental")]
    Experimental,

    #[serde(rename = "looking-for-maintainer")]
    LookingForMaintainer,

    #[serde(rename = "deprecated")]
    Deprecated,
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct EncodableBadge {
    pub badge_type: String,
    pub attributes: HashMap<String, Option<String>>,
}

impl Queryable<badges::SqlType, Pg> for Badge {
    type Row = (i32, String, serde_json::Value);

    fn build((_, badge_type, attributes): Self::Row) -> Self {
        let json = json!({"badge_type": badge_type, "attributes": attributes});
        serde_json::from_value(json).expect("Invalid CI badge in the database")
    }
}

impl Badge {
    pub fn encodable(self) -> EncodableBadge {
        serde_json::from_value(serde_json::to_value(self).unwrap()).unwrap()
    }

    pub fn update_crate<'a>(
        conn: &PgConnection,
        krate: &Crate,
        badges: Option<&'a HashMap<String, HashMap<String, String>>>,
    ) -> CargoResult<Vec<&'a str>> {
        use diesel::{insert, delete};

        #[derive(Insertable)]
        #[table_name = "badges"]
        struct NewBadge<'a> {
            crate_id: i32,
            badge_type: &'a str,
            attributes: serde_json::Value,
        }

        let mut invalid_badges = vec![];
        let mut new_badges = vec![];

        if let Some(badges) = badges {
            for (k, v) in badges {
                let attributes_json = serde_json::to_value(v).unwrap();

                let json = json!({"badge_type": k, "attributes": attributes_json});
                if serde_json::from_value::<Badge>(json).is_ok() {
                    new_badges.push(NewBadge {
                        crate_id: krate.id,
                        badge_type: &**k,
                        attributes: attributes_json,
                    });
                } else {
                    invalid_badges.push(&**k);
                }
            }
        }

        conn.transaction(|| {
            delete(badges::table.filter(badges::crate_id.eq(krate.id)))
                .execute(conn)?;
            insert(&new_badges).into(badges::table).execute(conn)?;
            Ok(invalid_badges)
        })
    }
}
<commit_msg>Refactor to an enum-wide serde rename<commit_after>use krate::Crate;
use schema::badges;
use util::CargoResult;

use diesel::pg::{Pg, PgConnection};
use diesel::prelude::*;
use serde_json;
use std::collections::HashMap;

#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")]
pub enum Badge {
    TravisCi {
        repository: String,
        branch: Option<String>,
    },
    Appveyor {
        repository: String,
        branch: Option<String>,
        service: Option<String>,
    },
    #[serde(rename = "gitlab")]
    GitLab {
        repository: String,
        branch: Option<String>,
    },
    CircleCi {
        repository: String,
        branch: Option<String>,
    },
    IsItMaintainedIssueResolution { repository: String },
    IsItMaintainedOpenIssues { repository: String },
    Codecov {
        repository: String,
        branch: Option<String>,
        service: Option<String>,
    },
    Coveralls {
        repository: String,
        branch: Option<String>,
        service: Option<String>,
    },
    Maintenance { value: MaintenanceValue },
}

#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum MaintenanceValue {
    ActivelyDeveloped,
    PassivelyMaintained,
    AsIs,
    None,
    Experimental,
    LookingForMaintainer,
    Deprecated,
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct EncodableBadge {
    pub badge_type: String,
    pub attributes: HashMap<String, Option<String>>,
}

impl Queryable<badges::SqlType, Pg> for Badge {
    type Row = (i32, String, serde_json::Value);

    fn build((_, badge_type, attributes): Self::Row) -> Self {
        let json = json!({"badge_type": badge_type, "attributes": attributes});
        serde_json::from_value(json).expect("Invalid CI badge in the database")
    }
}

impl Badge {
    pub fn encodable(self) -> EncodableBadge {
        serde_json::from_value(serde_json::to_value(self).unwrap()).unwrap()
    }

    pub fn update_crate<'a>(
        conn: &PgConnection,
        krate: &Crate,
        badges: Option<&'a HashMap<String, HashMap<String, String>>>,
    ) -> CargoResult<Vec<&'a str>> {
        use diesel::{insert, delete};

        #[derive(Insertable)]
        #[table_name = "badges"]
        struct NewBadge<'a> {
            crate_id: i32,
            badge_type: &'a str,
            attributes: serde_json::Value,
        }

        let mut invalid_badges = vec![];
        let mut new_badges = vec![];

        if let Some(badges) = badges {
            for (k, v) in badges {
                let attributes_json = serde_json::to_value(v).unwrap();

                let json = json!({"badge_type": k, "attributes": attributes_json});
                if serde_json::from_value::<Badge>(json).is_ok() {
                    new_badges.push(NewBadge {
                        crate_id: krate.id,
                        badge_type: &**k,
                        attributes: attributes_json,
                    });
                } else {
                    invalid_badges.push(&**k);
                }
            }
        }

        conn.transaction(|| {
            delete(badges::table.filter(badges::crate_id.eq(krate.id)))
                .execute(conn)?;
            insert(&new_badges).into(badges::table).execute(conn)?;
            Ok(invalid_badges)
        })
    }
}
<|endoftext|>


<commit_before>extern crate ncurses;
use ncurses::*;
use Cursorstate;
use std::cmp;

pub fn draw(
    buf: &[u8],
    cursorpos: usize,
    cols: usize,
    command: &String,
    debug: &mut String,
    cstate: Cursorstate,
    screenoffset: usize,
) {
    erase();

    debug.clear();
//    let screensize = get_screen_size(cols);
//    debug.push_str(&format!("   screensize:{:?}", screensize));
//    debug.push_str(&format!("   screenoffset:{:?}", screenoffset));
//    debug.push_str(&format!("   buf.len():{:?}", buf.len()));

    let screenheight: usize;
    screenheight = getmaxy(stdscr()) as usize;
//    debug.push_str(&format!("   screenheight:{:?}", screenheight));

    let mut tmpbuflen = buf.len();
    if tmpbuflen >= 1 { tmpbuflen -= 1; }
    let rows = tmpbuflen / cols + 1;

//    debug.push_str(&format!("   rows:{:?}", rows));

    for z in 0..rows {
        // 8 hex digits (4GB/cols or 0.25GB@cols=SPALTEN)
        printw(&format!("{:08X}: ", get_absolute_line(cols, screenoffset, z)));
        // Additional space between line number and hex
        printw(" ");
        for s in 0..cols {
            let pos: usize = z*cols + s;
            if pos < buf.len() {

                color_left_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw(&format!("{:01X}", buf[pos] >> 4));
                color_left_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                color_right_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw(&format!("{:01X}", buf[pos] & 0x0F));
                color_right_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                printw(" ");
            } else if pos == buf.len() {

                color_left_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw("-");
                color_left_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                color_right_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw("-");
                color_right_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                printw(" ");
            } else {
                printw("-- ");
            }
        }
        // Additional space between hex and ascii
        printw(" ");
        for s in 0..cols {
            let pos: usize = z*cols + s;
            color_ascii_cond(true, pos+cols*screenoffset == cursorpos, cstate);
            if pos < buf.len() {
                if let c @ 32...126 = buf[pos] {
                    if c as char == '%' {
                        // '%' needs to be escaped by a '%' in ncurses
                        printw("%%");
                    } else {
                        printw(&format!("{}", c as char));
                    }
                } else {
                    // Mark non-ascii symbols
                    printw(&format!("."));
                }
            } else if pos == buf.len() {
                // Pad ascii with spaces
                printw(" ");
            }

            color_ascii_cond(false, pos+cols*screenoffset == cursorpos, cstate);
        }
        printw("\n");
    }
    for _ in 1 .. screenheight - rows {
        // Put the cursor on last line of terminal
        printw("\n");
    }
    printw(&format!("{}", command));
    printw(&format!("{}", debug));
}

fn get_absolute_line(cols: usize, screenoffset: usize, z: usize) -> usize {
    return z * cols + screenoffset * cols;
}
pub fn get_screen_size(
    cols: usize,
    ) -> usize {
    let screenheight: usize;
    screenheight = getmaxy(stdscr()) as usize;

    let mut ret: usize = 0;

    // Last line reserved for Status/Commands/etc (Like in vim)
    if screenheight >= 1 {
        ret = (screenheight-1) * cols;
    }
    return ret;
}
pub fn get_absolute_draw_indices(
    buflen: usize,
    cols: usize,
    screenoffset: usize,
    ) -> (usize, usize) {

    let max_draw_len:usize = cmp::min(buflen, get_screen_size(cols)); //hier muss bei get_screen_size noch auf 16er abgerundet werden?

    let starting_pos: usize = screenoffset * cols;
    let mut ending_pos: usize = starting_pos + max_draw_len;
    if ending_pos > buflen {
        ending_pos = buflen;
    }

    return (starting_pos, ending_pos);
}

fn color_left_nibble(color: bool, cstate: Cursorstate) {
    if color {
        if cstate == Cursorstate::Leftnibble {
            attron(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attron(A_UNDERLINE());
        }
    } else {
        if cstate == Cursorstate::Leftnibble {
            attroff(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attroff(A_UNDERLINE());
        }
    }
}
fn color_left_nibble_cond(color: bool, condition: bool, cstate: Cursorstate) {
    if condition {
        color_left_nibble(color, cstate);
    }
}

fn color_right_nibble(color: bool, cstate: Cursorstate) {
    if color {
        if cstate == Cursorstate::Rightnibble {
            attron(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attron(A_UNDERLINE());
        }
    } else {
        if cstate == Cursorstate::Rightnibble {
            attroff(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attroff(A_UNDERLINE());
        }
    }
}
fn color_right_nibble_cond(color: bool, condition: bool, cstate: Cursorstate) {
    if condition {
        color_right_nibble(color, cstate);
    }
}

fn color_ascii(color: bool, cstate: Cursorstate) {
    if color {
        if cstate == Cursorstate::Asciichar {
            attron(COLOR_PAIR(1) | A_STANDOUT());
        } else {
            attron(A_UNDERLINE());
        }
    } else {
        if cstate == Cursorstate::Asciichar {
            attroff(COLOR_PAIR(1) | A_STANDOUT());
        } else {
            attroff(A_UNDERLINE());
        }
    }
}
fn color_ascii_cond(color: bool, condition: bool, cstate: Cursorstate) {
    if condition {
        color_ascii(color, cstate);
    }
}
<commit_msg>Remove unnecessary debug.clear()<commit_after>extern crate ncurses;
use ncurses::*;
use Cursorstate;
use std::cmp;

pub fn draw(
    buf: &[u8],
    cursorpos: usize,
    cols: usize,
    command: &String,
    debug: &mut String,
    cstate: Cursorstate,
    screenoffset: usize,
) {
    erase();

//    debug.clear();
//    let screensize = get_screen_size(cols);
//    debug.push_str(&format!("   screensize:{:?}", screensize));
//    debug.push_str(&format!("   screenoffset:{:?}", screenoffset));
//    debug.push_str(&format!("   buf.len():{:?}", buf.len()));

    let screenheight: usize;
    screenheight = getmaxy(stdscr()) as usize;
//    debug.push_str(&format!("   screenheight:{:?}", screenheight));

    let mut tmpbuflen = buf.len();
    if tmpbuflen >= 1 { tmpbuflen -= 1; }
    let rows = tmpbuflen / cols + 1;

//    debug.push_str(&format!("   rows:{:?}", rows));

    for z in 0..rows {
        // 8 hex digits (4GB/cols or 0.25GB@cols=SPALTEN)
        printw(&format!("{:08X}: ", get_absolute_line(cols, screenoffset, z)));
        // Additional space between line number and hex
        printw(" ");
        for s in 0..cols {
            let pos: usize = z*cols + s;
            if pos < buf.len() {

                color_left_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw(&format!("{:01X}", buf[pos] >> 4));
                color_left_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                color_right_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw(&format!("{:01X}", buf[pos] & 0x0F));
                color_right_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                printw(" ");
            } else if pos == buf.len() {

                color_left_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw("-");
                color_left_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                color_right_nibble_cond(true, pos+cols*screenoffset == cursorpos, cstate);
                printw("-");
                color_right_nibble_cond(false, pos+cols*screenoffset == cursorpos, cstate);

                printw(" ");
            } else {
                printw("-- ");
            }
        }
        // Additional space between hex and ascii
        printw(" ");
        for s in 0..cols {
            let pos: usize = z*cols + s;
            color_ascii_cond(true, pos+cols*screenoffset == cursorpos, cstate);
            if pos < buf.len() {
                if let c @ 32...126 = buf[pos] {
                    if c as char == '%' {
                        // '%' needs to be escaped by a '%' in ncurses
                        printw("%%");
                    } else {
                        printw(&format!("{}", c as char));
                    }
                } else {
                    // Mark non-ascii symbols
                    printw(&format!("."));
                }
            } else if pos == buf.len() {
                // Pad ascii with spaces
                printw(" ");
            }

            color_ascii_cond(false, pos+cols*screenoffset == cursorpos, cstate);
        }
        printw("\n");
    }
    for _ in 1 .. screenheight - rows {
        // Put the cursor on last line of terminal
        printw("\n");
    }
    printw(&format!("{}", command));
    printw(&format!("{}", debug));
}

fn get_absolute_line(cols: usize, screenoffset: usize, z: usize) -> usize {
    return z * cols + screenoffset * cols;
}
pub fn get_screen_size(
    cols: usize,
    ) -> usize {
    let screenheight: usize;
    screenheight = getmaxy(stdscr()) as usize;

    let mut ret: usize = 0;

    // Last line reserved for Status/Commands/etc (Like in vim)
    if screenheight >= 1 {
        ret = (screenheight-1) * cols;
    }
    return ret;
}
pub fn get_absolute_draw_indices(
    buflen: usize,
    cols: usize,
    screenoffset: usize,
    ) -> (usize, usize) {

    let max_draw_len:usize = cmp::min(buflen, get_screen_size(cols)); //hier muss bei get_screen_size noch auf 16er abgerundet werden?

    let starting_pos: usize = screenoffset * cols;
    let mut ending_pos: usize = starting_pos + max_draw_len;
    if ending_pos > buflen {
        ending_pos = buflen;
    }

    return (starting_pos, ending_pos);
}

fn color_left_nibble(color: bool, cstate: Cursorstate) {
    if color {
        if cstate == Cursorstate::Leftnibble {
            attron(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attron(A_UNDERLINE());
        }
    } else {
        if cstate == Cursorstate::Leftnibble {
            attroff(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attroff(A_UNDERLINE());
        }
    }
}
fn color_left_nibble_cond(color: bool, condition: bool, cstate: Cursorstate) {
    if condition {
        color_left_nibble(color, cstate);
    }
}

fn color_right_nibble(color: bool, cstate: Cursorstate) {
    if color {
        if cstate == Cursorstate::Rightnibble {
            attron(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attron(A_UNDERLINE());
        }
    } else {
        if cstate == Cursorstate::Rightnibble {
            attroff(COLOR_PAIR(1) | A_STANDOUT());
        } else if cstate == Cursorstate::Asciichar {
            attroff(A_UNDERLINE());
        }
    }
}
fn color_right_nibble_cond(color: bool, condition: bool, cstate: Cursorstate) {
    if condition {
        color_right_nibble(color, cstate);
    }
}

fn color_ascii(color: bool, cstate: Cursorstate) {
    if color {
        if cstate == Cursorstate::Asciichar {
            attron(COLOR_PAIR(1) | A_STANDOUT());
        } else {
            attron(A_UNDERLINE());
        }
    } else {
        if cstate == Cursorstate::Asciichar {
            attroff(COLOR_PAIR(1) | A_STANDOUT());
        } else {
            attroff(A_UNDERLINE());
        }
    }
}
fn color_ascii_cond(color: bool, condition: bool, cstate: Cursorstate) {
    if condition {
        color_ascii(color, cstate);
    }
}
<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#![deny(
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

#[macro_use] extern crate log;

extern crate filters;
extern crate itertools;
extern crate regex;
extern crate semver;
extern crate toml;

extern crate libimagstore;
extern crate libimagentrytag;

// core functionality modules of the crate,
// these depend only on libimagstore

pub mod cli;
pub mod builtin;

// extended functionality of the crate
// these depend on other internal libraries than libimagstore and use the upper core modules for
// their functionality

pub mod tags;
<commit_msg>Remove unused import in libimagentryfilter<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#![deny(
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

extern crate filters;
extern crate itertools;
extern crate regex;
extern crate semver;
extern crate toml;

extern crate libimagstore;
extern crate libimagentrytag;

// core functionality modules of the crate,
// these depend only on libimagstore

pub mod cli;
pub mod builtin;

// extended functionality of the crate
// these depend on other internal libraries than libimagstore and use the upper core modules for
// their functionality

pub mod tags;
<|endoftext|>


<commit_before>extern crate bus;
extern crate time;
extern crate num_cpus;

use bus::Bus;

fn helper(buf: usize, iter: usize, rxs: usize) -> u64 {
    use std::thread;

    let mut c = Bus::new(buf);
    let wait = (0..rxs)
        .map(|_| c.add_rx())
        .map(|mut rx| {
            thread::spawn(move || {
                // use std::time::Duration;
                // let w = Duration::new(0, 10);
                loop {
                    if let Ok(true) = rx.recv() {
                        break;
                    }
                    // match rx.try_recv() {
                    // Ok(true) => break,
                    // Err(..) => thread::sleep(w),
                    // _ => (),
                    // }
                }
            })
        })
        .collect::<Vec<_>>();

    let start = time::precise_time_ns();
    for _ in 0..iter {
        c.broadcast(false)
    }

    c.broadcast(true);
    for w in wait.into_iter() {
        w.join().unwrap();
    }

    time::precise_time_ns() - start
}

fn main() {
    let num = 2_000_000;

    for threads in 1..(num_cpus::get() + 10) {
        println!("{} {} {:.*} μs/op",
                 threads,
                 1_000,
                 2,
                 helper(1_000, num, threads) as f64 / num as f64);
    }
}
<commit_msg>Let benchmarker use either try_ or blocking<commit_after>extern crate bus;
extern crate time;
extern crate num_cpus;

use bus::Bus;

const USE_TRY_RECV: bool = false;
const USE_TRY_SEND: bool = false;

fn helper(buf: usize, iter: usize, rxs: usize) -> u64 {
    use std::time::Duration;
    use std::thread;

    let mut c = Bus::new(buf);
    let wait = (0..rxs)
        .map(|_| c.add_rx())
        .map(|mut rx| {
            thread::spawn(move || {
                let w = Duration::new(0, 10);
                loop {
                    if USE_TRY_RECV {
                        match rx.try_recv() {
                            Ok(true) => break,
                            Err(..) => thread::sleep(w),
                            _ => (),
                        }
                    } else {
                        if let Ok(true) = rx.recv() {
                            break;
                        }
                    }
                }
            })
        })
        .collect::<Vec<_>>();

    let w = Duration::new(0, 10);
    let mut send = |v| {
        if USE_TRY_SEND {
            while let Err(..) = c.try_broadcast(v) {
                thread::sleep(w);
            }
        } else {
            c.broadcast(v);
        }
    };

    let start = time::precise_time_ns();
    for _ in 0..iter {
        send(false);
    }

    send(true);
    for w in wait.into_iter() {
        w.join().unwrap();
    }

    time::precise_time_ns() - start
}

fn main() {
    let num = 2_000_000;

    for threads in 1..(num_cpus::get() + 10) {
        println!("{} {} {:.*} μs/op",
                 threads,
                 1_000,
                 2,
                 helper(1_000, num, threads) as f64 / num as f64);
    }
}
<|endoftext|>


<commit_before>use base::math::*;

pub struct Camera {
    pub position: Point3f, // PRP
    pub view_up_vector: Vector3f, // VUV
    // used to calculate the look_at_point
    pub theta: f32,
    pub phi: f32,
}

impl Default for Camera {
    fn default() -> Camera {
        Camera {
            position: Point3::new(0.0, 0.0, 60.0),
            phi: 0.0,
            theta: 0.0,
            view_up_vector: Vector3::unit_z(),
        }
    }
}

impl Camera {
    /// Returns the projection matrix
    pub fn proj_matrix(&self) -> Matrix4<f32> {
        perspective(deg(60.0), 16.0 / 9.0, 0.1, 100.0)
    }

    /// Returns view matrix
    pub fn view_matrix(&self) -> Matrix4<f32> {
        Matrix4::look_at(self.position, self.get_look_at_point(), self.view_up_vector)
    }

    /// Calculates the look_at_point by using theta and phi on the unit sphere
    pub fn get_look_at_point(&self) -> Point3f {
        self.position + self.get_look_at_vector()
    }

    pub fn get_look_at_vector(&self) -> Vector3f {
        Vector3f::new(self.theta.sin() * self.phi.cos(),
                      self.theta.sin() * self.phi.sin(),
                      self.theta.cos())
    }

    pub fn move_by(&mut self, pos_diff: Vector3f) {
        self.position += pos_diff;
    }

    /// Method to call when forward or backward movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for foward movement
    pub fn move_forward(&mut self, factor: f32) {
        let mut lookatvector = self.get_look_at_vector();
        lookatvector.z = 0.0;
        lookatvector.normalize();
        lookatvector *= factor;
        self.move_by(lookatvector);
    }

    // Implement forwars, backward, left and right seperately

    /// Method to call when left or right movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for left movement
    /// `factor` has to be negative for right movement
    // pub fn move_left_right(&mut self, factor: f32) {
    //     let mut lookatvector = self.get_look_at_vector();
    //     lookatvector.z = 0.0;
    //     lookatvector.normalize();
    //     // Get the orthogonal 2d-vector, which is 90 degrees to the left
    // let mut move_dir = Vector3f::new(-lookatvector.y, lookatvector.x,
    // 0.0);
    //     move_dir *= factor;
    //     self.move_by(move_dir);
    //
    // }
    /// Method to call when upward or downward movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for upward movement
    /// `factor` has to be negative for downward movement
    // pub fn move_up_down(&mut self, factor: f32) {
    //     self.move_by(Vector3f::new(0.0, 0.0, factor));
    // }

    pub fn change_dir(&mut self, theta_diff: f32, phi_diff: f32) {
        self.theta += theta_diff;
        self.phi += phi_diff;
        // new matrix will be calculated
    }
}
<commit_msg>add documentation<commit_after>use base::math::*;

pub struct Camera {
    pub position: Point3f, // PRP
    pub view_up_vector: Vector3f, // VUV
    // used to calculate the look_at_point
    pub theta: f32,
    pub phi: f32,
}

// Initinal values
impl Default for Camera {
    fn default() -> Camera {
        Camera {
            position: Point3::new(0.0, 0.0, 60.0),
            phi: 0.0,
            theta: 0.0,
            view_up_vector: Vector3::unit_z(),
        }
    }
}

impl Camera {
    /// Returns the projection matrix
    pub fn proj_matrix(&self) -> Matrix4<f32> {
        perspective(deg(60.0), 16.0 / 9.0, 0.1, 100.0)
    }

    /// Returns view matrix
    pub fn view_matrix(&self) -> Matrix4<f32> {
        Matrix4::look_at(self.position, self.get_look_at_point(), self.view_up_vector)
    }

    /// Calculates the look_at_point by adding the current position to the
    /// look_at_vector
    pub fn get_look_at_point(&self) -> Point3f {
        self.position + self.get_look_at_vector()
    }

    /// Calculates the look_at_vector by using theta and phi on the unit sphere
    pub fn get_look_at_vector(&self) -> Vector3f {
        Vector3f::new(self.theta.sin() * self.phi.cos(),
                      self.theta.sin() * self.phi.sin(),
                      self.theta.cos())
    }

    /// Internal function to move the position of the camera
    /// Will be called by the other functions (move_forwars etc)
    pub fn move_by(&mut self, pos_diff: Vector3f) {
        self.position += pos_diff;
    }

    /// Method to call when forward or backward movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for foward movement
    pub fn move_forward(&mut self, factor: f32) {
        let mut lookatvector = self.get_look_at_vector();
        lookatvector.z = 0.0;
        lookatvector.normalize();
        lookatvector *= factor;
        self.move_by(lookatvector);
    }

    // Implement forwars, backward, left and right seperately

    /// Method to call when left or right movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for left movement
    /// `factor` has to be negative for right movement
    // pub fn move_left_right(&mut self, factor: f32) {
    //     let mut lookatvector = self.get_look_at_vector();
    //     lookatvector.z = 0.0;
    //     lookatvector.normalize();
    //     // Get the orthogonal 2d-vector, which is 90 degrees to the left
    // let mut move_dir = Vector3f::new(-lookatvector.y, lookatvector.x,
    // 0.0);
    //     move_dir *= factor;
    //     self.move_by(move_dir);
    //
    // }
    /// Method to call when upward or downward movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for upward movement
    /// `factor` has to be negative for downward movement
    // pub fn move_up_down(&mut self, factor: f32) {
    //     self.move_by(Vector3f::new(0.0, 0.0, factor));
    // }
    /// Changes `theta` and `phi` to essentially change the direction the
    /// camera looks
    pub fn change_dir(&mut self, theta_diff: f32, phi_diff: f32) {
        self.theta += theta_diff;
        self.phi += phi_diff;
    }
}
<|endoftext|>


<commit_before>// Bare MIPS32r2, little endian, softfloat
// can be used for MIPS M4K core (e.g. on PIC32MX devices)

use crate::spec::{LinkerFlavor, LldFlavor, RelocModel};
use crate::spec::{PanicStrategy, Target, TargetOptions};

pub fn target() -> Target {
    Target {
        llvm_target: "mipsel-unknown-none".to_string(),
        target_endian: "little".to_string(),
        pointer_width: 32,
        target_c_int_width: "32".to_string(),
        data_layout: "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64".to_string(),
        arch: "mips".to_string(),
        target_os: "none".to_string(),
        target_env: String::new(),
        target_vendor: String::new(),
        linker_flavor: LinkerFlavor::Lld(LldFlavor::Ld),

        options: TargetOptions {
            cpu: "mips32r2".to_string(),
            features: "+mips32r2,+soft-float,+noabicalls".to_string(),
            max_atomic_width: Some(32),
            executables: true,
            linker: Some("rust-lld".to_owned()),
            panic_strategy: PanicStrategy::Abort,
            relocation_model: RelocModel::Static,
            emit_debug_gdb_scripts: false,
            ..Default::default()
        },
    }
}
<commit_msg>add blacklist for unsupported calling conventions<commit_after>// Bare MIPS32r2, little endian, softfloat
// can be used for MIPS M4K core (e.g. on PIC32MX devices)

use crate::spec::abi::Abi;
use crate::spec::{LinkerFlavor, LldFlavor, RelocModel};
use crate::spec::{PanicStrategy, Target, TargetOptions};

pub fn target() -> Target {
    Target {
        llvm_target: "mipsel-unknown-none".to_string(),
        target_endian: "little".to_string(),
        pointer_width: 32,
        target_c_int_width: "32".to_string(),
        data_layout: "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64".to_string(),
        arch: "mips".to_string(),
        target_os: "none".to_string(),
        target_env: String::new(),
        target_vendor: String::new(),
        linker_flavor: LinkerFlavor::Lld(LldFlavor::Ld),

        options: TargetOptions {
            cpu: "mips32r2".to_string(),
            features: "+mips32r2,+soft-float,+noabicalls".to_string(),
            max_atomic_width: Some(32),
            executables: true,
            linker: Some("rust-lld".to_owned()),
            panic_strategy: PanicStrategy::Abort,
            relocation_model: RelocModel::Static,
            unsupported_abis: vec![
                Abi::Stdcall,
                Abi::Fastcall,
                Abi::Vectorcall,
                Abi::Thiscall,
                Abi::Win64,
                Abi::SysV64,
            ],
            emit_debug_gdb_scripts: false,
            ..Default::default()
        },
    }
}
<|endoftext|>