<commit_before>use crate::expression::subselect::Subselect;
use crate::expression::{AsExpression, Expression, ValidGrouping};
use crate::pg::Pg;
use crate::query_builder::*;
use crate::result::QueryResult;
use crate::sql_types::Array;

/// Creates a PostgreSQL `ANY` expression.
///
/// As with most bare functions, this is not exported by default. You can import
/// it specifically from `diesel::pg::expression::dsl::any`, or glob import
/// `diesel::dsl::any`.
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// # use diesel::dsl::*;
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = establish_connection();
/// #     connection.execute("INSERT INTO users (name) VALUES ('Jim')").unwrap();
/// let sean = (1, "Sean".to_string());
/// let jim = (3, "Jim".to_string());
/// let data = users.filter(name.eq(any(vec!["Sean", "Jim"])));
/// assert_eq!(Ok(vec![sean, jim]), data.load(&connection));
/// # }
/// ```
pub fn any<ST, T>(vals: T) -> Any<T::Expression>
where
    T: AsArrayExpression<ST>,
{
    Any::new(vals.as_expression())
}

/// Creates a PostgreSQL `ALL` expression.
///
/// As with most bare functions, this is not exported by default. You can import
/// it specifically as `diesel::pg::expression::dsl::all`, or glob import
/// `diesel::dsl::all`.
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// # use diesel::dsl::*;
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = establish_connection();
/// #     connection.execute("INSERT INTO users (name) VALUES ('Jim')").unwrap();
/// let tess = (2, "Tess".to_string());
/// let data = users.filter(name.ne(all(vec!["Sean", "Jim"])));
/// assert_eq!(Ok(vec![tess]), data.load(&connection));
/// # }
/// ```
pub fn all<ST, T>(vals: T) -> All<T::Expression>
where
    T: AsArrayExpression<ST>,
{
    All::new(vals.as_expression())
}

#[doc(hidden)]
#[derive(Debug, Copy, Clone, QueryId, ValidGrouping)]
pub struct Any<Expr> {
    expr: Expr,
}

impl<Expr> Any<Expr> {
    fn new(expr: Expr) -> Self {
        Any { expr: expr }
    }
}

impl<Expr, ST> Expression for Any<Expr>
where
    Expr: Expression<SqlType = Array<ST>>,
{
    type SqlType = ST;
}

impl<Expr> QueryFragment<Pg> for Any<Expr>
where
    Expr: QueryFragment<Pg>,
{
    fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
        out.push_sql("ANY(");
        self.expr.walk_ast(out.reborrow())?;
        out.push_sql(")");
        Ok(())
    }
}

impl_selectable_expression!(Any<Expr>);

#[doc(hidden)]
#[derive(Debug, Copy, Clone, QueryId, ValidGrouping)]
pub struct All<Expr> {
    expr: Expr,
}

impl<Expr> All<Expr> {
    fn new(expr: Expr) -> Self {
        All { expr: expr }
    }
}

impl<Expr, ST> Expression for All<Expr>
where
    Expr: Expression<SqlType = Array<ST>>,
{
    type SqlType = ST;
}

impl<Expr> QueryFragment<Pg> for All<Expr>
where
    Expr: QueryFragment<Pg>,
{
    fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
        out.push_sql("ALL(");
        self.expr.walk_ast(out.reborrow())?;
        out.push_sql(")");
        Ok(())
    }
}

impl_selectable_expression!(All<Expr>);

pub trait AsArrayExpression<ST> {
    type Expression: Expression<SqlType = Array<ST>>;

    fn as_expression(self) -> Self::Expression;
}

impl<ST, T> AsArrayExpression<ST> for T
where
    T: AsExpression<Array<ST>>,
{
    type Expression = <T as AsExpression<Array<ST>>>::Expression;

    fn as_expression(self) -> Self::Expression {
        AsExpression::as_expression(self)
    }
}

impl<ST, S, F, W, O, L, Of, G, FU> AsArrayExpression<ST>
    for SelectStatement<S, F, W, O, L, Of, G, FU>
where
    Self: SelectQuery<SqlType = ST>,
{
    type Expression = Subselect<Self, Array<ST>>;

    fn as_expression(self) -> Self::Expression {
        Subselect::new(self)
    }
}

impl<'a, ST, QS, DB> AsArrayExpression<ST> for BoxedSelectStatement<'a, ST, QS, DB>
where
    Self: SelectQuery<SqlType = ST>,
{
    type Expression = Subselect<Self, Array<ST>>;

    fn as_expression(self) -> Self::Expression {
        Subselect::new(self)
    }
}
<commit_msg>It's not a glob-import anymore<commit_after>use crate::expression::subselect::Subselect;
use crate::expression::{AsExpression, Expression, ValidGrouping};
use crate::pg::Pg;
use crate::query_builder::*;
use crate::result::QueryResult;
use crate::sql_types::Array;

/// Creates a PostgreSQL `ANY` expression.
///
/// As with most bare functions, this is not exported by default. You can import
/// it specifically from `diesel::pg::expression::dsl::any`, or `diesel::dsl::any`.
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// # use diesel::dsl::*;
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = establish_connection();
/// #     connection.execute("INSERT INTO users (name) VALUES ('Jim')").unwrap();
/// let sean = (1, "Sean".to_string());
/// let jim = (3, "Jim".to_string());
/// let data = users.filter(name.eq(any(vec!["Sean", "Jim"])));
/// assert_eq!(Ok(vec![sean, jim]), data.load(&connection));
/// # }
/// ```
pub fn any<ST, T>(vals: T) -> Any<T::Expression>
where
    T: AsArrayExpression<ST>,
{
    Any::new(vals.as_expression())
}

/// Creates a PostgreSQL `ALL` expression.
///
/// As with most bare functions, this is not exported by default. You can import
/// it specifically as `diesel::pg::expression::dsl::all`, or `diesel::dsl::all`.
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// # use diesel::dsl::*;
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = establish_connection();
/// #     connection.execute("INSERT INTO users (name) VALUES ('Jim')").unwrap();
/// let tess = (2, "Tess".to_string());
/// let data = users.filter(name.ne(all(vec!["Sean", "Jim"])));
/// assert_eq!(Ok(vec![tess]), data.load(&connection));
/// # }
/// ```
pub fn all<ST, T>(vals: T) -> All<T::Expression>
where
    T: AsArrayExpression<ST>,
{
    All::new(vals.as_expression())
}

#[doc(hidden)]
#[derive(Debug, Copy, Clone, QueryId, ValidGrouping)]
pub struct Any<Expr> {
    expr: Expr,
}

impl<Expr> Any<Expr> {
    fn new(expr: Expr) -> Self {
        Any { expr: expr }
    }
}

impl<Expr, ST> Expression for Any<Expr>
where
    Expr: Expression<SqlType = Array<ST>>,
{
    type SqlType = ST;
}

impl<Expr> QueryFragment<Pg> for Any<Expr>
where
    Expr: QueryFragment<Pg>,
{
    fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
        out.push_sql("ANY(");
        self.expr.walk_ast(out.reborrow())?;
        out.push_sql(")");
        Ok(())
    }
}

impl_selectable_expression!(Any<Expr>);

#[doc(hidden)]
#[derive(Debug, Copy, Clone, QueryId, ValidGrouping)]
pub struct All<Expr> {
    expr: Expr,
}

impl<Expr> All<Expr> {
    fn new(expr: Expr) -> Self {
        All { expr: expr }
    }
}

impl<Expr, ST> Expression for All<Expr>
where
    Expr: Expression<SqlType = Array<ST>>,
{
    type SqlType = ST;
}

impl<Expr> QueryFragment<Pg> for All<Expr>
where
    Expr: QueryFragment<Pg>,
{
    fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
        out.push_sql("ALL(");
        self.expr.walk_ast(out.reborrow())?;
        out.push_sql(")");
        Ok(())
    }
}

impl_selectable_expression!(All<Expr>);

pub trait AsArrayExpression<ST> {
    type Expression: Expression<SqlType = Array<ST>>;

    fn as_expression(self) -> Self::Expression;
}

impl<ST, T> AsArrayExpression<ST> for T
where
    T: AsExpression<Array<ST>>,
{
    type Expression = <T as AsExpression<Array<ST>>>::Expression;

    fn as_expression(self) -> Self::Expression {
        AsExpression::as_expression(self)
    }
}

impl<ST, S, F, W, O, L, Of, G, FU> AsArrayExpression<ST>
    for SelectStatement<S, F, W, O, L, Of, G, FU>
where
    Self: SelectQuery<SqlType = ST>,
{
    type Expression = Subselect<Self, Array<ST>>;

    fn as_expression(self) -> Self::Expression {
        Subselect::new(self)
    }
}

impl<'a, ST, QS, DB> AsArrayExpression<ST> for BoxedSelectStatement<'a, ST, QS, DB>
where
    Self: SelectQuery<SqlType = ST>,
{
    type Expression = Subselect<Self, Array<ST>>;

    fn as_expression(self) -> Self::Expression {
        Subselect::new(self)
    }
}
<|endoftext|>


<commit_before>/// For some reason, Pest cannot find the grammar file if listed in parser/mod.rs, so I listed it here
use pest::Parser;
use pest::iterators::Pair;
use pest::inputs::StrInput;

use ast::Expression;

use std::f64;

const _GRAMMAR: &'static str = include_str!("grammar/grammar.pest");

#[derive(Parser)]
#[grammar = "grammar/grammar.pest"]
pub struct ExpressionParser;

fn parse_expression(input: Pair<Rule, StrInput>) -> Expression {
    match input.as_rule() {
        Rule::function_literal => {
            let mut pairs = input.into_inner();

            panic!("Nth(0): {:?}, Nth(1): {:?}, Nth(2): {:?}", pairs.nth(0), pairs.nth(1), pairs.nth(2));

            Expression::FuncLiteral(
//                format!("{}", pairs.nth(0).unwrap().into_span().as_str()),
//               Box::new(parse_expression(pairs.nth(1).unwrap().into_span())),
//                Box::new(parse_expression(pairs.nth(2).unwrap().into_span()))
                format!("{}", pairs.nth(0).unwrap().into_span().as_str()),
                Box::new(parse_expression(pairs.nth(1).unwrap())),
                Box::new(parse_expression(pairs.nth(2).unwrap()))
            )
        }

        Rule::function_call_literal => {
            let mut pairs = input.into_inner();

            println!("{:?}", pairs);

            Expression::FuncCall(
                format!("{}", pairs.nth(0).unwrap().into_span().as_str()),
                Some(Box::new(parse_expression(pairs.nth(2).unwrap())))
            )
        }

        Rule::boolean_literal =>
            Expression::Boolean(
                input.into_span().as_str().parse::<bool>().unwrap()
            ),

        Rule::string_literal =>
            Expression::String(format!("{}", input.into_span().as_str())
            ),

        Rule::identifier_literal =>
            Expression::Identifier(input.into_span().as_str().to_string()),

        // TODO: For now, just conver the value into a normal f64. No formatting!
        Rule::decimal_digits_literal =>
            Expression::Number(
                input.into_span().as_str().parse::<f64>().unwrap()
            ),

        Rule::binary_digits_literal =>
            // The parse function does not support binary digits, so do it the hard way
            Expression::Number(
                f64::from(i32::from_str_radix(&input.into_span().as_str()[2..], 2).unwrap())
            ),

        Rule::oct_digits_literal =>
            // The parse function does not support octal digits, so do it the hard way
            Expression::Number(
                f64::from(i32::from_str_radix(&input.into_span().as_str()[2..], 8).unwrap())
            ),

        Rule::hex_digits_literal =>
            // The parse function does not support hexadecimal digits, so do it the hard way
            Expression::Number(
                f64::from(i32::from_str_radix(&input.into_span().as_str()[2..], 16).unwrap())
            ),

        Rule::list_literal =>
            Expression::List(input
                            .into_inner()
                            .into_iter()
                            .map(|r| Box::new(parse_expression(r)))
                            .collect()),

        // Temporary
        _ => unreachable!()
    }

}

pub fn parse(input: String) -> Result<Expression, String> {
    // TODO: Remove unwrap
    match ExpressionParser::parse_str(Rule::main, &input) {
        Ok(mut pair) =>
            Ok(parse_expression(pair.nth(0).unwrap().into_inner().nth(0).unwrap())),

        Err(e) => Err(format!("{}", e))
    }
}<commit_msg>Change parse_expression test.<commit_after>/// For some reason, Pest cannot find the grammar file if listed in parser/mod.rs, so I listed it here
use pest::Parser;
use pest::iterators::Pair;
use pest::inputs::StrInput;

use ast::Expression;

use std::f64;

const _GRAMMAR: &'static str = include_str!("grammar/grammar.pest");

#[derive(Parser)]
#[grammar = "grammar/grammar.pest"]
pub struct ExpressionParser;

fn parse_expression(input: Pair<Rule, StrInput>) -> Expression {
    match input.as_rule() {
        Rule::function_literal => {
            let mut pairs = input.into_inner();

            panic!("Pairs: {:?}, Nth(0): {:?}, Nth(1): {:?}, Nth(2): {:?}", pairs.clone(), pairs.nth(0), pairs.nth(1), pairs.nth(2));

            Expression::FuncLiteral(
//                format!("{}", pairs.nth(0).unwrap().into_span().as_str()),
//               Box::new(parse_expression(pairs.nth(1).unwrap().into_span())),
//                Box::new(parse_expression(pairs.nth(2).unwrap().into_span()))
                format!("{}", pairs.nth(0).unwrap().into_span().as_str()),
                Box::new(parse_expression(pairs.nth(1).unwrap())),
                Box::new(parse_expression(pairs.nth(2).unwrap()))
            )
        }

        Rule::function_call_literal => {
            let mut pairs = input.into_inner();

            println!("{:?}", pairs);

            Expression::FuncCall(
                format!("{}", pairs.nth(0).unwrap().into_span().as_str()),
                Some(Box::new(parse_expression(pairs.nth(2).unwrap())))
            )
        }

        Rule::boolean_literal =>
            Expression::Boolean(
                input.into_span().as_str().parse::<bool>().unwrap()
            ),

        Rule::string_literal =>
            Expression::String(format!("{}", input.into_span().as_str())
            ),

        Rule::identifier_literal =>
            Expression::Identifier(input.into_span().as_str().to_string()),

        // TODO: For now, just conver the value into a normal f64. No formatting!
        Rule::decimal_digits_literal =>
            Expression::Number(
                input.into_span().as_str().parse::<f64>().unwrap()
            ),

        Rule::binary_digits_literal =>
            // The parse function does not support binary digits, so do it the hard way
            Expression::Number(
                f64::from(i32::from_str_radix(&input.into_span().as_str()[2..], 2).unwrap())
            ),

        Rule::oct_digits_literal =>
            // The parse function does not support octal digits, so do it the hard way
            Expression::Number(
                f64::from(i32::from_str_radix(&input.into_span().as_str()[2..], 8).unwrap())
            ),

        Rule::hex_digits_literal =>
            // The parse function does not support hexadecimal digits, so do it the hard way
            Expression::Number(
                f64::from(i32::from_str_radix(&input.into_span().as_str()[2..], 16).unwrap())
            ),

        Rule::list_literal =>
            Expression::List(input
                            .into_inner()
                            .into_iter()
                            .map(|r| Box::new(parse_expression(r)))
                            .collect()),

        // Temporary
        _ => unreachable!()
    }

}

pub fn parse(input: String) -> Result<Expression, String> {
    // TODO: Remove unwrap
    match ExpressionParser::parse_str(Rule::main, &input) {
        Ok(mut pair) =>
            Ok(parse_expression(pair.nth(0).unwrap().into_inner().nth(0).unwrap())),

        Err(e) => Err(format!("{}", e))
    }
}<|endoftext|>


<commit_before><commit_msg>Rename some parsing events for a more consistent naming scheme<commit_after><|endoftext|>


<commit_before>pub use self::os::{PROT_EXEC};
pub use self::os::{PROT_NONE};
pub use self::os::{PROT_READ};
pub use self::os::{PROT_WRITE};
pub use self::os::{MAP_FIXED};
pub use self::os::{MAP_PRIVATE};
pub use self::os::{MAP_SHARED};
pub use self::os::{MS_ASYNC};
pub use self::os::{MS_INVALIDATE};
pub use self::os::{MS_SYNC};
pub use self::os::{MCL_CURRENT};
pub use self::os::{MCL_FUTURE};
pub use self::os::{MAP_FAILED};
pub use self::os::{POSIX_MADV_DONTNEED};
pub use self::os::{POSIX_MADV_NORMAL};
pub use self::os::{POSIX_MADV_RANDOM};
pub use self::os::{POSIX_MADV_SEQUENTIAL};
pub use self::os::{POSIX_MADV_WILLNEED};

#[cfg(target_os = "linux")]
#[path = "linux/mod.rs"]
mod os;

pub fn mlock(addr: *const ::void_t, len: ::size_t) -> ::int_t {
    extern { fn mlock(addr: *const ::void_t, len: ::size_t) -> ::int_t; }
    unsafe { mlock(addr, len) }
}

pub fn mlockall(flags: ::int_t) -> ::int_t {
    extern { fn mlockall(flags: ::int_t) -> ::int_t; }
    unsafe { mlockall(flags) }
}

pub fn mmap(addr: *mut ::void_t, len: ::size_t, prot: ::int_t,
            flags: ::int_t, fd: ::int_t, offset: ::sys::types::off_t) -> *mut ::void_t {
    extern { fn mmap(addr: *mut ::void_t, len: ::size_t, prot: ::int_t, flags: ::int_t,
                     fd: ::int_t, offset: ::sys::types::off_t) -> *mut ::void_t; }
    unsafe { mmap(addr, len, prot, flags, fd, offset) }
}

pub fn mprotect(addr: *mut ::void_t, len: ::size_t, prot: ::int_t) -> ::int_t {
    extern { fn mprotect(addr: *mut ::void_t, len: ::size_t, prot: ::int_t) -> ::int_t; }
    unsafe { mprotect(addr, len, prot) }
}

pub fn msync(addr: *mut ::void_t, len: ::size_t, flags: ::int_t) -> ::int_t {
    extern { fn msync(addr: *mut ::void_t, len: ::size_t, flags: ::int_t) -> ::int_t; }
    unsafe { msync(addr, len, flags) }
}

pub fn munlock(addr: *const ::void_t, len: ::size_t) -> ::int_t {
    extern { fn munlock(addr: *const ::void_t, len: ::size_t) -> ::int_t; }
    unsafe { munlock(addr, len) }
}

pub fn munlockall() -> ::int_t {
    extern { fn munlockall() -> ::int_t; }
    unsafe { munlockall() }
}

pub fn munmap(addr: *mut ::void_t, len: ::size_t) -> ::int_t {
    extern { fn munmap(addr: *mut ::void_t, len: ::size_t) -> ::int_t; }
    unsafe { munmap(addr, len) }
}

pub fn posix_madvise(addr: *mut ::void_t, len: ::size_t, advice: ::int_t) -> ::int_t {
    extern { fn posix_madvise(addr: *mut ::void_t, len: ::size_t,
                              advice: ::int_t) -> ::int_t; }
    unsafe { posix_madvise(addr, len, advice) }
}

pub fn shm_open<T: ::NTStr>(name: &T, oflag: ::int_t,
                            mode: ::sys::types::mode_t) -> ::int_t {
    extern { fn shm_open(name: *const ::char_t, oflag: ::int_t,
                         mode: ::sys::types::mode_t) -> ::int_t; }
    unsafe { shm_open(name.as_ptr(), oflag, mode) }
}

pub fn shm_unlink<T: ::NTStr>(name: &T) -> ::int_t {
    extern { fn shm_unlink(name: *const ::char_t) -> ::int_t; }
    unsafe { shm_unlink(name.as_ptr()) }
}
<commit_msg>sys/mman.h<commit_after>pub use self::os::{PROT_EXEC};
pub use self::os::{PROT_NONE};
pub use self::os::{PROT_READ};
pub use self::os::{PROT_WRITE};
pub use self::os::{MAP_FIXED};
pub use self::os::{MAP_PRIVATE};
pub use self::os::{MAP_SHARED};
pub use self::os::{MS_ASYNC};
pub use self::os::{MS_INVALIDATE};
pub use self::os::{MS_SYNC};
pub use self::os::{MCL_CURRENT};
pub use self::os::{MCL_FUTURE};
pub use self::os::{MAP_FAILED};
pub use self::os::{POSIX_MADV_DONTNEED};
pub use self::os::{POSIX_MADV_NORMAL};
pub use self::os::{POSIX_MADV_RANDOM};
pub use self::os::{POSIX_MADV_SEQUENTIAL};
pub use self::os::{POSIX_MADV_WILLNEED};

use {void_t, size_t, int_t, NTStr, char_t};
use sys::types::{off_t, mode_t};

#[cfg(target_os = "linux")]
#[path = "linux/mod.rs"]
mod os;

pub fn mlock(addr: *const void_t, len: size_t) -> int_t {
    extern { fn mlock(addr: *const void_t, len: size_t) -> int_t; }
    unsafe { mlock(addr, len) }
}

pub fn mlockall(flags: int_t) -> int_t {
    extern { fn mlockall(flags: int_t) -> int_t; }
    unsafe { mlockall(flags) }
}

pub fn mmap(addr: *mut void_t, len: size_t, prot: int_t,
            flags: int_t, fd: int_t, offset: off_t) -> *mut void_t {
    extern { fn mmap(addr: *mut void_t, len: size_t, prot: int_t, flags: int_t,
                     fd: int_t, offset: off_t) -> *mut void_t; }
    unsafe { mmap(addr, len, prot, flags, fd, offset) }
}

pub fn mprotect(addr: *mut void_t, len: size_t, prot: int_t) -> int_t {
    extern { fn mprotect(addr: *mut void_t, len: size_t, prot: int_t) -> int_t; }
    unsafe { mprotect(addr, len, prot) }
}

pub fn msync(addr: *mut void_t, len: size_t, flags: int_t) -> int_t {
    extern { fn msync(addr: *mut void_t, len: size_t, flags: int_t) -> int_t; }
    unsafe { msync(addr, len, flags) }
}

pub fn munlock(addr: *const void_t, len: size_t) -> int_t {
    extern { fn munlock(addr: *const void_t, len: size_t) -> int_t; }
    unsafe { munlock(addr, len) }
}

pub fn munlockall() -> int_t {
    extern { fn munlockall() -> int_t; }
    unsafe { munlockall() }
}

pub fn munmap(addr: *mut void_t, len: size_t) -> int_t {
    extern { fn munmap(addr: *mut void_t, len: size_t) -> int_t; }
    unsafe { munmap(addr, len) }
}

pub fn posix_madvise(addr: *mut void_t, len: size_t, advice: int_t) -> int_t {
    extern { fn posix_madvise(addr: *mut void_t, len: size_t,
                              advice: int_t) -> int_t; }
    unsafe { posix_madvise(addr, len, advice) }
}

pub fn shm_open<T: NTStr>(name: &T, oflag: int_t,
                            mode: mode_t) -> int_t {
    extern { fn shm_open(name: *const char_t, oflag: int_t,
                         mode: mode_t) -> int_t; }
    unsafe { shm_open(name.as_ptr(), oflag, mode) }
}

pub fn shm_unlink<T: NTStr>(name: &T) -> int_t {
    extern { fn shm_unlink(name: *const char_t) -> int_t; }
    unsafe { shm_unlink(name.as_ptr()) }
}
<|endoftext|>


<commit_before>use fake::locales::{EN, ZH_TW};
use fake::Fake;

fn lorem_faker() {
    use fake::faker::lorem::raw::*;

    let val: String = Word(EN).fake();
    println!("{:?}", val);

    let val: Vec<String> = Words(EN, 3..5).fake();
    println!("{:?}", val);

    let val: String = Sentence(EN, 3..5).fake();
    println!("{:?}", val);

    let val: Vec<String> = Sentences(EN, 3..5).fake();
    println!("{:?}", val);

    let val: String = Paragraph(EN, 3..5).fake();
    println!("{:?}", val);

    let val: Vec<String> = Paragraphs(EN, 3..5).fake();
    println!("{:?}", val);
}

fn name_faker() {
    use fake::faker::name::raw::*;

    let val: String = FirstName(EN).fake();
    println!("{:?}", val);

    let val: String = LastName(EN).fake();
    println!("{:?}", val);

    let val: String = Title(EN).fake();
    println!("{:?}", val);

    let val: String = Suffix(EN).fake();
    println!("{:?}", val);

    let val: String = Name(EN).fake();
    println!("{:?}", val);

    let val: String = NameWithTitle(EN).fake();
    println!("{:?}", val);

    let val: String = Name(ZH_TW).fake();
    println!("{:?}", val);

    let val: String = NameWithTitle(ZH_TW).fake();
    println!("{:?}", val);
}

fn job_faker() {
    use fake::faker::job::raw::*;
    let val: String = Seniority(EN).fake();
    println!("{:?}", val);

    let val: String = Field(EN).fake();
    println!("{:?}", val);

    let val: String = Position(EN).fake();
    println!("{:?}", val);

    let val: String = Title(EN).fake();
    println!("{:?}", val);

    let val: Vec<String> = (Title(EN), 2..4).fake();
    println!("{:?}", val);
}

fn address_faker() {
    use fake::faker::address::raw::*;

    let val: String = CityPrefix(EN).fake();
    println!("{:?}", val);

    let val: String = CitySuffix(EN).fake();
    println!("{:?}", val);

    let val: String = CityName(EN).fake();
    println!("{:?}", val);

    let val: String = CountryName(EN).fake();
    println!("{:?}", val);

    let val: String = CountryCode(EN).fake();
    println!("{:?}", val);

    let val: String = StateName(EN).fake();
    println!("{:?}", val);

    let val: String = StateAbbr(EN).fake();
    println!("{:?}", val);

    let val: String = StreetSuffix(EN).fake();
    println!("{:?}", val);

    let val: String = StreetName(EN).fake();
    println!("{:?}", val);

    let val: String = SecondaryAddressType(EN).fake();
    println!("{:?}", val);

    let val: String = SecondaryAddress(EN).fake();
    println!("{:?}", val);

    let val: String = ZipCode(EN).fake();
    println!("{:?}", val);

    let val: String = PostCode(EN).fake();
    println!("{:?}", val);

    let val: String = BuildingNumber(EN).fake();
    println!("{:?}", val);

    let val: String = TimeZone(EN).fake();
    println!("{:?}", val);

    let val: f32 = Latitude(EN).fake();
    println!("{:?}", val);

    let val: f64 = Latitude(EN).fake();
    println!("{:?}", val);

    let val: f32 = Longitude(EN).fake();
    println!("{:?}", val);

    let val: f64 = Longitude(EN).fake();
    println!("{:?}", val);
}

fn bool_faker() {
    use fake::faker::boolean::raw::*;

    use fake::faker::boolean::en;
    let b = en::Boolean(50);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }

    //50% true
    let b = Boolean(EN, 50);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }

    // 0% true
    let b = Boolean(EN, 0);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }

    // 100% true
    let b = Boolean(EN, 100);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }
}

fn company_faker() {
    use fake::faker::company::raw::*;

    let val: String = CompanySuffix(EN).fake();
    println!("{:?}", val);

    let val: String = CompanyName(EN).fake();
    println!("{:?}", val);

    let val: String = Buzzword(EN).fake();
    println!("{:?}", val);

    let val: String = BuzzwordMiddle(EN).fake();
    println!("{:?}", val);

    let val: String = BuzzwordTail(EN).fake();
    println!("{:?}", val);

    let val: String = CatchPhase(EN).fake();
    println!("{:?}", val);

    let val: String = BsVerb(EN).fake();
    println!("{:?}", val);

    let val: String = BsAdj(EN).fake();
    println!("{:?}", val);

    let val: String = BsNoun(EN).fake();
    println!("{:?}", val);

    let val: String = Bs(EN).fake();
    println!("{:?}", val);

    let val: String = Profession(EN).fake();
    println!("{:?}", val);

    let val: String = Industry(EN).fake();
    println!("{:?}", val);
}

fn internet_faker() {
    use fake::faker::internet::raw::*;

    let val: String = FreeEmailProvider(EN).fake();
    println!("{:?}", val);

    let val: String = DomainSuffix(EN).fake();
    println!("{:?}", val);

    let val: String = FreeEmail(EN).fake();
    println!("{:?}", val);

    let val: String = SafeEmail(EN).fake();
    println!("{:?}", val);

    let val: String = Username(EN).fake();
    println!("{:?}", val);

    let val: String = Password(EN, 8..20).fake();
    println!("{:?}", val);

    let val: String = IPv4(EN).fake();
    println!("{:?}", val);

    let val: String = IPv6(EN).fake();
    println!("{:?}", val);

    let val: String = Color(EN).fake();
    println!("{:?}", val);

    let val: String = UserAgent(EN).fake();
    println!("{:?}", val);
}

fn number_faker() {
    use fake::faker::number::raw::*;

    let val: String = Digit(EN).fake();
    println!("{:?}", val);

    // ^: 1-9, #: 0-9
    let val: String = NumberWithFormat(EN, "^###").fake();
    println!("{:?}", val);

    let val: String = NumberWithFormat(EN, "FLAT 0# ^#/F").fake();
    println!("{:?}", val);
}

fn phone_number_faker() {
    use fake::faker::number::raw::NumberWithFormat;
    use fake::faker::phone_number::raw::*;

    let val: String = PhoneNumber(EN).fake();
    println!("{:?}", val);

    let val: String = CellNumber(EN).fake();
    println!("{:?}", val);

    // custom phone number format
    let val: String = NumberWithFormat(EN, "(+852) 6### ####").fake();
    println!("{:?}", val);
}

#[cfg(feature = "http")]
fn http_faker() {
    use fake::faker::http::raw::*;
    use fake::Faker;
    use http::status::{InvalidStatusCode, StatusCode};

    let val: String = RfcStatusCode(EN).fake();
    println!("{:?}", val);

    let val: String = ValidStatusCode(EN).fake();
    println!("{:?}", val);

    let val: StatusCode = RfcStatusCode(EN).fake();
    println!("{:?}", val);

    let val: StatusCode = ValidStatusCode(EN).fake();
    println!("{:?}", val);

    let codes = [200, 401, 404, 500].as_ref();
    let val: StatusCode = codes.fake();
    println!("{:?}", val);

    let codes = [200, 401, 404, 500, 611].as_ref();
    let val: Result<StatusCode, InvalidStatusCode> = codes.fake();
    println!("{:?}", val);

    let val: StatusCode = Faker.fake();
    println!("{:?}", val);

    let val: http::Version = Faker.fake();
    println!("{:?}", val);
}

#[cfg(feature = "chrono")]
fn chrono_faker() {
    use chrono::Utc;
    use fake::faker::chrono::raw::*;
    use fake::Faker;

    let val: chrono::NaiveTime = Time(EN).fake();
    println!("{:?}", val);

    let val: String = Time(EN).fake();
    println!("{:?}", val);

    let val: chrono::NaiveDate = Date(EN).fake();
    println!("{:?}", val);

    let val: String = Date(EN).fake();
    println!("{:?}", val);

    let val: chrono::NaiveDateTime = DateTime(EN).fake();
    println!("{:?}", val);

    let val: chrono::DateTime<Utc> = DateTime(EN).fake();
    println!("{:?}", val);

    let val: String = DateTime(EN).fake();
    println!("{:?}", val);

    let val: chrono::Duration = Duration(EN).fake();
    println!("{}", val);

    let val: chrono::Duration = Faker.fake();
    println!("{}", val);

    let start_dt: chrono::DateTime<Utc> = DateTimeBefore(EN, Utc::now()).fake();
    println!("{}", start_dt);

    let end_dt: chrono::DateTime<Utc> = DateTimeAfter(EN, Utc::now()).fake();
    println!("{}", end_dt);

    let between: chrono::DateTime<Utc> = DateTimeBetween(EN, start_dt, end_dt).fake();
    println!("{}", between);
}

fn filesystem_faker() {
    use fake::faker::filesystem::raw::*;
    use std::path::PathBuf;

    let val: String = FilePath(EN).fake();
    println!("{:?}", val);

    let val: PathBuf = FilePath(EN).fake();
    println!("{:?}", val);

    let val: String = FileName(EN).fake();
    println!("{:?}", val);

    let val: String = FilePath(EN).fake();
    println!("{:?}", val);

    let val: String = DirPath(EN).fake();
    println!("{:?}", val);

    let val: PathBuf = DirPath(EN).fake();
    println!("{:?}", val);
}

fn currency_faker() {
    use fake::faker::currency::raw::*;

    let val: String = CurrencyCode(EN).fake();
    println!("{:?}", val);

    let val: String = CurrencyName(EN).fake();
    println!("{:?}", val);

    let val: String = CurrencySymbol(EN).fake();
    println!("{:?}", val);
}

fn main() {
    lorem_faker();
    name_faker();
    job_faker();
    address_faker();
    bool_faker();
    company_faker();
    internet_faker();
    number_faker();
    phone_number_faker();
    filesystem_faker();
    currency_faker();

    #[cfg(feature = "http")]
    http_faker();

    #[cfg(feature = "chrono")]
    chrono_faker();
}
<commit_msg>update example<commit_after>use fake::locales::{EN, ZH_TW};
use fake::Fake;

fn lorem_faker() {
    use fake::faker::lorem::raw::*;

    let val: String = Word(EN).fake();
    println!("{:?}", val);

    let val: Vec<String> = Words(EN, 3..5).fake();
    println!("{:?}", val);

    let val: String = Sentence(EN, 3..5).fake();
    println!("{:?}", val);

    let val: Vec<String> = Sentences(EN, 3..5).fake();
    println!("{:?}", val);

    let val: String = Paragraph(EN, 3..5).fake();
    println!("{:?}", val);

    let val: Vec<String> = Paragraphs(EN, 3..5).fake();
    println!("{:?}", val);
}

fn name_faker() {
    use fake::faker::name::raw::*;

    let val: String = FirstName(EN).fake();
    println!("{:?}", val);

    let val: String = LastName(EN).fake();
    println!("{:?}", val);

    let val: String = Title(EN).fake();
    println!("{:?}", val);

    let val: String = Suffix(EN).fake();
    println!("{:?}", val);

    let val: String = Name(EN).fake();
    println!("{:?}", val);

    let val: String = NameWithTitle(EN).fake();
    println!("{:?}", val);

    let val: String = Name(ZH_TW).fake();
    println!("{:?}", val);

    let val: String = NameWithTitle(ZH_TW).fake();
    println!("{:?}", val);
}

fn job_faker() {
    use fake::faker::job::raw::*;
    let val: String = Seniority(EN).fake();
    println!("{:?}", val);

    let val: String = Field(EN).fake();
    println!("{:?}", val);

    let val: String = Position(EN).fake();
    println!("{:?}", val);

    let val: String = Title(EN).fake();
    println!("{:?}", val);

    let val: Vec<String> = (Title(EN), 2..4).fake();
    println!("{:?}", val);
}

fn address_faker() {
    use fake::faker::address::raw::*;

    let val: String = CityPrefix(EN).fake();
    println!("{:?}", val);

    let val: String = CitySuffix(EN).fake();
    println!("{:?}", val);

    let val: String = CityName(EN).fake();
    println!("{:?}", val);

    let val: String = CountryName(EN).fake();
    println!("{:?}", val);

    let val: String = CountryCode(EN).fake();
    println!("{:?}", val);

    let val: String = StateName(EN).fake();
    println!("{:?}", val);

    let val: String = StateAbbr(EN).fake();
    println!("{:?}", val);

    let val: String = StreetSuffix(EN).fake();
    println!("{:?}", val);

    let val: String = StreetName(EN).fake();
    println!("{:?}", val);

    let val: String = SecondaryAddressType(EN).fake();
    println!("{:?}", val);

    let val: String = SecondaryAddress(EN).fake();
    println!("{:?}", val);

    let val: String = ZipCode(EN).fake();
    println!("{:?}", val);

    let val: String = PostCode(EN).fake();
    println!("{:?}", val);

    let val: String = BuildingNumber(EN).fake();
    println!("{:?}", val);

    let val: String = TimeZone(EN).fake();
    println!("{:?}", val);

    let val: f32 = Latitude(EN).fake();
    println!("{:?}", val);

    let val: f64 = Latitude(EN).fake();
    println!("{:?}", val);

    let val: f32 = Longitude(EN).fake();
    println!("{:?}", val);

    let val: f64 = Longitude(EN).fake();
    println!("{:?}", val);
}

fn bool_faker() {
    use fake::faker::boolean::raw::*;

    use fake::faker::boolean::en;
    let b = en::Boolean(50);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }

    //50% true
    let b = Boolean(EN, 50);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }

    // 0% true
    let b = Boolean(EN, 0);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }

    // 100% true
    let b = Boolean(EN, 100);
    for _ in 0..5 {
        let val: bool = b.fake();
        println!("{:?}", val);
    }
}

fn company_faker() {
    use fake::faker::company::raw::*;

    let val: String = CompanySuffix(EN).fake();
    println!("{:?}", val);

    let val: String = CompanyName(EN).fake();
    println!("{:?}", val);

    let val: String = Buzzword(EN).fake();
    println!("{:?}", val);

    let val: String = BuzzwordMiddle(EN).fake();
    println!("{:?}", val);

    let val: String = BuzzwordTail(EN).fake();
    println!("{:?}", val);

    let val: String = CatchPhase(EN).fake();
    println!("{:?}", val);

    let val: String = BsVerb(EN).fake();
    println!("{:?}", val);

    let val: String = BsAdj(EN).fake();
    println!("{:?}", val);

    let val: String = BsNoun(EN).fake();
    println!("{:?}", val);

    let val: String = Bs(EN).fake();
    println!("{:?}", val);

    let val: String = Profession(EN).fake();
    println!("{:?}", val);

    let val: String = Industry(EN).fake();
    println!("{:?}", val);
}

fn internet_faker() {
    use fake::faker::internet::raw::*;

    let val: String = FreeEmailProvider(EN).fake();
    println!("{:?}", val);

    let val: String = DomainSuffix(EN).fake();
    println!("{:?}", val);

    let val: String = FreeEmail(EN).fake();
    println!("{:?}", val);

    let val: String = SafeEmail(EN).fake();
    println!("{:?}", val);

    let val: String = Username(EN).fake();
    println!("{:?}", val);

    let val: String = Password(EN, 8..20).fake();
    println!("{:?}", val);

    let val: String = IPv4(EN).fake();
    println!("{:?}", val);

    let val: String = IPv6(EN).fake();
    println!("{:?}", val);

    let val: String = Color(EN).fake();
    println!("{:?}", val);

    let val: String = UserAgent(EN).fake();
    println!("{:?}", val);
}

fn number_faker() {
    use fake::faker::number::raw::*;

    let val: String = Digit(EN).fake();
    println!("{:?}", val);

    // ^: 1-9, #: 0-9
    let val: String = NumberWithFormat(EN, "^###").fake();
    println!("{:?}", val);

    let val: String = NumberWithFormat(EN, "FLAT 0# ^#/F").fake();
    println!("{:?}", val);
}

fn phone_number_faker() {
    use fake::faker::number::raw::NumberWithFormat;
    use fake::faker::phone_number::raw::*;

    let val: String = PhoneNumber(EN).fake();
    println!("{:?}", val);

    let val: String = CellNumber(EN).fake();
    println!("{:?}", val);

    // custom phone number format
    let val: String = NumberWithFormat(EN, "(+852) 6### ####").fake();
    println!("{:?}", val);
}

#[cfg(feature = "http")]
fn http_faker() {
    use fake::faker::http::raw::*;
    use fake::Faker;
    use http::status::{InvalidStatusCode, StatusCode};

    let val: String = RfcStatusCode(EN).fake();
    println!("{:?}", val);

    let val: String = ValidStatusCode(EN).fake();
    println!("{:?}", val);

    let val: StatusCode = RfcStatusCode(EN).fake();
    println!("{:?}", val);

    let val: StatusCode = ValidStatusCode(EN).fake();
    println!("{:?}", val);

    let codes = [200, 401, 404, 500].as_ref();
    let val: StatusCode = codes.fake();
    println!("{:?}", val);

    let codes = [200, 401, 404, 500, 611].as_ref();
    let val: Result<StatusCode, InvalidStatusCode> = codes.fake();
    println!("{:?}", val);

    let val: StatusCode = Faker.fake();
    println!("{:?}", val);

    let val: http::Version = Faker.fake();
    println!("{:?}", val);
}

#[cfg(feature = "chrono")]
fn chrono_faker() {
    use chrono::Utc;
    use fake::faker::chrono::raw::*;
    use fake::Faker;

    let val: chrono::NaiveTime = Time(EN).fake();
    println!("{:?}", val);

    let val: String = Time(EN).fake();
    println!("{:?}", val);

    let val: chrono::NaiveDate = Date(EN).fake();
    println!("{:?}", val);

    let val: String = Date(EN).fake();
    println!("{:?}", val);

    let val: chrono::NaiveDateTime = DateTime(EN).fake();
    println!("{:?}", val);

    let val: chrono::DateTime<Utc> = DateTime(EN).fake();
    println!("{:?}", val);

    let val: String = DateTime(EN).fake();
    println!("{:?}", val);

    let val: chrono::Duration = Duration(EN).fake();
    println!("{}", val);

    let val: chrono::Duration = Faker.fake();
    println!("{}", val);

    let start_dt: chrono::DateTime<Utc> = DateTimeBefore(EN, Utc::now()).fake();
    println!("{}", start_dt);

    let end_dt: chrono::DateTime<Utc> = DateTimeAfter(EN, Utc::now()).fake();
    println!("{}", end_dt);

    let between: chrono::DateTime<Utc> = DateTimeBetween(EN, start_dt, end_dt).fake();
    println!("{}", between);
}

fn filesystem_faker() {
    use fake::faker::filesystem::raw::*;
    use std::path::PathBuf;

    let val: String = FilePath(EN).fake();
    println!("{:?}", val);

    let val: PathBuf = FilePath(EN).fake();
    println!("{:?}", val);

    let val: String = FileName(EN).fake();
    println!("{:?}", val);

    let val: String = FileExtension(EN).fake();
    println!("{:?}", val);

    let val: String = DirPath(EN).fake();
    println!("{:?}", val);

    let val: PathBuf = DirPath(EN).fake();
    println!("{:?}", val);
}

fn currency_faker() {
    use fake::faker::currency::raw::*;

    let val: String = CurrencyCode(EN).fake();
    println!("{:?}", val);

    let val: String = CurrencyName(EN).fake();
    println!("{:?}", val);

    let val: String = CurrencySymbol(EN).fake();
    println!("{:?}", val);
}

fn main() {
    lorem_faker();
    name_faker();
    job_faker();
    address_faker();
    bool_faker();
    company_faker();
    internet_faker();
    number_faker();
    phone_number_faker();
    filesystem_faker();
    currency_faker();

    #[cfg(feature = "http")]
    http_faker();

    #[cfg(feature = "chrono")]
    chrono_faker();
}
<|endoftext|>


<commit_before>extern crate piston_window;
extern crate harfbuzz_rs;
extern crate image as piston_image;
extern crate rusttype;
extern crate glfw_window;

use harfbuzz_rs::{Face, UnicodeBuffer};
use harfbuzz_rs::rusttype::{rusttype_font_from_face, rusttype_scale_from_hb_font};

use piston_window::*;
use piston_image::{ImageBuffer, Rgba};
use glfw_window::GlfwWindow;

fn main() {
    let mut window: PistonWindow<GlfwWindow> = WindowSettings::new("Hello World!", [512; 2])
        .build()
        .unwrap();

    window.set_swap_buffers(true);
    let glyphs = shape(&mut window);

    println!("window size {:?}", window.window.size());
    println!("window draw size {:?}", window.draw_size());
    println!("render target view dimensions {:?}",
             window.output_color.get_dimensions());

    while let Some(e) = window.next() {
        window.draw_2d(&e, |c, g| {
            clear([1.0, 1.0, 1.0, 1.0], g);
            for &(image, ref texture) in &glyphs {
                image.draw(texture, &DrawState::default(), c.transform, g);
            }
        });
    }
}

fn shape<T: Window>(win: &mut PistonWindow<T>) -> Vec<(Image, G2dTexture)> {
    let index = 0;
    let path = "testfiles/Optima.ttc";
    let mut font = Face::from_file(path, index)
        .expect("Error reading font file.")
        .create_font();

    let s_factor: f64 = 0.5;
    let fontsize = 80.0;
    font.set_scale(fontsize as i32 * 64, fontsize as i32 * 64);
    font.set_ppem(96 * 64, 96 * 64);

    let rt_font = rusttype_font_from_face(&font.face());
    let scale = rusttype_scale_from_hb_font(&font);

    // Create a buffer with some text and shape it...
    let result = UnicodeBuffer::new().add_str("Hello World! iiiiiiiiiiiiiiiiii").shape(&font, &[]);

    // ... and get the results.
    let positions = result.get_glyph_positions();
    let infos = result.get_glyph_infos();

    let mut cursor = (10*64, 100*64);
    let mut vec = Vec::with_capacity(result.len());
    // iterate over the shaped glyphs
    for (position, info) in positions.iter().zip(infos) {
        let gid = info.codepoint;
        let x_advance = position.x_advance;
        let x_offset = position.x_offset;
        let y_offset = position.y_offset;

        let x_pos: f64 = (cursor.0 + x_offset) as f64 / 64.0;
        let y_pos: f64 = (cursor.1 + y_offset) as f64 / 64.0;

        // separate x_pos and y_pos into integral an fractional parts for subpixel positioning.
        let x_pos_int = x_pos.trunc();
        let x_pos_frac = x_pos.fract();
        let y_pos_int = y_pos.trunc();
        let y_pos_frac = y_pos.fract();

        // no metrics hinting
        cursor.0 += x_advance;

        let glyph = match rt_font.glyph(rusttype::GlyphId(gid)) {
            Some(glyph) => glyph,
            None => continue,
        };

        let glyph = glyph.scaled(scale).positioned(rusttype::Point {
            x: x_pos_frac as f32,
            y: y_pos_frac as f32,
        });
        let bbox = match glyph.pixel_bounding_box() {
            Some(bbox) => bbox,
            None => continue,
        };
        let image_buffer = draw_glyph(&glyph);

        let x_origin = (x_pos_int + bbox.min.x as f64) * s_factor;
        let y_origin = (y_pos_int + bbox.min.y as f64) * s_factor;
        let width = (bbox.max.x - bbox.min.x) as f64 * s_factor;
        let height = (bbox.max.y - bbox.min.y) as f64 * s_factor;
        let image = Image::new().rect([x_origin, y_origin, width, height]);

        let texture = Texture::from_image(&mut win.factory, &image_buffer, &TextureSettings::new())
            .unwrap();

        vec.push((image, texture));
    }

    vec
}

fn draw_glyph(glyph: &rusttype::PositionedGlyph) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
    let bbox = glyph.pixel_bounding_box().unwrap();
    let mut image_buffer = ImageBuffer::new((bbox.max.x - bbox.min.x) as u32,
                                            (bbox.max.y - bbox.min.y) as u32);
    glyph.draw(|x, y, v| {
        let v = (255.0 * v).round() as u8;
        image_buffer.put_pixel(x, y, Rgba { data: [0, 0, 0, v] })
    });
    image_buffer
}
<commit_msg>Use ScaledRusttypeFont in render.rs example.<commit_after>extern crate piston_window;
extern crate harfbuzz_rs;
extern crate image as piston_image;
extern crate rusttype;
extern crate glfw_window;

use harfbuzz_rs::{Face, UnicodeBuffer};
use harfbuzz_rs::rusttype::ScaledRusttypeFont;

use piston_window::*;
use piston_image::{ImageBuffer, Rgba};
use glfw_window::GlfwWindow;

fn main() {
    let mut window: PistonWindow<GlfwWindow> = WindowSettings::new("Hello World!", [512; 2])
        .build()
        .unwrap();

    window.set_swap_buffers(true);
    let glyphs = shape(&mut window);

    println!("window size {:?}", window.window.size());
    println!("window draw size {:?}", window.draw_size());
    println!("render target view dimensions {:?}",
             window.output_color.get_dimensions());

    while let Some(e) = window.next() {
        window.draw_2d(&e, |c, g| {
            clear([1.0, 1.0, 1.0, 1.0], g);
            for &(image, ref texture) in &glyphs {
                image.draw(texture, &DrawState::default(), c.transform, g);
            }
        });
    }
}

fn shape<T: Window>(win: &mut PistonWindow<T>) -> Vec<(Image, G2dTexture)> {
    let index = 0;
    let path = "testfiles/Optima.ttc";
    let mut hb_font = Face::from_file(path, index)
        .expect("Error reading font file.")
        .create_font();

    let s_factor: f64 = 0.5;
    let fontsize: f64 = 80.0;
    hb_font.set_scale(fontsize as i32 * 64, fontsize as i32 * 64);
    hb_font.set_ppem(96 * 64, 96 * 64);

    let rt_font = ScaledRusttypeFont::from_hb_font(&hb_font);

    // Create a buffer with some text and shape it...
    let result = UnicodeBuffer::new().add_str("Hello World! iiiiiiiiiiiiiiiiii").shape(&hb_font, &[]);

    // ... and get the results.
    let positions = result.get_glyph_positions();
    let infos = result.get_glyph_infos();

    let mut cursor = (10*64, 100*64);
    let mut vec = Vec::with_capacity(result.len());
    // iterate over the shaped glyphs
    for (position, info) in positions.iter().zip(infos) {
        let gid = info.codepoint;
        let x_advance = position.x_advance;
        let x_offset = position.x_offset;
        let y_offset = position.y_offset;

        let x_pos: f64 = (cursor.0 + x_offset) as f64 / 64.0;
        let y_pos: f64 = (cursor.1 + y_offset) as f64 / 64.0;

        // separate x_pos and y_pos into integral an fractional parts for subpixel positioning.
        let x_pos_int = x_pos.trunc();
        let x_pos_frac = x_pos.fract();
        let y_pos_int = y_pos.trunc();
        let y_pos_frac = y_pos.fract();

        // no metrics hinting
        cursor.0 += x_advance;

        let glyph = match rt_font.font.glyph(rusttype::GlyphId(gid)) {
            Some(glyph) => glyph,
            None => continue,
        };

        let glyph = glyph.scaled(rt_font.scale).positioned(rusttype::Point {
            x: x_pos_frac as f32,
            y: y_pos_frac as f32,
        });
        let bbox = match glyph.pixel_bounding_box() {
            Some(bbox) => bbox,
            None => continue,
        };
        let image_buffer = draw_glyph(&glyph);

        let x_origin = (x_pos_int + bbox.min.x as f64) * s_factor;
        let y_origin = (y_pos_int + bbox.min.y as f64) * s_factor;
        let width = (bbox.max.x - bbox.min.x) as f64 * s_factor;
        let height = (bbox.max.y - bbox.min.y) as f64 * s_factor;
        let image = Image::new().rect([x_origin, y_origin, width, height]);

        let texture = Texture::from_image(&mut win.factory, &image_buffer, &TextureSettings::new())
            .unwrap();

        vec.push((image, texture));
    }

    vec
}

fn draw_glyph(glyph: &rusttype::PositionedGlyph) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
    let bbox = glyph.pixel_bounding_box().unwrap();
    let mut image_buffer = ImageBuffer::new((bbox.max.x - bbox.min.x) as u32,
                                            (bbox.max.y - bbox.min.y) as u32);
    glyph.draw(|x, y, v| {
        let v = (255.0 * v).round() as u8;
        image_buffer.put_pixel(x, y, Rgba { data: [0, 0, 0, v] })
    });
    image_buffer
}
<|endoftext|>


<commit_before>extern crate waves;
#[macro_use]
extern crate log;

use waves::*;
use std::cmp::max;

wave!(ReverbWave);

struct Reverb {
    delay: f64,
    gain: f32,
}

struct ReverbWave {
    reverbs: Vec<Reverb>,
    delay_channel : Vec<f32>,
    at: usize,
}

impl Wave for ReverbWave {
    type Input = f32;
    type Output = f32;

    fn new() -> (Self, WaveDescription) { // .... and a param definition
        (
            ReverbWave {
                reverbs: vec![
                    Reverb { delay: 0.1, gain: 0.5 },
                    Reverb { delay: 0.13, gain: 0.2 },
                    Reverb { delay: 0.18, gain: 0.1 },
                ],
                delay_channel : Vec::new(),
                at: 0,
            },
            WaveDescription {
                name : "Reverb".into(),
                vendor : "Waves".into(),
                unique_id: 9999632,
                category: plugin::Category::Effect,
            }
        )
    }

    fn process(&mut self, time:TimeSpan, input: &[f32]) -> Vec<f32> {
        let mut out = Vec::with_capacity(time.samples);

        let reverbs : Vec<_> = self.reverbs.iter().map(|r| ((r.delay / time.time_per_sample()) as usize, r.gain)).collect();

        let max_samples = reverbs.last().expect("a reverb").0 + 1; // assumes ordered for now

        // ensure circular buffer is big enough
        while self.delay_channel.len() < max_samples {
            self.delay_channel.push(0.0);
        }

        for v in input.into_iter().cloned() {
            let frontier_idx = (self.at + max_samples - 1) % max_samples;
            // zero out frontier
            self.delay_channel[frontier_idx] = 0.0;

            let o = v + self.delay_channel[self.at];
            out.push(o);

            for &(delay, gain) in &reverbs {
                let delay_idx = (self.at + delay) % max_samples; // circ buffer
                self.delay_channel[delay_idx] = o * gain;
            }

            self.at = (self.at + 1) % max_samples;
        }

        out
    }
}
<commit_msg>Tweaked settings<commit_after>extern crate waves;
#[macro_use]
extern crate log;

use waves::*;
use std::cmp::max;

wave!(ReverbWave);

struct Reverb {
    delay: f64,
    gain: f32,
}

struct ReverbWave {
    reverbs: Vec<Reverb>,
    delay_channel : Vec<f32>,
    at: usize,
}

impl Wave for ReverbWave {
    type Input = f32;
    type Output = f32;

    fn new() -> (Self, WaveDescription) { // .... and a param definition
        (
            ReverbWave {
                reverbs: vec![
                    Reverb { delay: 0.020, gain: 0.6 },
                    Reverb { delay: 0.033, gain: 0.22 },
                    Reverb { delay: 0.047, gain: 0.15 },
                ],
                delay_channel : Vec::new(),
                at: 0,
            },
            WaveDescription {
                name : "Reverb".into(),
                vendor : "Waves".into(),
                unique_id: 9999632,
                category: plugin::Category::Effect,
            }
        )
    }

    fn process(&mut self, time:TimeSpan, input: &[f32]) -> Vec<f32> {
        let mut out = Vec::with_capacity(time.samples);

        let reverbs : Vec<_> = self.reverbs.iter().map(|r| ((r.delay / time.time_per_sample()) as usize, r.gain)).collect();

        let max_samples = reverbs.last().expect("a reverb").0 + 1; // assumes ordered for now

        // ensure circular buffer is big enough
        while self.delay_channel.len() < max_samples {
            self.delay_channel.push(0.0);
        }

        for v in input.into_iter().cloned() {
            let frontier_idx = (self.at + max_samples - 1) % max_samples;
            // zero out frontier
            self.delay_channel[frontier_idx] = 0.0;

            let o = v + self.delay_channel[self.at];
            out.push(o);

            for &(delay, gain) in &reverbs {
                let delay_idx = (self.at + delay) % max_samples; // circ buffer
                self.delay_channel[delay_idx] = o * gain;
            }

            self.at = (self.at + 1) % max_samples;
        }

        out
    }
}
<|endoftext|>


<commit_before>use std::net::TcpListener;
use std::net::TcpStream;

use solicit::server::SimpleServer;
use solicit::http::HttpScheme;
use solicit::http::StreamId;
use solicit::http::Header;
use solicit::http::connection::HttpConnection;
use solicit::http::session::DefaultSessionState;
use solicit::http::session::DefaultStream;
use solicit::http::session::Stream;
use solicit::http::session::StreamState;
use solicit::http::session::StreamDataChunk;
use solicit::http::session::StreamDataError;
use solicit::http::transport::TransportStream;
use solicit::http::server::ServerConnection;

struct GrpcStream {
    default_stream: DefaultStream,
}

impl Stream for GrpcStream {
    fn new(stream_id: StreamId) -> Self {
        GrpcStream {
            default_stream: DefaultStream::new(stream_id)
        }
    }

    fn new_data_chunk(&mut self, data: &[u8]) {
        self.default_stream.new_data_chunk(data)
    }

    fn set_headers(&mut self, headers: Vec<Header>) {
        self.default_stream.set_headers(headers)
    }

    fn set_state(&mut self, state: StreamState) {
        self.default_stream.set_state(state)
    }

    fn get_data_chunk(&mut self, buf: &mut [u8]) -> Result<StreamDataChunk, StreamDataError> {
        self.default_stream.get_data_chunk(buf)
    }

    fn id(&self) -> StreamId {
        self.default_stream.id()
    }

    fn state(&self) -> StreamState {
        self.default_stream.state()
    }
}

struct GrpcSessionState {
    default_state: DefaultSessionState<GrpcStream>,
}

struct GrpcServerConnection {
    server_conn: ServerConnection<TcpStream, TcpStream>,
}

impl GrpcServerConnection {
    fn new(mut stream: TcpStream) -> GrpcServerConnection {
        let mut preface = [0; 24];
        stream.read_exact(&mut preface).unwrap();
        if &preface != b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" {
            panic!();
        }

        let conn = HttpConnection::<TcpStream, TcpStream>::with_stream(stream, HttpScheme::Http);
        let mut server_conn: ServerConnection<TcpStream, TcpStream> = ServerConnection::with_connection(conn, DefaultSessionState::new());

        let mut r = GrpcServerConnection {
            server_conn: server_conn,
        };

        r.server_conn.init().unwrap();
        r
    }

    fn run(&mut self) {
        panic!();
    }
}

pub struct GrpcServer {
    listener: TcpListener,
}

impl GrpcServer {
    pub fn new() -> GrpcServer {
        GrpcServer {
            listener: TcpListener::bind("127.0.0.1:50051").unwrap(),
        }
    }

    pub fn run(&mut self) {
        for mut stream in self.listener.incoming().map(|s| s.unwrap()) {
            println!("client connected!");
            GrpcServerConnection::new(stream).run();
        }
    }
}

<commit_msg>backup<commit_after>use std::net::TcpListener;
use std::net::TcpStream;

use solicit::server::SimpleServer;
use solicit::http::HttpScheme;
use solicit::http::StreamId;
use solicit::http::Header;
use solicit::http::connection::HttpConnection;
use solicit::http::session::DefaultSessionState;
use solicit::http::session::DefaultStream;
use solicit::http::session::Stream;
use solicit::http::session::StreamState;
use solicit::http::session::StreamDataChunk;
use solicit::http::session::StreamDataError;
use solicit::http::transport::TransportStream;
use solicit::http::server::ServerConnection;

struct GrpcStream {
    default_stream: DefaultStream,
}

impl Stream for GrpcStream {
    fn new(stream_id: StreamId) -> Self {
        println!("hooray! new stream {}", stream_id);
        GrpcStream {
            default_stream: DefaultStream::new(stream_id)
        }
    }

    fn set_headers(&mut self, headers: Vec<Header>) {
        println!("hooray! headers: {:?}", headers);
        self.default_stream.set_headers(headers)
    }

    fn new_data_chunk(&mut self, data: &[u8]) {
        println!("hooray! data: {:?}", data);
        self.default_stream.new_data_chunk(data)
    }

    fn set_state(&mut self, state: StreamState) {
        println!("set_state: {:?}", state);
        self.default_stream.set_state(state)
    }

    fn get_data_chunk(&mut self, buf: &mut [u8]) -> Result<StreamDataChunk, StreamDataError> {
        panic!("get_data_chunk should not be called");
        //self.default_stream.get_data_chunk(buf)
    }

    fn id(&self) -> StreamId {
        self.default_stream.id()
    }

    fn state(&self) -> StreamState {
        self.default_stream.state()
    }
}

/*
struct GrpcSessionState {
    default_state: DefaultSessionState,
}

impl GrpcSessionState {
    fn new() -> Self {
        GrpcSessionState {
            default_state: DefaultSessionState::new(),
        }
    }
}
*/

struct GrpcServerConnection {
    server_conn: ServerConnection<TcpStream, TcpStream, DefaultSessionState<GrpcStream>>,
}

impl GrpcServerConnection {
    fn new(mut stream: TcpStream) -> GrpcServerConnection {
        let mut preface = [0; 24];
        stream.read_exact(&mut preface).unwrap();
        if &preface != b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" {
            panic!();
        }

        let conn = HttpConnection::<TcpStream, TcpStream>::with_stream(stream, HttpScheme::Http);
        let mut server_conn = ServerConnection::with_connection(conn, DefaultSessionState::new());

        let mut r = GrpcServerConnection {
            server_conn: server_conn,
        };

        r.server_conn.init().unwrap();
        r
    }

    fn run(&mut self) {
        loop {
            let r = self.server_conn.handle_next_frame();
            match r {
                e @ Err(..) => {
                    println!("{:?}", e);
                    return;
                }
                _ => {},
            }
        }
    }
}

pub struct GrpcServer {
    listener: TcpListener,
}

impl GrpcServer {
    pub fn new() -> GrpcServer {
        GrpcServer {
            listener: TcpListener::bind("127.0.0.1:50051").unwrap(),
        }
    }

    pub fn run(&mut self) {
        for mut stream in self.listener.incoming().map(|s| s.unwrap()) {
            println!("client connected!");
            GrpcServerConnection::new(stream).run();
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Remove explicit `PartialEq::ne` implementation.<commit_after><|endoftext|>


<commit_before><commit_msg>lw works with real, not with vectors. like sw.<commit_after><|endoftext|>


<commit_before>/*!
A binding for `SDL2_ttf`.
 */

extern crate sdl2;
extern crate sdl2_sys;

#[macro_use]
extern crate bitflags;

#[allow(non_camel_case_types, dead_code)]
mod ffi;
mod font;
mod context;

// Setup linking for all targets.
#[cfg(target_os="macos")]
mod mac {
    #[cfg(mac_framework)]
    #[link(kind="framework", name="SDL2_ttf")]
    extern {}

    #[cfg(not(mac_framework))]
    #[link(name="SDL2_ttf")]
    extern {}
}

#[cfg(any(target_os="windows", target_os="linux", target_os="freebsd"))]
mod others {
    #[link(name="SDL2_ttf")]
    extern {}
}

pub use context::{
    init, has_been_initialized, get_linked_version, Sdl2TtfContext
};
pub use font::{
    Font, FontStyle, Hinting, GlyphMetrics, PartialRendering, FontError,
    FontResult, STYLE_NORMAL, STYLE_BOLD, STYLE_ITALIC, STYLE_UNDERLINE, STYLE_STRIKETHROUGH
};
<commit_msg>Exported sdl_ttf::context::InitError<commit_after>/*!
A binding for `SDL2_ttf`.
 */

extern crate sdl2;
extern crate sdl2_sys;

#[macro_use]
extern crate bitflags;

#[allow(non_camel_case_types, dead_code)]
mod ffi;
mod font;
mod context;

// Setup linking for all targets.
#[cfg(target_os="macos")]
mod mac {
    #[cfg(mac_framework)]
    #[link(kind="framework", name="SDL2_ttf")]
    extern {}

    #[cfg(not(mac_framework))]
    #[link(name="SDL2_ttf")]
    extern {}
}

#[cfg(any(target_os="windows", target_os="linux", target_os="freebsd"))]
mod others {
    #[link(name="SDL2_ttf")]
    extern {}
}

pub use context::{
    init, has_been_initialized, get_linked_version, Sdl2TtfContext, InitError,
};
pub use font::{
    Font, FontStyle, Hinting, GlyphMetrics, PartialRendering, FontError,
    FontResult, STYLE_NORMAL, STYLE_BOLD, STYLE_ITALIC, STYLE_UNDERLINE, STYLE_STRIKETHROUGH
};
<|endoftext|>


<commit_before>//! combinators applying parsers in sequence

#[macro_use]
mod macros;

use internal::IResult;
use error::ParseError;

pub fn pair<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, (O1, O2), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    second(input).map(|(i, o2)| (i, (o1, o2)))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn pairc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, (O1, O2), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  pair(first, second)(input)
}

pub fn preceded<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  move |input: I| {
    let (input, _) = first(input)?;
    second(input)
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn precededc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  preceded(first, second)(input)
}

pub fn terminated<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O1, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    second(input).map(|(i, _)| (i, o1))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn terminatedc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O1, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  terminated(first, second)(input)
}

pub fn separated_pair<I, O1, O2, O3, E: ParseError<I>, F, G, H>(first: F, sep: G, second: H) -> impl Fn(I) -> IResult<I, (O1, O3), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    let (input, _) = sep(input)?;
    second(input).map(|(i, o2)| (i, (o1, o2)))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn separated_pairc<I, O1, O2, O3, E: ParseError<I>, F, G, H>(input: I, first: F, sep: G, second: H) -> IResult<I, (O1, O3), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  separated_pair(first, sep, second)(input)
}

pub fn delimited<I, O1, O2, O3, E: ParseError<I>, F, G, H>(first: F, sep: G, second: H) -> impl Fn(I) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  move |input: I| {
    let (input, _) = first(input)?;
    let (input, o2) = sep(input)?;
    second(input).map(|(i, _)| (i, o2))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn delimitedc<I, O1, O2, O3, E: ParseError<I>, F, G, H>(input: I, first: F, sep: G, second: H) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  delimited(first, sep, second)(input)
}

/// helper trait for the tuple combinator
///
/// this trait is implemented for tuples of parsers of up to 21 elements
pub trait Tuple<I,O,E> {
  /// parses the input and returns a tuple of results of each parser
  fn parse(&self, input: I) -> IResult<I,O,E>;
}

macro_rules! tuple_trait(
  ($name1:ident $ty1:ident, $name2: ident $ty2:ident, $($name:ident $ty:ident),*) => (
    tuple_trait!(__impl $name1 $ty1, $name2 $ty2; $($name $ty),*);
  );
  (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident, $($name2:ident $ty2:ident),*) => (
    tuple_trait_impl!($($name $ty),+);
    tuple_trait!(__impl $($name $ty),+ , $name1 $ty1; $($name2 $ty2),*);
  );
  (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident) => (
    tuple_trait_impl!($($name $ty),+);
    tuple_trait_impl!($($name $ty),+, $name1 $ty1);
  );
);

macro_rules! tuple_trait_impl(
  ($($name:ident $ty: ident),+) => (
    impl<
      Input: Clone, $($ty),+ , Error: ParseError<Input>,
      $($name: Fn(Input) -> IResult<Input, $ty, Error>),+
    > Tuple<Input, ( $($ty),+ ), Error> for ( $($name),+ ) {

      fn parse(&self, input: Input) -> IResult<Input, ( $($ty),+ ), Error> {
        tuple_trait_inner!(0, self, input, (), $($name)+)

      }
    }
  );
);

macro_rules! tuple_trait_inner(
  ($it:tt, $self:expr, $input:expr, (), $head:ident $($id:ident)+) => ({
    let (i, o) = $self.$it($input.clone())?;

    succ!($it, tuple_trait_inner!($self, i, ( o ), $($id)+))
  });
  ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident $($id:ident)+) => ({
    let (i, o) = $self.$it($input.clone())?;

    succ!($it, tuple_trait_inner!($self, i, ($($parsed)* , o), $($id)+))
  });
  ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident) => ({
    let (i, o) = $self.$it($input.clone())?;

    Ok((i, ($($parsed)* , o)))
  });
);

tuple_trait!(FnA A, FnB B, FnC C, FnD D, FnE E, FnF F, FnG G, FnH H, FnI I, FnJ J, FnK K, FnL L,
  FnM M, FnN N, FnO O, FnP P, FnQ Q, FnR R, FnS S, FnT T, FnU U);

/// applies a tuple of parsers one by one and returns their results as a tuple
pub fn tuple<I: Clone, O, E: ParseError<I>, List: Tuple<I,O,E>>(l: List)  -> impl Fn(I) -> IResult<I, O, E> {
  move |i: I| {
    l.parse(i)
  }
}
<commit_msg>add example of pair<commit_after>//! combinators applying parsers in sequence

#[macro_use]
mod macros;

use internal::IResult;
use error::ParseError;

/// Gets an object from the first parser,
/// then get another object from the second parser.
/// # Arguments
/// * `first` The first parser to apply.
/// * `second` The second parser to apply.
/// ```rust
/// # #[macro_use] extern crate nom;
/// # use nom::{Err, error::ErrorKind, Needed};
/// # use nom::Needed::Size;
/// use nom::sequence::pair;
/// use nom::bytes::complete::tag;
/// # fn main() {
/// let first_parser = |s: &'static str| {
///   tag::<_, _, (_, ErrorKind)>("abc")(s)
/// };
/// let second_parser = |s: &'static str| {
///   tag::<_, _, (_, ErrorKind)>("efg")(s)
/// };
/// let parser = |s: &'static str| {
///   pair::<_, _, _, (_, ErrorKind), _, _>(first_parser, second_parser)(s)
/// };
///
/// assert_eq!(parser("abcefg"), Ok(("", ("abc", "efg"))));
/// assert_eq!(parser("abcefghij"), Ok(("hij", ("abc", "efg"))));
/// assert_eq!(parser(""), Err(Err::Error(("", ErrorKind::Tag))));
/// assert_eq!(parser("123"), Err(Err::Error(("123", ErrorKind::Tag))));
/// # }
/// ```
pub fn pair<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, (O1, O2), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    second(input).map(|(i, o2)| (i, (o1, o2)))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn pairc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, (O1, O2), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  pair(first, second)(input)
}

pub fn preceded<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  move |input: I| {
    let (input, _) = first(input)?;
    second(input)
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn precededc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  preceded(first, second)(input)
}

pub fn terminated<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O1, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    second(input).map(|(i, _)| (i, o1))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn terminatedc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O1, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
{
  terminated(first, second)(input)
}

pub fn separated_pair<I, O1, O2, O3, E: ParseError<I>, F, G, H>(first: F, sep: G, second: H) -> impl Fn(I) -> IResult<I, (O1, O3), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    let (input, _) = sep(input)?;
    second(input).map(|(i, o2)| (i, (o1, o2)))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn separated_pairc<I, O1, O2, O3, E: ParseError<I>, F, G, H>(input: I, first: F, sep: G, second: H) -> IResult<I, (O1, O3), E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  separated_pair(first, sep, second)(input)
}

pub fn delimited<I, O1, O2, O3, E: ParseError<I>, F, G, H>(first: F, sep: G, second: H) -> impl Fn(I) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  move |input: I| {
    let (input, _) = first(input)?;
    let (input, o2) = sep(input)?;
    second(input).map(|(i, _)| (i, o2))
  }
}

// this implementation is used for type inference issues in macros
#[doc(hidden)]
pub fn delimitedc<I, O1, O2, O3, E: ParseError<I>, F, G, H>(input: I, first: F, sep: G, second: H) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(I) -> IResult<I, O2, E>,
  H: Fn(I) -> IResult<I, O3, E>,
{
  delimited(first, sep, second)(input)
}

/// helper trait for the tuple combinator
///
/// this trait is implemented for tuples of parsers of up to 21 elements
pub trait Tuple<I,O,E> {
  /// parses the input and returns a tuple of results of each parser
  fn parse(&self, input: I) -> IResult<I,O,E>;
}

macro_rules! tuple_trait(
  ($name1:ident $ty1:ident, $name2: ident $ty2:ident, $($name:ident $ty:ident),*) => (
    tuple_trait!(__impl $name1 $ty1, $name2 $ty2; $($name $ty),*);
  );
  (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident, $($name2:ident $ty2:ident),*) => (
    tuple_trait_impl!($($name $ty),+);
    tuple_trait!(__impl $($name $ty),+ , $name1 $ty1; $($name2 $ty2),*);
  );
  (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident) => (
    tuple_trait_impl!($($name $ty),+);
    tuple_trait_impl!($($name $ty),+, $name1 $ty1);
  );
);

macro_rules! tuple_trait_impl(
  ($($name:ident $ty: ident),+) => (
    impl<
      Input: Clone, $($ty),+ , Error: ParseError<Input>,
      $($name: Fn(Input) -> IResult<Input, $ty, Error>),+
    > Tuple<Input, ( $($ty),+ ), Error> for ( $($name),+ ) {

      fn parse(&self, input: Input) -> IResult<Input, ( $($ty),+ ), Error> {
        tuple_trait_inner!(0, self, input, (), $($name)+)

      }
    }
  );
);

macro_rules! tuple_trait_inner(
  ($it:tt, $self:expr, $input:expr, (), $head:ident $($id:ident)+) => ({
    let (i, o) = $self.$it($input.clone())?;

    succ!($it, tuple_trait_inner!($self, i, ( o ), $($id)+))
  });
  ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident $($id:ident)+) => ({
    let (i, o) = $self.$it($input.clone())?;

    succ!($it, tuple_trait_inner!($self, i, ($($parsed)* , o), $($id)+))
  });
  ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident) => ({
    let (i, o) = $self.$it($input.clone())?;

    Ok((i, ($($parsed)* , o)))
  });
);

tuple_trait!(FnA A, FnB B, FnC C, FnD D, FnE E, FnF F, FnG G, FnH H, FnI I, FnJ J, FnK K, FnL L,
  FnM M, FnN N, FnO O, FnP P, FnQ Q, FnR R, FnS S, FnT T, FnU U);

/// applies a tuple of parsers one by one and returns their results as a tuple
pub fn tuple<I: Clone, O, E: ParseError<I>, List: Tuple<I,O,E>>(l: List)  -> impl Fn(I) -> IResult<I, O, E> {
  move |i: I| {
    l.parse(i)
  }
}
<|endoftext|>


<commit_before>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Trait for testing approximate equality
pub trait ApproxEq<Eps> {
    fn approx_epsilon() -> Eps;
    fn approx_eq(&self, other: &Self) -> bool;
    fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
}

impl ApproxEq<f32> for f32 {
    #[inline]
    fn approx_epsilon() -> f32 { 1.0e-6 }

    #[inline]
    fn approx_eq(&self, other: &f32) -> bool {
       self.approx_eq_eps(other, &1.0e-6)
    }

    #[inline]
    fn approx_eq_eps(&self, other: &f32, approx_epsilon: &f32) -> bool {
       (*self - *other).abs() < *approx_epsilon
    }
}

impl ApproxEq<f64> for f64 {
    #[inline]
    fn approx_epsilon() -> f64 { 1.0e-6 }

    #[inline]
    fn approx_eq(&self, other: &f64) -> bool {
        self.approx_eq_eps(other, &1.0e-6)
    }

    #[inline]
    fn approx_eq_eps(&self, other: &f64, approx_epsilon: &f64) -> bool {
        (*self - *other).abs() < *approx_epsilon
    }
}<commit_msg>Import std::num::Float explicitly.<commit_after>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::num::Float;

/// Trait for testing approximate equality
pub trait ApproxEq<Eps> {
    fn approx_epsilon() -> Eps;
    fn approx_eq(&self, other: &Self) -> bool;
    fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
}

impl ApproxEq<f32> for f32 {
    #[inline]
    fn approx_epsilon() -> f32 { 1.0e-6 }

    #[inline]
    fn approx_eq(&self, other: &f32) -> bool {
       self.approx_eq_eps(other, &1.0e-6)
    }

    #[inline]
    fn approx_eq_eps(&self, other: &f32, approx_epsilon: &f32) -> bool {
       (*self - *other).abs() < *approx_epsilon
    }
}

impl ApproxEq<f64> for f64 {
    #[inline]
    fn approx_epsilon() -> f64 { 1.0e-6 }

    #[inline]
    fn approx_eq(&self, other: &f64) -> bool {
        self.approx_eq_eps(other, &1.0e-6)
    }

    #[inline]
    fn approx_eq_eps(&self, other: &f64, approx_epsilon: &f64) -> bool {
        (*self - *other).abs() < *approx_epsilon
    }
}
<|endoftext|>


<commit_before>//! Helper functions for dealing with shaders.

// External crates.
use gl;
use gl::types::{
    GLboolean,
    GLchar,
    GLenum,
    GLint,
    GLsizeiptr,
    GLuint,
};

use std::ffi::CString;
use std::ptr;
use std::mem;
use std::iter::repeat;

/// Describes a shader attribute.
pub struct DynamicAttribute {
    /// The vertex buffer object.
    vbo: GLuint,
    /// The number of components.
    size: i32,
    /// The location of the attribute in shader.
    location: GLuint,
    /// Whether to normalize when sending to GPU.
    normalize: GLboolean,
    /// The type, for example gl::FLOAT.
    ty: GLenum,
}

impl Drop for DynamicAttribute {
    fn drop(&mut self) {
        unsafe {
            gl::DeleteBuffers(1, &self.vbo)
        }
    }
}

impl DynamicAttribute {
    /// Binds to a vertex array object.
    ///
    /// The vertex array object remembers the format for later.
    fn bind_vao(&self, vao: GLuint) {
        let stride = 0;
        unsafe {
            gl::BindVertexArray(vao);
            gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo);
            gl::VertexAttribPointer(
                self.location,
                self.size,
                self.ty,
                self.normalize,
                stride,
                ptr::null()
            );
        }
    }

    fn new(
        program: GLuint,
        name: &str,
        size: i32,
        normalize: GLboolean,
        ty: GLenum,
        vao: GLuint
    ) -> Result<DynamicAttribute, String> {
        let location = try!(attribute_location(program, name));
        let mut vbo = 0;
        unsafe {
            gl::GenBuffers(1, &mut vbo);
        }
        let res = DynamicAttribute {
                vbo: vbo,
                size: size,
                location: location,
                normalize: normalize,
                ty: ty,
            };
        res.bind_vao(vao);
        Ok(res)
    }

    /// Create XYZ vertex attribute.
    pub fn xyz(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 3, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create XY vertex attribute.
    pub fn xy(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 2, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create RGB color attribute.
    pub fn rgb(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 3, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create RGBA color attribute.
    pub fn rgba(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 4, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create texture coordinate attribute.
    pub fn uv(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 2, gl::FALSE, gl::FLOAT, vao)
    }

    /// Sets attribute data.
    pub unsafe fn set<T>(&self, data: &[T]) {
        gl::EnableVertexAttribArray(self.location);
        gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo);
        gl::BufferData(
            gl::ARRAY_BUFFER,
            data.len() as GLsizeiptr * mem::size_of::<T>() as GLsizeiptr,
            mem::transmute(data.as_ptr()),
            gl::DYNAMIC_DRAW
        );
    }
}

/// Compiles a shader.
///
/// Returns a shader or a message with the error.
pub fn compile_shader(
    shader_type: GLenum,
    source: &str
) -> Result<GLuint, String> {
    unsafe {
        let shader = gl::CreateShader(shader_type);
        gl::ShaderSource(shader, 1,
            &match CString::new(source.as_bytes()) {
                Ok(x) => x.as_ptr(),
                Err(err) => { return Err(format!("compile_shader: {}", err)); }
            }, ptr::null());
        gl::CompileShader(shader);
        let mut status = gl::FALSE as GLint;
        gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);
        if status == (gl::TRUE as GLint) {
            Ok(shader)
        } else {
            let mut len = 0;
            gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);

            if len == 0 {
                Err("Compilation failed with no log. The OpenGL context might have been created on another thread, or not have been created.".to_string())
            }
            else {
                // Subtract 1 to skip the trailing null character.
                let mut buf: Vec<u8> = repeat(0u8).take(len as usize - 1).collect();
                gl::GetShaderInfoLog(
                    shader,
                    len,
                    ptr::null_mut(),
                    buf.as_mut_ptr() as *mut GLchar
                );

                gl::DeleteShader(shader);

                Err(String::from_utf8(buf).ok().expect(
                    "ShaderInfoLog not valid utf8"
                ))
            }
        }
    }
}

/// Creates a vertex buffer for an attribute from a program.
///
/// Returns `None` if there is no attribute with such name.
pub fn attribute_location(program: GLuint, name: &str) -> Result<GLuint, String> {
    unsafe {
        let id = gl::GetAttribLocation(program,
            match CString::new(name.as_bytes()) {
                Ok(x) => x.as_ptr(),
                Err(err) => { return Err(format!("attribute_location: {}", err)); }
            });
        if id < 0 {
            Err(format!("Attribute '{}' does not exists in shader", name))
        } else {
            Ok(id as GLuint)
        }
    }
}

<commit_msg>CString object must live for as long as its pointer<commit_after>//! Helper functions for dealing with shaders.

// External crates.
use gl;
use gl::types::{
    GLboolean,
    GLchar,
    GLenum,
    GLint,
    GLsizeiptr,
    GLuint,
};

use std::ffi::CString;
use std::ptr;
use std::mem;
use std::iter::repeat;

/// Describes a shader attribute.
pub struct DynamicAttribute {
    /// The vertex buffer object.
    vbo: GLuint,
    /// The number of components.
    size: i32,
    /// The location of the attribute in shader.
    location: GLuint,
    /// Whether to normalize when sending to GPU.
    normalize: GLboolean,
    /// The type, for example gl::FLOAT.
    ty: GLenum,
}

impl Drop for DynamicAttribute {
    fn drop(&mut self) {
        unsafe {
            gl::DeleteBuffers(1, &self.vbo)
        }
    }
}

impl DynamicAttribute {
    /// Binds to a vertex array object.
    ///
    /// The vertex array object remembers the format for later.
    fn bind_vao(&self, vao: GLuint) {
        let stride = 0;
        unsafe {
            gl::BindVertexArray(vao);
            gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo);
            gl::VertexAttribPointer(
                self.location,
                self.size,
                self.ty,
                self.normalize,
                stride,
                ptr::null()
            );
        }
    }

    fn new(
        program: GLuint,
        name: &str,
        size: i32,
        normalize: GLboolean,
        ty: GLenum,
        vao: GLuint
    ) -> Result<DynamicAttribute, String> {
        let location = try!(attribute_location(program, name));
        let mut vbo = 0;
        unsafe {
            gl::GenBuffers(1, &mut vbo);
        }
        let res = DynamicAttribute {
                vbo: vbo,
                size: size,
                location: location,
                normalize: normalize,
                ty: ty,
            };
        res.bind_vao(vao);
        Ok(res)
    }

    /// Create XYZ vertex attribute.
    pub fn xyz(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 3, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create XY vertex attribute.
    pub fn xy(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 2, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create RGB color attribute.
    pub fn rgb(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 3, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create RGBA color attribute.
    pub fn rgba(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 4, gl::FALSE, gl::FLOAT, vao)
    }

    /// Create texture coordinate attribute.
    pub fn uv(program: GLuint, name: &str, vao: GLuint) -> Result<DynamicAttribute, String> {
        DynamicAttribute::new(program, name, 2, gl::FALSE, gl::FLOAT, vao)
    }

    /// Sets attribute data.
    pub unsafe fn set<T>(&self, data: &[T]) {
        gl::EnableVertexAttribArray(self.location);
        gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo);
        gl::BufferData(
            gl::ARRAY_BUFFER,
            data.len() as GLsizeiptr * mem::size_of::<T>() as GLsizeiptr,
            mem::transmute(data.as_ptr()),
            gl::DYNAMIC_DRAW
        );
    }
}

/// Compiles a shader.
///
/// Returns a shader or a message with the error.
pub fn compile_shader(
    shader_type: GLenum,
    source: &str
) -> Result<GLuint, String> {
    unsafe {
        let shader = gl::CreateShader(shader_type);
        gl::ShaderSource(shader, 1,
            &match CString::new(source.as_bytes()) {
                Ok(x) => x.as_ptr(),
                Err(err) => { return Err(format!("compile_shader: {}", err)); }
            }, ptr::null());
        gl::CompileShader(shader);
        let mut status = gl::FALSE as GLint;
        gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);
        if status == (gl::TRUE as GLint) {
            Ok(shader)
        } else {
            let mut len = 0;
            gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);

            if len == 0 {
                Err("Compilation failed with no log. The OpenGL context might have been created on another thread, or not have been created.".to_string())
            }
            else {
                // Subtract 1 to skip the trailing null character.
                let mut buf: Vec<u8> = repeat(0u8).take(len as usize - 1).collect();
                gl::GetShaderInfoLog(
                    shader,
                    len,
                    ptr::null_mut(),
                    buf.as_mut_ptr() as *mut GLchar
                );

                gl::DeleteShader(shader);

                Err(String::from_utf8(buf).ok().expect(
                    "ShaderInfoLog not valid utf8"
                ))
            }
        }
    }
}

/// Creates a vertex buffer for an attribute from a program.
///
/// Returns `None` if there is no attribute with such name.
pub fn attribute_location(program: GLuint, name: &str) -> Result<GLuint, String> {
    unsafe {
        let id = gl::GetAttribLocation(program,
            match CString::new(name.as_bytes()) {
                Ok(x) => x,
                Err(err) => { return Err(format!("attribute_location: {}", err)); }
            }.as_ptr());
        if id < 0 {
            Err(format!("Attribute '{}' does not exists in shader", name))
        } else {
            Ok(id as GLuint)
        }
    }
}

<|endoftext|>


<commit_before>use crate::cli::Command;
use mprovision as mp;
use std::io::{self, Write};
use std::path::Path;
use std::path::PathBuf;
use std::result;
use std::time::{Duration, SystemTime};

mod cli;

type Result = result::Result<(), main_error::MainError>;

fn main() -> Result {
    match cli::run() {
        Command::List(cli::ListParams {
            text,
            expire_in_days,
            directory,
            oneline,
        }) => list(&text, expire_in_days, directory, oneline),
        Command::ShowUuid(cli::ShowUuidParams { uuid, directory }) => show_uuid(&uuid, directory),
        Command::ShowFile(cli::ShowFileParams { file }) => show_file(&file),
        Command::Remove(cli::RemoveParams { ids, directory }) => remove(&ids, directory),
        Command::Clean(cli::CleanParams { directory }) => clean(directory),
    }
}

fn list(
    text: &Option<String>,
    expires_in_days: Option<u64>,
    directory: Option<PathBuf>,
    oneline: bool,
) -> Result {
    let dir = mp::with_directory(directory)?;
    let entries = mp::entries(&dir).map(std::iter::Iterator::collect)?;
    let date =
        expires_in_days.map(|days| SystemTime::now() + Duration::from_secs(days * 24 * 60 * 60));
    let filter_string = text.as_ref();
    let mut profiles = mp::filter(entries, |profile| match (date, filter_string) {
        (Some(date), Some(string)) => {
            profile.info.expiration_date <= date && profile.info.contains(string)
        }
        (Some(date), _) => profile.info.expiration_date <= date,
        (_, Some(string)) => profile.info.contains(string),
        (_, _) => true,
    });
    profiles.sort_by(|a, b| a.info.creation_date.cmp(&b.info.creation_date));
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    for (i, profile) in profiles.iter().enumerate() {
        let separator = if i + 1 == profiles.len() { "" } else { "\n" };
        writeln!(&mut stdout, "{}{}", profile.info.description(), separator)?;
    }
    Ok(())
}

fn show_uuid(uuid: &str, directory: Option<PathBuf>) -> Result {
    let dir = mp::with_directory(directory)?;
    let profile = mp::find_by_uuid(&dir, &uuid)?;
    show_file(&profile.path)
}

fn show_file(path: &Path) -> Result {
    let xml = mp::show(&path)?;
    writeln!(io::stdout(), "{}", xml)?;
    Ok(())
}

fn remove(ids: &[String], directory: Option<PathBuf>) -> Result {
    let dir = mp::with_directory(directory)?;
    let profiles = mp::find_by_ids(&dir, &ids)?;
    remove_profiles(&profiles)
}

fn clean(directory: Option<PathBuf>) -> Result {
    let date = SystemTime::now();
    let dir = mp::with_directory(directory)?;
    let entries = mp::entries(&dir).map(std::iter::Iterator::collect)?;
    let profiles = mp::filter(entries, |profile| profile.info.expiration_date <= date);
    remove_profiles(&profiles)
}

fn remove_profiles(profiles: &[mp::Profile]) -> Result {
    let mut errors_exist = false;
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    for (i, profile) in profiles.iter().enumerate() {
        match mp::remove(&profile.path) {
            Ok(()) => {
                let separator = if i + 1 == profiles.len() { "" } else { "\n" };
                writeln!(&mut stdout, "{}{}", profile.info.description(), separator)?
            }
            Err(err) => {
                errors_exist = true;
                writeln!(io::stderr(), "{}", err)?
            }
        }
    }
    if errors_exist {
        // Don't need to show anything – all errors are already printed.
        Err(String::new().into())
    } else {
        Ok(())
    }
}
<commit_msg>Implement format in oneline<commit_after>use crate::cli::Command;
use chrono::{DateTime, Utc};
use mprovision as mp;
use std::io::{self, Write};
use std::path::Path;
use std::path::PathBuf;
use std::result;
use std::time::{Duration, SystemTime};

mod cli;

type Result = result::Result<(), main_error::MainError>;

fn main() -> Result {
    match cli::run() {
        Command::List(cli::ListParams {
            text,
            expire_in_days,
            directory,
            oneline,
        }) => list(&text, expire_in_days, directory, oneline),
        Command::ShowUuid(cli::ShowUuidParams { uuid, directory }) => show_uuid(&uuid, directory),
        Command::ShowFile(cli::ShowFileParams { file }) => show_file(&file),
        Command::Remove(cli::RemoveParams { ids, directory }) => remove(&ids, directory),
        Command::Clean(cli::CleanParams { directory }) => clean(directory),
    }
}

fn list(
    text: &Option<String>,
    expires_in_days: Option<u64>,
    directory: Option<PathBuf>,
    oneline: bool,
) -> Result {
    let dir = mp::with_directory(directory)?;
    let entries = mp::entries(&dir).map(std::iter::Iterator::collect)?;
    let date =
        expires_in_days.map(|days| SystemTime::now() + Duration::from_secs(days * 24 * 60 * 60));
    let filter_string = text.as_ref();
    let mut profiles = mp::filter(entries, |profile| match (date, filter_string) {
        (Some(date), Some(string)) => {
            profile.info.expiration_date <= date && profile.info.contains(string)
        }
        (Some(date), _) => profile.info.expiration_date <= date,
        (_, Some(string)) => profile.info.contains(string),
        (_, _) => true,
    });
    profiles.sort_by(|a, b| a.info.creation_date.cmp(&b.info.creation_date));
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    if oneline {
        for profile in profiles {
            writeln!(
                &mut stdout,
                "{} {} {} {}",
                profile.info.uuid,
                DateTime::<Utc>::from(profile.info.expiration_date).format("%Y-%m-%d"),
                profile.info.app_identifier,
                profile.info.name
            )?;
        }
    } else {
        for (i, profile) in profiles.iter().enumerate() {
            let separator = if i + 1 == profiles.len() { "" } else { "\n" };
            writeln!(&mut stdout, "{}{}", profile.info.description(), separator)?;
        }
    }
    Ok(())
}

fn show_uuid(uuid: &str, directory: Option<PathBuf>) -> Result {
    let dir = mp::with_directory(directory)?;
    let profile = mp::find_by_uuid(&dir, &uuid)?;
    show_file(&profile.path)
}

fn show_file(path: &Path) -> Result {
    let xml = mp::show(&path)?;
    writeln!(io::stdout(), "{}", xml)?;
    Ok(())
}

fn remove(ids: &[String], directory: Option<PathBuf>) -> Result {
    let dir = mp::with_directory(directory)?;
    let profiles = mp::find_by_ids(&dir, &ids)?;
    remove_profiles(&profiles)
}

fn clean(directory: Option<PathBuf>) -> Result {
    let date = SystemTime::now();
    let dir = mp::with_directory(directory)?;
    let entries = mp::entries(&dir).map(std::iter::Iterator::collect)?;
    let profiles = mp::filter(entries, |profile| profile.info.expiration_date <= date);
    remove_profiles(&profiles)
}

fn remove_profiles(profiles: &[mp::Profile]) -> Result {
    let mut errors_exist = false;
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    for (i, profile) in profiles.iter().enumerate() {
        match mp::remove(&profile.path) {
            Ok(()) => {
                let separator = if i + 1 == profiles.len() { "" } else { "\n" };
                writeln!(&mut stdout, "{}{}", profile.info.description(), separator)?
            }
            Err(err) => {
                errors_exist = true;
                writeln!(io::stderr(), "{}", err)?
            }
        }
    }
    if errors_exist {
        // Don't need to show anything – all errors are already printed.
        Err(String::new().into())
    } else {
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>refactor: use rust-clippy suggestions<commit_after><|endoftext|>


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

extern crate rusoto_core;
extern crate rusoto_budgets;

use rusoto_budgets::{Budgets, BudgetsClient, DescribeBudgetsRequest};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};

// Switch to DescribeReportDefinitions when botocore is updated?
#[test]
fn should_describe_budgets() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = BudgetsClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
    // This request needs the accountId set:
    let request = DescribeBudgetsRequest::default();

    let response = client.describe_budgets(&request).unwrap();
    println!("response: {:?}", response);
}<commit_msg>Ignore budgets test.<commit_after>#![cfg(feature = "budgets")]

extern crate rusoto_core;
extern crate rusoto_budgets;

use rusoto_budgets::{Budgets, BudgetsClient, DescribeBudgetsRequest};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};

// Switch to DescribeReportDefinitions when botocore is updated?
#[test]
#[ignore] // Ignore until we get this working
fn should_describe_budgets() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = BudgetsClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
    // This request needs the accountId set:
    let request = DescribeBudgetsRequest::default();

    let response = client.describe_budgets(&request).unwrap();
    println!("response: {:?}", response);
}<|endoftext|>


<commit_before>use exchange::Exchange;

#[derive(Debug)]
#[derive(PartialEq)]
pub enum Coinnect {
    BitstampApi
}

impl Coinnect {
    /// Create a new CoinnectApi by providing an API key & API secret
    pub fn new(exchange: Exchange, customer_id: &str, api_key: &str, api_secret: &str) -> Exchange {
        println!("customer_id: {}, api_key: {}, api_secret: {}", customer_id, api_key, api_secret);
        match exchange {
            Exchange::Bitstamp => Exchange::Bitstamp,
            Exchange::Kraken => Exchange::Kraken,
            Exchange::Poloniex => Exchange::Poloniex,
        }
    }
}<commit_msg>Remove a debug println<commit_after>use exchange::Exchange;

#[derive(Debug)]
#[derive(PartialEq)]
pub enum Coinnect {
    BitstampApi
}

impl Coinnect {
    /// Create a new CoinnectApi by providing an API key & API secret
    pub fn new(exchange: Exchange, customer_id: &str, api_key: &str, api_secret: &str) -> Exchange {
        match exchange {
            Exchange::Bitstamp => Exchange::Bitstamp,
            Exchange::Kraken => Exchange::Kraken,
            Exchange::Poloniex => Exchange::Poloniex,
        }
    }
}<|endoftext|>