file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
parse.rs | use diagnostic::Pos;
use nom::{ErrorKind, IResult, Needed};
use std::cell::RefCell;
use std::vec::Drain;
use syntax::Expr::*;
use syntax::{Expr, Ty};
use typed_arena::Arena;
pub mod lex {
use super::*;
fn space(i: &str) -> IResult<&str, ()> {
let mut chars = i.chars();
match chars.next() {
Some(c) if c.is_whitespace() => IResult::Done(chars.as_str(), ()),
Some('#') => map!(i, take_until!("\n"), |_| ()),
Some(_) => IResult::Error(ErrorKind::Custom(0)),
None => IResult::Incomplete(Needed::Size(1)),
}
}
macro_rules! token (
(pub $name:ident<$i:ty, $o:ty>, $submac:ident!( $($args:tt)* )) => (
#[allow(unused_variables)]
pub fn $name( i: $i ) -> $crate::nom::IResult<$i, $o, u32> {
delimited!(i,
many0!(call!($crate::parse::lex::space)),
$submac!($($args)*),
many0!(call!($crate::parse::lex::space))
)
}
);
);
// FIXME: Use is_xid_start and is_xid_continue.
fn is_ident_continue(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '%'
}
token!(pub ident<&str, String>, do_parse!(
not!(call!(keyw::any)) >>
name: take_while1!(is_ident_continue) >>
(name.to_string())
));
token!(pub str<&str, String>, do_parse!(
tag!("\"") >>
name: take_until!("\"") >>
tag!("\"") >>
(name.to_string())
));
pub mod keyw {
named!(pub any<&str, &str>, alt!(
call!(end) |
call!(false_) |
call!(forall) |
call!(fun) |
call!(in_) |
call!(let_) |
call!(true_) |
call!(val)
));
token!(pub end <&str, &str>, tag!("end"));
token!(pub false_<&str, &str>, tag!("false"));
token!(pub forall<&str, &str>, alt!(tag!("forall") | tag!("∀")));
token!(pub fun <&str, &str>, tag!("fun"));
token!(pub in_ <&str, &str>, tag!("in"));
token!(pub let_ <&str, &str>, tag!("let"));
token!(pub true_ <&str, &str>, tag!("true"));
token!(pub val <&str, &str>, tag!("val"));
}
pub mod punc {
token!(pub arrow <&str, &str>, tag!("->"));
token!(pub equals <&str, &str>, tag!("="));
token!(pub colon <&str, &str>, tag!(":"));
token!(pub comma <&str, &str>, tag!(","));
token!(pub left_paren <&str, &str>, tag!("("));
token!(pub right_paren<&str, &str>, tag!(")"));
}
}
pub mod expr {
use super::*;
type A<'e, 't> = (&'e Arena<Expr<'e, 't>>, &'t Arena<Ty<'t>>);
type I<'s> = &'s str;
type O<'e, 't> = &'e Expr<'e, 't>;
static POS: Pos = Pos(0);
pub fn level_1<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, fold_many1!(call!(level_2, a), None, |acc, arg| {
match acc {
Some(callee) => Some(&*a.0.alloc(App(POS, callee, arg))),
None => Some(arg),
}
}), Option::unwrap)
}
pub fn level_2<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
alt!(i,
do_parse!(
call!(lex::punc::left_paren) >>
expr: call!(level_1, a) >>
call!(lex::punc::right_paren) >>
(expr)
) |
call!(bool, a) |
call!(str, a) |
call!(var, a) |
call!(abs, a) |
call!(let_, a)
)
}
pub fn bool<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
alt!(i,
map!(call!(lex::keyw::false_), |_| &*a.0.alloc(Bool(POS, false))) |
map!(call!(lex::keyw::true_), |_| &*a.0.alloc(Bool(POS, true)))
)
}
pub fn str<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, call!(lex::str), |x| &*a.0.alloc(Str(POS, RefCell::new(x))))
}
pub fn var<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, call!(lex::ident), |x| &*a.0.alloc(Var(POS, x)))
}
pub fn abs<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
do_parse!(i,
call!(lex::keyw::fun) >>
param: call!(lex::ident) >>
call!(lex::punc::arrow) >>
body: call!(level_1, a) >>
call!(lex::keyw::end) >>
(a.0.alloc(Abs(POS, param, body)))
)
}
pub fn let_<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
let make_let = |acc, mut vals|
drain_all(&mut vals)
.rev()
.fold(acc, |acc, (name, ty, value)|
a.0.alloc(Let(POS, name, ty, value, acc)));
do_parse!(i,
call!(lex::keyw::let_) >>
vals: many0!(do_parse!(
call!(lex::keyw::val) >>
name: call!(lex::ident) >>
ty: opt!(do_parse!(
call!(lex::punc::colon) >>
ty: call!(ty::level_1, a.1) >>
(ty)
)) >>
call!(lex::punc::equals) >>
value: call!(level_1, a) >>
(name, ty, value)
)) >>
call!(lex::keyw::in_) >>
body: call!(level_1, a) >>
call!(lex::keyw::end) >>
(make_let(body, vals))
)
}
fn drain_all<T>(vec: &mut Vec<T>) -> Drain<T> {
let range = 0.. vec.len();
vec.drain(range)
}
}
pub mod ty {
use super::*;
type A<'t> = &'t Arena<Ty<'t>>;
type I<'s> = &'s str;
type O<'t> = &'t Ty<'t>;
pub fn level_1<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
do_parse!(i,
left: call!(level_2, a) >>
right: opt!(do_parse!(
call!(lex::punc::arrow) >>
right: call!(level_1, a) >>
(right)
)) >>
(right.iter().fold(left, |acc, ty| a.alloc(Ty::Func(acc, ty))))
)
}
| call!(lex::punc::left_paren) >>
ty: call!(level_1, a) >>
call!(lex::punc::right_paren) >>
(ty)
) |
call!(var, a) |
call!(forall, a)
)
}
pub fn var<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
map!(i, call!(lex::ident), |x| &*a.alloc(Ty::Var(x)))
}
pub fn forall<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
do_parse!(i,
call!(lex::keyw::forall) >>
var: call!(lex::ident) >>
call!(lex::punc::comma) >>
inner: call!(level_1, a) >>
(a.alloc(Ty::Forall(var, inner)))
)
}
}
#[cfg(test)]
mod test {
use super::*;
mod expr_test {
use super::*;
#[test]
fn test_bool() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("false", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_var() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("fantastic", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_abs() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("fun a -> a end", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_app() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("foo bar (baz qux)", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_let() {
let ta = Arena::new();
let ea = Arena::new();
{
let r = expr::level_1("let val x = y in z end", (&ea, &ta));
println!("{:?}", r);
}
{
let r = expr::level_1("let val v = w val x = y in z end", (&ea, &ta));
println!("{:?}", r);
}
}
}
} | pub fn level_2<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
alt!(i,
do_parse!( | random_line_split |
parse.rs | use diagnostic::Pos;
use nom::{ErrorKind, IResult, Needed};
use std::cell::RefCell;
use std::vec::Drain;
use syntax::Expr::*;
use syntax::{Expr, Ty};
use typed_arena::Arena;
pub mod lex {
use super::*;
fn space(i: &str) -> IResult<&str, ()> {
let mut chars = i.chars();
match chars.next() {
Some(c) if c.is_whitespace() => IResult::Done(chars.as_str(), ()),
Some('#') => map!(i, take_until!("\n"), |_| ()),
Some(_) => IResult::Error(ErrorKind::Custom(0)),
None => IResult::Incomplete(Needed::Size(1)),
}
}
macro_rules! token (
(pub $name:ident<$i:ty, $o:ty>, $submac:ident!( $($args:tt)* )) => (
#[allow(unused_variables)]
pub fn $name( i: $i ) -> $crate::nom::IResult<$i, $o, u32> {
delimited!(i,
many0!(call!($crate::parse::lex::space)),
$submac!($($args)*),
many0!(call!($crate::parse::lex::space))
)
}
);
);
// FIXME: Use is_xid_start and is_xid_continue.
fn is_ident_continue(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '%'
}
token!(pub ident<&str, String>, do_parse!(
not!(call!(keyw::any)) >>
name: take_while1!(is_ident_continue) >>
(name.to_string())
));
token!(pub str<&str, String>, do_parse!(
tag!("\"") >>
name: take_until!("\"") >>
tag!("\"") >>
(name.to_string())
));
pub mod keyw {
named!(pub any<&str, &str>, alt!(
call!(end) |
call!(false_) |
call!(forall) |
call!(fun) |
call!(in_) |
call!(let_) |
call!(true_) |
call!(val)
));
token!(pub end <&str, &str>, tag!("end"));
token!(pub false_<&str, &str>, tag!("false"));
token!(pub forall<&str, &str>, alt!(tag!("forall") | tag!("∀")));
token!(pub fun <&str, &str>, tag!("fun"));
token!(pub in_ <&str, &str>, tag!("in"));
token!(pub let_ <&str, &str>, tag!("let"));
token!(pub true_ <&str, &str>, tag!("true"));
token!(pub val <&str, &str>, tag!("val"));
}
pub mod punc {
token!(pub arrow <&str, &str>, tag!("->"));
token!(pub equals <&str, &str>, tag!("="));
token!(pub colon <&str, &str>, tag!(":"));
token!(pub comma <&str, &str>, tag!(","));
token!(pub left_paren <&str, &str>, tag!("("));
token!(pub right_paren<&str, &str>, tag!(")"));
}
}
pub mod expr {
use super::*;
type A<'e, 't> = (&'e Arena<Expr<'e, 't>>, &'t Arena<Ty<'t>>);
type I<'s> = &'s str;
type O<'e, 't> = &'e Expr<'e, 't>;
static POS: Pos = Pos(0);
pub fn level_1<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, fold_many1!(call!(level_2, a), None, |acc, arg| {
match acc {
Some(callee) => Some(&*a.0.alloc(App(POS, callee, arg))),
None => Some(arg),
}
}), Option::unwrap)
}
pub fn level_2<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
alt!(i,
do_parse!(
call!(lex::punc::left_paren) >>
expr: call!(level_1, a) >>
call!(lex::punc::right_paren) >>
(expr)
) |
call!(bool, a) |
call!(str, a) |
call!(var, a) |
call!(abs, a) |
call!(let_, a)
)
}
pub fn bool<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
alt!(i,
map!(call!(lex::keyw::false_), |_| &*a.0.alloc(Bool(POS, false))) |
map!(call!(lex::keyw::true_), |_| &*a.0.alloc(Bool(POS, true)))
)
}
pub fn str<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, call!(lex::str), |x| &*a.0.alloc(Str(POS, RefCell::new(x))))
}
pub fn var<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, call!(lex::ident), |x| &*a.0.alloc(Var(POS, x)))
}
pub fn abs<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
do_parse!(i,
call!(lex::keyw::fun) >>
param: call!(lex::ident) >>
call!(lex::punc::arrow) >>
body: call!(level_1, a) >>
call!(lex::keyw::end) >>
(a.0.alloc(Abs(POS, param, body)))
)
}
pub fn let_<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
| body: call!(level_1, a) >>
call!(lex::keyw::end) >>
(make_let(body, vals))
)
}
fn drain_all<T>(vec: &mut Vec<T>) -> Drain<T> {
let range = 0.. vec.len();
vec.drain(range)
}
}
pub mod ty {
use super::*;
type A<'t> = &'t Arena<Ty<'t>>;
type I<'s> = &'s str;
type O<'t> = &'t Ty<'t>;
pub fn level_1<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
do_parse!(i,
left: call!(level_2, a) >>
right: opt!(do_parse!(
call!(lex::punc::arrow) >>
right: call!(level_1, a) >>
(right)
)) >>
(right.iter().fold(left, |acc, ty| a.alloc(Ty::Func(acc, ty))))
)
}
pub fn level_2<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
alt!(i,
do_parse!(
call!(lex::punc::left_paren) >>
ty: call!(level_1, a) >>
call!(lex::punc::right_paren) >>
(ty)
) |
call!(var, a) |
call!(forall, a)
)
}
pub fn var<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
map!(i, call!(lex::ident), |x| &*a.alloc(Ty::Var(x)))
}
pub fn forall<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
do_parse!(i,
call!(lex::keyw::forall) >>
var: call!(lex::ident) >>
call!(lex::punc::comma) >>
inner: call!(level_1, a) >>
(a.alloc(Ty::Forall(var, inner)))
)
}
}
#[cfg(test)]
mod test {
use super::*;
mod expr_test {
use super::*;
#[test]
fn test_bool() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("false", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_var() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("fantastic", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_abs() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("fun a -> a end", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_app() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("foo bar (baz qux)", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_let() {
let ta = Arena::new();
let ea = Arena::new();
{
let r = expr::level_1("let val x = y in z end", (&ea, &ta));
println!("{:?}", r);
}
{
let r = expr::level_1("let val v = w val x = y in z end", (&ea, &ta));
println!("{:?}", r);
}
}
}
}
| let make_let = |acc, mut vals|
drain_all(&mut vals)
.rev()
.fold(acc, |acc, (name, ty, value)|
a.0.alloc(Let(POS, name, ty, value, acc)));
do_parse!(i,
call!(lex::keyw::let_) >>
vals: many0!(do_parse!(
call!(lex::keyw::val) >>
name: call!(lex::ident) >>
ty: opt!(do_parse!(
call!(lex::punc::colon) >>
ty: call!(ty::level_1, a.1) >>
(ty)
)) >>
call!(lex::punc::equals) >>
value: call!(level_1, a) >>
(name, ty, value)
)) >>
call!(lex::keyw::in_) >> | identifier_body |
parse.rs | use diagnostic::Pos;
use nom::{ErrorKind, IResult, Needed};
use std::cell::RefCell;
use std::vec::Drain;
use syntax::Expr::*;
use syntax::{Expr, Ty};
use typed_arena::Arena;
pub mod lex {
use super::*;
fn space(i: &str) -> IResult<&str, ()> {
let mut chars = i.chars();
match chars.next() {
Some(c) if c.is_whitespace() => IResult::Done(chars.as_str(), ()),
Some('#') => map!(i, take_until!("\n"), |_| ()),
Some(_) => IResult::Error(ErrorKind::Custom(0)),
None => IResult::Incomplete(Needed::Size(1)),
}
}
macro_rules! token (
(pub $name:ident<$i:ty, $o:ty>, $submac:ident!( $($args:tt)* )) => (
#[allow(unused_variables)]
pub fn $name( i: $i ) -> $crate::nom::IResult<$i, $o, u32> {
delimited!(i,
many0!(call!($crate::parse::lex::space)),
$submac!($($args)*),
many0!(call!($crate::parse::lex::space))
)
}
);
);
// FIXME: Use is_xid_start and is_xid_continue.
fn is_ident_continue(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '%'
}
token!(pub ident<&str, String>, do_parse!(
not!(call!(keyw::any)) >>
name: take_while1!(is_ident_continue) >>
(name.to_string())
));
token!(pub str<&str, String>, do_parse!(
tag!("\"") >>
name: take_until!("\"") >>
tag!("\"") >>
(name.to_string())
));
pub mod keyw {
named!(pub any<&str, &str>, alt!(
call!(end) |
call!(false_) |
call!(forall) |
call!(fun) |
call!(in_) |
call!(let_) |
call!(true_) |
call!(val)
));
token!(pub end <&str, &str>, tag!("end"));
token!(pub false_<&str, &str>, tag!("false"));
token!(pub forall<&str, &str>, alt!(tag!("forall") | tag!("∀")));
token!(pub fun <&str, &str>, tag!("fun"));
token!(pub in_ <&str, &str>, tag!("in"));
token!(pub let_ <&str, &str>, tag!("let"));
token!(pub true_ <&str, &str>, tag!("true"));
token!(pub val <&str, &str>, tag!("val"));
}
pub mod punc {
token!(pub arrow <&str, &str>, tag!("->"));
token!(pub equals <&str, &str>, tag!("="));
token!(pub colon <&str, &str>, tag!(":"));
token!(pub comma <&str, &str>, tag!(","));
token!(pub left_paren <&str, &str>, tag!("("));
token!(pub right_paren<&str, &str>, tag!(")"));
}
}
pub mod expr {
use super::*;
type A<'e, 't> = (&'e Arena<Expr<'e, 't>>, &'t Arena<Ty<'t>>);
type I<'s> = &'s str;
type O<'e, 't> = &'e Expr<'e, 't>;
static POS: Pos = Pos(0);
pub fn level_1<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, fold_many1!(call!(level_2, a), None, |acc, arg| {
match acc {
Some(callee) => Some(&*a.0.alloc(App(POS, callee, arg))),
None => Some(arg),
}
}), Option::unwrap)
}
pub fn level_2<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
alt!(i,
do_parse!(
call!(lex::punc::left_paren) >>
expr: call!(level_1, a) >>
call!(lex::punc::right_paren) >>
(expr)
) |
call!(bool, a) |
call!(str, a) |
call!(var, a) |
call!(abs, a) |
call!(let_, a)
)
}
pub fn bool<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
alt!(i,
map!(call!(lex::keyw::false_), |_| &*a.0.alloc(Bool(POS, false))) |
map!(call!(lex::keyw::true_), |_| &*a.0.alloc(Bool(POS, true)))
)
}
pub fn str<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, call!(lex::str), |x| &*a.0.alloc(Str(POS, RefCell::new(x))))
}
pub fn var<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
map!(i, call!(lex::ident), |x| &*a.0.alloc(Var(POS, x)))
}
pub fn abs<'s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
do_parse!(i,
call!(lex::keyw::fun) >>
param: call!(lex::ident) >>
call!(lex::punc::arrow) >>
body: call!(level_1, a) >>
call!(lex::keyw::end) >>
(a.0.alloc(Abs(POS, param, body)))
)
}
pub fn le | s, 'e, 't>(i: I<'s>, a: A<'e, 't>) -> IResult<I<'s>, O<'e, 't>> {
let make_let = |acc, mut vals|
drain_all(&mut vals)
.rev()
.fold(acc, |acc, (name, ty, value)|
a.0.alloc(Let(POS, name, ty, value, acc)));
do_parse!(i,
call!(lex::keyw::let_) >>
vals: many0!(do_parse!(
call!(lex::keyw::val) >>
name: call!(lex::ident) >>
ty: opt!(do_parse!(
call!(lex::punc::colon) >>
ty: call!(ty::level_1, a.1) >>
(ty)
)) >>
call!(lex::punc::equals) >>
value: call!(level_1, a) >>
(name, ty, value)
)) >>
call!(lex::keyw::in_) >>
body: call!(level_1, a) >>
call!(lex::keyw::end) >>
(make_let(body, vals))
)
}
fn drain_all<T>(vec: &mut Vec<T>) -> Drain<T> {
let range = 0.. vec.len();
vec.drain(range)
}
}
pub mod ty {
use super::*;
type A<'t> = &'t Arena<Ty<'t>>;
type I<'s> = &'s str;
type O<'t> = &'t Ty<'t>;
pub fn level_1<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
do_parse!(i,
left: call!(level_2, a) >>
right: opt!(do_parse!(
call!(lex::punc::arrow) >>
right: call!(level_1, a) >>
(right)
)) >>
(right.iter().fold(left, |acc, ty| a.alloc(Ty::Func(acc, ty))))
)
}
pub fn level_2<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
alt!(i,
do_parse!(
call!(lex::punc::left_paren) >>
ty: call!(level_1, a) >>
call!(lex::punc::right_paren) >>
(ty)
) |
call!(var, a) |
call!(forall, a)
)
}
pub fn var<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
map!(i, call!(lex::ident), |x| &*a.alloc(Ty::Var(x)))
}
pub fn forall<'s, 't>(i: I<'s>, a: A<'t>) -> IResult<I<'s>, O<'t>> {
do_parse!(i,
call!(lex::keyw::forall) >>
var: call!(lex::ident) >>
call!(lex::punc::comma) >>
inner: call!(level_1, a) >>
(a.alloc(Ty::Forall(var, inner)))
)
}
}
#[cfg(test)]
mod test {
use super::*;
mod expr_test {
use super::*;
#[test]
fn test_bool() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("false", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_var() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("fantastic", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_abs() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("fun a -> a end", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_app() {
let ta = Arena::new();
let ea = Arena::new();
let r = expr::level_1("foo bar (baz qux)", (&ea, &ta));
println!("{:?}", r);
}
#[test]
fn test_let() {
let ta = Arena::new();
let ea = Arena::new();
{
let r = expr::level_1("let val x = y in z end", (&ea, &ta));
println!("{:?}", r);
}
{
let r = expr::level_1("let val v = w val x = y in z end", (&ea, &ta));
println!("{:?}", r);
}
}
}
}
| t_<' | identifier_name |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, window_from_node};
use dom::nodelist::NodeList;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() &&!element.get_disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if!self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>()!= picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple);
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!(disabled) {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn | (&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value, DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
| parse_plain_attribute | identifier_name |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, window_from_node};
use dom::nodelist::NodeList;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() &&!element.get_disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if!self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>()!= picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> |
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple);
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!(disabled) {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value, DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
| {
let window = window_from_node(self);
ValidityState::new(window.r())
} | identifier_body |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, window_from_node};
use dom::nodelist::NodeList;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
| return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() &&!element.get_disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if!self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>()!= picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple);
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!(disabled) {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value, DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {} | // https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() { | random_line_split |
math_query_sql.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#[macro_use]
extern crate criterion;
use criterion::Criterion;
use std::sync::{Arc, Mutex};
use tokio::runtime::Runtime;
extern crate arrow;
extern crate datafusion;
use arrow::{
array::{Float32Array, Float64Array},
datatypes::{DataType, Field, Schema},
record_batch::RecordBatch,
};
use datafusion::error::Result;
use datafusion::datasource::MemTable;
use datafusion::execution::context::ExecutionContext;
fn | (ctx: Arc<Mutex<ExecutionContext>>, sql: &str) {
let rt = Runtime::new().unwrap();
// execute the query
let df = ctx.lock().unwrap().sql(&sql).unwrap();
rt.block_on(df.collect()).unwrap();
}
fn create_context(
array_len: usize,
batch_size: usize,
) -> Result<Arc<Mutex<ExecutionContext>>> {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("f32", DataType::Float32, false),
Field::new("f64", DataType::Float64, false),
]));
// define data.
let batches = (0..array_len / batch_size)
.map(|i| {
RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(Float32Array::from(vec![i as f32; batch_size])),
Arc::new(Float64Array::from(vec![i as f64; batch_size])),
],
)
.unwrap()
})
.collect::<Vec<_>>();
let mut ctx = ExecutionContext::new();
// declare a table in memory. In spark API, this corresponds to createDataFrame(...).
let provider = MemTable::new(schema, vec![batches])?;
ctx.register_table("t", Box::new(provider));
Ok(Arc::new(Mutex::new(ctx)))
}
fn criterion_benchmark(c: &mut Criterion) {
let array_len = 1048576; // 2^20
let batch_size = 512; // 2^9
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_20_9", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 1048576; // 2^20
let batch_size = 4096; // 2^12
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_20_12", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 4194304; // 2^22
let batch_size = 4096; // 2^12
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_22_12", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 4194304; // 2^22
let batch_size = 16384; // 2^14
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_22_14", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| query | identifier_name |
math_query_sql.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#[macro_use]
extern crate criterion;
use criterion::Criterion;
use std::sync::{Arc, Mutex};
use tokio::runtime::Runtime;
extern crate arrow;
extern crate datafusion;
use arrow::{
array::{Float32Array, Float64Array},
datatypes::{DataType, Field, Schema},
record_batch::RecordBatch,
};
use datafusion::error::Result;
| use datafusion::datasource::MemTable;
use datafusion::execution::context::ExecutionContext;
fn query(ctx: Arc<Mutex<ExecutionContext>>, sql: &str) {
let rt = Runtime::new().unwrap();
// execute the query
let df = ctx.lock().unwrap().sql(&sql).unwrap();
rt.block_on(df.collect()).unwrap();
}
fn create_context(
array_len: usize,
batch_size: usize,
) -> Result<Arc<Mutex<ExecutionContext>>> {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("f32", DataType::Float32, false),
Field::new("f64", DataType::Float64, false),
]));
// define data.
let batches = (0..array_len / batch_size)
.map(|i| {
RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(Float32Array::from(vec![i as f32; batch_size])),
Arc::new(Float64Array::from(vec![i as f64; batch_size])),
],
)
.unwrap()
})
.collect::<Vec<_>>();
let mut ctx = ExecutionContext::new();
// declare a table in memory. In spark API, this corresponds to createDataFrame(...).
let provider = MemTable::new(schema, vec![batches])?;
ctx.register_table("t", Box::new(provider));
Ok(Arc::new(Mutex::new(ctx)))
}
fn criterion_benchmark(c: &mut Criterion) {
let array_len = 1048576; // 2^20
let batch_size = 512; // 2^9
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_20_9", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 1048576; // 2^20
let batch_size = 4096; // 2^12
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_20_12", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 4194304; // 2^22
let batch_size = 4096; // 2^12
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_22_12", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 4194304; // 2^22
let batch_size = 16384; // 2^14
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_22_14", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches); | random_line_split |
|
math_query_sql.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#[macro_use]
extern crate criterion;
use criterion::Criterion;
use std::sync::{Arc, Mutex};
use tokio::runtime::Runtime;
extern crate arrow;
extern crate datafusion;
use arrow::{
array::{Float32Array, Float64Array},
datatypes::{DataType, Field, Schema},
record_batch::RecordBatch,
};
use datafusion::error::Result;
use datafusion::datasource::MemTable;
use datafusion::execution::context::ExecutionContext;
fn query(ctx: Arc<Mutex<ExecutionContext>>, sql: &str) {
let rt = Runtime::new().unwrap();
// execute the query
let df = ctx.lock().unwrap().sql(&sql).unwrap();
rt.block_on(df.collect()).unwrap();
}
fn create_context(
array_len: usize,
batch_size: usize,
) -> Result<Arc<Mutex<ExecutionContext>>> |
let mut ctx = ExecutionContext::new();
// declare a table in memory. In spark API, this corresponds to createDataFrame(...).
let provider = MemTable::new(schema, vec![batches])?;
ctx.register_table("t", Box::new(provider));
Ok(Arc::new(Mutex::new(ctx)))
}
fn criterion_benchmark(c: &mut Criterion) {
let array_len = 1048576; // 2^20
let batch_size = 512; // 2^9
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_20_9", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 1048576; // 2^20
let batch_size = 4096; // 2^12
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_20_12", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 4194304; // 2^22
let batch_size = 4096; // 2^12
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_22_12", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
let array_len = 4194304; // 2^22
let batch_size = 16384; // 2^14
let ctx = create_context(array_len, batch_size).unwrap();
c.bench_function("sqrt_22_14", |b| {
b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("f32", DataType::Float32, false),
Field::new("f64", DataType::Float64, false),
]));
// define data.
let batches = (0..array_len / batch_size)
.map(|i| {
RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(Float32Array::from(vec![i as f32; batch_size])),
Arc::new(Float64Array::from(vec![i as f64; batch_size])),
],
)
.unwrap()
})
.collect::<Vec<_>>(); | identifier_body |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
#[dom_struct]
pub struct WebGLUniformLocation {
reflector_: Reflector,
id: i32,
program_id: u32,
}
impl WebGLUniformLocation {
fn new_inherited(id: i32, program_id: u32) -> WebGLUniformLocation { | WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
program_id: program_id,
}
}
pub fn new(global: GlobalRef, id: i32, program_id: u32) -> Root<WebGLUniformLocation> {
reflect_dom_object(
box WebGLUniformLocation::new_inherited(id, program_id), global, WebGLUniformLocationBinding::Wrap)
}
}
impl WebGLUniformLocation {
pub fn id(&self) -> i32 {
self.id
}
pub fn program_id(&self) -> u32 {
self.program_id
}
} | random_line_split |
|
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
#[dom_struct]
pub struct WebGLUniformLocation {
reflector_: Reflector,
id: i32,
program_id: u32,
}
impl WebGLUniformLocation {
fn new_inherited(id: i32, program_id: u32) -> WebGLUniformLocation {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
program_id: program_id,
}
}
pub fn | (global: GlobalRef, id: i32, program_id: u32) -> Root<WebGLUniformLocation> {
reflect_dom_object(
box WebGLUniformLocation::new_inherited(id, program_id), global, WebGLUniformLocationBinding::Wrap)
}
}
impl WebGLUniformLocation {
pub fn id(&self) -> i32 {
self.id
}
pub fn program_id(&self) -> u32 {
self.program_id
}
}
| new | identifier_name |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
#[dom_struct]
pub struct WebGLUniformLocation {
reflector_: Reflector,
id: i32,
program_id: u32,
}
impl WebGLUniformLocation {
fn new_inherited(id: i32, program_id: u32) -> WebGLUniformLocation {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
program_id: program_id,
}
}
pub fn new(global: GlobalRef, id: i32, program_id: u32) -> Root<WebGLUniformLocation> {
reflect_dom_object(
box WebGLUniformLocation::new_inherited(id, program_id), global, WebGLUniformLocationBinding::Wrap)
}
}
impl WebGLUniformLocation {
pub fn id(&self) -> i32 |
pub fn program_id(&self) -> u32 {
self.program_id
}
}
| {
self.id
} | identifier_body |
issue-47715.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 Foo {}
trait Bar<T> {}
trait Iterable {
type Item;
}
struct Container<T: Iterable<Item = impl Foo>> {
//~^ ERROR `impl Trait` not allowed
field: T
}
enum Enum<T: Iterable<Item = impl Foo>> {
//~^ ERROR `impl Trait` not allowed
A(T),
}
union Union<T: Iterable<Item = impl Foo> + Copy> {
//~^ ERROR `impl Trait` not allowed
x: T,
}
| fn main() {
} | type Type<T: Iterable<Item = impl Foo>> = T;
//~^ ERROR `impl Trait` not allowed
| random_line_split |
issue-47715.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 Foo {}
trait Bar<T> {}
trait Iterable {
type Item;
}
struct Container<T: Iterable<Item = impl Foo>> {
//~^ ERROR `impl Trait` not allowed
field: T
}
enum | <T: Iterable<Item = impl Foo>> {
//~^ ERROR `impl Trait` not allowed
A(T),
}
union Union<T: Iterable<Item = impl Foo> + Copy> {
//~^ ERROR `impl Trait` not allowed
x: T,
}
type Type<T: Iterable<Item = impl Foo>> = T;
//~^ ERROR `impl Trait` not allowed
fn main() {
}
| Enum | identifier_name |
shader.rs | use gfx;
use gfx::traits::FactoryExt;
use vecmath::{self, Matrix4};
static VERTEX: &[u8] = b"
#version 150 core
uniform mat4 u_projection, u_view;
in vec2 at_tex_coord;
in vec3 at_color, at_position;
out vec2 v_tex_coord;
out vec3 v_color;
void main() {
v_tex_coord = at_tex_coord;
v_color = at_color;
gl_Position = u_projection * u_view * vec4(at_position, 1.0);
}
";
static FRAGMENT: &[u8] = b"
#version 150 core
out vec4 out_color;
uniform sampler2D s_texture;
in vec2 v_tex_coord;
in vec3 v_color;
void main() {
vec4 tex_color = texture(s_texture, v_tex_coord);
if(tex_color.a == 0.0) // Discard transparent pixels.
discard;
out_color = tex_color * vec4(v_color, 1.0);
}
";
gfx_pipeline!( pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
transform: gfx::Global<[[f32; 4]; 4]> = "u_projection",
view: gfx::Global<[[f32; 4]; 4]> = "u_view",
color: gfx::TextureSampler<[f32; 4]> = "s_texture",
out_color: gfx::RenderTarget<gfx::format::Srgba8> = "out_color",
out_depth: gfx::DepthTarget<gfx::format::DepthStencil> =
gfx::preset::depth::LESS_EQUAL_WRITE,
});
gfx_vertex_struct!(Vertex {
xyz: [f32; 3] = "at_position",
uv: [f32; 2] = "at_tex_coord",
rgb: [f32; 3] = "at_color",
});
pub struct Renderer<R: gfx::Resources, F: gfx::Factory<R>, C: gfx::CommandBuffer<R>> {
factory: F,
pub pipe: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
encoder: gfx::Encoder<R, C>,
clear_color: [f32; 4],
clear_depth: f32,
clear_stencil: u8,
slice: gfx::Slice<R>,
}
impl<R: gfx::Resources, F: gfx::Factory<R>, C: gfx::CommandBuffer<R>> Renderer<R, F, C> {
pub fn new(
mut factory: F,
encoder: gfx::Encoder<R, C>,
target: gfx::handle::RenderTargetView<R, gfx::format::Srgba8>,
depth: gfx::handle::DepthStencilView<R, (gfx::format::D24_S8, gfx::format::Unorm)>,
tex: gfx::handle::Texture<R, gfx::format::R8_G8_B8_A8>,
) -> Renderer<R, F, C> {
let sampler = factory.create_sampler(gfx::texture::SamplerInfo::new(
gfx::texture::FilterMethod::Scale,
gfx::texture::WrapMode::Tile,
));
let texture_view = factory
.view_texture_as_shader_resource::<gfx::format::Rgba8>(
&tex,
(0, 0),
gfx::format::Swizzle::new(),
)
.unwrap();
let prog = factory.link_program(VERTEX, FRAGMENT).unwrap();
let mut rasterizer = gfx::state::Rasterizer::new_fill();
rasterizer.front_face = gfx::state::FrontFace::Clockwise;
let pipe = factory
.create_pipeline_from_program(
&prog,
gfx::Primitive::TriangleList,
rasterizer,
pipe::new(),
)
.unwrap();
let vbuf = factory.create_vertex_buffer(&[]);
let slice = gfx::Slice::new_match_vertex_buffer(&vbuf);
let data = pipe::Data {
vbuf,
transform: vecmath::mat4_id(),
view: vecmath::mat4_id(),
color: (texture_view, sampler),
out_color: target,
out_depth: depth,
};
Renderer {
factory,
pipe,
data,
encoder,
clear_color: [0.81, 0.8, 1.0, 1.0],
clear_depth: 1.0,
clear_stencil: 0,
slice,
}
}
pub fn set_projection(&mut self, proj_mat: Matrix4<f32>) {
self.data.transform = proj_mat;
}
pub fn set_view(&mut self, view_mat: Matrix4<f32>) |
pub fn clear(&mut self) {
self.encoder.clear(&self.data.out_color, self.clear_color);
self.encoder
.clear_depth(&self.data.out_depth, self.clear_depth);
self.encoder
.clear_stencil(&self.data.out_depth, self.clear_stencil);
}
pub fn flush<D: gfx::Device<Resources = R, CommandBuffer = C> + Sized>(
&mut self,
device: &mut D,
) {
self.encoder.flush(device);
}
pub fn create_buffer(&mut self, data: &[Vertex]) -> gfx::handle::Buffer<R, Vertex> {
let vbuf = self.factory.create_vertex_buffer(data);
self.slice = gfx::Slice::new_match_vertex_buffer(&vbuf);
vbuf
}
pub fn render(&mut self, buffer: &mut gfx::handle::Buffer<R, Vertex>) {
self.data.vbuf = buffer.clone();
self.slice.end = buffer.len() as u32;
self.encoder.draw(&self.slice, &self.pipe, &self.data);
}
}
| {
self.data.view = view_mat;
} | identifier_body |
shader.rs | use gfx;
use gfx::traits::FactoryExt;
use vecmath::{self, Matrix4};
static VERTEX: &[u8] = b"
#version 150 core
uniform mat4 u_projection, u_view;
in vec2 at_tex_coord;
in vec3 at_color, at_position;
out vec2 v_tex_coord;
out vec3 v_color;
void main() {
v_tex_coord = at_tex_coord;
v_color = at_color;
gl_Position = u_projection * u_view * vec4(at_position, 1.0);
}
";
static FRAGMENT: &[u8] = b"
#version 150 core
out vec4 out_color;
uniform sampler2D s_texture;
in vec2 v_tex_coord;
in vec3 v_color;
void main() {
vec4 tex_color = texture(s_texture, v_tex_coord);
if(tex_color.a == 0.0) // Discard transparent pixels.
discard;
out_color = tex_color * vec4(v_color, 1.0);
}
";
gfx_pipeline!( pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
transform: gfx::Global<[[f32; 4]; 4]> = "u_projection",
view: gfx::Global<[[f32; 4]; 4]> = "u_view",
color: gfx::TextureSampler<[f32; 4]> = "s_texture",
out_color: gfx::RenderTarget<gfx::format::Srgba8> = "out_color",
out_depth: gfx::DepthTarget<gfx::format::DepthStencil> =
gfx::preset::depth::LESS_EQUAL_WRITE,
});
gfx_vertex_struct!(Vertex {
xyz: [f32; 3] = "at_position",
uv: [f32; 2] = "at_tex_coord",
rgb: [f32; 3] = "at_color",
});
pub struct Renderer<R: gfx::Resources, F: gfx::Factory<R>, C: gfx::CommandBuffer<R>> {
factory: F,
pub pipe: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
encoder: gfx::Encoder<R, C>,
clear_color: [f32; 4],
clear_depth: f32,
clear_stencil: u8,
slice: gfx::Slice<R>,
}
impl<R: gfx::Resources, F: gfx::Factory<R>, C: gfx::CommandBuffer<R>> Renderer<R, F, C> {
pub fn new(
mut factory: F,
encoder: gfx::Encoder<R, C>,
target: gfx::handle::RenderTargetView<R, gfx::format::Srgba8>,
depth: gfx::handle::DepthStencilView<R, (gfx::format::D24_S8, gfx::format::Unorm)>,
tex: gfx::handle::Texture<R, gfx::format::R8_G8_B8_A8>,
) -> Renderer<R, F, C> {
let sampler = factory.create_sampler(gfx::texture::SamplerInfo::new(
gfx::texture::FilterMethod::Scale,
gfx::texture::WrapMode::Tile,
));
let texture_view = factory
.view_texture_as_shader_resource::<gfx::format::Rgba8>(
&tex,
(0, 0),
gfx::format::Swizzle::new(),
)
.unwrap();
let prog = factory.link_program(VERTEX, FRAGMENT).unwrap();
let mut rasterizer = gfx::state::Rasterizer::new_fill();
rasterizer.front_face = gfx::state::FrontFace::Clockwise;
let pipe = factory
.create_pipeline_from_program(
&prog,
gfx::Primitive::TriangleList,
rasterizer,
pipe::new(),
)
.unwrap();
let vbuf = factory.create_vertex_buffer(&[]);
let slice = gfx::Slice::new_match_vertex_buffer(&vbuf);
let data = pipe::Data {
vbuf,
transform: vecmath::mat4_id(),
view: vecmath::mat4_id(),
color: (texture_view, sampler),
out_color: target,
out_depth: depth,
};
Renderer {
factory,
pipe,
data,
encoder,
clear_color: [0.81, 0.8, 1.0, 1.0],
clear_depth: 1.0,
clear_stencil: 0,
slice,
}
}
pub fn set_projection(&mut self, proj_mat: Matrix4<f32>) {
self.data.transform = proj_mat;
}
pub fn set_view(&mut self, view_mat: Matrix4<f32>) {
self.data.view = view_mat;
}
pub fn clear(&mut self) {
self.encoder.clear(&self.data.out_color, self.clear_color);
self.encoder
.clear_depth(&self.data.out_depth, self.clear_depth);
self.encoder
.clear_stencil(&self.data.out_depth, self.clear_stencil);
}
pub fn flush<D: gfx::Device<Resources = R, CommandBuffer = C> + Sized>(
&mut self,
device: &mut D,
) {
self.encoder.flush(device);
}
pub fn create_buffer(&mut self, data: &[Vertex]) -> gfx::handle::Buffer<R, Vertex> {
let vbuf = self.factory.create_vertex_buffer(data);
self.slice = gfx::Slice::new_match_vertex_buffer(&vbuf);
vbuf
}
| self.data.vbuf = buffer.clone();
self.slice.end = buffer.len() as u32;
self.encoder.draw(&self.slice, &self.pipe, &self.data);
}
} | pub fn render(&mut self, buffer: &mut gfx::handle::Buffer<R, Vertex>) { | random_line_split |
shader.rs | use gfx;
use gfx::traits::FactoryExt;
use vecmath::{self, Matrix4};
static VERTEX: &[u8] = b"
#version 150 core
uniform mat4 u_projection, u_view;
in vec2 at_tex_coord;
in vec3 at_color, at_position;
out vec2 v_tex_coord;
out vec3 v_color;
void main() {
v_tex_coord = at_tex_coord;
v_color = at_color;
gl_Position = u_projection * u_view * vec4(at_position, 1.0);
}
";
static FRAGMENT: &[u8] = b"
#version 150 core
out vec4 out_color;
uniform sampler2D s_texture;
in vec2 v_tex_coord;
in vec3 v_color;
void main() {
vec4 tex_color = texture(s_texture, v_tex_coord);
if(tex_color.a == 0.0) // Discard transparent pixels.
discard;
out_color = tex_color * vec4(v_color, 1.0);
}
";
gfx_pipeline!( pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
transform: gfx::Global<[[f32; 4]; 4]> = "u_projection",
view: gfx::Global<[[f32; 4]; 4]> = "u_view",
color: gfx::TextureSampler<[f32; 4]> = "s_texture",
out_color: gfx::RenderTarget<gfx::format::Srgba8> = "out_color",
out_depth: gfx::DepthTarget<gfx::format::DepthStencil> =
gfx::preset::depth::LESS_EQUAL_WRITE,
});
gfx_vertex_struct!(Vertex {
xyz: [f32; 3] = "at_position",
uv: [f32; 2] = "at_tex_coord",
rgb: [f32; 3] = "at_color",
});
pub struct Renderer<R: gfx::Resources, F: gfx::Factory<R>, C: gfx::CommandBuffer<R>> {
factory: F,
pub pipe: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
encoder: gfx::Encoder<R, C>,
clear_color: [f32; 4],
clear_depth: f32,
clear_stencil: u8,
slice: gfx::Slice<R>,
}
impl<R: gfx::Resources, F: gfx::Factory<R>, C: gfx::CommandBuffer<R>> Renderer<R, F, C> {
pub fn new(
mut factory: F,
encoder: gfx::Encoder<R, C>,
target: gfx::handle::RenderTargetView<R, gfx::format::Srgba8>,
depth: gfx::handle::DepthStencilView<R, (gfx::format::D24_S8, gfx::format::Unorm)>,
tex: gfx::handle::Texture<R, gfx::format::R8_G8_B8_A8>,
) -> Renderer<R, F, C> {
let sampler = factory.create_sampler(gfx::texture::SamplerInfo::new(
gfx::texture::FilterMethod::Scale,
gfx::texture::WrapMode::Tile,
));
let texture_view = factory
.view_texture_as_shader_resource::<gfx::format::Rgba8>(
&tex,
(0, 0),
gfx::format::Swizzle::new(),
)
.unwrap();
let prog = factory.link_program(VERTEX, FRAGMENT).unwrap();
let mut rasterizer = gfx::state::Rasterizer::new_fill();
rasterizer.front_face = gfx::state::FrontFace::Clockwise;
let pipe = factory
.create_pipeline_from_program(
&prog,
gfx::Primitive::TriangleList,
rasterizer,
pipe::new(),
)
.unwrap();
let vbuf = factory.create_vertex_buffer(&[]);
let slice = gfx::Slice::new_match_vertex_buffer(&vbuf);
let data = pipe::Data {
vbuf,
transform: vecmath::mat4_id(),
view: vecmath::mat4_id(),
color: (texture_view, sampler),
out_color: target,
out_depth: depth,
};
Renderer {
factory,
pipe,
data,
encoder,
clear_color: [0.81, 0.8, 1.0, 1.0],
clear_depth: 1.0,
clear_stencil: 0,
slice,
}
}
pub fn set_projection(&mut self, proj_mat: Matrix4<f32>) {
self.data.transform = proj_mat;
}
pub fn set_view(&mut self, view_mat: Matrix4<f32>) {
self.data.view = view_mat;
}
pub fn clear(&mut self) {
self.encoder.clear(&self.data.out_color, self.clear_color);
self.encoder
.clear_depth(&self.data.out_depth, self.clear_depth);
self.encoder
.clear_stencil(&self.data.out_depth, self.clear_stencil);
}
pub fn flush<D: gfx::Device<Resources = R, CommandBuffer = C> + Sized>(
&mut self,
device: &mut D,
) {
self.encoder.flush(device);
}
pub fn create_buffer(&mut self, data: &[Vertex]) -> gfx::handle::Buffer<R, Vertex> {
let vbuf = self.factory.create_vertex_buffer(data);
self.slice = gfx::Slice::new_match_vertex_buffer(&vbuf);
vbuf
}
pub fn | (&mut self, buffer: &mut gfx::handle::Buffer<R, Vertex>) {
self.data.vbuf = buffer.clone();
self.slice.end = buffer.len() as u32;
self.encoder.draw(&self.slice, &self.pipe, &self.data);
}
}
| render | identifier_name |
chardetect.rs | use chardet::detect;
use rayon::prelude::*;
use super::consts::space_fix;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;
#[derive(Debug, Default)]
pub struct CharDet {
pub files: Vec<String>,
}
impl CharDet {
pub fn call(self) {
debug!("{:?}", self);
let max_len = self.files.as_slice().iter().max_by_key(|p| p.len()).unwrap().len();
// println!("{}{:3}CharSet{:13}Rate{:8}Info", space_fix("File",max_len), "", "", "");
self.files.par_iter().for_each(|file| match chardet(file) {
Ok(o) => {
let (mut charset, rate, info) = o;
// "WINDOWS_1258".len() = 12 -> 12+6 = 18
if charset.is_empty() {
charset = "Binary".to_owned();
}
println!(
"{}: {} {:.4}{:6}{}",
space_fix(file, max_len),
space_fix(&charset, 18),
rate,
"",
info
);
}
Err(e) => eprintln!("{}: {:?}", space_fix(file, max_len), e),
})
} | }
if!path.is_file() {
return Err(format!("Args(File): {:?} is not a file", path));
}
}
Ok(())
}
}
fn chardet(f: &str) -> io::Result<(String, f32, String)> {
let mut file = BufReader::new(File::open(f)?);
let mut bytes = Vec::default();
file.read_to_end(&mut bytes)?;
Ok(detect(bytes.as_slice()))
} | pub fn check(&self) -> Result<(), String> {
for path in &self.files {
let path = Path::new(path);
if !path.exists() {
return Err(format!("Args(File): {:?} is not exists", path)); | random_line_split |
chardetect.rs | use chardet::detect;
use rayon::prelude::*;
use super::consts::space_fix;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;
#[derive(Debug, Default)]
pub struct CharDet {
pub files: Vec<String>,
}
impl CharDet {
pub fn call(self) {
debug!("{:?}", self);
let max_len = self.files.as_slice().iter().max_by_key(|p| p.len()).unwrap().len();
// println!("{}{:3}CharSet{:13}Rate{:8}Info", space_fix("File",max_len), "", "", "");
self.files.par_iter().for_each(|file| match chardet(file) {
Ok(o) => {
let (mut charset, rate, info) = o;
// "WINDOWS_1258".len() = 12 -> 12+6 = 18
if charset.is_empty() {
charset = "Binary".to_owned();
}
println!(
"{}: {} {:.4}{:6}{}",
space_fix(file, max_len),
space_fix(&charset, 18),
rate,
"",
info
);
}
Err(e) => eprintln!("{}: {:?}", space_fix(file, max_len), e),
})
}
pub fn check(&self) -> Result<(), String> {
for path in &self.files {
let path = Path::new(path);
if!path.exists() {
return Err(format!("Args(File): {:?} is not exists", path));
}
if!path.is_file() {
return Err(format!("Args(File): {:?} is not a file", path));
}
}
Ok(())
}
}
fn chardet(f: &str) -> io::Result<(String, f32, String)> | {
let mut file = BufReader::new(File::open(f)?);
let mut bytes = Vec::default();
file.read_to_end(&mut bytes)?;
Ok(detect(bytes.as_slice()))
} | identifier_body |
|
chardetect.rs | use chardet::detect;
use rayon::prelude::*;
use super::consts::space_fix;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;
#[derive(Debug, Default)]
pub struct CharDet {
pub files: Vec<String>,
}
impl CharDet {
pub fn | (self) {
debug!("{:?}", self);
let max_len = self.files.as_slice().iter().max_by_key(|p| p.len()).unwrap().len();
// println!("{}{:3}CharSet{:13}Rate{:8}Info", space_fix("File",max_len), "", "", "");
self.files.par_iter().for_each(|file| match chardet(file) {
Ok(o) => {
let (mut charset, rate, info) = o;
// "WINDOWS_1258".len() = 12 -> 12+6 = 18
if charset.is_empty() {
charset = "Binary".to_owned();
}
println!(
"{}: {} {:.4}{:6}{}",
space_fix(file, max_len),
space_fix(&charset, 18),
rate,
"",
info
);
}
Err(e) => eprintln!("{}: {:?}", space_fix(file, max_len), e),
})
}
pub fn check(&self) -> Result<(), String> {
for path in &self.files {
let path = Path::new(path);
if!path.exists() {
return Err(format!("Args(File): {:?} is not exists", path));
}
if!path.is_file() {
return Err(format!("Args(File): {:?} is not a file", path));
}
}
Ok(())
}
}
fn chardet(f: &str) -> io::Result<(String, f32, String)> {
let mut file = BufReader::new(File::open(f)?);
let mut bytes = Vec::default();
file.read_to_end(&mut bytes)?;
Ok(detect(bytes.as_slice()))
}
| call | identifier_name |
chardetect.rs | use chardet::detect;
use rayon::prelude::*;
use super::consts::space_fix;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;
#[derive(Debug, Default)]
pub struct CharDet {
pub files: Vec<String>,
}
impl CharDet {
pub fn call(self) {
debug!("{:?}", self);
let max_len = self.files.as_slice().iter().max_by_key(|p| p.len()).unwrap().len();
// println!("{}{:3}CharSet{:13}Rate{:8}Info", space_fix("File",max_len), "", "", "");
self.files.par_iter().for_each(|file| match chardet(file) {
Ok(o) => {
let (mut charset, rate, info) = o;
// "WINDOWS_1258".len() = 12 -> 12+6 = 18
if charset.is_empty() |
println!(
"{}: {} {:.4}{:6}{}",
space_fix(file, max_len),
space_fix(&charset, 18),
rate,
"",
info
);
}
Err(e) => eprintln!("{}: {:?}", space_fix(file, max_len), e),
})
}
pub fn check(&self) -> Result<(), String> {
for path in &self.files {
let path = Path::new(path);
if!path.exists() {
return Err(format!("Args(File): {:?} is not exists", path));
}
if!path.is_file() {
return Err(format!("Args(File): {:?} is not a file", path));
}
}
Ok(())
}
}
fn chardet(f: &str) -> io::Result<(String, f32, String)> {
let mut file = BufReader::new(File::open(f)?);
let mut bytes = Vec::default();
file.read_to_end(&mut bytes)?;
Ok(detect(bytes.as_slice()))
}
| {
charset = "Binary".to_owned();
} | conditional_block |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(box_syntax)]
use std::ascii::{AsciiExt, OwnedAsciiExt};
use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn sort_and_fmt(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{:?} {:0.3}\n",
k.to_ascii_uppercase(),
v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii_lowercase();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.remove(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
F: FnMut(&[u8]),
{
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(&bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
}
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) { | let mut line: Vec<u8>;
loop {
line = from_parent.recv().unwrap();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer).unwrap();
}
// given a FASTA file on stdin, process sequence THREE
fn main() {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bytes!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = range(0, sizes.len()).map(|_| {
Some(channel::<String>())
}).collect::<Vec<_>>();
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
from_child.push(from_child_);
let (to_child, from_parent) = channel();
Thread::spawn(move|| {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
Some(_) => { proc_mode = true; }
None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb).unwrap();
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new()).unwrap();
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{:?}", from_child[ii].recv().unwrap());
}
} | let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
| random_line_split |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(box_syntax)]
use std::ascii::{AsciiExt, OwnedAsciiExt};
use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn sort_and_fmt(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{:?} {:0.3}\n",
k.to_ascii_uppercase(),
v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii_lowercase();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.remove(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
F: FnMut(&[u8]),
|
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
let mut line: Vec<u8>;
loop {
line = from_parent.recv().unwrap();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer).unwrap();
}
// given a FASTA file on stdin, process sequence THREE
fn main() {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bytes!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = range(0, sizes.len()).map(|_| {
Some(channel::<String>())
}).collect::<Vec<_>>();
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
from_child.push(from_child_);
let (to_child, from_parent) = channel();
Thread::spawn(move|| {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
Some(_) => { proc_mode = true; }
None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb).unwrap();
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new()).unwrap();
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{:?}", from_child[ii].recv().unwrap());
}
}
| {
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(&bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
} | identifier_body |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(box_syntax)]
use std::ascii::{AsciiExt, OwnedAsciiExt};
use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn sort_and_fmt(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{:?} {:0.3}\n",
k.to_ascii_uppercase(),
v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii_lowercase();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn | (mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.remove(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
F: FnMut(&[u8]),
{
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(&bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
}
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
let mut line: Vec<u8>;
loop {
line = from_parent.recv().unwrap();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer).unwrap();
}
// given a FASTA file on stdin, process sequence THREE
fn main() {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bytes!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = range(0, sizes.len()).map(|_| {
Some(channel::<String>())
}).collect::<Vec<_>>();
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
from_child.push(from_child_);
let (to_child, from_parent) = channel();
Thread::spawn(move|| {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
Some(_) => { proc_mode = true; }
None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb).unwrap();
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new()).unwrap();
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{:?}", from_child[ii].recv().unwrap());
}
}
| update_freq | identifier_name |
ntr_sender.rs | use byteorder::{ByteOrder, LittleEndian};
use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
#[derive(Debug)]
pub struct NtrSender {
tcp_stream: TcpStream,
current_seq: u32,
is_heartbeat_sendable: bool,
}
impl NtrSender {
pub fn new(tcp_stream: TcpStream) -> Self {
NtrSender {
tcp_stream: tcp_stream,
current_seq: 1000,
is_heartbeat_sendable: true,
}
}
pub fn is_heartbeat_sendable(&self) -> bool {
self.is_heartbeat_sendable
}
pub fn set_is_heartbeat_sendable(&mut self, b: bool) {
self.is_heartbeat_sendable = b;
}
pub fn send_mem_read_packet(&mut self, addr: u32, size: u32, pid: u32) -> io::Result<usize> {
self.send_empty_packet(9, pid, addr, size)
}
pub fn send_mem_write_packet(&mut self, addr: u32, pid: u32, buf: &[u8]) -> io::Result<usize> {
let args = &mut [0u32; 16];
args[0] = pid;
args[1] = addr;
args[2] = buf.len() as u32;
self.send_packet(1, 10, args, args[2])?;
self.tcp_stream.write(buf)
}
pub fn send_heartbeat_packet(&mut self) -> io::Result<usize> {
self.send_packet(0, 0, &[0u32; 16], 0)
}
pub fn send_list_process_packet(&mut self) -> io::Result<usize> {
self.send_empty_packet(5, 0, 0, 0)
}
fn send_packet(&mut self,
packet_type: u32,
cmd: u32,
args: &[u32; 16],
data_len: u32)
-> io::Result<usize> {
let mut buf = [0u8; 84];
LittleEndian::write_u32(&mut buf[0..4], 0x12345678);
LittleEndian::write_u32(&mut buf[4..8], self.current_seq);
LittleEndian::write_u32(&mut buf[8..12], packet_type);
LittleEndian::write_u32(&mut buf[12..16], cmd);
for (mut i, val) in args.iter().enumerate() {
i = 4 * i + 16;
LittleEndian::write_u32(&mut buf[i..(i + 4)], *val);
}
LittleEndian::write_u32(&mut buf[80..84], data_len);
self.current_seq += 1000;
self.tcp_stream.write(&buf)
}
fn | (&mut self,
cmd: u32,
arg0: u32,
arg1: u32,
arg2: u32)
-> io::Result<usize> {
let mut args = [0u32; 16];
args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
self.send_packet(0, cmd, &args, 0)
}
}
| send_empty_packet | identifier_name |
ntr_sender.rs | use byteorder::{ByteOrder, LittleEndian};
use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
#[derive(Debug)]
pub struct NtrSender {
tcp_stream: TcpStream,
current_seq: u32,
is_heartbeat_sendable: bool,
}
impl NtrSender {
pub fn new(tcp_stream: TcpStream) -> Self {
NtrSender {
tcp_stream: tcp_stream,
current_seq: 1000,
is_heartbeat_sendable: true,
}
}
pub fn is_heartbeat_sendable(&self) -> bool |
pub fn set_is_heartbeat_sendable(&mut self, b: bool) {
self.is_heartbeat_sendable = b;
}
pub fn send_mem_read_packet(&mut self, addr: u32, size: u32, pid: u32) -> io::Result<usize> {
self.send_empty_packet(9, pid, addr, size)
}
pub fn send_mem_write_packet(&mut self, addr: u32, pid: u32, buf: &[u8]) -> io::Result<usize> {
let args = &mut [0u32; 16];
args[0] = pid;
args[1] = addr;
args[2] = buf.len() as u32;
self.send_packet(1, 10, args, args[2])?;
self.tcp_stream.write(buf)
}
pub fn send_heartbeat_packet(&mut self) -> io::Result<usize> {
self.send_packet(0, 0, &[0u32; 16], 0)
}
pub fn send_list_process_packet(&mut self) -> io::Result<usize> {
self.send_empty_packet(5, 0, 0, 0)
}
fn send_packet(&mut self,
packet_type: u32,
cmd: u32,
args: &[u32; 16],
data_len: u32)
-> io::Result<usize> {
let mut buf = [0u8; 84];
LittleEndian::write_u32(&mut buf[0..4], 0x12345678);
LittleEndian::write_u32(&mut buf[4..8], self.current_seq);
LittleEndian::write_u32(&mut buf[8..12], packet_type);
LittleEndian::write_u32(&mut buf[12..16], cmd);
for (mut i, val) in args.iter().enumerate() {
i = 4 * i + 16;
LittleEndian::write_u32(&mut buf[i..(i + 4)], *val);
}
LittleEndian::write_u32(&mut buf[80..84], data_len);
self.current_seq += 1000;
self.tcp_stream.write(&buf)
}
fn send_empty_packet(&mut self,
cmd: u32,
arg0: u32,
arg1: u32,
arg2: u32)
-> io::Result<usize> {
let mut args = [0u32; 16];
args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
self.send_packet(0, cmd, &args, 0)
}
}
| {
self.is_heartbeat_sendable
} | identifier_body |
ntr_sender.rs | use byteorder::{ByteOrder, LittleEndian};
use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
#[derive(Debug)]
pub struct NtrSender {
tcp_stream: TcpStream,
current_seq: u32,
is_heartbeat_sendable: bool,
}
impl NtrSender {
pub fn new(tcp_stream: TcpStream) -> Self {
NtrSender {
tcp_stream: tcp_stream,
current_seq: 1000,
is_heartbeat_sendable: true,
}
}
pub fn is_heartbeat_sendable(&self) -> bool {
self.is_heartbeat_sendable
}
pub fn set_is_heartbeat_sendable(&mut self, b: bool) {
self.is_heartbeat_sendable = b;
}
pub fn send_mem_read_packet(&mut self, addr: u32, size: u32, pid: u32) -> io::Result<usize> {
self.send_empty_packet(9, pid, addr, size)
}
pub fn send_mem_write_packet(&mut self, addr: u32, pid: u32, buf: &[u8]) -> io::Result<usize> {
let args = &mut [0u32; 16];
args[0] = pid;
args[1] = addr;
args[2] = buf.len() as u32;
self.send_packet(1, 10, args, args[2])?;
self.tcp_stream.write(buf)
}
pub fn send_heartbeat_packet(&mut self) -> io::Result<usize> {
self.send_packet(0, 0, &[0u32; 16], 0)
}
pub fn send_list_process_packet(&mut self) -> io::Result<usize> {
self.send_empty_packet(5, 0, 0, 0)
}
fn send_packet(&mut self,
packet_type: u32,
cmd: u32,
args: &[u32; 16],
data_len: u32)
-> io::Result<usize> {
let mut buf = [0u8; 84];
LittleEndian::write_u32(&mut buf[0..4], 0x12345678);
LittleEndian::write_u32(&mut buf[4..8], self.current_seq);
LittleEndian::write_u32(&mut buf[8..12], packet_type);
LittleEndian::write_u32(&mut buf[12..16], cmd);
for (mut i, val) in args.iter().enumerate() {
i = 4 * i + 16;
LittleEndian::write_u32(&mut buf[i..(i + 4)], *val);
}
LittleEndian::write_u32(&mut buf[80..84], data_len);
self.current_seq += 1000;
self.tcp_stream.write(&buf)
}
fn send_empty_packet(&mut self,
cmd: u32,
arg0: u32,
arg1: u32,
arg2: u32)
-> io::Result<usize> {
let mut args = [0u32; 16]; | }
} | args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
self.send_packet(0, cmd, &args, 0) | random_line_split |
recu.rs | /*
recu.rs
demonstrates enums, recursive datatypes, and methdos
vanilla
*/
fn main() {
let list = ~Node(1, ~Node(2, ~Node(3, ~Empty)));
let list2 = ~Node(2, ~Node(3, ~Node(5, ~Empty)));
println!("Sum of all values in the list: {:i}.", list.sum());
println!("Product of all values in the list {:i}.",list2.prod());
}
enum IntList {
Node(int, ~IntList),
Empty
}
impl IntList {
fn sum(~self) -> int {
// As in C and C++, pointers are dereferenced with the asterisk `*` operator.
match *self {
Node(value, next) => value + next.sum(),
Empty => 0
}
}
fn prod(~self) -> int {
match *self {
Node(value,next) => value * next.prod(), | }
}
} | Empty => 1 | random_line_split |
recu.rs | /*
recu.rs
demonstrates enums, recursive datatypes, and methdos
vanilla
*/
fn main() {
let list = ~Node(1, ~Node(2, ~Node(3, ~Empty)));
let list2 = ~Node(2, ~Node(3, ~Node(5, ~Empty)));
println!("Sum of all values in the list: {:i}.", list.sum());
println!("Product of all values in the list {:i}.",list2.prod());
}
enum | {
Node(int, ~IntList),
Empty
}
impl IntList {
fn sum(~self) -> int {
// As in C and C++, pointers are dereferenced with the asterisk `*` operator.
match *self {
Node(value, next) => value + next.sum(),
Empty => 0
}
}
fn prod(~self) -> int {
match *self {
Node(value,next) => value * next.prod(),
Empty => 1
}
}
}
| IntList | identifier_name |
clock.rs | use std::fmt;
/// This represents the 90kHz, 33-bit [System Time Clock][STC] (STC) and
/// the 9-bit STC extension value, which represents 1/300th of a tick.
///
/// [STC]: http://www.bretl.com/mpeghtml/STC.HTM
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Clock {
value: u64,
}
impl Clock {
/// Given a 33-bit System Time Clock value, construct a new `Clock`
/// value.
pub fn base(stc: u64) -> Clock |
/// Return a new `Clock` value, setting the 9-bit extension to the
/// specified value.
pub fn with_ext(&self, ext: u16) -> Clock {
Clock { value: self.value &!0x1f | u64::from(ext) }
}
/// Convert a `Clock` value to seconds.
pub fn to_seconds(&self) -> f64 {
let base = (self.value >> 9) as f64;
let ext = (self.value & 0x1F) as f64;
(base + ext / 300.0) / 90000.0
}
}
impl<'a> fmt::Display for Clock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = self.to_seconds();
let h = (s / 3600.0).trunc();
s = s % 3600.0;
let m = (s / 60.0).trunc();
s = s % 60.0;
write!(f, "{}:{:02}:{:1.3}", h, m, s)
}
}
/// Parse a 33-bit `Clock` value with 3 marker bits, consuming 36 bits.
named!(pub clock<(&[u8], usize), Clock>,
do_parse!(
// Bits 32..30.
hi: take_bits!(u64, 3) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
// Bits 29..15.
mid: take_bits!(u64, 15) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
// Bits 14..0.
lo: take_bits!(u64, 15) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
(Clock::base(hi << 30 | mid << 15 | lo))
)
);
/// Parse a 33-bit `Clock` value plus a 9-bit extension and 4 marker bits,
/// consuming 46 bits.
named!(pub clock_and_ext<(&[u8], usize), Clock>,
do_parse!(
clock: call!(clock) >>
ext: take_bits!(u16, 9) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
(clock.with_ext(ext))
)
);
#[test]
fn parse_clock() {
use nom::IResult;
assert_eq!(clock((&[0x44, 0x02, 0xc4, 0x82, 0x04][..], 2)),
IResult::Done((&[0x04][..], 6),
Clock::base(0b_000_000000001011000_001000001000000)));
assert_eq!(clock_and_ext((&[0x44, 0x02, 0xc4, 0x82, 0x04, 0xa9][..], 2)),
IResult::Done((&[][..], 0),
Clock::base(0b_000_000000001011000_001000001000000)
.with_ext(0b001010100)));
}
| {
Clock { value: stc << 9 }
} | identifier_body |
clock.rs | use std::fmt;
/// This represents the 90kHz, 33-bit [System Time Clock][STC] (STC) and
/// the 9-bit STC extension value, which represents 1/300th of a tick.
///
/// [STC]: http://www.bretl.com/mpeghtml/STC.HTM
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Clock {
value: u64,
}
impl Clock {
/// Given a 33-bit System Time Clock value, construct a new `Clock`
/// value.
pub fn base(stc: u64) -> Clock {
Clock { value: stc << 9 }
}
/// Return a new `Clock` value, setting the 9-bit extension to the
/// specified value.
pub fn with_ext(&self, ext: u16) -> Clock {
Clock { value: self.value &!0x1f | u64::from(ext) }
}
/// Convert a `Clock` value to seconds.
pub fn to_seconds(&self) -> f64 {
let base = (self.value >> 9) as f64;
let ext = (self.value & 0x1F) as f64;
(base + ext / 300.0) / 90000.0
}
}
impl<'a> fmt::Display for Clock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = self.to_seconds();
let h = (s / 3600.0).trunc();
s = s % 3600.0;
let m = (s / 60.0).trunc();
s = s % 60.0;
write!(f, "{}:{:02}:{:1.3}", h, m, s)
}
}
/// Parse a 33-bit `Clock` value with 3 marker bits, consuming 36 bits.
named!(pub clock<(&[u8], usize), Clock>,
do_parse!(
// Bits 32..30.
hi: take_bits!(u64, 3) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
// Bits 29..15.
mid: take_bits!(u64, 15) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
// Bits 14..0.
lo: take_bits!(u64, 15) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
(Clock::base(hi << 30 | mid << 15 | lo))
)
);
/// Parse a 33-bit `Clock` value plus a 9-bit extension and 4 marker bits,
/// consuming 46 bits.
named!(pub clock_and_ext<(&[u8], usize), Clock>,
do_parse!(
clock: call!(clock) >>
ext: take_bits!(u16, 9) >>
// Marker bit. | );
#[test]
fn parse_clock() {
use nom::IResult;
assert_eq!(clock((&[0x44, 0x02, 0xc4, 0x82, 0x04][..], 2)),
IResult::Done((&[0x04][..], 6),
Clock::base(0b_000_000000001011000_001000001000000)));
assert_eq!(clock_and_ext((&[0x44, 0x02, 0xc4, 0x82, 0x04, 0xa9][..], 2)),
IResult::Done((&[][..], 0),
Clock::base(0b_000_000000001011000_001000001000000)
.with_ext(0b001010100)));
} | tag_bits!(u8, 1, 0b1) >>
(clock.with_ext(ext))
) | random_line_split |
clock.rs | use std::fmt;
/// This represents the 90kHz, 33-bit [System Time Clock][STC] (STC) and
/// the 9-bit STC extension value, which represents 1/300th of a tick.
///
/// [STC]: http://www.bretl.com/mpeghtml/STC.HTM
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Clock {
value: u64,
}
impl Clock {
/// Given a 33-bit System Time Clock value, construct a new `Clock`
/// value.
pub fn base(stc: u64) -> Clock {
Clock { value: stc << 9 }
}
/// Return a new `Clock` value, setting the 9-bit extension to the
/// specified value.
pub fn with_ext(&self, ext: u16) -> Clock {
Clock { value: self.value &!0x1f | u64::from(ext) }
}
/// Convert a `Clock` value to seconds.
pub fn to_seconds(&self) -> f64 {
let base = (self.value >> 9) as f64;
let ext = (self.value & 0x1F) as f64;
(base + ext / 300.0) / 90000.0
}
}
impl<'a> fmt::Display for Clock {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = self.to_seconds();
let h = (s / 3600.0).trunc();
s = s % 3600.0;
let m = (s / 60.0).trunc();
s = s % 60.0;
write!(f, "{}:{:02}:{:1.3}", h, m, s)
}
}
/// Parse a 33-bit `Clock` value with 3 marker bits, consuming 36 bits.
named!(pub clock<(&[u8], usize), Clock>,
do_parse!(
// Bits 32..30.
hi: take_bits!(u64, 3) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
// Bits 29..15.
mid: take_bits!(u64, 15) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
// Bits 14..0.
lo: take_bits!(u64, 15) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
(Clock::base(hi << 30 | mid << 15 | lo))
)
);
/// Parse a 33-bit `Clock` value plus a 9-bit extension and 4 marker bits,
/// consuming 46 bits.
named!(pub clock_and_ext<(&[u8], usize), Clock>,
do_parse!(
clock: call!(clock) >>
ext: take_bits!(u16, 9) >>
// Marker bit.
tag_bits!(u8, 1, 0b1) >>
(clock.with_ext(ext))
)
);
#[test]
fn parse_clock() {
use nom::IResult;
assert_eq!(clock((&[0x44, 0x02, 0xc4, 0x82, 0x04][..], 2)),
IResult::Done((&[0x04][..], 6),
Clock::base(0b_000_000000001011000_001000001000000)));
assert_eq!(clock_and_ext((&[0x44, 0x02, 0xc4, 0x82, 0x04, 0xa9][..], 2)),
IResult::Done((&[][..], 0),
Clock::base(0b_000_000000001011000_001000001000000)
.with_ext(0b001010100)));
}
| fmt | identifier_name |
unsized.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *a
// gdbg-check:$1 = {value = [...] "abc"}
// gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]}
// gdb-command:print *b
// gdbg-check:$2 = {value = {value = [...] "abc"}}
// gdbr-check:$2 = unsized::Foo<unsized::Foo<[u8]>> {value: unsized::Foo<[u8]> {value: [...]}}
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
struct Foo<T:?Sized> {
value: T
}
fn | () {
let foo: Foo<Foo<[u8; 4]>> = Foo {
value: Foo {
value: *b"abc\0"
}
};
let a: &Foo<[u8]> = &foo.value;
let b: &Foo<Foo<[u8]>> = &foo;
zzz(); // #break
}
fn zzz() { () }
| main | identifier_name |
unsized.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *a
// gdbg-check:$1 = {value = [...] "abc"}
// gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]}
// gdb-command:print *b
// gdbg-check:$2 = {value = {value = [...] "abc"}}
// gdbr-check:$2 = unsized::Foo<unsized::Foo<[u8]>> {value: unsized::Foo<[u8]> {value: [...]}}
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
struct Foo<T:?Sized> {
value: T
}
fn main() |
fn zzz() { () }
| {
let foo: Foo<Foo<[u8; 4]>> = Foo {
value: Foo {
value: *b"abc\0"
}
};
let a: &Foo<[u8]> = &foo.value;
let b: &Foo<Foo<[u8]>> = &foo;
zzz(); // #break
} | identifier_body |
unsized.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 | // === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *a
// gdbg-check:$1 = {value = [...] "abc"}
// gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]}
// gdb-command:print *b
// gdbg-check:$2 = {value = {value = [...] "abc"}}
// gdbr-check:$2 = unsized::Foo<unsized::Foo<[u8]>> {value: unsized::Foo<[u8]> {value: [...]}}
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
struct Foo<T:?Sized> {
value: T
}
fn main() {
let foo: Foo<Foo<[u8; 4]>> = Foo {
value: Foo {
value: *b"abc\0"
}
};
let a: &Foo<[u8]> = &foo.value;
let b: &Foo<Foo<[u8]>> = &foo;
zzz(); // #break
}
fn zzz() { () } | // except according to those terms.
// compile-flags:-g
| random_line_split |
trait-default-method-bound-subst4.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
#[allow(default_methods)];
trait A<T> {
fn g(&self, x: uint) -> uint { x }
}
impl<T> A<T> for int { }
fn f<T, V: A<T>>(i: V, j: uint) -> uint {
i.g(j)
}
pub fn | () {
assert!(f::<float, int>(0, 2u) == 2u);
assert!(f::<uint, int>(0, 2u) == 2u);
}
| main | identifier_name |
trait-default-method-bound-subst4.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
#[allow(default_methods)];
trait A<T> {
fn g(&self, x: uint) -> uint { x }
}
impl<T> A<T> for int { }
fn f<T, V: A<T>>(i: V, j: uint) -> uint |
pub fn main () {
assert!(f::<float, int>(0, 2u) == 2u);
assert!(f::<uint, int>(0, 2u) == 2u);
}
| {
i.g(j)
} | identifier_body |
trait-default-method-bound-subst4.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // 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.
#[allow(default_methods)];
trait A<T> {
fn g(&self, x: uint) -> uint { x }
}
impl<T> A<T> for int { }
fn f<T, V: A<T>>(i: V, j: uint) -> uint {
i.g(j)
}
pub fn main () {
assert!(f::<float, int>(0, 2u) == 2u);
assert!(f::<uint, int>(0, 2u) == 2u);
} | random_line_split |
|
consensus.rs |
use lib::blockchain::{Chain,Blockchain};
use serde_json;
use reqwest::{Client, StatusCode};
use std::io::{Read};
#[derive(Deserialize)]
struct ChainResponse {
chain: Chain
}
pub struct Consensus;
impl Consensus {
pub fn resolve_conflicts(blockchain: &mut Blockchain) -> bool {
let nodes: Vec<String> = blockchain
.nodes()
.iter()
.cloned()
.map(|node| node.into_string())
.collect();
let neighbour_chains = Self::get(nodes.as_slice());
Self::take_authoritive(blockchain, neighbour_chains)
}
fn take_authoritive(blockchain: &mut Blockchain, chains: Vec<Chain>) -> bool {
let mut is_replaced = false;
let mut new_chain: Option<Chain> = None;
let mut max_length = blockchain.len();
for chain in chains {
if chain.len() > max_length && blockchain.valid_chain(&chain) |
}
if let Some(longest_chain) = new_chain {
blockchain.replace(longest_chain);
is_replaced = true;
}
is_replaced
}
fn get(nodes: &[String]) -> Vec<Chain> {
let chains_raw = Self::get_neighbour_chains(nodes);
Self::deserialize(chains_raw)
}
fn get_neighbour_chains(nodes: &[String]) -> Vec<String> {
let mut chains = Vec::<String>::new();
let client = Client::new();
//upgrade: rayon or tokio-hyper to request async
for node in nodes {
let url = format!("{}/chain", node);
match client.get(url.as_str()).send() {
Ok(mut res) => {
if res.status() == StatusCode::Ok {
let mut buffer = String::new();
let bytes_read = res.read_to_string(&mut buffer).unwrap_or_else(|e| {
error!("Couldnt' read buffer {}", e);
return 0;
});
if bytes_read > 0 {
chains.push(buffer);
}
} else {
error!("Failed to get chain from {}. Response was {:?}. Ignoring", url, res)
}
},
Err(e) => error!("Failed to get chain from {}. Error was {:?}. Ignoring", url, e)
}
}
chains
}
fn deserialize(chains_raw: Vec<String>) -> Vec<Chain> {
let mut chains = Vec::<Chain>::new();
for raw in chains_raw {
//upgrade: remove nodes who return invalid chains?
match serde_json::from_str::<ChainResponse>(raw.as_str()) {
Ok(chain_res) => chains.push(chain_res.chain),
Err(e) => error!("Unable to deserialize chain {:?} raw: {}", e, raw)
}
}
chains
}
}
#[cfg(test)]
mod tests {
use lib::blockchain::Blockchain;
use lib::consensus::Consensus;
//use env_logger;
#[cfg(feature = "integration")]
#[test]
fn get_neighbour_chains() {
//env_logger::init().unwrap();
let url = "http://localhost:8000";
let urls = vec![String::from(url)];
let chains = Consensus::get(urls.as_slice());
assert!(chains.len() > 0, format!("expected a populated chain. do you have a node running at {}?", url));
}
#[test]
fn take_authoritive() {
//Same or less blocks we keep our own. Longer we replace
let mut blockchain_1 = Blockchain::new_with(1);
let mut blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 0 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 1 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 2 blocks (replace)");
}
}
| {
max_length = chain.len();
new_chain = Some(chain);
} | conditional_block |
consensus.rs |
use lib::blockchain::{Chain,Blockchain};
use serde_json;
use reqwest::{Client, StatusCode};
use std::io::{Read};
#[derive(Deserialize)]
struct ChainResponse {
chain: Chain
}
pub struct Consensus;
impl Consensus {
pub fn resolve_conflicts(blockchain: &mut Blockchain) -> bool {
let nodes: Vec<String> = blockchain
.nodes()
.iter()
.cloned()
.map(|node| node.into_string())
.collect();
let neighbour_chains = Self::get(nodes.as_slice());
Self::take_authoritive(blockchain, neighbour_chains)
}
fn take_authoritive(blockchain: &mut Blockchain, chains: Vec<Chain>) -> bool {
let mut is_replaced = false;
let mut new_chain: Option<Chain> = None;
let mut max_length = blockchain.len();
for chain in chains {
if chain.len() > max_length && blockchain.valid_chain(&chain) {
max_length = chain.len();
new_chain = Some(chain);
}
}
if let Some(longest_chain) = new_chain {
blockchain.replace(longest_chain);
is_replaced = true;
}
is_replaced
}
fn get(nodes: &[String]) -> Vec<Chain> {
let chains_raw = Self::get_neighbour_chains(nodes);
Self::deserialize(chains_raw)
}
fn get_neighbour_chains(nodes: &[String]) -> Vec<String> {
let mut chains = Vec::<String>::new();
let client = Client::new();
//upgrade: rayon or tokio-hyper to request async
for node in nodes {
let url = format!("{}/chain", node);
match client.get(url.as_str()).send() {
Ok(mut res) => {
if res.status() == StatusCode::Ok {
let mut buffer = String::new();
let bytes_read = res.read_to_string(&mut buffer).unwrap_or_else(|e| {
error!("Couldnt' read buffer {}", e);
return 0;
});
if bytes_read > 0 {
chains.push(buffer);
}
} else {
error!("Failed to get chain from {}. Response was {:?}. Ignoring", url, res)
}
},
Err(e) => error!("Failed to get chain from {}. Error was {:?}. Ignoring", url, e)
}
}
chains
}
fn deserialize(chains_raw: Vec<String>) -> Vec<Chain> {
let mut chains = Vec::<Chain>::new();
for raw in chains_raw {
//upgrade: remove nodes who return invalid chains?
match serde_json::from_str::<ChainResponse>(raw.as_str()) {
Ok(chain_res) => chains.push(chain_res.chain),
Err(e) => error!("Unable to deserialize chain {:?} raw: {}", e, raw)
}
}
chains
}
}
#[cfg(test)]
mod tests {
use lib::blockchain::Blockchain;
use lib::consensus::Consensus;
//use env_logger;
#[cfg(feature = "integration")]
#[test]
fn get_neighbour_chains() |
#[test]
fn take_authoritive() {
//Same or less blocks we keep our own. Longer we replace
let mut blockchain_1 = Blockchain::new_with(1);
let mut blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 0 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 1 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 2 blocks (replace)");
}
}
| {
//env_logger::init().unwrap();
let url = "http://localhost:8000";
let urls = vec![String::from(url)];
let chains = Consensus::get(urls.as_slice());
assert!(chains.len() > 0, format!("expected a populated chain. do you have a node running at {} ?", url));
} | identifier_body |
consensus.rs |
use lib::blockchain::{Chain,Blockchain};
use serde_json;
use reqwest::{Client, StatusCode};
use std::io::{Read};
#[derive(Deserialize)]
struct ChainResponse {
chain: Chain
}
pub struct Consensus;
impl Consensus {
pub fn resolve_conflicts(blockchain: &mut Blockchain) -> bool {
let nodes: Vec<String> = blockchain
.nodes()
.iter()
.cloned()
.map(|node| node.into_string())
.collect();
let neighbour_chains = Self::get(nodes.as_slice());
Self::take_authoritive(blockchain, neighbour_chains)
}
fn | (blockchain: &mut Blockchain, chains: Vec<Chain>) -> bool {
let mut is_replaced = false;
let mut new_chain: Option<Chain> = None;
let mut max_length = blockchain.len();
for chain in chains {
if chain.len() > max_length && blockchain.valid_chain(&chain) {
max_length = chain.len();
new_chain = Some(chain);
}
}
if let Some(longest_chain) = new_chain {
blockchain.replace(longest_chain);
is_replaced = true;
}
is_replaced
}
fn get(nodes: &[String]) -> Vec<Chain> {
let chains_raw = Self::get_neighbour_chains(nodes);
Self::deserialize(chains_raw)
}
fn get_neighbour_chains(nodes: &[String]) -> Vec<String> {
let mut chains = Vec::<String>::new();
let client = Client::new();
//upgrade: rayon or tokio-hyper to request async
for node in nodes {
let url = format!("{}/chain", node);
match client.get(url.as_str()).send() {
Ok(mut res) => {
if res.status() == StatusCode::Ok {
let mut buffer = String::new();
let bytes_read = res.read_to_string(&mut buffer).unwrap_or_else(|e| {
error!("Couldnt' read buffer {}", e);
return 0;
});
if bytes_read > 0 {
chains.push(buffer);
}
} else {
error!("Failed to get chain from {}. Response was {:?}. Ignoring", url, res)
}
},
Err(e) => error!("Failed to get chain from {}. Error was {:?}. Ignoring", url, e)
}
}
chains
}
fn deserialize(chains_raw: Vec<String>) -> Vec<Chain> {
let mut chains = Vec::<Chain>::new();
for raw in chains_raw {
//upgrade: remove nodes who return invalid chains?
match serde_json::from_str::<ChainResponse>(raw.as_str()) {
Ok(chain_res) => chains.push(chain_res.chain),
Err(e) => error!("Unable to deserialize chain {:?} raw: {}", e, raw)
}
}
chains
}
}
#[cfg(test)]
mod tests {
use lib::blockchain::Blockchain;
use lib::consensus::Consensus;
//use env_logger;
#[cfg(feature = "integration")]
#[test]
fn get_neighbour_chains() {
//env_logger::init().unwrap();
let url = "http://localhost:8000";
let urls = vec![String::from(url)];
let chains = Consensus::get(urls.as_slice());
assert!(chains.len() > 0, format!("expected a populated chain. do you have a node running at {}?", url));
}
#[test]
fn take_authoritive() {
//Same or less blocks we keep our own. Longer we replace
let mut blockchain_1 = Blockchain::new_with(1);
let mut blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 0 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 1 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 2 blocks (replace)");
}
}
| take_authoritive | identifier_name |
consensus.rs | use lib::blockchain::{Chain,Blockchain};
use serde_json;
use reqwest::{Client, StatusCode};
use std::io::{Read};
#[derive(Deserialize)]
struct ChainResponse {
chain: Chain
}
pub struct Consensus;
impl Consensus {
pub fn resolve_conflicts(blockchain: &mut Blockchain) -> bool {
let nodes: Vec<String> = blockchain
.nodes()
.iter()
.cloned()
.map(|node| node.into_string())
.collect();
let neighbour_chains = Self::get(nodes.as_slice());
Self::take_authoritive(blockchain, neighbour_chains)
}
fn take_authoritive(blockchain: &mut Blockchain, chains: Vec<Chain>) -> bool {
let mut is_replaced = false;
let mut new_chain: Option<Chain> = None;
let mut max_length = blockchain.len();
for chain in chains {
if chain.len() > max_length && blockchain.valid_chain(&chain) {
max_length = chain.len();
new_chain = Some(chain);
}
}
if let Some(longest_chain) = new_chain {
blockchain.replace(longest_chain);
is_replaced = true;
}
is_replaced
}
fn get(nodes: &[String]) -> Vec<Chain> {
let chains_raw = Self::get_neighbour_chains(nodes);
Self::deserialize(chains_raw)
}
fn get_neighbour_chains(nodes: &[String]) -> Vec<String> {
let mut chains = Vec::<String>::new();
let client = Client::new();
//upgrade: rayon or tokio-hyper to request async
for node in nodes {
let url = format!("{}/chain", node);
match client.get(url.as_str()).send() {
Ok(mut res) => {
if res.status() == StatusCode::Ok {
let mut buffer = String::new();
let bytes_read = res.read_to_string(&mut buffer).unwrap_or_else(|e| {
error!("Couldnt' read buffer {}", e);
return 0;
});
if bytes_read > 0 {
chains.push(buffer);
}
} else {
error!("Failed to get chain from {}. Response was {:?}. Ignoring", url, res)
}
},
Err(e) => error!("Failed to get chain from {}. Error was {:?}. Ignoring", url, e)
}
}
chains
}
fn deserialize(chains_raw: Vec<String>) -> Vec<Chain> {
let mut chains = Vec::<Chain>::new();
for raw in chains_raw {
//upgrade: remove nodes who return invalid chains?
match serde_json::from_str::<ChainResponse>(raw.as_str()) {
Ok(chain_res) => chains.push(chain_res.chain),
Err(e) => error!("Unable to deserialize chain {:?} raw: {}", e, raw)
}
}
chains
}
}
#[cfg(test)]
mod tests {
use lib::blockchain::Blockchain;
use lib::consensus::Consensus;
//use env_logger;
#[cfg(feature = "integration")]
#[test]
fn get_neighbour_chains() {
//env_logger::init().unwrap();
let url = "http://localhost:8000";
let urls = vec![String::from(url)];
let chains = Consensus::get(urls.as_slice());
assert!(chains.len() > 0, format!("expected a populated chain. do you have a node running at {}?", url));
}
#[test]
fn take_authoritive() {
//Same or less blocks we keep our own. Longer we replace
let mut blockchain_1 = Blockchain::new_with(1);
let mut blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 0 blocks (don't replace)");
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap(); |
blockchain_1 = Blockchain::new_with(1);
blockchain_2 = Blockchain::new_with(1);
blockchain_1.mine().unwrap();
blockchain_2.mine().unwrap();
blockchain_2.mine().unwrap();
assert!(Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 2 blocks (replace)");
}
} | assert!(!Consensus::take_authoritive(&mut blockchain_1, vec![blockchain_2.into_chain()]), "1 block vs 1 blocks (don't replace)"); | random_line_split |
cache_test.rs | use super::*;
use envmnt;
use std::env;
use std::path::PathBuf;
#[test]
fn load_from_path_exists() {
let cwd = env::current_dir().unwrap();
let path = cwd.join("examples/cargo-make");
let cache_data = load_from_path(path);
assert_eq!(cache_data.last_update_check.unwrap(), 1000u64); | #[test]
fn load_from_path_not_exists() {
let path = PathBuf::from("examples2/.cargo-make");
let cache_data = load_from_path(path);
assert!(cache_data.last_update_check.is_none());
}
#[test]
#[ignore]
fn load_with_cargo_home() {
let path = env::current_dir().unwrap();
let directory = path.join("examples/cargo-make");
envmnt::set("CARGO_MAKE_HOME", directory.to_str().unwrap());
let cache_data = load();
envmnt::remove("CARGO_MAKE_HOME");
assert_eq!(cache_data.last_update_check.unwrap(), 1000u64);
}
#[test]
#[ignore]
fn load_without_cargo_home() {
envmnt::remove("CARGO_MAKE_HOME");
load();
} | }
| random_line_split |
cache_test.rs | use super::*;
use envmnt;
use std::env;
use std::path::PathBuf;
#[test]
fn load_from_path_exists() {
let cwd = env::current_dir().unwrap();
let path = cwd.join("examples/cargo-make");
let cache_data = load_from_path(path);
assert_eq!(cache_data.last_update_check.unwrap(), 1000u64);
}
#[test]
fn load_from_path_not_exists() {
let path = PathBuf::from("examples2/.cargo-make");
let cache_data = load_from_path(path);
assert!(cache_data.last_update_check.is_none());
}
#[test]
#[ignore]
fn load_with_cargo_home() |
#[test]
#[ignore]
fn load_without_cargo_home() {
envmnt::remove("CARGO_MAKE_HOME");
load();
}
| {
let path = env::current_dir().unwrap();
let directory = path.join("examples/cargo-make");
envmnt::set("CARGO_MAKE_HOME", directory.to_str().unwrap());
let cache_data = load();
envmnt::remove("CARGO_MAKE_HOME");
assert_eq!(cache_data.last_update_check.unwrap(), 1000u64);
} | identifier_body |
cache_test.rs | use super::*;
use envmnt;
use std::env;
use std::path::PathBuf;
#[test]
fn | () {
let cwd = env::current_dir().unwrap();
let path = cwd.join("examples/cargo-make");
let cache_data = load_from_path(path);
assert_eq!(cache_data.last_update_check.unwrap(), 1000u64);
}
#[test]
fn load_from_path_not_exists() {
let path = PathBuf::from("examples2/.cargo-make");
let cache_data = load_from_path(path);
assert!(cache_data.last_update_check.is_none());
}
#[test]
#[ignore]
fn load_with_cargo_home() {
let path = env::current_dir().unwrap();
let directory = path.join("examples/cargo-make");
envmnt::set("CARGO_MAKE_HOME", directory.to_str().unwrap());
let cache_data = load();
envmnt::remove("CARGO_MAKE_HOME");
assert_eq!(cache_data.last_update_check.unwrap(), 1000u64);
}
#[test]
#[ignore]
fn load_without_cargo_home() {
envmnt::remove("CARGO_MAKE_HOME");
load();
}
| load_from_path_exists | identifier_name |
utils.rs | use url::percent_encoding::percent_decode;
use context::Parameters;
pub fn parse_parameters(source: &[u8]) -> Parameters {
let mut parameters = Parameters::new();
let source: Vec<u8> = source.iter()
.map(|&e| if e == '+' as u8 {'' as u8 } else { e })
.collect();
for parameter in source.split(|&e| e == '&' as u8) {
let mut parts = parameter.split(|&e| e == '=' as u8);
match (parts.next(), parts.next()) {
(Some(name), Some(value)) => {
let name = percent_decode(name);
let value = percent_decode(value);
parameters.insert(name, value);
},
(Some(name), None) => | ,
_ => {}
}
}
parameters
}
#[cfg(test)]
mod test {
use std::borrow::ToOwned;
use super::parse_parameters;
#[test]
fn parsing_parameters() {
let parameters = parse_parameters(b"a=1&aa=2&ab=202");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "202".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn parsing_parameters_with_plus() {
let parameters = parse_parameters(b"a=1&aa=2+%2B+extra+meat&ab=202+fifth+avenue");
let a = "1".to_owned().into();
let aa = "2 + extra meat".to_owned().into();
let ab = "202 fifth avenue".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn parsing_strange_parameters() {
let parameters = parse_parameters(b"a=1=2&=2&ab=");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw(""), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
} | {
let name = percent_decode(name);
parameters.insert(name, String::new());
} | conditional_block |
utils.rs | use url::percent_encoding::percent_decode;
use context::Parameters;
pub fn parse_parameters(source: &[u8]) -> Parameters {
let mut parameters = Parameters::new();
let source: Vec<u8> = source.iter()
.map(|&e| if e == '+' as u8 {'' as u8 } else { e })
.collect();
for parameter in source.split(|&e| e == '&' as u8) {
let mut parts = parameter.split(|&e| e == '=' as u8);
match (parts.next(), parts.next()) {
(Some(name), Some(value)) => {
let name = percent_decode(name);
let value = percent_decode(value);
parameters.insert(name, value);
},
(Some(name), None) => {
let name = percent_decode(name);
parameters.insert(name, String::new());
},
_ => {}
}
}
parameters
}
#[cfg(test)]
mod test {
use std::borrow::ToOwned;
use super::parse_parameters;
#[test]
fn parsing_parameters() |
#[test]
fn parsing_parameters_with_plus() {
let parameters = parse_parameters(b"a=1&aa=2+%2B+extra+meat&ab=202+fifth+avenue");
let a = "1".to_owned().into();
let aa = "2 + extra meat".to_owned().into();
let ab = "202 fifth avenue".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn parsing_strange_parameters() {
let parameters = parse_parameters(b"a=1=2&=2&ab=");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw(""), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
} | {
let parameters = parse_parameters(b"a=1&aa=2&ab=202");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "202".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
} | identifier_body |
utils.rs | use url::percent_encoding::percent_decode;
use context::Parameters;
pub fn parse_parameters(source: &[u8]) -> Parameters {
let mut parameters = Parameters::new();
let source: Vec<u8> = source.iter()
.map(|&e| if e == '+' as u8 {'' as u8 } else { e })
.collect();
for parameter in source.split(|&e| e == '&' as u8) {
let mut parts = parameter.split(|&e| e == '=' as u8);
match (parts.next(), parts.next()) {
(Some(name), Some(value)) => {
let name = percent_decode(name);
let value = percent_decode(value);
parameters.insert(name, value);
},
(Some(name), None) => {
let name = percent_decode(name);
parameters.insert(name, String::new());
},
_ => {}
}
}
parameters
}
#[cfg(test)]
mod test {
use std::borrow::ToOwned;
use super::parse_parameters;
#[test]
fn parsing_parameters() {
let parameters = parse_parameters(b"a=1&aa=2&ab=202");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "202".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn parsing_parameters_with_plus() {
let parameters = parse_parameters(b"a=1&aa=2+%2B+extra+meat&ab=202+fifth+avenue");
let a = "1".to_owned().into();
let aa = "2 + extra meat".to_owned().into();
let ab = "202 fifth avenue".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn | () {
let parameters = parse_parameters(b"a=1=2&=2&ab=");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw(""), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
} | parsing_strange_parameters | identifier_name |
utils.rs | use url::percent_encoding::percent_decode;
use context::Parameters;
pub fn parse_parameters(source: &[u8]) -> Parameters {
let mut parameters = Parameters::new();
let source: Vec<u8> = source.iter()
.map(|&e| if e == '+' as u8 {'' as u8 } else { e })
.collect();
for parameter in source.split(|&e| e == '&' as u8) {
let mut parts = parameter.split(|&e| e == '=' as u8);
match (parts.next(), parts.next()) {
(Some(name), Some(value)) => {
let name = percent_decode(name);
let value = percent_decode(value);
parameters.insert(name, value);
},
(Some(name), None) => {
let name = percent_decode(name);
parameters.insert(name, String::new());
},
_ => {}
}
}
parameters
}
#[cfg(test)]
mod test {
use std::borrow::ToOwned;
use super::parse_parameters;
#[test]
fn parsing_parameters() {
let parameters = parse_parameters(b"a=1&aa=2&ab=202");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "202".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn parsing_parameters_with_plus() {
let parameters = parse_parameters(b"a=1&aa=2+%2B+extra+meat&ab=202+fifth+avenue");
let a = "1".to_owned().into();
let aa = "2 + extra meat".to_owned().into();
let ab = "202 fifth avenue".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a));
assert_eq!(parameters.get_raw("aa"), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
}
#[test]
fn parsing_strange_parameters() {
let parameters = parse_parameters(b"a=1=2&=2&ab=");
let a = "1".to_owned().into();
let aa = "2".to_owned().into();
let ab = "".to_owned().into();
assert_eq!(parameters.get_raw("a"), Some(&a)); | } | assert_eq!(parameters.get_raw(""), Some(&aa));
assert_eq!(parameters.get_raw("ab"), Some(&ab));
} | random_line_split |
types.rs | // This module implements a number of types..
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use getopts;
/// Command params type.
pub type Params = Vec<String>;
/// Command callback func type.
pub type CommandCallback = fn(Params);
/// Options are usually optional values on the command line.
#[derive(Clone)]
pub struct Options {
short_name: &'static str,
long_name: &'static str,
help: &'static str,
is_flag: bool,
is_bool_flag: bool,
multiple: bool,
required: bool,
default: Option<&'static str>,
}
impl Options {
pub fn new(s_name: &'static str, l_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool,
multiple: bool, required: bool, default: Option<&'static str>) -> Options {
Options {
short_name: s_name,
long_name: l_name,
help: help,
is_flag: is_flag,
is_bool_flag: is_bool_flag,
multiple: multiple,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
if self.is_flag {
if!self.is_bool_flag {
parser.optflagopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optflagmulti(self.short_name, self.long_name, self.help);
} else {
parser.optflag(self.short_name, self.long_name, self.help);
}
} else {
if self.required {
parser.reqopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optmulti(self.short_name, self.long_name, self.help, self.long_name);
} else {
parser.optopt(self.short_name, self.long_name, self.help, self.long_name);
}
}
}
pub fn get_help_record(&self) -> (String, String) {
let mut options = String::from_str("");
options.push_str("-");
options.push_str(self.short_name);
options.push_str(", ");
options.push_str("--");
options.push_str(self.long_name);
let mut extra = String::from_str("");
if self.default.is_some() {
extra.push_str("default: ");
extra.push_str(self.default.unwrap());
}
if self.required {
if extra.is_empty() {
extra.push_str("required");
} else {
extra.push_str("; required");
}
}
let mut help: String = self.help.to_string();
if self.help.len()!= 0 {
help.push_str(" ");
}
if!extra.is_empty() {
help = format!("{}[{}]", help, extra);
}
return (options, help);
}
}
/// Arguments are positional parameters to a command.
pub struct Argument {
name: &'static str,
required: bool,
default: Option<&'static str>,
}
impl Argument {
pub fn new(name: &'static str, required: bool, default: Option<&'static str>) -> Argument { | name: name,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
}
pub fn get_usage_piece(&self) -> String {
match self.required {
true => format!("{}", self.name),
false => format!("[{}]", self.name),
}
}
} | Argument { | random_line_split |
types.rs | // This module implements a number of types..
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use getopts;
/// Command params type.
pub type Params = Vec<String>;
/// Command callback func type.
pub type CommandCallback = fn(Params);
/// Options are usually optional values on the command line.
#[derive(Clone)]
pub struct Options {
short_name: &'static str,
long_name: &'static str,
help: &'static str,
is_flag: bool,
is_bool_flag: bool,
multiple: bool,
required: bool,
default: Option<&'static str>,
}
impl Options {
pub fn new(s_name: &'static str, l_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool,
multiple: bool, required: bool, default: Option<&'static str>) -> Options {
Options {
short_name: s_name,
long_name: l_name,
help: help,
is_flag: is_flag,
is_bool_flag: is_bool_flag,
multiple: multiple,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
if self.is_flag {
if!self.is_bool_flag {
parser.optflagopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optflagmulti(self.short_name, self.long_name, self.help);
} else {
parser.optflag(self.short_name, self.long_name, self.help);
}
} else {
if self.required {
parser.reqopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optmulti(self.short_name, self.long_name, self.help, self.long_name);
} else {
parser.optopt(self.short_name, self.long_name, self.help, self.long_name);
}
}
}
pub fn get_help_record(&self) -> (String, String) {
let mut options = String::from_str("");
options.push_str("-");
options.push_str(self.short_name);
options.push_str(", ");
options.push_str("--");
options.push_str(self.long_name);
let mut extra = String::from_str("");
if self.default.is_some() {
extra.push_str("default: ");
extra.push_str(self.default.unwrap());
}
if self.required {
if extra.is_empty() {
extra.push_str("required");
} else {
extra.push_str("; required");
}
}
let mut help: String = self.help.to_string();
if self.help.len()!= 0 {
help.push_str(" ");
}
if!extra.is_empty() {
help = format!("{}[{}]", help, extra);
}
return (options, help);
}
}
/// Arguments are positional parameters to a command.
pub struct Argument {
name: &'static str,
required: bool,
default: Option<&'static str>,
}
impl Argument {
pub fn | (name: &'static str, required: bool, default: Option<&'static str>) -> Argument {
Argument {
name: name,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
}
pub fn get_usage_piece(&self) -> String {
match self.required {
true => format!("{}", self.name),
false => format!("[{}]", self.name),
}
}
}
| new | identifier_name |
types.rs | // This module implements a number of types..
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use getopts;
/// Command params type.
pub type Params = Vec<String>;
/// Command callback func type.
pub type CommandCallback = fn(Params);
/// Options are usually optional values on the command line.
#[derive(Clone)]
pub struct Options {
short_name: &'static str,
long_name: &'static str,
help: &'static str,
is_flag: bool,
is_bool_flag: bool,
multiple: bool,
required: bool,
default: Option<&'static str>,
}
impl Options {
pub fn new(s_name: &'static str, l_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool,
multiple: bool, required: bool, default: Option<&'static str>) -> Options |
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
if self.is_flag {
if!self.is_bool_flag {
parser.optflagopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optflagmulti(self.short_name, self.long_name, self.help);
} else {
parser.optflag(self.short_name, self.long_name, self.help);
}
} else {
if self.required {
parser.reqopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optmulti(self.short_name, self.long_name, self.help, self.long_name);
} else {
parser.optopt(self.short_name, self.long_name, self.help, self.long_name);
}
}
}
pub fn get_help_record(&self) -> (String, String) {
let mut options = String::from_str("");
options.push_str("-");
options.push_str(self.short_name);
options.push_str(", ");
options.push_str("--");
options.push_str(self.long_name);
let mut extra = String::from_str("");
if self.default.is_some() {
extra.push_str("default: ");
extra.push_str(self.default.unwrap());
}
if self.required {
if extra.is_empty() {
extra.push_str("required");
} else {
extra.push_str("; required");
}
}
let mut help: String = self.help.to_string();
if self.help.len()!= 0 {
help.push_str(" ");
}
if!extra.is_empty() {
help = format!("{}[{}]", help, extra);
}
return (options, help);
}
}
/// Arguments are positional parameters to a command.
pub struct Argument {
name: &'static str,
required: bool,
default: Option<&'static str>,
}
impl Argument {
pub fn new(name: &'static str, required: bool, default: Option<&'static str>) -> Argument {
Argument {
name: name,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
}
pub fn get_usage_piece(&self) -> String {
match self.required {
true => format!("{}", self.name),
false => format!("[{}]", self.name),
}
}
}
| {
Options {
short_name: s_name,
long_name: l_name,
help: help,
is_flag: is_flag,
is_bool_flag: is_bool_flag,
multiple: multiple,
required: required,
default: default,
}
} | identifier_body |
types.rs | // This module implements a number of types..
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use getopts;
/// Command params type.
pub type Params = Vec<String>;
/// Command callback func type.
pub type CommandCallback = fn(Params);
/// Options are usually optional values on the command line.
#[derive(Clone)]
pub struct Options {
short_name: &'static str,
long_name: &'static str,
help: &'static str,
is_flag: bool,
is_bool_flag: bool,
multiple: bool,
required: bool,
default: Option<&'static str>,
}
impl Options {
pub fn new(s_name: &'static str, l_name: &'static str, help: &'static str, is_flag: bool, is_bool_flag: bool,
multiple: bool, required: bool, default: Option<&'static str>) -> Options {
Options {
short_name: s_name,
long_name: l_name,
help: help,
is_flag: is_flag,
is_bool_flag: is_bool_flag,
multiple: multiple,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
if self.is_flag {
if!self.is_bool_flag | else if self.multiple {
parser.optflagmulti(self.short_name, self.long_name, self.help);
} else {
parser.optflag(self.short_name, self.long_name, self.help);
}
} else {
if self.required {
parser.reqopt(self.short_name, self.long_name, self.help, self.long_name);
} else if self.multiple {
parser.optmulti(self.short_name, self.long_name, self.help, self.long_name);
} else {
parser.optopt(self.short_name, self.long_name, self.help, self.long_name);
}
}
}
pub fn get_help_record(&self) -> (String, String) {
let mut options = String::from_str("");
options.push_str("-");
options.push_str(self.short_name);
options.push_str(", ");
options.push_str("--");
options.push_str(self.long_name);
let mut extra = String::from_str("");
if self.default.is_some() {
extra.push_str("default: ");
extra.push_str(self.default.unwrap());
}
if self.required {
if extra.is_empty() {
extra.push_str("required");
} else {
extra.push_str("; required");
}
}
let mut help: String = self.help.to_string();
if self.help.len()!= 0 {
help.push_str(" ");
}
if!extra.is_empty() {
help = format!("{}[{}]", help, extra);
}
return (options, help);
}
}
/// Arguments are positional parameters to a command.
pub struct Argument {
name: &'static str,
required: bool,
default: Option<&'static str>,
}
impl Argument {
pub fn new(name: &'static str, required: bool, default: Option<&'static str>) -> Argument {
Argument {
name: name,
required: required,
default: default,
}
}
pub fn add_to_parser(&self, parser: &mut getopts::Options) {
}
pub fn get_usage_piece(&self) -> String {
match self.required {
true => format!("{}", self.name),
false => format!("[{}]", self.name),
}
}
}
| {
parser.optflagopt(self.short_name, self.long_name, self.help, self.long_name);
} | conditional_block |
message_service.rs | use libc::c_char;
use std::ffi::CString;
#[repr(C)]
pub struct CMessageFuncs1 {
info: extern "C" fn(title: *const c_char, message: *const c_char),
error: extern "C" fn(title: *const c_char, message: *const c_char),
warning: extern "C" fn(title: *const c_char, message: *const c_char),
}
pub struct Messages {
pub api: *mut CMessageFuncs1,
}
macro_rules! message_fun { | unsafe {
((*self.api).$name)(ts.as_ptr(), ms.as_ptr());
}
}
}
}
impl Messages {
message_fun!(info);
message_fun!(error);
message_fun!(warning);
} | ($name:ident) => {
pub fn $name(&mut self, title: &str, message: &str) {
let ts = CString::new(title).unwrap();
let ms = CString::new(message).unwrap(); | random_line_split |
message_service.rs | use libc::c_char;
use std::ffi::CString;
#[repr(C)]
pub struct | {
info: extern "C" fn(title: *const c_char, message: *const c_char),
error: extern "C" fn(title: *const c_char, message: *const c_char),
warning: extern "C" fn(title: *const c_char, message: *const c_char),
}
pub struct Messages {
pub api: *mut CMessageFuncs1,
}
macro_rules! message_fun {
($name:ident) => {
pub fn $name(&mut self, title: &str, message: &str) {
let ts = CString::new(title).unwrap();
let ms = CString::new(message).unwrap();
unsafe {
((*self.api).$name)(ts.as_ptr(), ms.as_ptr());
}
}
}
}
impl Messages {
message_fun!(info);
message_fun!(error);
message_fun!(warning);
}
| CMessageFuncs1 | identifier_name |
buffer.rs | /// Memory buffers for the benefit of `std::io::net` which has slow read/write.
use std::io::{Reader, Writer, Stream};
use std::cmp::min;
use std::vec;
// 64KB chunks (moderately arbitrary)
static READ_BUF_SIZE: uint = 0x10000;
static WRITE_BUF_SIZE: uint = 0x10000;
// TODO: consider removing constants and giving a buffer size in the constructor
pub struct BufferedStream<T> {
wrapped: T,
read_buffer: ~[u8],
// The current position in the buffer
read_pos: uint,
// The last valid position in the reader
read_max: uint,
write_buffer: ~[u8],
write_len: uint,
writing_chunked_body: bool,
}
impl<T: Stream> BufferedStream<T> {
pub fn new(stream: T) -> BufferedStream<T> {
let mut read_buffer = vec::with_capacity(READ_BUF_SIZE);
unsafe { read_buffer.set_len(READ_BUF_SIZE); }
let mut write_buffer = vec::with_capacity(WRITE_BUF_SIZE);
unsafe { write_buffer.set_len(WRITE_BUF_SIZE); }
BufferedStream {
wrapped: stream,
read_buffer: read_buffer,
read_pos: 0u,
read_max: 0u,
write_buffer: write_buffer,
write_len: 0u,
writing_chunked_body: false,
}
}
}
impl<T: Reader> BufferedStream<T> {
/// Poke a single byte back so it will be read next. For this to make sense, you must have just
/// read that byte. If `self.pos` is 0 and `self.max` is not 0 (i.e. if the buffer is just
/// filled
/// Very great caution must be used in calling this as it will fail if `self.pos` is 0.
pub fn poke_byte(&mut self, byte: u8) {
match (self.read_pos, self.read_max) {
(0, 0) => self.read_max = 1,
(0, _) => fail!("poke called when buffer is full"),
(_, _) => self.read_pos -= 1,
}
self.read_buffer[self.read_pos] = byte;
}
#[inline]
fn fill_buffer(&mut self) -> bool {
assert_eq!(self.read_pos, self.read_max);
match self.wrapped.read(self.read_buffer) {
None => {
self.read_pos = 0;
self.read_max = 0;
false
},
Some(i) => {
self.read_pos = 0;
self.read_max = i;
true
},
}
}
/// Slightly faster implementation of read_byte than that which is provided by ReaderUtil
/// (which just uses `read()`)
#[inline]
pub fn read_byte(&mut self) -> Option<u8> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
self.read_pos += 1;
Some(self.read_buffer[self.read_pos - 1])
}
}
impl<T: Writer> BufferedStream<T> {
/// Finish off writing a response: this flushes the writer and in case of chunked
/// Transfer-Encoding writes the ending zero-length chunk to indicate completion.
///
/// At the time of calling this, headers MUST have been written, including the
/// ending CRLF, or else an invalid HTTP response may be written.
pub fn finish_response(&mut self) {
self.flush();
if self.writing_chunked_body {
self.wrapped.write(bytes!("0\r\n\r\n"));
}
}
}
impl<T: Reader> Reader for BufferedStream<T> {
/// Read at most N bytes into `buf`, where N is the minimum of `buf.len()` and the buffer size.
///
/// At present, this makes no attempt to fill its buffer proactively, instead waiting until you
/// ask.
fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
let size = min(self.read_max - self.read_pos, buf.len());
vec::bytes::copy_memory(buf, self.read_buffer.slice_from(self.read_pos).slice_to(size));
self.read_pos += size;
Some(size)
}
/// Return whether the Reader has reached the end of the stream AND exhausted its buffer.
fn eof(&mut self) -> bool {
self.read_pos == self.read_max && self.wrapped.eof()
}
}
impl<T: Writer> Writer for BufferedStream<T> {
fn write(&mut self, buf: &[u8]) {
if buf.len() + self.write_len > self.write_buffer.len() {
// This is the lazy approach which may involve multiple writes where it's really not
// warranted. Maybe deal with that later.
if self.writing_chunked_body {
let s = format!("{}\r\n", (self.write_len + buf.len()).to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
if self.write_len > 0 {
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
self.write_len = 0;
}
self.wrapped.write(buf);
self.write_len = 0;
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
} else {
unsafe { self.write_buffer.mut_slice_from(self.write_len).copy_memory(buf); }
self.write_len += buf.len();
if self.write_len == self.write_buffer.len() {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
self.wrapped.write(self.write_buffer);
self.wrapped.write(bytes!("\r\n"));
} else {
self.wrapped.write(self.write_buffer);
}
self.write_len = 0;
}
}
}
fn flush(&mut self) {
if self.write_len > 0 |
self.wrapped.flush();
}
}
| {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
self.write_len = 0;
} | conditional_block |
buffer.rs | /// Memory buffers for the benefit of `std::io::net` which has slow read/write.
use std::io::{Reader, Writer, Stream};
use std::cmp::min;
use std::vec;
// 64KB chunks (moderately arbitrary)
static READ_BUF_SIZE: uint = 0x10000;
static WRITE_BUF_SIZE: uint = 0x10000;
// TODO: consider removing constants and giving a buffer size in the constructor
pub struct BufferedStream<T> {
wrapped: T,
read_buffer: ~[u8],
// The current position in the buffer
read_pos: uint,
// The last valid position in the reader
read_max: uint,
write_buffer: ~[u8],
write_len: uint,
writing_chunked_body: bool,
}
impl<T: Stream> BufferedStream<T> {
pub fn new(stream: T) -> BufferedStream<T> {
let mut read_buffer = vec::with_capacity(READ_BUF_SIZE);
unsafe { read_buffer.set_len(READ_BUF_SIZE); } | read_pos: 0u,
read_max: 0u,
write_buffer: write_buffer,
write_len: 0u,
writing_chunked_body: false,
}
}
}
impl<T: Reader> BufferedStream<T> {
/// Poke a single byte back so it will be read next. For this to make sense, you must have just
/// read that byte. If `self.pos` is 0 and `self.max` is not 0 (i.e. if the buffer is just
/// filled
/// Very great caution must be used in calling this as it will fail if `self.pos` is 0.
pub fn poke_byte(&mut self, byte: u8) {
match (self.read_pos, self.read_max) {
(0, 0) => self.read_max = 1,
(0, _) => fail!("poke called when buffer is full"),
(_, _) => self.read_pos -= 1,
}
self.read_buffer[self.read_pos] = byte;
}
#[inline]
fn fill_buffer(&mut self) -> bool {
assert_eq!(self.read_pos, self.read_max);
match self.wrapped.read(self.read_buffer) {
None => {
self.read_pos = 0;
self.read_max = 0;
false
},
Some(i) => {
self.read_pos = 0;
self.read_max = i;
true
},
}
}
/// Slightly faster implementation of read_byte than that which is provided by ReaderUtil
/// (which just uses `read()`)
#[inline]
pub fn read_byte(&mut self) -> Option<u8> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
self.read_pos += 1;
Some(self.read_buffer[self.read_pos - 1])
}
}
impl<T: Writer> BufferedStream<T> {
/// Finish off writing a response: this flushes the writer and in case of chunked
/// Transfer-Encoding writes the ending zero-length chunk to indicate completion.
///
/// At the time of calling this, headers MUST have been written, including the
/// ending CRLF, or else an invalid HTTP response may be written.
pub fn finish_response(&mut self) {
self.flush();
if self.writing_chunked_body {
self.wrapped.write(bytes!("0\r\n\r\n"));
}
}
}
impl<T: Reader> Reader for BufferedStream<T> {
/// Read at most N bytes into `buf`, where N is the minimum of `buf.len()` and the buffer size.
///
/// At present, this makes no attempt to fill its buffer proactively, instead waiting until you
/// ask.
fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
let size = min(self.read_max - self.read_pos, buf.len());
vec::bytes::copy_memory(buf, self.read_buffer.slice_from(self.read_pos).slice_to(size));
self.read_pos += size;
Some(size)
}
/// Return whether the Reader has reached the end of the stream AND exhausted its buffer.
fn eof(&mut self) -> bool {
self.read_pos == self.read_max && self.wrapped.eof()
}
}
impl<T: Writer> Writer for BufferedStream<T> {
fn write(&mut self, buf: &[u8]) {
if buf.len() + self.write_len > self.write_buffer.len() {
// This is the lazy approach which may involve multiple writes where it's really not
// warranted. Maybe deal with that later.
if self.writing_chunked_body {
let s = format!("{}\r\n", (self.write_len + buf.len()).to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
if self.write_len > 0 {
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
self.write_len = 0;
}
self.wrapped.write(buf);
self.write_len = 0;
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
} else {
unsafe { self.write_buffer.mut_slice_from(self.write_len).copy_memory(buf); }
self.write_len += buf.len();
if self.write_len == self.write_buffer.len() {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
self.wrapped.write(self.write_buffer);
self.wrapped.write(bytes!("\r\n"));
} else {
self.wrapped.write(self.write_buffer);
}
self.write_len = 0;
}
}
}
fn flush(&mut self) {
if self.write_len > 0 {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
self.write_len = 0;
}
self.wrapped.flush();
}
} | let mut write_buffer = vec::with_capacity(WRITE_BUF_SIZE);
unsafe { write_buffer.set_len(WRITE_BUF_SIZE); }
BufferedStream {
wrapped: stream,
read_buffer: read_buffer, | random_line_split |
buffer.rs | /// Memory buffers for the benefit of `std::io::net` which has slow read/write.
use std::io::{Reader, Writer, Stream};
use std::cmp::min;
use std::vec;
// 64KB chunks (moderately arbitrary)
static READ_BUF_SIZE: uint = 0x10000;
static WRITE_BUF_SIZE: uint = 0x10000;
// TODO: consider removing constants and giving a buffer size in the constructor
pub struct BufferedStream<T> {
wrapped: T,
read_buffer: ~[u8],
// The current position in the buffer
read_pos: uint,
// The last valid position in the reader
read_max: uint,
write_buffer: ~[u8],
write_len: uint,
writing_chunked_body: bool,
}
impl<T: Stream> BufferedStream<T> {
pub fn new(stream: T) -> BufferedStream<T> {
let mut read_buffer = vec::with_capacity(READ_BUF_SIZE);
unsafe { read_buffer.set_len(READ_BUF_SIZE); }
let mut write_buffer = vec::with_capacity(WRITE_BUF_SIZE);
unsafe { write_buffer.set_len(WRITE_BUF_SIZE); }
BufferedStream {
wrapped: stream,
read_buffer: read_buffer,
read_pos: 0u,
read_max: 0u,
write_buffer: write_buffer,
write_len: 0u,
writing_chunked_body: false,
}
}
}
impl<T: Reader> BufferedStream<T> {
/// Poke a single byte back so it will be read next. For this to make sense, you must have just
/// read that byte. If `self.pos` is 0 and `self.max` is not 0 (i.e. if the buffer is just
/// filled
/// Very great caution must be used in calling this as it will fail if `self.pos` is 0.
pub fn poke_byte(&mut self, byte: u8) {
match (self.read_pos, self.read_max) {
(0, 0) => self.read_max = 1,
(0, _) => fail!("poke called when buffer is full"),
(_, _) => self.read_pos -= 1,
}
self.read_buffer[self.read_pos] = byte;
}
#[inline]
fn fill_buffer(&mut self) -> bool {
assert_eq!(self.read_pos, self.read_max);
match self.wrapped.read(self.read_buffer) {
None => {
self.read_pos = 0;
self.read_max = 0;
false
},
Some(i) => {
self.read_pos = 0;
self.read_max = i;
true
},
}
}
/// Slightly faster implementation of read_byte than that which is provided by ReaderUtil
/// (which just uses `read()`)
#[inline]
pub fn read_byte(&mut self) -> Option<u8> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
self.read_pos += 1;
Some(self.read_buffer[self.read_pos - 1])
}
}
impl<T: Writer> BufferedStream<T> {
/// Finish off writing a response: this flushes the writer and in case of chunked
/// Transfer-Encoding writes the ending zero-length chunk to indicate completion.
///
/// At the time of calling this, headers MUST have been written, including the
/// ending CRLF, or else an invalid HTTP response may be written.
pub fn finish_response(&mut self) {
self.flush();
if self.writing_chunked_body {
self.wrapped.write(bytes!("0\r\n\r\n"));
}
}
}
impl<T: Reader> Reader for BufferedStream<T> {
/// Read at most N bytes into `buf`, where N is the minimum of `buf.len()` and the buffer size.
///
/// At present, this makes no attempt to fill its buffer proactively, instead waiting until you
/// ask.
fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
let size = min(self.read_max - self.read_pos, buf.len());
vec::bytes::copy_memory(buf, self.read_buffer.slice_from(self.read_pos).slice_to(size));
self.read_pos += size;
Some(size)
}
/// Return whether the Reader has reached the end of the stream AND exhausted its buffer.
fn | (&mut self) -> bool {
self.read_pos == self.read_max && self.wrapped.eof()
}
}
impl<T: Writer> Writer for BufferedStream<T> {
fn write(&mut self, buf: &[u8]) {
if buf.len() + self.write_len > self.write_buffer.len() {
// This is the lazy approach which may involve multiple writes where it's really not
// warranted. Maybe deal with that later.
if self.writing_chunked_body {
let s = format!("{}\r\n", (self.write_len + buf.len()).to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
if self.write_len > 0 {
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
self.write_len = 0;
}
self.wrapped.write(buf);
self.write_len = 0;
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
} else {
unsafe { self.write_buffer.mut_slice_from(self.write_len).copy_memory(buf); }
self.write_len += buf.len();
if self.write_len == self.write_buffer.len() {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
self.wrapped.write(self.write_buffer);
self.wrapped.write(bytes!("\r\n"));
} else {
self.wrapped.write(self.write_buffer);
}
self.write_len = 0;
}
}
}
fn flush(&mut self) {
if self.write_len > 0 {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
self.write_len = 0;
}
self.wrapped.flush();
}
}
| eof | identifier_name |
buffer.rs | /// Memory buffers for the benefit of `std::io::net` which has slow read/write.
use std::io::{Reader, Writer, Stream};
use std::cmp::min;
use std::vec;
// 64KB chunks (moderately arbitrary)
static READ_BUF_SIZE: uint = 0x10000;
static WRITE_BUF_SIZE: uint = 0x10000;
// TODO: consider removing constants and giving a buffer size in the constructor
pub struct BufferedStream<T> {
wrapped: T,
read_buffer: ~[u8],
// The current position in the buffer
read_pos: uint,
// The last valid position in the reader
read_max: uint,
write_buffer: ~[u8],
write_len: uint,
writing_chunked_body: bool,
}
impl<T: Stream> BufferedStream<T> {
pub fn new(stream: T) -> BufferedStream<T> |
}
impl<T: Reader> BufferedStream<T> {
/// Poke a single byte back so it will be read next. For this to make sense, you must have just
/// read that byte. If `self.pos` is 0 and `self.max` is not 0 (i.e. if the buffer is just
/// filled
/// Very great caution must be used in calling this as it will fail if `self.pos` is 0.
pub fn poke_byte(&mut self, byte: u8) {
match (self.read_pos, self.read_max) {
(0, 0) => self.read_max = 1,
(0, _) => fail!("poke called when buffer is full"),
(_, _) => self.read_pos -= 1,
}
self.read_buffer[self.read_pos] = byte;
}
#[inline]
fn fill_buffer(&mut self) -> bool {
assert_eq!(self.read_pos, self.read_max);
match self.wrapped.read(self.read_buffer) {
None => {
self.read_pos = 0;
self.read_max = 0;
false
},
Some(i) => {
self.read_pos = 0;
self.read_max = i;
true
},
}
}
/// Slightly faster implementation of read_byte than that which is provided by ReaderUtil
/// (which just uses `read()`)
#[inline]
pub fn read_byte(&mut self) -> Option<u8> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
self.read_pos += 1;
Some(self.read_buffer[self.read_pos - 1])
}
}
impl<T: Writer> BufferedStream<T> {
/// Finish off writing a response: this flushes the writer and in case of chunked
/// Transfer-Encoding writes the ending zero-length chunk to indicate completion.
///
/// At the time of calling this, headers MUST have been written, including the
/// ending CRLF, or else an invalid HTTP response may be written.
pub fn finish_response(&mut self) {
self.flush();
if self.writing_chunked_body {
self.wrapped.write(bytes!("0\r\n\r\n"));
}
}
}
impl<T: Reader> Reader for BufferedStream<T> {
/// Read at most N bytes into `buf`, where N is the minimum of `buf.len()` and the buffer size.
///
/// At present, this makes no attempt to fill its buffer proactively, instead waiting until you
/// ask.
fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
if self.read_pos == self.read_max &&!self.fill_buffer() {
// Run out of buffered content, no more to come
return None;
}
let size = min(self.read_max - self.read_pos, buf.len());
vec::bytes::copy_memory(buf, self.read_buffer.slice_from(self.read_pos).slice_to(size));
self.read_pos += size;
Some(size)
}
/// Return whether the Reader has reached the end of the stream AND exhausted its buffer.
fn eof(&mut self) -> bool {
self.read_pos == self.read_max && self.wrapped.eof()
}
}
impl<T: Writer> Writer for BufferedStream<T> {
fn write(&mut self, buf: &[u8]) {
if buf.len() + self.write_len > self.write_buffer.len() {
// This is the lazy approach which may involve multiple writes where it's really not
// warranted. Maybe deal with that later.
if self.writing_chunked_body {
let s = format!("{}\r\n", (self.write_len + buf.len()).to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
if self.write_len > 0 {
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
self.write_len = 0;
}
self.wrapped.write(buf);
self.write_len = 0;
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
} else {
unsafe { self.write_buffer.mut_slice_from(self.write_len).copy_memory(buf); }
self.write_len += buf.len();
if self.write_len == self.write_buffer.len() {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
self.wrapped.write(self.write_buffer);
self.wrapped.write(bytes!("\r\n"));
} else {
self.wrapped.write(self.write_buffer);
}
self.write_len = 0;
}
}
}
fn flush(&mut self) {
if self.write_len > 0 {
if self.writing_chunked_body {
let s = format!("{}\r\n", self.write_len.to_str_radix(16));
self.wrapped.write(s.as_bytes());
}
self.wrapped.write(self.write_buffer.slice_to(self.write_len));
if self.writing_chunked_body {
self.wrapped.write(bytes!("\r\n"));
}
self.write_len = 0;
}
self.wrapped.flush();
}
}
| {
let mut read_buffer = vec::with_capacity(READ_BUF_SIZE);
unsafe { read_buffer.set_len(READ_BUF_SIZE); }
let mut write_buffer = vec::with_capacity(WRITE_BUF_SIZE);
unsafe { write_buffer.set_len(WRITE_BUF_SIZE); }
BufferedStream {
wrapped: stream,
read_buffer: read_buffer,
read_pos: 0u,
read_max: 0u,
write_buffer: write_buffer,
write_len: 0u,
writing_chunked_body: false,
}
} | identifier_body |
error.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
/*!
This module contains the definition of the program's main error type.
*/
use std::error::Error;
use std::fmt;
use std::io;
use std::result::Result as StdResult;
/**
Shorthand for the program's common result type.
*/
pub type Result<T> = StdResult<T, MainError>;
/**
Represents an error in the program.
*/
#[derive(Debug)]
pub enum MainError {
Io(Blame, io::Error),
OtherOwned(Blame, String),
OtherBorrowed(Blame, &'static str),
}
/**
Records who we have chosen to blame for a particular error.
This is used to distinguish between "report this to a user" and "explode violently".
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Blame { Human, Internal }
impl MainError {
pub fn is_human(&self) -> bool {
use self::MainError::*;
match *self {
Io(blame, _)
| OtherOwned(blame, _)
| OtherBorrowed(blame, _) => blame == Blame::Human,
}
}
}
impl fmt::Display for MainError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> StdResult<(), fmt::Error> {
use self::MainError::*;
use std::fmt::Display;
match *self {
Io(_, ref err) => Display::fmt(err, fmt),
OtherOwned(_, ref err) => Display::fmt(err, fmt),
OtherBorrowed(_, ref err) => Display::fmt(err, fmt),
}
}
}
impl Error for MainError {
fn de | self) -> &str {
use self::MainError::*;
match *self {
Io(_, ref err) => err.description(),
OtherOwned(_, ref err) => err,
OtherBorrowed(_, ref err) => err,
}
}
}
macro_rules! from_impl {
($src_ty:ty => $dst_ty:ty, $src:ident -> $e:expr) => {
impl From<$src_ty> for $dst_ty {
fn from($src: $src_ty) -> $dst_ty {
$e
}
}
}
}
from_impl! { (Blame, io::Error) => MainError, v -> MainError::Io(v.0, v.1) }
from_impl! { (Blame, String) => MainError, v -> MainError::OtherOwned(v.0, v.1) }
from_impl! { (Blame, &'static str) => MainError, v -> MainError::OtherBorrowed(v.0, v.1) }
from_impl! { io::Error => MainError, v -> MainError::Io(Blame::Internal, v) }
from_impl! { String => MainError, v -> MainError::OtherOwned(Blame::Internal, v) }
from_impl! { &'static str => MainError, v -> MainError::OtherBorrowed(Blame::Internal, v) }
| scription(& | identifier_name |
error.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All | files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
/*!
This module contains the definition of the program's main error type.
*/
use std::error::Error;
use std::fmt;
use std::io;
use std::result::Result as StdResult;
/**
Shorthand for the program's common result type.
*/
pub type Result<T> = StdResult<T, MainError>;
/**
Represents an error in the program.
*/
#[derive(Debug)]
pub enum MainError {
Io(Blame, io::Error),
OtherOwned(Blame, String),
OtherBorrowed(Blame, &'static str),
}
/**
Records who we have chosen to blame for a particular error.
This is used to distinguish between "report this to a user" and "explode violently".
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Blame { Human, Internal }
impl MainError {
pub fn is_human(&self) -> bool {
use self::MainError::*;
match *self {
Io(blame, _)
| OtherOwned(blame, _)
| OtherBorrowed(blame, _) => blame == Blame::Human,
}
}
}
impl fmt::Display for MainError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> StdResult<(), fmt::Error> {
use self::MainError::*;
use std::fmt::Display;
match *self {
Io(_, ref err) => Display::fmt(err, fmt),
OtherOwned(_, ref err) => Display::fmt(err, fmt),
OtherBorrowed(_, ref err) => Display::fmt(err, fmt),
}
}
}
impl Error for MainError {
fn description(&self) -> &str {
use self::MainError::*;
match *self {
Io(_, ref err) => err.description(),
OtherOwned(_, ref err) => err,
OtherBorrowed(_, ref err) => err,
}
}
}
macro_rules! from_impl {
($src_ty:ty => $dst_ty:ty, $src:ident -> $e:expr) => {
impl From<$src_ty> for $dst_ty {
fn from($src: $src_ty) -> $dst_ty {
$e
}
}
}
}
from_impl! { (Blame, io::Error) => MainError, v -> MainError::Io(v.0, v.1) }
from_impl! { (Blame, String) => MainError, v -> MainError::OtherOwned(v.0, v.1) }
from_impl! { (Blame, &'static str) => MainError, v -> MainError::OtherBorrowed(v.0, v.1) }
from_impl! { io::Error => MainError, v -> MainError::Io(Blame::Internal, v) }
from_impl! { String => MainError, v -> MainError::OtherOwned(Blame::Internal, v) }
from_impl! { &'static str => MainError, v -> MainError::OtherBorrowed(Blame::Internal, v) } | random_line_split |
|
mod.rs | pub mod controller;
pub use controller::{AreaEvent, Controller};
mod dispatcher;
pub use dispatcher::Dispatcher;
mod waveform_with_overlay;
pub use waveform_with_overlay::WaveformWithOverlay;
use crate::UIEventChannel;
#[derive(Debug)]
pub enum Event {
Area(AreaEvent),
UpdateRenderingCndt(Option<(f64, f64)>),
Refresh,
// FIXME those 2 are not audio specific, rather for a dedicated playback
StepBack,
StepForward,
Tick,
ZoomIn,
ZoomOut,
}
fn area_event(event: AreaEvent) |
pub fn update_rendering_cndt(dimensions: Option<(f64, f64)>) {
UIEventChannel::send(Event::UpdateRenderingCndt(dimensions));
}
pub fn refresh() {
UIEventChannel::send(Event::Refresh);
}
pub fn step_back() {
UIEventChannel::send(Event::StepBack);
}
pub fn step_forward() {
UIEventChannel::send(Event::StepForward);
}
pub fn tick() {
UIEventChannel::send(Event::Tick);
}
fn zoom_in() {
UIEventChannel::send(Event::ZoomIn);
}
fn zoom_out() {
UIEventChannel::send(Event::ZoomOut);
}
| {
UIEventChannel::send(Event::Area(event));
} | identifier_body |
mod.rs | pub mod controller;
pub use controller::{AreaEvent, Controller};
mod dispatcher;
pub use dispatcher::Dispatcher;
mod waveform_with_overlay;
pub use waveform_with_overlay::WaveformWithOverlay;
use crate::UIEventChannel;
#[derive(Debug)]
pub enum Event {
Area(AreaEvent),
UpdateRenderingCndt(Option<(f64, f64)>),
Refresh,
// FIXME those 2 are not audio specific, rather for a dedicated playback
StepBack,
StepForward,
Tick,
ZoomIn,
ZoomOut,
} |
pub fn update_rendering_cndt(dimensions: Option<(f64, f64)>) {
UIEventChannel::send(Event::UpdateRenderingCndt(dimensions));
}
pub fn refresh() {
UIEventChannel::send(Event::Refresh);
}
pub fn step_back() {
UIEventChannel::send(Event::StepBack);
}
pub fn step_forward() {
UIEventChannel::send(Event::StepForward);
}
pub fn tick() {
UIEventChannel::send(Event::Tick);
}
fn zoom_in() {
UIEventChannel::send(Event::ZoomIn);
}
fn zoom_out() {
UIEventChannel::send(Event::ZoomOut);
} |
fn area_event(event: AreaEvent) {
UIEventChannel::send(Event::Area(event));
} | random_line_split |
mod.rs | pub mod controller;
pub use controller::{AreaEvent, Controller};
mod dispatcher;
pub use dispatcher::Dispatcher;
mod waveform_with_overlay;
pub use waveform_with_overlay::WaveformWithOverlay;
use crate::UIEventChannel;
#[derive(Debug)]
pub enum Event {
Area(AreaEvent),
UpdateRenderingCndt(Option<(f64, f64)>),
Refresh,
// FIXME those 2 are not audio specific, rather for a dedicated playback
StepBack,
StepForward,
Tick,
ZoomIn,
ZoomOut,
}
fn | (event: AreaEvent) {
UIEventChannel::send(Event::Area(event));
}
pub fn update_rendering_cndt(dimensions: Option<(f64, f64)>) {
UIEventChannel::send(Event::UpdateRenderingCndt(dimensions));
}
pub fn refresh() {
UIEventChannel::send(Event::Refresh);
}
pub fn step_back() {
UIEventChannel::send(Event::StepBack);
}
pub fn step_forward() {
UIEventChannel::send(Event::StepForward);
}
pub fn tick() {
UIEventChannel::send(Event::Tick);
}
fn zoom_in() {
UIEventChannel::send(Event::ZoomIn);
}
fn zoom_out() {
UIEventChannel::send(Event::ZoomOut);
}
| area_event | identifier_name |
mod.rs | ///////////////////////////////////////////////////////////////
// Autogenerated by Thrift Compiler (1.0.0-dev)
//
// DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING
///////////////////////////////////////////////////////////////
#![allow(unused_mut, dead_code, non_snake_case, unused_imports)]
use ::thrift::rt::OrderedFloat;
use std::collections::{BTreeMap, BTreeSet};
| }
}
service! {
trait_name = SharedService,
processor_name = SharedServiceProcessor,
client_name = SharedServiceClient,
service_methods = [
SharedServiceGetStructArgs -> SharedServiceGetStructResult = a.getStruct(
key: i32 => 1,
) -> SharedStruct => SharedServiceGetStructError = [
] (SharedStruct),
],
parent_methods = [
],
bounds = [A: SharedService, ],
fields = [a: A, ]
} | strukt! {
name = SharedStruct,
fields = {
key: i32 => 1,
value: String => 2, | random_line_split |
def.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 middle::subst::ParamSpace;
use syntax::ast;
use syntax::ast_util::local_def;
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)]
pub enum Def {
DefFn(ast::DefId, ast::FnStyle),
DefStaticMethod(/* method */ ast::DefId, MethodProvenance, ast::FnStyle),
DefSelfTy(/* trait id */ ast::NodeId),
DefMod(ast::DefId),
DefForeignMod(ast::DefId),
DefStatic(ast::DefId, bool /* is_mutbl */),
DefLocal(ast::NodeId),
DefVariant(ast::DefId /* enum */, ast::DefId /* variant */, bool /* is_structure */),
DefTy(ast::DefId, bool /* is_enum */),
DefAssociatedTy(ast::DefId), | DefTyParam(ParamSpace, ast::DefId, uint),
DefUse(ast::DefId),
DefUpvar(ast::NodeId, // id of closed over local
ast::NodeId, // expr node that creates the closure
ast::NodeId), // block node for the closest enclosing proc
// or unboxed closure, DUMMY_NODE_ID otherwise
/// Note that if it's a tuple struct's definition, the node id of the ast::DefId
/// may either refer to the item definition's id or the StructDef.ctor_id.
///
/// The cases that I have encountered so far are (this is not exhaustive):
/// - If it's a ty_path referring to some tuple struct, then DefMap maps
/// it to a def whose id is the item definition's id.
/// - If it's an ExprPath referring to some tuple struct, then DefMap maps
/// it to a def whose id is the StructDef.ctor_id.
DefStruct(ast::DefId),
DefTyParamBinder(ast::NodeId), /* struct, impl or trait with ty params */
DefRegion(ast::NodeId),
DefLabel(ast::NodeId),
DefMethod(ast::DefId /* method */, Option<ast::DefId> /* trait */),
}
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)]
pub enum MethodProvenance {
FromTrait(ast::DefId),
FromImpl(ast::DefId),
}
impl Def {
pub fn def_id(&self) -> ast::DefId {
match *self {
DefFn(id, _) | DefStaticMethod(id, _, _) | DefMod(id) |
DefForeignMod(id) | DefStatic(id, _) |
DefVariant(_, id, _) | DefTy(id, _) | DefAssociatedTy(id) |
DefTyParam(_, id, _) | DefUse(id) | DefStruct(id) | DefTrait(id) |
DefMethod(id, _) => {
id
}
DefLocal(id) |
DefSelfTy(id) |
DefUpvar(id, _, _) |
DefRegion(id) |
DefTyParamBinder(id) |
DefLabel(id) => {
local_def(id)
}
DefPrimTy(_) => fail!()
}
}
pub fn variant_def_ids(&self) -> Option<(ast::DefId, ast::DefId)> {
match *self {
DefVariant(enum_id, var_id, _) => {
Some((enum_id, var_id))
}
_ => None
}
}
} | DefTrait(ast::DefId),
DefPrimTy(ast::PrimTy), | random_line_split |
def.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 middle::subst::ParamSpace;
use syntax::ast;
use syntax::ast_util::local_def;
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)]
pub enum Def {
DefFn(ast::DefId, ast::FnStyle),
DefStaticMethod(/* method */ ast::DefId, MethodProvenance, ast::FnStyle),
DefSelfTy(/* trait id */ ast::NodeId),
DefMod(ast::DefId),
DefForeignMod(ast::DefId),
DefStatic(ast::DefId, bool /* is_mutbl */),
DefLocal(ast::NodeId),
DefVariant(ast::DefId /* enum */, ast::DefId /* variant */, bool /* is_structure */),
DefTy(ast::DefId, bool /* is_enum */),
DefAssociatedTy(ast::DefId),
DefTrait(ast::DefId),
DefPrimTy(ast::PrimTy),
DefTyParam(ParamSpace, ast::DefId, uint),
DefUse(ast::DefId),
DefUpvar(ast::NodeId, // id of closed over local
ast::NodeId, // expr node that creates the closure
ast::NodeId), // block node for the closest enclosing proc
// or unboxed closure, DUMMY_NODE_ID otherwise
/// Note that if it's a tuple struct's definition, the node id of the ast::DefId
/// may either refer to the item definition's id or the StructDef.ctor_id.
///
/// The cases that I have encountered so far are (this is not exhaustive):
/// - If it's a ty_path referring to some tuple struct, then DefMap maps
/// it to a def whose id is the item definition's id.
/// - If it's an ExprPath referring to some tuple struct, then DefMap maps
/// it to a def whose id is the StructDef.ctor_id.
DefStruct(ast::DefId),
DefTyParamBinder(ast::NodeId), /* struct, impl or trait with ty params */
DefRegion(ast::NodeId),
DefLabel(ast::NodeId),
DefMethod(ast::DefId /* method */, Option<ast::DefId> /* trait */),
}
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)]
pub enum MethodProvenance {
FromTrait(ast::DefId),
FromImpl(ast::DefId),
}
impl Def {
pub fn | (&self) -> ast::DefId {
match *self {
DefFn(id, _) | DefStaticMethod(id, _, _) | DefMod(id) |
DefForeignMod(id) | DefStatic(id, _) |
DefVariant(_, id, _) | DefTy(id, _) | DefAssociatedTy(id) |
DefTyParam(_, id, _) | DefUse(id) | DefStruct(id) | DefTrait(id) |
DefMethod(id, _) => {
id
}
DefLocal(id) |
DefSelfTy(id) |
DefUpvar(id, _, _) |
DefRegion(id) |
DefTyParamBinder(id) |
DefLabel(id) => {
local_def(id)
}
DefPrimTy(_) => fail!()
}
}
pub fn variant_def_ids(&self) -> Option<(ast::DefId, ast::DefId)> {
match *self {
DefVariant(enum_id, var_id, _) => {
Some((enum_id, var_id))
}
_ => None
}
}
}
| def_id | identifier_name |
variadic-ffi.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
extern "stdcall" {
fn printf(_: *u8,...); //~ ERROR: variadic function must have C calling convention
}
extern {
fn foo(f: int, x: u8,...);
}
extern "C" fn bar(f: int, x: u8) {}
fn | () {
unsafe {
foo(); //~ ERROR: this function takes at least 2 parameters but 0 parameters were supplied
foo(1); //~ ERROR: this function takes at least 2 parameters but 1 parameter was supplied
let x: extern "C" unsafe fn(f: int, x: u8) = foo;
//~^ ERROR: mismatched types: expected `extern "C" unsafe fn(int, u8)` but found `extern "C" unsafe fn(int, u8,...)` (expected non-variadic fn but found variadic function)
let y: extern "C" unsafe fn(f: int, x: u8,...) = bar;
//~^ ERROR: mismatched types: expected `extern "C" unsafe fn(int, u8,...)` but found `extern "C" extern fn(int, u8)` (expected variadic fn but found non-variadic function)
foo(1, 2, 3f32); //~ ERROR: can't pass an f32 to variadic function, cast to c_double
foo(1, 2, true); //~ ERROR: can't pass bool to variadic function, cast to c_int
foo(1, 2, 1i8); //~ ERROR: can't pass i8 to variadic function, cast to c_int
foo(1, 2, 1u8); //~ ERROR: can't pass u8 to variadic function, cast to c_uint
foo(1, 2, 1i16); //~ ERROR: can't pass i16 to variadic function, cast to c_int
foo(1, 2, 1u16); //~ ERROR: can't pass u16 to variadic function, cast to c_uint
}
}
| main | identifier_name |
variadic-ffi.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
extern "stdcall" {
fn printf(_: *u8,...); //~ ERROR: variadic function must have C calling convention
}
extern {
fn foo(f: int, x: u8,...);
}
extern "C" fn bar(f: int, x: u8) {}
fn main() {
unsafe {
foo(); //~ ERROR: this function takes at least 2 parameters but 0 parameters were supplied
foo(1); //~ ERROR: this function takes at least 2 parameters but 1 parameter was supplied
let x: extern "C" unsafe fn(f: int, x: u8) = foo;
//~^ ERROR: mismatched types: expected `extern "C" unsafe fn(int, u8)` but found `extern "C" unsafe fn(int, u8,...)` (expected non-variadic fn but found variadic function)
let y: extern "C" unsafe fn(f: int, x: u8,...) = bar;
//~^ ERROR: mismatched types: expected `extern "C" unsafe fn(int, u8,...)` but found `extern "C" extern fn(int, u8)` (expected variadic fn but found non-variadic function)
| foo(1, 2, 3f32); //~ ERROR: can't pass an f32 to variadic function, cast to c_double
foo(1, 2, true); //~ ERROR: can't pass bool to variadic function, cast to c_int
foo(1, 2, 1i8); //~ ERROR: can't pass i8 to variadic function, cast to c_int
foo(1, 2, 1u8); //~ ERROR: can't pass u8 to variadic function, cast to c_uint
foo(1, 2, 1i16); //~ ERROR: can't pass i16 to variadic function, cast to c_int
foo(1, 2, 1u16); //~ ERROR: can't pass u16 to variadic function, cast to c_uint
}
} | random_line_split |
|
variadic-ffi.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
extern "stdcall" {
fn printf(_: *u8,...); //~ ERROR: variadic function must have C calling convention
}
extern {
fn foo(f: int, x: u8,...);
}
extern "C" fn bar(f: int, x: u8) {}
fn main() | {
unsafe {
foo(); //~ ERROR: this function takes at least 2 parameters but 0 parameters were supplied
foo(1); //~ ERROR: this function takes at least 2 parameters but 1 parameter was supplied
let x: extern "C" unsafe fn(f: int, x: u8) = foo;
//~^ ERROR: mismatched types: expected `extern "C" unsafe fn(int, u8)` but found `extern "C" unsafe fn(int, u8, ...)` (expected non-variadic fn but found variadic function)
let y: extern "C" unsafe fn(f: int, x: u8, ...) = bar;
//~^ ERROR: mismatched types: expected `extern "C" unsafe fn(int, u8, ...)` but found `extern "C" extern fn(int, u8)` (expected variadic fn but found non-variadic function)
foo(1, 2, 3f32); //~ ERROR: can't pass an f32 to variadic function, cast to c_double
foo(1, 2, true); //~ ERROR: can't pass bool to variadic function, cast to c_int
foo(1, 2, 1i8); //~ ERROR: can't pass i8 to variadic function, cast to c_int
foo(1, 2, 1u8); //~ ERROR: can't pass u8 to variadic function, cast to c_uint
foo(1, 2, 1i16); //~ ERROR: can't pass i16 to variadic function, cast to c_int
foo(1, 2, 1u16); //~ ERROR: can't pass u16 to variadic function, cast to c_uint
}
} | identifier_body |
|
import-crate-with-invalid-spans.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// aux-build:crate_with_invalid_spans.rs
extern crate crate_with_invalid_spans;
fn main() | {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo > span.hi.
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
} | identifier_body |
|
import-crate-with-invalid-spans.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// aux-build:crate_with_invalid_spans.rs
| // Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
} | extern crate crate_with_invalid_spans;
fn main() {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo > span.hi. | random_line_split |
import-crate-with-invalid-spans.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// aux-build:crate_with_invalid_spans.rs
extern crate crate_with_invalid_spans;
fn | () {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo > span.hi.
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
}
| main | identifier_name |
bluetoothremotegattservice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutHeap, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bluetoothdevice::BluetoothDevice;
use dom::bluetoothremotegattcharacteristic::BluetoothRemoteGATTCharacteristic;
use util::str::DOMString;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice
#[dom_struct]
pub struct BluetoothRemoteGATTService {
reflector_: Reflector,
device: MutHeap<JS<BluetoothDevice>>,
uuid: DOMString,
isPrimary: bool,
}
impl BluetoothRemoteGATTService {
pub fn new_inherited(device: &BluetoothDevice,
uuid: DOMString,
isPrimary: bool)
-> BluetoothRemoteGATTService {
BluetoothRemoteGATTService {
reflector_: Reflector::new(),
device: MutHeap::new(device),
uuid: uuid,
isPrimary: isPrimary,
}
}
pub fn new(global: GlobalRef,
device: &BluetoothDevice,
uuid: DOMString,
isPrimary: bool)
-> Root<BluetoothRemoteGATTService> {
reflect_dom_object(box BluetoothRemoteGATTService::new_inherited(device,
uuid,
isPrimary),
global,
BluetoothRemoteGATTServiceBinding::Wrap)
}
}
impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-device | self.device.get()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-isprimary
fn IsPrimary(&self) -> bool {
self.isPrimary
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-uuid
fn Uuid(&self) -> DOMString {
self.uuid.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-getcharacteristic
fn GetCharacteristic(&self) -> Option<Root<BluetoothRemoteGATTCharacteristic>> {
// UNIMPLEMENTED
None
}
} | fn Device(&self) -> Root<BluetoothDevice> { | random_line_split |
bluetoothremotegattservice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutHeap, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bluetoothdevice::BluetoothDevice;
use dom::bluetoothremotegattcharacteristic::BluetoothRemoteGATTCharacteristic;
use util::str::DOMString;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice
#[dom_struct]
pub struct BluetoothRemoteGATTService {
reflector_: Reflector,
device: MutHeap<JS<BluetoothDevice>>,
uuid: DOMString,
isPrimary: bool,
}
impl BluetoothRemoteGATTService {
pub fn new_inherited(device: &BluetoothDevice,
uuid: DOMString,
isPrimary: bool)
-> BluetoothRemoteGATTService {
BluetoothRemoteGATTService {
reflector_: Reflector::new(),
device: MutHeap::new(device),
uuid: uuid,
isPrimary: isPrimary,
}
}
pub fn new(global: GlobalRef,
device: &BluetoothDevice,
uuid: DOMString,
isPrimary: bool)
-> Root<BluetoothRemoteGATTService> {
reflect_dom_object(box BluetoothRemoteGATTService::new_inherited(device,
uuid,
isPrimary),
global,
BluetoothRemoteGATTServiceBinding::Wrap)
}
}
impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-device
fn Device(&self) -> Root<BluetoothDevice> {
self.device.get()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-isprimary
fn IsPrimary(&self) -> bool {
self.isPrimary
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-uuid
fn | (&self) -> DOMString {
self.uuid.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-getcharacteristic
fn GetCharacteristic(&self) -> Option<Root<BluetoothRemoteGATTCharacteristic>> {
// UNIMPLEMENTED
None
}
}
| Uuid | identifier_name |
gpu_vector.rs | //! Wrapper for an OpenGL buffer object.
use std::mem;
use gl;
use gl::types::*;
use resource::gl_primitive::GLPrimitive;
#[path = "../error.rs"]
mod error;
struct GLHandle {
handle: GLuint
}
impl GLHandle {
pub fn new(handle: GLuint) -> GLHandle {
GLHandle {
handle: handle
}
}
pub fn handle(&self) -> GLuint {
self.handle
}
}
impl Drop for GLHandle {
fn drop(&mut self) {
unsafe {
verify!(gl::DeleteBuffers(1, &self.handle))
}
}
}
// FIXME: generalize this for any resource: GPUResource
/// A vector of elements that can be loaded to the GPU, on the RAM, or both.
pub struct GPUVector<T> {
trash: bool,
len: usize,
buf_type: BufferType,
alloc_type: AllocationType,
handle: Option<(usize, GLHandle)>,
data: Option<Vec<T>>,
}
// FIXME: implement Clone
impl<T: GLPrimitive> GPUVector<T> {
/// Creates a new `GPUVector` that is not yet uploaded to the GPU.
pub fn new(data: Vec<T>, buf_type: BufferType, alloc_type: AllocationType) -> GPUVector<T> {
GPUVector {
trash: true,
len: data.len(),
buf_type: buf_type,
alloc_type: alloc_type,
handle: None,
data: Some(data)
}
}
/// The length of this vector.
#[inline]
pub fn len(&self) -> usize {
if self.trash {
match self.data {
Some(ref d) => d.len(),
None => panic!("This should never happend.")
}
}
else {
self.len
}
}
/// Mutably accesses the vector if it is available on RAM.
///
/// This method will mark this vector as `trash`.
#[inline]
pub fn data_mut<'a>(&'a mut self) -> &'a mut Option<Vec<T>> {
self.trash = true;
&mut self.data
}
/// Immutably accesses the vector if it is available on RAM.
#[inline]
pub fn data<'a>(&'a self) -> &'a Option<Vec<T>> {
&self.data
}
/// Returns `true` if this vector is already uploaded to the GPU.
#[inline] | pub fn is_on_gpu(&self) -> bool {
self.handle.is_some()
}
/// Returns `true` if the cpu data and gpu data are out of sync.
#[inline]
pub fn trash(&self) -> bool {
self.trash
}
/// Returns `true` if this vector is available on RAM.
///
/// Note that a `GPUVector` may be both on RAM and on the GPU.
#[inline]
pub fn is_on_ram(&self) -> bool {
self.data.is_some()
}
/// Loads the vector from the RAM to the GPU.
///
/// If the vector is not available on RAM or already loaded to the GPU, nothing will happen.
#[inline]
pub fn load_to_gpu(&mut self) {
if!self.is_on_gpu() {
let buf_type = self.buf_type;
let alloc_type = self.alloc_type;
let len = &mut self.len;
self.handle = self.data.as_ref().map(|d| {
*len = d.len();
(d.len(), GLHandle::new(upload_buffer(&d[..], buf_type, alloc_type)))
});
}
else if self.trash() {
for d in self.data.iter() {
self.len = d.len();
match self.handle {
None => { },
Some((ref mut len, ref handle)) => {
let handle = handle.handle();
*len = update_buffer(&d[..], *len, handle, self.buf_type, self.alloc_type)
}
}
}
}
self.trash = false;
}
/// Binds this vector to the appropriate gpu array.
///
/// This does not associate this buffer with any shader attribute.
#[inline]
pub fn bind(&mut self) {
self.load_to_gpu();
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).expect("Could not bind the vector: data unavailable.");
verify!(gl::BindBuffer(self.buf_type.to_gl(), handle));
}
/// Unbind this vector to the corresponding gpu buffer.
#[inline]
pub fn unbind(&mut self) {
if self.is_on_gpu() {
verify!(gl::BindBuffer(self.buf_type.to_gl(), 0));
}
}
/// Loads the vector from the GPU to the RAM.
///
/// If the vector is not available on the GPU or already loaded to the RAM, nothing will
/// happen.
#[inline]
pub fn load_to_ram(&mut self) {
if!self.is_on_ram() && self.is_on_gpu() {
assert!(!self.trash);
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).unwrap();
let mut data = Vec::with_capacity(self.len);
unsafe { data.set_len(self.len) };
download_buffer(handle, self.buf_type, &mut data[..]);
self.data = Some(data);
}
}
/// Unloads this resource from the GPU.
#[inline]
pub fn unload_from_gpu(&mut self) {
let _ = self.handle.as_ref().map(|&(_, ref h)| unsafe { verify!(gl::DeleteBuffers(1, &h.handle())) });
self.len = self.len();
self.handle = None;
self.trash = false;
}
/// Removes this resource from the RAM.
///
/// This is useful to save memory for vectors required on the GPU only.
#[inline]
pub fn unload_from_ram(&mut self) {
if self.trash && self.is_on_gpu() {
self.load_to_gpu();
}
self.data = None;
}
}
impl<T: Clone + GLPrimitive> GPUVector<T> {
/// Returns this vector as an owned vector if it is available on RAM.
///
/// If it has been uploaded to the GPU, and unloaded from the RAM, call `load_to_ram` first to
/// make the data accessible.
#[inline]
pub fn to_owned(&self) -> Option<Vec<T>> {
self.data.as_ref().map(|d| d.clone())
}
}
/// Type of gpu buffer.
#[derive(Clone, Copy)]
pub enum BufferType {
/// An array buffer bindable to a gl::ARRAY_BUFFER.
Array,
/// An array buffer bindable to a gl::ELEMENT_ARRAY_BUFFER.
ElementArray
}
impl BufferType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
BufferType::Array => gl::ARRAY_BUFFER,
BufferType::ElementArray => gl::ELEMENT_ARRAY_BUFFER
}
}
}
/// Allocation type of gpu buffers.
#[derive(Clone, Copy)]
pub enum AllocationType {
/// STATIC_DRAW allocation type.
StaticDraw,
/// DYNAMIC_DRAW allocation type.
DynamicDraw,
/// STREAM_DRAW allocation type.
StreamDraw
}
impl AllocationType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
AllocationType::StaticDraw => gl::STATIC_DRAW,
AllocationType::DynamicDraw => gl::DYNAMIC_DRAW,
AllocationType::StreamDraw => gl::STREAM_DRAW
}
}
}
/// Allocates and uploads a buffer to the gpu.
#[inline]
pub fn upload_buffer<T: GLPrimitive>(buf: &[T],
buf_type: BufferType,
allocation_type: AllocationType)
-> GLuint {
// Upload values of vertices
let mut buf_id: GLuint = 0;
unsafe {
verify!(gl::GenBuffers(1, &mut buf_id));
let _ = update_buffer(buf, 0, buf_id, buf_type, allocation_type);
}
buf_id
}
/// Downloads a buffer from the gpu.
///
///
#[inline]
pub fn download_buffer<T: GLPrimitive>(buf_id: GLuint, buf_type: BufferType, out: &mut [T]) {
unsafe {
verify!(gl::BindBuffer(buf_type.to_gl(), buf_id));
verify!(gl::GetBufferSubData(
buf_type.to_gl(),
0,
(out.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&out[0])));
}
}
/// Updates a buffer to the gpu.
///
/// Returns the number of element the bufer on the gpu can hold.
#[inline]
pub fn update_buffer<T: GLPrimitive>(buf: &[T],
gpu_buf_len: usize,
gpu_buf_id: GLuint,
gpu_buf_type: BufferType,
gpu_allocation_type: AllocationType)
-> usize {
unsafe {
verify!(gl::BindBuffer(gpu_buf_type.to_gl(), gpu_buf_id));
if buf.len() < gpu_buf_len {
verify!(gl::BufferSubData(
gpu_buf_type.to_gl(),
0,
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0])));
gpu_buf_len
}
else {
verify!(gl::BufferData(
gpu_buf_type.to_gl(),
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0]),
gpu_allocation_type.to_gl()));
buf.len()
}
}
} | random_line_split |
|
gpu_vector.rs | //! Wrapper for an OpenGL buffer object.
use std::mem;
use gl;
use gl::types::*;
use resource::gl_primitive::GLPrimitive;
#[path = "../error.rs"]
mod error;
struct GLHandle {
handle: GLuint
}
impl GLHandle {
pub fn new(handle: GLuint) -> GLHandle {
GLHandle {
handle: handle
}
}
pub fn handle(&self) -> GLuint {
self.handle
}
}
impl Drop for GLHandle {
fn drop(&mut self) {
unsafe {
verify!(gl::DeleteBuffers(1, &self.handle))
}
}
}
// FIXME: generalize this for any resource: GPUResource
/// A vector of elements that can be loaded to the GPU, on the RAM, or both.
pub struct GPUVector<T> {
trash: bool,
len: usize,
buf_type: BufferType,
alloc_type: AllocationType,
handle: Option<(usize, GLHandle)>,
data: Option<Vec<T>>,
}
// FIXME: implement Clone
impl<T: GLPrimitive> GPUVector<T> {
/// Creates a new `GPUVector` that is not yet uploaded to the GPU.
pub fn new(data: Vec<T>, buf_type: BufferType, alloc_type: AllocationType) -> GPUVector<T> {
GPUVector {
trash: true,
len: data.len(),
buf_type: buf_type,
alloc_type: alloc_type,
handle: None,
data: Some(data)
}
}
/// The length of this vector.
#[inline]
pub fn len(&self) -> usize {
if self.trash {
match self.data {
Some(ref d) => d.len(),
None => panic!("This should never happend.")
}
}
else {
self.len
}
}
/// Mutably accesses the vector if it is available on RAM.
///
/// This method will mark this vector as `trash`.
#[inline]
pub fn data_mut<'a>(&'a mut self) -> &'a mut Option<Vec<T>> {
self.trash = true;
&mut self.data
}
/// Immutably accesses the vector if it is available on RAM.
#[inline]
pub fn data<'a>(&'a self) -> &'a Option<Vec<T>> {
&self.data
}
/// Returns `true` if this vector is already uploaded to the GPU.
#[inline]
pub fn is_on_gpu(&self) -> bool {
self.handle.is_some()
}
/// Returns `true` if the cpu data and gpu data are out of sync.
#[inline]
pub fn trash(&self) -> bool {
self.trash
}
/// Returns `true` if this vector is available on RAM.
///
/// Note that a `GPUVector` may be both on RAM and on the GPU.
#[inline]
pub fn is_on_ram(&self) -> bool {
self.data.is_some()
}
/// Loads the vector from the RAM to the GPU.
///
/// If the vector is not available on RAM or already loaded to the GPU, nothing will happen.
#[inline]
pub fn load_to_gpu(&mut self) {
if!self.is_on_gpu() {
let buf_type = self.buf_type;
let alloc_type = self.alloc_type;
let len = &mut self.len;
self.handle = self.data.as_ref().map(|d| {
*len = d.len();
(d.len(), GLHandle::new(upload_buffer(&d[..], buf_type, alloc_type)))
});
}
else if self.trash() {
for d in self.data.iter() {
self.len = d.len();
match self.handle {
None => { },
Some((ref mut len, ref handle)) => {
let handle = handle.handle();
*len = update_buffer(&d[..], *len, handle, self.buf_type, self.alloc_type)
}
}
}
}
self.trash = false;
}
/// Binds this vector to the appropriate gpu array.
///
/// This does not associate this buffer with any shader attribute.
#[inline]
pub fn bind(&mut self) {
self.load_to_gpu();
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).expect("Could not bind the vector: data unavailable.");
verify!(gl::BindBuffer(self.buf_type.to_gl(), handle));
}
/// Unbind this vector to the corresponding gpu buffer.
#[inline]
pub fn unbind(&mut self) {
if self.is_on_gpu() {
verify!(gl::BindBuffer(self.buf_type.to_gl(), 0));
}
}
/// Loads the vector from the GPU to the RAM.
///
/// If the vector is not available on the GPU or already loaded to the RAM, nothing will
/// happen.
#[inline]
pub fn load_to_ram(&mut self) {
if!self.is_on_ram() && self.is_on_gpu() {
assert!(!self.trash);
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).unwrap();
let mut data = Vec::with_capacity(self.len);
unsafe { data.set_len(self.len) };
download_buffer(handle, self.buf_type, &mut data[..]);
self.data = Some(data);
}
}
/// Unloads this resource from the GPU.
#[inline]
pub fn unload_from_gpu(&mut self) {
let _ = self.handle.as_ref().map(|&(_, ref h)| unsafe { verify!(gl::DeleteBuffers(1, &h.handle())) });
self.len = self.len();
self.handle = None;
self.trash = false;
}
/// Removes this resource from the RAM.
///
/// This is useful to save memory for vectors required on the GPU only.
#[inline]
pub fn unload_from_ram(&mut self) {
if self.trash && self.is_on_gpu() {
self.load_to_gpu();
}
self.data = None;
}
}
impl<T: Clone + GLPrimitive> GPUVector<T> {
/// Returns this vector as an owned vector if it is available on RAM.
///
/// If it has been uploaded to the GPU, and unloaded from the RAM, call `load_to_ram` first to
/// make the data accessible.
#[inline]
pub fn to_owned(&self) -> Option<Vec<T>> {
self.data.as_ref().map(|d| d.clone())
}
}
/// Type of gpu buffer.
#[derive(Clone, Copy)]
pub enum BufferType {
/// An array buffer bindable to a gl::ARRAY_BUFFER.
Array,
/// An array buffer bindable to a gl::ELEMENT_ARRAY_BUFFER.
ElementArray
}
impl BufferType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
BufferType::Array => gl::ARRAY_BUFFER,
BufferType::ElementArray => gl::ELEMENT_ARRAY_BUFFER
}
}
}
/// Allocation type of gpu buffers.
#[derive(Clone, Copy)]
pub enum AllocationType {
/// STATIC_DRAW allocation type.
StaticDraw,
/// DYNAMIC_DRAW allocation type.
DynamicDraw,
/// STREAM_DRAW allocation type.
StreamDraw
}
impl AllocationType {
#[inline]
fn to_gl(&self) -> GLuint |
}
/// Allocates and uploads a buffer to the gpu.
#[inline]
pub fn upload_buffer<T: GLPrimitive>(buf: &[T],
buf_type: BufferType,
allocation_type: AllocationType)
-> GLuint {
// Upload values of vertices
let mut buf_id: GLuint = 0;
unsafe {
verify!(gl::GenBuffers(1, &mut buf_id));
let _ = update_buffer(buf, 0, buf_id, buf_type, allocation_type);
}
buf_id
}
/// Downloads a buffer from the gpu.
///
///
#[inline]
pub fn download_buffer<T: GLPrimitive>(buf_id: GLuint, buf_type: BufferType, out: &mut [T]) {
unsafe {
verify!(gl::BindBuffer(buf_type.to_gl(), buf_id));
verify!(gl::GetBufferSubData(
buf_type.to_gl(),
0,
(out.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&out[0])));
}
}
/// Updates a buffer to the gpu.
///
/// Returns the number of element the bufer on the gpu can hold.
#[inline]
pub fn update_buffer<T: GLPrimitive>(buf: &[T],
gpu_buf_len: usize,
gpu_buf_id: GLuint,
gpu_buf_type: BufferType,
gpu_allocation_type: AllocationType)
-> usize {
unsafe {
verify!(gl::BindBuffer(gpu_buf_type.to_gl(), gpu_buf_id));
if buf.len() < gpu_buf_len {
verify!(gl::BufferSubData(
gpu_buf_type.to_gl(),
0,
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0])));
gpu_buf_len
}
else {
verify!(gl::BufferData(
gpu_buf_type.to_gl(),
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0]),
gpu_allocation_type.to_gl()));
buf.len()
}
}
}
| {
match *self {
AllocationType::StaticDraw => gl::STATIC_DRAW,
AllocationType::DynamicDraw => gl::DYNAMIC_DRAW,
AllocationType::StreamDraw => gl::STREAM_DRAW
}
} | identifier_body |
gpu_vector.rs | //! Wrapper for an OpenGL buffer object.
use std::mem;
use gl;
use gl::types::*;
use resource::gl_primitive::GLPrimitive;
#[path = "../error.rs"]
mod error;
struct | {
handle: GLuint
}
impl GLHandle {
pub fn new(handle: GLuint) -> GLHandle {
GLHandle {
handle: handle
}
}
pub fn handle(&self) -> GLuint {
self.handle
}
}
impl Drop for GLHandle {
fn drop(&mut self) {
unsafe {
verify!(gl::DeleteBuffers(1, &self.handle))
}
}
}
// FIXME: generalize this for any resource: GPUResource
/// A vector of elements that can be loaded to the GPU, on the RAM, or both.
pub struct GPUVector<T> {
trash: bool,
len: usize,
buf_type: BufferType,
alloc_type: AllocationType,
handle: Option<(usize, GLHandle)>,
data: Option<Vec<T>>,
}
// FIXME: implement Clone
impl<T: GLPrimitive> GPUVector<T> {
/// Creates a new `GPUVector` that is not yet uploaded to the GPU.
pub fn new(data: Vec<T>, buf_type: BufferType, alloc_type: AllocationType) -> GPUVector<T> {
GPUVector {
trash: true,
len: data.len(),
buf_type: buf_type,
alloc_type: alloc_type,
handle: None,
data: Some(data)
}
}
/// The length of this vector.
#[inline]
pub fn len(&self) -> usize {
if self.trash {
match self.data {
Some(ref d) => d.len(),
None => panic!("This should never happend.")
}
}
else {
self.len
}
}
/// Mutably accesses the vector if it is available on RAM.
///
/// This method will mark this vector as `trash`.
#[inline]
pub fn data_mut<'a>(&'a mut self) -> &'a mut Option<Vec<T>> {
self.trash = true;
&mut self.data
}
/// Immutably accesses the vector if it is available on RAM.
#[inline]
pub fn data<'a>(&'a self) -> &'a Option<Vec<T>> {
&self.data
}
/// Returns `true` if this vector is already uploaded to the GPU.
#[inline]
pub fn is_on_gpu(&self) -> bool {
self.handle.is_some()
}
/// Returns `true` if the cpu data and gpu data are out of sync.
#[inline]
pub fn trash(&self) -> bool {
self.trash
}
/// Returns `true` if this vector is available on RAM.
///
/// Note that a `GPUVector` may be both on RAM and on the GPU.
#[inline]
pub fn is_on_ram(&self) -> bool {
self.data.is_some()
}
/// Loads the vector from the RAM to the GPU.
///
/// If the vector is not available on RAM or already loaded to the GPU, nothing will happen.
#[inline]
pub fn load_to_gpu(&mut self) {
if!self.is_on_gpu() {
let buf_type = self.buf_type;
let alloc_type = self.alloc_type;
let len = &mut self.len;
self.handle = self.data.as_ref().map(|d| {
*len = d.len();
(d.len(), GLHandle::new(upload_buffer(&d[..], buf_type, alloc_type)))
});
}
else if self.trash() {
for d in self.data.iter() {
self.len = d.len();
match self.handle {
None => { },
Some((ref mut len, ref handle)) => {
let handle = handle.handle();
*len = update_buffer(&d[..], *len, handle, self.buf_type, self.alloc_type)
}
}
}
}
self.trash = false;
}
/// Binds this vector to the appropriate gpu array.
///
/// This does not associate this buffer with any shader attribute.
#[inline]
pub fn bind(&mut self) {
self.load_to_gpu();
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).expect("Could not bind the vector: data unavailable.");
verify!(gl::BindBuffer(self.buf_type.to_gl(), handle));
}
/// Unbind this vector to the corresponding gpu buffer.
#[inline]
pub fn unbind(&mut self) {
if self.is_on_gpu() {
verify!(gl::BindBuffer(self.buf_type.to_gl(), 0));
}
}
/// Loads the vector from the GPU to the RAM.
///
/// If the vector is not available on the GPU or already loaded to the RAM, nothing will
/// happen.
#[inline]
pub fn load_to_ram(&mut self) {
if!self.is_on_ram() && self.is_on_gpu() {
assert!(!self.trash);
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).unwrap();
let mut data = Vec::with_capacity(self.len);
unsafe { data.set_len(self.len) };
download_buffer(handle, self.buf_type, &mut data[..]);
self.data = Some(data);
}
}
/// Unloads this resource from the GPU.
#[inline]
pub fn unload_from_gpu(&mut self) {
let _ = self.handle.as_ref().map(|&(_, ref h)| unsafe { verify!(gl::DeleteBuffers(1, &h.handle())) });
self.len = self.len();
self.handle = None;
self.trash = false;
}
/// Removes this resource from the RAM.
///
/// This is useful to save memory for vectors required on the GPU only.
#[inline]
pub fn unload_from_ram(&mut self) {
if self.trash && self.is_on_gpu() {
self.load_to_gpu();
}
self.data = None;
}
}
impl<T: Clone + GLPrimitive> GPUVector<T> {
/// Returns this vector as an owned vector if it is available on RAM.
///
/// If it has been uploaded to the GPU, and unloaded from the RAM, call `load_to_ram` first to
/// make the data accessible.
#[inline]
pub fn to_owned(&self) -> Option<Vec<T>> {
self.data.as_ref().map(|d| d.clone())
}
}
/// Type of gpu buffer.
#[derive(Clone, Copy)]
pub enum BufferType {
/// An array buffer bindable to a gl::ARRAY_BUFFER.
Array,
/// An array buffer bindable to a gl::ELEMENT_ARRAY_BUFFER.
ElementArray
}
impl BufferType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
BufferType::Array => gl::ARRAY_BUFFER,
BufferType::ElementArray => gl::ELEMENT_ARRAY_BUFFER
}
}
}
/// Allocation type of gpu buffers.
#[derive(Clone, Copy)]
pub enum AllocationType {
/// STATIC_DRAW allocation type.
StaticDraw,
/// DYNAMIC_DRAW allocation type.
DynamicDraw,
/// STREAM_DRAW allocation type.
StreamDraw
}
impl AllocationType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
AllocationType::StaticDraw => gl::STATIC_DRAW,
AllocationType::DynamicDraw => gl::DYNAMIC_DRAW,
AllocationType::StreamDraw => gl::STREAM_DRAW
}
}
}
/// Allocates and uploads a buffer to the gpu.
#[inline]
pub fn upload_buffer<T: GLPrimitive>(buf: &[T],
buf_type: BufferType,
allocation_type: AllocationType)
-> GLuint {
// Upload values of vertices
let mut buf_id: GLuint = 0;
unsafe {
verify!(gl::GenBuffers(1, &mut buf_id));
let _ = update_buffer(buf, 0, buf_id, buf_type, allocation_type);
}
buf_id
}
/// Downloads a buffer from the gpu.
///
///
#[inline]
pub fn download_buffer<T: GLPrimitive>(buf_id: GLuint, buf_type: BufferType, out: &mut [T]) {
unsafe {
verify!(gl::BindBuffer(buf_type.to_gl(), buf_id));
verify!(gl::GetBufferSubData(
buf_type.to_gl(),
0,
(out.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&out[0])));
}
}
/// Updates a buffer to the gpu.
///
/// Returns the number of element the bufer on the gpu can hold.
#[inline]
pub fn update_buffer<T: GLPrimitive>(buf: &[T],
gpu_buf_len: usize,
gpu_buf_id: GLuint,
gpu_buf_type: BufferType,
gpu_allocation_type: AllocationType)
-> usize {
unsafe {
verify!(gl::BindBuffer(gpu_buf_type.to_gl(), gpu_buf_id));
if buf.len() < gpu_buf_len {
verify!(gl::BufferSubData(
gpu_buf_type.to_gl(),
0,
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0])));
gpu_buf_len
}
else {
verify!(gl::BufferData(
gpu_buf_type.to_gl(),
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0]),
gpu_allocation_type.to_gl()));
buf.len()
}
}
}
| GLHandle | identifier_name |
gpu_vector.rs | //! Wrapper for an OpenGL buffer object.
use std::mem;
use gl;
use gl::types::*;
use resource::gl_primitive::GLPrimitive;
#[path = "../error.rs"]
mod error;
struct GLHandle {
handle: GLuint
}
impl GLHandle {
pub fn new(handle: GLuint) -> GLHandle {
GLHandle {
handle: handle
}
}
pub fn handle(&self) -> GLuint {
self.handle
}
}
impl Drop for GLHandle {
fn drop(&mut self) {
unsafe {
verify!(gl::DeleteBuffers(1, &self.handle))
}
}
}
// FIXME: generalize this for any resource: GPUResource
/// A vector of elements that can be loaded to the GPU, on the RAM, or both.
pub struct GPUVector<T> {
trash: bool,
len: usize,
buf_type: BufferType,
alloc_type: AllocationType,
handle: Option<(usize, GLHandle)>,
data: Option<Vec<T>>,
}
// FIXME: implement Clone
impl<T: GLPrimitive> GPUVector<T> {
/// Creates a new `GPUVector` that is not yet uploaded to the GPU.
pub fn new(data: Vec<T>, buf_type: BufferType, alloc_type: AllocationType) -> GPUVector<T> {
GPUVector {
trash: true,
len: data.len(),
buf_type: buf_type,
alloc_type: alloc_type,
handle: None,
data: Some(data)
}
}
/// The length of this vector.
#[inline]
pub fn len(&self) -> usize {
if self.trash {
match self.data {
Some(ref d) => d.len(),
None => panic!("This should never happend.")
}
}
else {
self.len
}
}
/// Mutably accesses the vector if it is available on RAM.
///
/// This method will mark this vector as `trash`.
#[inline]
pub fn data_mut<'a>(&'a mut self) -> &'a mut Option<Vec<T>> {
self.trash = true;
&mut self.data
}
/// Immutably accesses the vector if it is available on RAM.
#[inline]
pub fn data<'a>(&'a self) -> &'a Option<Vec<T>> {
&self.data
}
/// Returns `true` if this vector is already uploaded to the GPU.
#[inline]
pub fn is_on_gpu(&self) -> bool {
self.handle.is_some()
}
/// Returns `true` if the cpu data and gpu data are out of sync.
#[inline]
pub fn trash(&self) -> bool {
self.trash
}
/// Returns `true` if this vector is available on RAM.
///
/// Note that a `GPUVector` may be both on RAM and on the GPU.
#[inline]
pub fn is_on_ram(&self) -> bool {
self.data.is_some()
}
/// Loads the vector from the RAM to the GPU.
///
/// If the vector is not available on RAM or already loaded to the GPU, nothing will happen.
#[inline]
pub fn load_to_gpu(&mut self) {
if!self.is_on_gpu() {
let buf_type = self.buf_type;
let alloc_type = self.alloc_type;
let len = &mut self.len;
self.handle = self.data.as_ref().map(|d| {
*len = d.len();
(d.len(), GLHandle::new(upload_buffer(&d[..], buf_type, alloc_type)))
});
}
else if self.trash() |
self.trash = false;
}
/// Binds this vector to the appropriate gpu array.
///
/// This does not associate this buffer with any shader attribute.
#[inline]
pub fn bind(&mut self) {
self.load_to_gpu();
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).expect("Could not bind the vector: data unavailable.");
verify!(gl::BindBuffer(self.buf_type.to_gl(), handle));
}
/// Unbind this vector to the corresponding gpu buffer.
#[inline]
pub fn unbind(&mut self) {
if self.is_on_gpu() {
verify!(gl::BindBuffer(self.buf_type.to_gl(), 0));
}
}
/// Loads the vector from the GPU to the RAM.
///
/// If the vector is not available on the GPU or already loaded to the RAM, nothing will
/// happen.
#[inline]
pub fn load_to_ram(&mut self) {
if!self.is_on_ram() && self.is_on_gpu() {
assert!(!self.trash);
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).unwrap();
let mut data = Vec::with_capacity(self.len);
unsafe { data.set_len(self.len) };
download_buffer(handle, self.buf_type, &mut data[..]);
self.data = Some(data);
}
}
/// Unloads this resource from the GPU.
#[inline]
pub fn unload_from_gpu(&mut self) {
let _ = self.handle.as_ref().map(|&(_, ref h)| unsafe { verify!(gl::DeleteBuffers(1, &h.handle())) });
self.len = self.len();
self.handle = None;
self.trash = false;
}
/// Removes this resource from the RAM.
///
/// This is useful to save memory for vectors required on the GPU only.
#[inline]
pub fn unload_from_ram(&mut self) {
if self.trash && self.is_on_gpu() {
self.load_to_gpu();
}
self.data = None;
}
}
impl<T: Clone + GLPrimitive> GPUVector<T> {
/// Returns this vector as an owned vector if it is available on RAM.
///
/// If it has been uploaded to the GPU, and unloaded from the RAM, call `load_to_ram` first to
/// make the data accessible.
#[inline]
pub fn to_owned(&self) -> Option<Vec<T>> {
self.data.as_ref().map(|d| d.clone())
}
}
/// Type of gpu buffer.
#[derive(Clone, Copy)]
pub enum BufferType {
/// An array buffer bindable to a gl::ARRAY_BUFFER.
Array,
/// An array buffer bindable to a gl::ELEMENT_ARRAY_BUFFER.
ElementArray
}
impl BufferType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
BufferType::Array => gl::ARRAY_BUFFER,
BufferType::ElementArray => gl::ELEMENT_ARRAY_BUFFER
}
}
}
/// Allocation type of gpu buffers.
#[derive(Clone, Copy)]
pub enum AllocationType {
/// STATIC_DRAW allocation type.
StaticDraw,
/// DYNAMIC_DRAW allocation type.
DynamicDraw,
/// STREAM_DRAW allocation type.
StreamDraw
}
impl AllocationType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
AllocationType::StaticDraw => gl::STATIC_DRAW,
AllocationType::DynamicDraw => gl::DYNAMIC_DRAW,
AllocationType::StreamDraw => gl::STREAM_DRAW
}
}
}
/// Allocates and uploads a buffer to the gpu.
#[inline]
pub fn upload_buffer<T: GLPrimitive>(buf: &[T],
buf_type: BufferType,
allocation_type: AllocationType)
-> GLuint {
// Upload values of vertices
let mut buf_id: GLuint = 0;
unsafe {
verify!(gl::GenBuffers(1, &mut buf_id));
let _ = update_buffer(buf, 0, buf_id, buf_type, allocation_type);
}
buf_id
}
/// Downloads a buffer from the gpu.
///
///
#[inline]
pub fn download_buffer<T: GLPrimitive>(buf_id: GLuint, buf_type: BufferType, out: &mut [T]) {
unsafe {
verify!(gl::BindBuffer(buf_type.to_gl(), buf_id));
verify!(gl::GetBufferSubData(
buf_type.to_gl(),
0,
(out.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&out[0])));
}
}
/// Updates a buffer to the gpu.
///
/// Returns the number of element the bufer on the gpu can hold.
#[inline]
pub fn update_buffer<T: GLPrimitive>(buf: &[T],
gpu_buf_len: usize,
gpu_buf_id: GLuint,
gpu_buf_type: BufferType,
gpu_allocation_type: AllocationType)
-> usize {
unsafe {
verify!(gl::BindBuffer(gpu_buf_type.to_gl(), gpu_buf_id));
if buf.len() < gpu_buf_len {
verify!(gl::BufferSubData(
gpu_buf_type.to_gl(),
0,
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0])));
gpu_buf_len
}
else {
verify!(gl::BufferData(
gpu_buf_type.to_gl(),
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0]),
gpu_allocation_type.to_gl()));
buf.len()
}
}
}
| {
for d in self.data.iter() {
self.len = d.len();
match self.handle {
None => { },
Some((ref mut len, ref handle)) => {
let handle = handle.handle();
*len = update_buffer(&d[..], *len, handle, self.buf_type, self.alloc_type)
}
}
}
} | conditional_block |
never-value-fallback-issue-66757.rs | // Regression test for #66757
//
// Test than when you have a `!` value (e.g., the local variable
// never) and an uninferred variable (here the argument to `From`) it
// doesn't fallback to `()` but rather `!`.
//
// revisions: nofallback fallback
//[fallback] run-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
struct E;
impl From<!> for E {
fn from(_:!) -> E {
E
} | #[allow(unused_must_use)]
fn foo(never:!) {
<E as From<!>>::from(never); // Ok
<E as From<_>>::from(never); //[nofallback]~ ERROR trait bound `E: From<()>` is not satisfied
}
fn main() { } | }
#[allow(unreachable_code)]
#[allow(dead_code)] | random_line_split |
never-value-fallback-issue-66757.rs | // Regression test for #66757
//
// Test than when you have a `!` value (e.g., the local variable
// never) and an uninferred variable (here the argument to `From`) it
// doesn't fallback to `()` but rather `!`.
//
// revisions: nofallback fallback
//[fallback] run-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
struct E;
impl From<!> for E {
fn from(_:!) -> E {
E
}
}
#[allow(unreachable_code)]
#[allow(dead_code)]
#[allow(unused_must_use)]
fn foo(never:!) {
<E as From<!>>::from(never); // Ok
<E as From<_>>::from(never); //[nofallback]~ ERROR trait bound `E: From<()>` is not satisfied
}
fn | () { }
| main | identifier_name |
never-value-fallback-issue-66757.rs | // Regression test for #66757
//
// Test than when you have a `!` value (e.g., the local variable
// never) and an uninferred variable (here the argument to `From`) it
// doesn't fallback to `()` but rather `!`.
//
// revisions: nofallback fallback
//[fallback] run-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
struct E;
impl From<!> for E {
fn from(_:!) -> E {
E
}
}
#[allow(unreachable_code)]
#[allow(dead_code)]
#[allow(unused_must_use)]
fn foo(never:!) |
fn main() { }
| {
<E as From<!>>::from(never); // Ok
<E as From<_>>::from(never); //[nofallback]~ ERROR trait bound `E: From<()>` is not satisfied
} | identifier_body |
box.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for box properties.
use values::animated::ToAnimatedZero;
/// A generic value for the `vertical-align` property.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum VerticalAlign<LengthOrPercentage> {
/// `baseline`
Baseline,
/// `sub`
Sub,
/// `super`
Super,
/// `top`
Top,
/// `text-top`
TextTop,
/// `middle`
Middle,
/// `bottom`
Bottom,
/// `text-bottom`
TextBottom,
/// `-moz-middle-with-baseline`
#[cfg(feature = "gecko")]
MozMiddleWithBaseline,
/// `<length-percentage>`
Length(LengthOrPercentage),
}
impl<L> VerticalAlign<L> {
/// Returns `baseline`.
#[inline]
pub fn | () -> Self {
VerticalAlign::Baseline
}
}
impl<L> ToAnimatedZero for VerticalAlign<L> {
fn to_animated_zero(&self) -> Result<Self, ()> {
Err(())
}
}
/// https://drafts.csswg.org/css-animations/#animation-iteration-count
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum AnimationIterationCount<Number> {
/// A `<number>` value.
Number(Number),
/// The `infinite` keyword.
Infinite,
}
/// A generic value for the `perspective` property.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum Perspective<NonNegativeLength> {
/// A non-negative length.
Length(NonNegativeLength),
/// The keyword `none`.
None,
}
impl<L> Perspective<L> {
/// Returns `none`.
#[inline]
pub fn none() -> Self {
Perspective::None
}
}
| baseline | identifier_name |
box.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for box properties.
use values::animated::ToAnimatedZero;
/// A generic value for the `vertical-align` property.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum VerticalAlign<LengthOrPercentage> {
/// `baseline`
Baseline,
/// `sub`
Sub,
/// `super`
Super,
/// `top`
Top,
/// `text-top`
TextTop,
/// `middle`
Middle,
/// `bottom`
Bottom,
/// `text-bottom`
TextBottom,
/// `-moz-middle-with-baseline`
#[cfg(feature = "gecko")]
MozMiddleWithBaseline,
/// `<length-percentage>`
Length(LengthOrPercentage),
}
impl<L> VerticalAlign<L> {
/// Returns `baseline`.
#[inline]
pub fn baseline() -> Self {
VerticalAlign::Baseline
}
}
impl<L> ToAnimatedZero for VerticalAlign<L> {
fn to_animated_zero(&self) -> Result<Self, ()> {
Err(())
}
}
/// https://drafts.csswg.org/css-animations/#animation-iteration-count
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum AnimationIterationCount<Number> { | /// The `infinite` keyword.
Infinite,
}
/// A generic value for the `perspective` property.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum Perspective<NonNegativeLength> {
/// A non-negative length.
Length(NonNegativeLength),
/// The keyword `none`.
None,
}
impl<L> Perspective<L> {
/// Returns `none`.
#[inline]
pub fn none() -> Self {
Perspective::None
}
} | /// A `<number>` value.
Number(Number), | random_line_split |
sign.rs | use nodes;
use eval::array_helpers::{simple_monadic_array};
use eval::eval::{AplFloat, AplInteger, AplComplex, AplArray, Value, eval_monadic};
use eval::divide::divide;
use eval::magnitude::magnitude;
pub fn sign(first: &Value) -> Result<~Value, ~str> {
match first {
&AplFloat(val) => {
Ok(if val < 0.0 {
~AplInteger(-1)
} else if val > 0.0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplInteger(val) => {
Ok(if val < 0 {
~AplInteger(-1)
} else if val > 0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplComplex(_c) => {
magnitude(first).and_then(|magnituded| {
divide(first, magnituded)
})
},
&AplArray(ref _depth, ref _dimensions, ref _values) => {
simple_monadic_array(sign, first)
}
}
}
pub fn eval_sign(left: &nodes::Node) -> Result<~Value, ~str> | {
eval_monadic(sign, left)
} | identifier_body |
|
sign.rs | use nodes;
use eval::array_helpers::{simple_monadic_array};
use eval::eval::{AplFloat, AplInteger, AplComplex, AplArray, Value, eval_monadic};
use eval::divide::divide;
use eval::magnitude::magnitude;
pub fn sign(first: &Value) -> Result<~Value, ~str> {
match first {
&AplFloat(val) => {
Ok(if val < 0.0 | else if val > 0.0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplInteger(val) => {
Ok(if val < 0 {
~AplInteger(-1)
} else if val > 0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplComplex(_c) => {
magnitude(first).and_then(|magnituded| {
divide(first, magnituded)
})
},
&AplArray(ref _depth, ref _dimensions, ref _values) => {
simple_monadic_array(sign, first)
}
}
}
pub fn eval_sign(left: &nodes::Node) -> Result<~Value, ~str> {
eval_monadic(sign, left)
}
| {
~AplInteger(-1)
} | conditional_block |
sign.rs | use nodes;
use eval::array_helpers::{simple_monadic_array};
use eval::eval::{AplFloat, AplInteger, AplComplex, AplArray, Value, eval_monadic};
use eval::divide::divide;
use eval::magnitude::magnitude;
pub fn sign(first: &Value) -> Result<~Value, ~str> {
match first {
&AplFloat(val) => {
Ok(if val < 0.0 {
~AplInteger(-1)
} else if val > 0.0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplInteger(val) => {
Ok(if val < 0 {
~AplInteger(-1)
} else if val > 0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
}, | divide(first, magnituded)
})
},
&AplArray(ref _depth, ref _dimensions, ref _values) => {
simple_monadic_array(sign, first)
}
}
}
pub fn eval_sign(left: &nodes::Node) -> Result<~Value, ~str> {
eval_monadic(sign, left)
} | &AplComplex(_c) => {
magnitude(first).and_then(|magnituded| { | random_line_split |
sign.rs | use nodes;
use eval::array_helpers::{simple_monadic_array};
use eval::eval::{AplFloat, AplInteger, AplComplex, AplArray, Value, eval_monadic};
use eval::divide::divide;
use eval::magnitude::magnitude;
pub fn | (first: &Value) -> Result<~Value, ~str> {
match first {
&AplFloat(val) => {
Ok(if val < 0.0 {
~AplInteger(-1)
} else if val > 0.0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplInteger(val) => {
Ok(if val < 0 {
~AplInteger(-1)
} else if val > 0 {
~AplInteger(1)
} else {
~AplInteger(0)
})
},
&AplComplex(_c) => {
magnitude(first).and_then(|magnituded| {
divide(first, magnituded)
})
},
&AplArray(ref _depth, ref _dimensions, ref _values) => {
simple_monadic_array(sign, first)
}
}
}
pub fn eval_sign(left: &nodes::Node) -> Result<~Value, ~str> {
eval_monadic(sign, left)
}
| sign | identifier_name |
set_room_account_data.rs | //! [PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}](https://matrix.org/docs/spec/client_server/r0.6.0#put-matrix-client-r0-user-userid-rooms-roomid-account-data-type)
use ruma_api::ruma_api;
use ruma_identifiers::{RoomId, UserId};
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata {
description: "Associate account data with a room.",
method: PUT,
name: "set_room_account_data",
path: "/_matrix/client/r0/user/:user_id/rooms/:room_id/account_data/:event_type",
rate_limited: false,
requires_authentication: true,
}
request {
/// Arbitrary JSON to store as config data. | pub data: Box<RawJsonValue>,
/// The event type of the account_data to set.
///
/// Custom types should be namespaced to avoid clashes.
#[ruma_api(path)]
pub event_type: String,
/// The ID of the room to set account_data on.
#[ruma_api(path)]
pub room_id: RoomId,
/// The ID of the user to set account_data for.
///
/// The access token must be authorized to make requests for this user ID.
#[ruma_api(path)]
pub user_id: UserId,
}
response {}
error: crate::Error
} | ///
/// To create a `Box<RawJsonValue>`, use `serde_json::value::to_raw_value`.
#[ruma_api(body)] | random_line_split |
csvdump.rs | use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use clap::{App, Arg, ArgMatches, SubCommand};
| use crate::blockchain::parser::types::CoinType;
use crate::blockchain::proto::block::Block;
use crate::blockchain::proto::tx::{EvaluatedTx, EvaluatedTxOut, TxInput};
use crate::blockchain::proto::Hashed;
use crate::callbacks::Callback;
use crate::common::utils;
use crate::errors::OpResult;
/// Dumps the whole blockchain into csv files
pub struct CsvDump {
// Each structure gets stored in a separate csv file
dump_folder: PathBuf,
block_writer: BufWriter<File>,
tx_writer: BufWriter<File>,
txin_writer: BufWriter<File>,
txout_writer: BufWriter<File>,
start_height: u64,
end_height: u64,
tx_count: u64,
in_count: u64,
out_count: u64,
}
impl CsvDump {
fn create_writer(cap: usize, path: PathBuf) -> OpResult<BufWriter<File>> {
Ok(BufWriter::with_capacity(cap, File::create(&path)?))
}
}
impl Callback for CsvDump {
fn build_subcommand<'a, 'b>() -> App<'a, 'b>
where
Self: Sized,
{
SubCommand::with_name("csvdump")
.about("Dumps the whole blockchain into CSV files")
.version("0.1")
.author("gcarq <[email protected]>")
.arg(
Arg::with_name("dump-folder")
.help("Folder to store csv files")
.index(1)
.required(true),
)
}
fn new(matches: &ArgMatches) -> OpResult<Self>
where
Self: Sized,
{
let dump_folder = &PathBuf::from(matches.value_of("dump-folder").unwrap());
let cap = 4000000;
let cb = CsvDump {
dump_folder: PathBuf::from(dump_folder),
block_writer: CsvDump::create_writer(cap, dump_folder.join("blocks.csv.tmp"))?,
tx_writer: CsvDump::create_writer(cap, dump_folder.join("transactions.csv.tmp"))?,
txin_writer: CsvDump::create_writer(cap, dump_folder.join("tx_in.csv.tmp"))?,
txout_writer: CsvDump::create_writer(cap, dump_folder.join("tx_out.csv.tmp"))?,
start_height: 0,
end_height: 0,
tx_count: 0,
in_count: 0,
out_count: 0,
};
Ok(cb)
}
fn on_start(&mut self, _: &CoinType, block_height: u64) -> OpResult<()> {
self.start_height = block_height;
info!(target: "callback", "Using `csvdump` with dump folder: {}...", &self.dump_folder.display());
Ok(())
}
fn on_block(&mut self, block: &Block, block_height: u64) -> OpResult<()> {
// serialize block
self.block_writer
.write_all(block.as_csv(block_height).as_bytes())?;
// serialize transaction
let block_hash = utils::arr_to_hex_swapped(&block.header.hash);
for tx in &block.txs {
self.tx_writer
.write_all(tx.as_csv(&block_hash).as_bytes())?;
let txid_str = utils::arr_to_hex_swapped(&tx.hash);
// serialize inputs
for input in &tx.value.inputs {
self.txin_writer
.write_all(input.as_csv(&txid_str).as_bytes())?;
}
self.in_count += tx.value.in_count.value;
// serialize outputs
for (i, output) in tx.value.outputs.iter().enumerate() {
self.txout_writer
.write_all(output.as_csv(&txid_str, i as u32).as_bytes())?;
}
self.out_count += tx.value.out_count.value;
}
self.tx_count += block.tx_count.value;
Ok(())
}
fn on_complete(&mut self, block_height: u64) -> OpResult<()> {
self.end_height = block_height;
// Keep in sync with c'tor
for f in &["blocks", "transactions", "tx_in", "tx_out"] {
// Rename temp files
fs::rename(
self.dump_folder.as_path().join(format!("{}.csv.tmp", f)),
self.dump_folder.as_path().join(format!(
"{}-{}-{}.csv",
f, self.start_height, self.end_height
)),
)?;
}
info!(target: "callback", "Done.\nDumped all {} blocks:\n\
\t-> transactions: {:9}\n\
\t-> inputs: {:9}\n\
\t-> outputs: {:9}",
self.end_height, self.tx_count, self.in_count, self.out_count);
Ok(())
}
}
impl Block {
#[inline]
fn as_csv(&self, block_height: u64) -> String {
// (@hash, height, version, blocksize, @hashPrev, @hashMerkleRoot, nTime, nBits, nNonce)
format!(
"{};{};{};{};{};{};{};{};{}\n",
&utils::arr_to_hex_swapped(&self.header.hash),
&block_height,
&self.header.value.version,
&self.size,
&utils::arr_to_hex_swapped(&self.header.value.prev_hash),
&utils::arr_to_hex_swapped(&self.header.value.merkle_root),
&self.header.value.timestamp,
&self.header.value.bits,
&self.header.value.nonce
)
}
}
impl Hashed<EvaluatedTx> {
#[inline]
fn as_csv(&self, block_hash: &str) -> String {
// (@txid, @hashBlock, version, lockTime)
format!(
"{};{};{};{}\n",
&utils::arr_to_hex_swapped(&self.hash),
&block_hash,
&self.value.version,
&self.value.locktime
)
}
}
impl TxInput {
#[inline]
fn as_csv(&self, txid: &str) -> String {
// (@txid, @hashPrevOut, indexPrevOut, scriptSig, sequence)
format!(
"{};{};{};{};{}\n",
&txid,
&utils::arr_to_hex_swapped(&self.outpoint.txid),
&self.outpoint.index,
&utils::arr_to_hex(&self.script_sig),
&self.seq_no
)
}
}
impl EvaluatedTxOut {
#[inline]
fn as_csv(&self, txid: &str, index: u32) -> String {
let address = match self.script.address.clone() {
Some(address) => address,
None => {
debug!(target: "csvdump", "Unable to evaluate address for utxo in txid: {} ({})", txid, self.script.pattern);
String::new()
}
};
// (@txid, indexOut, value, @scriptPubKey, address)
format!(
"{};{};{};{};{}\n",
&txid,
&index,
&self.out.value,
&utils::arr_to_hex(&self.out.script_pubkey),
&address
)
}
} | random_line_split |
|
csvdump.rs | use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use clap::{App, Arg, ArgMatches, SubCommand};
use crate::blockchain::parser::types::CoinType;
use crate::blockchain::proto::block::Block;
use crate::blockchain::proto::tx::{EvaluatedTx, EvaluatedTxOut, TxInput};
use crate::blockchain::proto::Hashed;
use crate::callbacks::Callback;
use crate::common::utils;
use crate::errors::OpResult;
/// Dumps the whole blockchain into csv files
pub struct CsvDump {
// Each structure gets stored in a separate csv file
dump_folder: PathBuf,
block_writer: BufWriter<File>,
tx_writer: BufWriter<File>,
txin_writer: BufWriter<File>,
txout_writer: BufWriter<File>,
start_height: u64,
end_height: u64,
tx_count: u64,
in_count: u64,
out_count: u64,
}
impl CsvDump {
fn create_writer(cap: usize, path: PathBuf) -> OpResult<BufWriter<File>> {
Ok(BufWriter::with_capacity(cap, File::create(&path)?))
}
}
impl Callback for CsvDump {
fn | <'a, 'b>() -> App<'a, 'b>
where
Self: Sized,
{
SubCommand::with_name("csvdump")
.about("Dumps the whole blockchain into CSV files")
.version("0.1")
.author("gcarq <[email protected]>")
.arg(
Arg::with_name("dump-folder")
.help("Folder to store csv files")
.index(1)
.required(true),
)
}
fn new(matches: &ArgMatches) -> OpResult<Self>
where
Self: Sized,
{
let dump_folder = &PathBuf::from(matches.value_of("dump-folder").unwrap());
let cap = 4000000;
let cb = CsvDump {
dump_folder: PathBuf::from(dump_folder),
block_writer: CsvDump::create_writer(cap, dump_folder.join("blocks.csv.tmp"))?,
tx_writer: CsvDump::create_writer(cap, dump_folder.join("transactions.csv.tmp"))?,
txin_writer: CsvDump::create_writer(cap, dump_folder.join("tx_in.csv.tmp"))?,
txout_writer: CsvDump::create_writer(cap, dump_folder.join("tx_out.csv.tmp"))?,
start_height: 0,
end_height: 0,
tx_count: 0,
in_count: 0,
out_count: 0,
};
Ok(cb)
}
fn on_start(&mut self, _: &CoinType, block_height: u64) -> OpResult<()> {
self.start_height = block_height;
info!(target: "callback", "Using `csvdump` with dump folder: {}...", &self.dump_folder.display());
Ok(())
}
fn on_block(&mut self, block: &Block, block_height: u64) -> OpResult<()> {
// serialize block
self.block_writer
.write_all(block.as_csv(block_height).as_bytes())?;
// serialize transaction
let block_hash = utils::arr_to_hex_swapped(&block.header.hash);
for tx in &block.txs {
self.tx_writer
.write_all(tx.as_csv(&block_hash).as_bytes())?;
let txid_str = utils::arr_to_hex_swapped(&tx.hash);
// serialize inputs
for input in &tx.value.inputs {
self.txin_writer
.write_all(input.as_csv(&txid_str).as_bytes())?;
}
self.in_count += tx.value.in_count.value;
// serialize outputs
for (i, output) in tx.value.outputs.iter().enumerate() {
self.txout_writer
.write_all(output.as_csv(&txid_str, i as u32).as_bytes())?;
}
self.out_count += tx.value.out_count.value;
}
self.tx_count += block.tx_count.value;
Ok(())
}
fn on_complete(&mut self, block_height: u64) -> OpResult<()> {
self.end_height = block_height;
// Keep in sync with c'tor
for f in &["blocks", "transactions", "tx_in", "tx_out"] {
// Rename temp files
fs::rename(
self.dump_folder.as_path().join(format!("{}.csv.tmp", f)),
self.dump_folder.as_path().join(format!(
"{}-{}-{}.csv",
f, self.start_height, self.end_height
)),
)?;
}
info!(target: "callback", "Done.\nDumped all {} blocks:\n\
\t-> transactions: {:9}\n\
\t-> inputs: {:9}\n\
\t-> outputs: {:9}",
self.end_height, self.tx_count, self.in_count, self.out_count);
Ok(())
}
}
impl Block {
#[inline]
fn as_csv(&self, block_height: u64) -> String {
// (@hash, height, version, blocksize, @hashPrev, @hashMerkleRoot, nTime, nBits, nNonce)
format!(
"{};{};{};{};{};{};{};{};{}\n",
&utils::arr_to_hex_swapped(&self.header.hash),
&block_height,
&self.header.value.version,
&self.size,
&utils::arr_to_hex_swapped(&self.header.value.prev_hash),
&utils::arr_to_hex_swapped(&self.header.value.merkle_root),
&self.header.value.timestamp,
&self.header.value.bits,
&self.header.value.nonce
)
}
}
impl Hashed<EvaluatedTx> {
#[inline]
fn as_csv(&self, block_hash: &str) -> String {
// (@txid, @hashBlock, version, lockTime)
format!(
"{};{};{};{}\n",
&utils::arr_to_hex_swapped(&self.hash),
&block_hash,
&self.value.version,
&self.value.locktime
)
}
}
impl TxInput {
#[inline]
fn as_csv(&self, txid: &str) -> String {
// (@txid, @hashPrevOut, indexPrevOut, scriptSig, sequence)
format!(
"{};{};{};{};{}\n",
&txid,
&utils::arr_to_hex_swapped(&self.outpoint.txid),
&self.outpoint.index,
&utils::arr_to_hex(&self.script_sig),
&self.seq_no
)
}
}
impl EvaluatedTxOut {
#[inline]
fn as_csv(&self, txid: &str, index: u32) -> String {
let address = match self.script.address.clone() {
Some(address) => address,
None => {
debug!(target: "csvdump", "Unable to evaluate address for utxo in txid: {} ({})", txid, self.script.pattern);
String::new()
}
};
// (@txid, indexOut, value, @scriptPubKey, address)
format!(
"{};{};{};{};{}\n",
&txid,
&index,
&self.out.value,
&utils::arr_to_hex(&self.out.script_pubkey),
&address
)
}
}
| build_subcommand | identifier_name |
csvdump.rs | use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use clap::{App, Arg, ArgMatches, SubCommand};
use crate::blockchain::parser::types::CoinType;
use crate::blockchain::proto::block::Block;
use crate::blockchain::proto::tx::{EvaluatedTx, EvaluatedTxOut, TxInput};
use crate::blockchain::proto::Hashed;
use crate::callbacks::Callback;
use crate::common::utils;
use crate::errors::OpResult;
/// Dumps the whole blockchain into csv files
pub struct CsvDump {
// Each structure gets stored in a separate csv file
dump_folder: PathBuf,
block_writer: BufWriter<File>,
tx_writer: BufWriter<File>,
txin_writer: BufWriter<File>,
txout_writer: BufWriter<File>,
start_height: u64,
end_height: u64,
tx_count: u64,
in_count: u64,
out_count: u64,
}
impl CsvDump {
fn create_writer(cap: usize, path: PathBuf) -> OpResult<BufWriter<File>> {
Ok(BufWriter::with_capacity(cap, File::create(&path)?))
}
}
impl Callback for CsvDump {
fn build_subcommand<'a, 'b>() -> App<'a, 'b>
where
Self: Sized,
|
fn new(matches: &ArgMatches) -> OpResult<Self>
where
Self: Sized,
{
let dump_folder = &PathBuf::from(matches.value_of("dump-folder").unwrap());
let cap = 4000000;
let cb = CsvDump {
dump_folder: PathBuf::from(dump_folder),
block_writer: CsvDump::create_writer(cap, dump_folder.join("blocks.csv.tmp"))?,
tx_writer: CsvDump::create_writer(cap, dump_folder.join("transactions.csv.tmp"))?,
txin_writer: CsvDump::create_writer(cap, dump_folder.join("tx_in.csv.tmp"))?,
txout_writer: CsvDump::create_writer(cap, dump_folder.join("tx_out.csv.tmp"))?,
start_height: 0,
end_height: 0,
tx_count: 0,
in_count: 0,
out_count: 0,
};
Ok(cb)
}
fn on_start(&mut self, _: &CoinType, block_height: u64) -> OpResult<()> {
self.start_height = block_height;
info!(target: "callback", "Using `csvdump` with dump folder: {}...", &self.dump_folder.display());
Ok(())
}
fn on_block(&mut self, block: &Block, block_height: u64) -> OpResult<()> {
// serialize block
self.block_writer
.write_all(block.as_csv(block_height).as_bytes())?;
// serialize transaction
let block_hash = utils::arr_to_hex_swapped(&block.header.hash);
for tx in &block.txs {
self.tx_writer
.write_all(tx.as_csv(&block_hash).as_bytes())?;
let txid_str = utils::arr_to_hex_swapped(&tx.hash);
// serialize inputs
for input in &tx.value.inputs {
self.txin_writer
.write_all(input.as_csv(&txid_str).as_bytes())?;
}
self.in_count += tx.value.in_count.value;
// serialize outputs
for (i, output) in tx.value.outputs.iter().enumerate() {
self.txout_writer
.write_all(output.as_csv(&txid_str, i as u32).as_bytes())?;
}
self.out_count += tx.value.out_count.value;
}
self.tx_count += block.tx_count.value;
Ok(())
}
fn on_complete(&mut self, block_height: u64) -> OpResult<()> {
self.end_height = block_height;
// Keep in sync with c'tor
for f in &["blocks", "transactions", "tx_in", "tx_out"] {
// Rename temp files
fs::rename(
self.dump_folder.as_path().join(format!("{}.csv.tmp", f)),
self.dump_folder.as_path().join(format!(
"{}-{}-{}.csv",
f, self.start_height, self.end_height
)),
)?;
}
info!(target: "callback", "Done.\nDumped all {} blocks:\n\
\t-> transactions: {:9}\n\
\t-> inputs: {:9}\n\
\t-> outputs: {:9}",
self.end_height, self.tx_count, self.in_count, self.out_count);
Ok(())
}
}
impl Block {
#[inline]
fn as_csv(&self, block_height: u64) -> String {
// (@hash, height, version, blocksize, @hashPrev, @hashMerkleRoot, nTime, nBits, nNonce)
format!(
"{};{};{};{};{};{};{};{};{}\n",
&utils::arr_to_hex_swapped(&self.header.hash),
&block_height,
&self.header.value.version,
&self.size,
&utils::arr_to_hex_swapped(&self.header.value.prev_hash),
&utils::arr_to_hex_swapped(&self.header.value.merkle_root),
&self.header.value.timestamp,
&self.header.value.bits,
&self.header.value.nonce
)
}
}
impl Hashed<EvaluatedTx> {
#[inline]
fn as_csv(&self, block_hash: &str) -> String {
// (@txid, @hashBlock, version, lockTime)
format!(
"{};{};{};{}\n",
&utils::arr_to_hex_swapped(&self.hash),
&block_hash,
&self.value.version,
&self.value.locktime
)
}
}
impl TxInput {
#[inline]
fn as_csv(&self, txid: &str) -> String {
// (@txid, @hashPrevOut, indexPrevOut, scriptSig, sequence)
format!(
"{};{};{};{};{}\n",
&txid,
&utils::arr_to_hex_swapped(&self.outpoint.txid),
&self.outpoint.index,
&utils::arr_to_hex(&self.script_sig),
&self.seq_no
)
}
}
impl EvaluatedTxOut {
#[inline]
fn as_csv(&self, txid: &str, index: u32) -> String {
let address = match self.script.address.clone() {
Some(address) => address,
None => {
debug!(target: "csvdump", "Unable to evaluate address for utxo in txid: {} ({})", txid, self.script.pattern);
String::new()
}
};
// (@txid, indexOut, value, @scriptPubKey, address)
format!(
"{};{};{};{};{}\n",
&txid,
&index,
&self.out.value,
&utils::arr_to_hex(&self.out.script_pubkey),
&address
)
}
}
| {
SubCommand::with_name("csvdump")
.about("Dumps the whole blockchain into CSV files")
.version("0.1")
.author("gcarq <[email protected]>")
.arg(
Arg::with_name("dump-folder")
.help("Folder to store csv files")
.index(1)
.required(true),
)
} | identifier_body |
line.rs | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate cgmath;
use cgmath::*;
#[test]
fn test_line_intersection() {
// collinear, intersection is line dest
let r1 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(0.25, 0.0));
let l1 = Line::new(Point2::new(1.5f32, 0.0), Point2::new(0.5, 0.0));
assert_eq!((r1, l1).intersection(), Some(Point2::new(0.5, 0.0)));
// collinear, intersection is at ray origin
let r2 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(5.0, 0.0));
let l2 = Line::new(Point2::new(-11.0f32, 0.0), Point2::new(1.0, 0.0));
assert_eq!((r2, l2).intersection(), Some(Point2::new(0.0, 0.0)));
// collinear, intersection is line origin
let r3 = Ray::new(Point2::new(0.0f32, 1.0), Vector2::new(0.0, -0.25));
let l3 = Line::new(Point2::new(0.0f32, 0.5), Point2::new(0.0, -0.5));
assert_eq!((r3, l3).intersection(), Some(Point2::new(0.0, 0.5)));
// collinear, no overlap
let r4 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(3.0, 0.0));
let l4 = Line::new(Point2::new(-10.0f32, 0.0), Point2::new(-5.0, 0.0));
assert_eq!((r4, l4).intersection(), None); |
// no intersection
let r5 = Ray::new(Point2::new(5.0f32, 5.0), Vector2::new(40.0, 8.0));
let l5 = Line::new(Point2::new(5.0f32, 4.8), Point2::new(10.0, 4.1));
assert_eq!((r5, l5).intersection(), None); // no intersection
// non-collinear intersection
let r6 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(10.0, 10.0));
let l6 = Line::new(Point2::new(0.0f32, 10.0), Point2::new(10.0, 0.0));
assert_eq!((r6, l6).intersection(), Some(Point2::new(5.0, 5.0)));
// line is a point that does not intersect
let r7 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 1.0));
let l7 = Line::new(Point2::new(1.0f32, 0.0), Point2::new(1.0, 0.0));
assert_eq!((r7, l7).intersection(), None);
// line is a point that does intersect
let r8 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 0.0));
let l8 = Line::new(Point2::new(3.0f32, 0.0), Point2::new(3.0, 0.0));
assert_eq!((r8, l8).intersection(), Some(Point2::new(3.0, 0.0)));
// line is a collinear point but no intersection
let r9 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 0.0));
let l9 = Line::new(Point2::new(-1.0f32, 0.0), Point2::new(-1.0, 0.0));
assert_eq!((r9, l9).intersection(), None);
} | random_line_split |
|
line.rs | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate cgmath;
use cgmath::*;
#[test]
fn | () {
// collinear, intersection is line dest
let r1 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(0.25, 0.0));
let l1 = Line::new(Point2::new(1.5f32, 0.0), Point2::new(0.5, 0.0));
assert_eq!((r1, l1).intersection(), Some(Point2::new(0.5, 0.0)));
// collinear, intersection is at ray origin
let r2 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(5.0, 0.0));
let l2 = Line::new(Point2::new(-11.0f32, 0.0), Point2::new(1.0, 0.0));
assert_eq!((r2, l2).intersection(), Some(Point2::new(0.0, 0.0)));
// collinear, intersection is line origin
let r3 = Ray::new(Point2::new(0.0f32, 1.0), Vector2::new(0.0, -0.25));
let l3 = Line::new(Point2::new(0.0f32, 0.5), Point2::new(0.0, -0.5));
assert_eq!((r3, l3).intersection(), Some(Point2::new(0.0, 0.5)));
// collinear, no overlap
let r4 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(3.0, 0.0));
let l4 = Line::new(Point2::new(-10.0f32, 0.0), Point2::new(-5.0, 0.0));
assert_eq!((r4, l4).intersection(), None);
// no intersection
let r5 = Ray::new(Point2::new(5.0f32, 5.0), Vector2::new(40.0, 8.0));
let l5 = Line::new(Point2::new(5.0f32, 4.8), Point2::new(10.0, 4.1));
assert_eq!((r5, l5).intersection(), None); // no intersection
// non-collinear intersection
let r6 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(10.0, 10.0));
let l6 = Line::new(Point2::new(0.0f32, 10.0), Point2::new(10.0, 0.0));
assert_eq!((r6, l6).intersection(), Some(Point2::new(5.0, 5.0)));
// line is a point that does not intersect
let r7 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 1.0));
let l7 = Line::new(Point2::new(1.0f32, 0.0), Point2::new(1.0, 0.0));
assert_eq!((r7, l7).intersection(), None);
// line is a point that does intersect
let r8 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 0.0));
let l8 = Line::new(Point2::new(3.0f32, 0.0), Point2::new(3.0, 0.0));
assert_eq!((r8, l8).intersection(), Some(Point2::new(3.0, 0.0)));
// line is a collinear point but no intersection
let r9 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 0.0));
let l9 = Line::new(Point2::new(-1.0f32, 0.0), Point2::new(-1.0, 0.0));
assert_eq!((r9, l9).intersection(), None);
}
| test_line_intersection | identifier_name |
line.rs | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate cgmath;
use cgmath::*;
#[test]
fn test_line_intersection() |
// no intersection
let r5 = Ray::new(Point2::new(5.0f32, 5.0), Vector2::new(40.0, 8.0));
let l5 = Line::new(Point2::new(5.0f32, 4.8), Point2::new(10.0, 4.1));
assert_eq!((r5, l5).intersection(), None); // no intersection
// non-collinear intersection
let r6 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(10.0, 10.0));
let l6 = Line::new(Point2::new(0.0f32, 10.0), Point2::new(10.0, 0.0));
assert_eq!((r6, l6).intersection(), Some(Point2::new(5.0, 5.0)));
// line is a point that does not intersect
let r7 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 1.0));
let l7 = Line::new(Point2::new(1.0f32, 0.0), Point2::new(1.0, 0.0));
assert_eq!((r7, l7).intersection(), None);
// line is a point that does intersect
let r8 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 0.0));
let l8 = Line::new(Point2::new(3.0f32, 0.0), Point2::new(3.0, 0.0));
assert_eq!((r8, l8).intersection(), Some(Point2::new(3.0, 0.0)));
// line is a collinear point but no intersection
let r9 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(1.0, 0.0));
let l9 = Line::new(Point2::new(-1.0f32, 0.0), Point2::new(-1.0, 0.0));
assert_eq!((r9, l9).intersection(), None);
}
| {
// collinear, intersection is line dest
let r1 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(0.25, 0.0));
let l1 = Line::new(Point2::new(1.5f32, 0.0), Point2::new(0.5, 0.0));
assert_eq!((r1, l1).intersection(), Some(Point2::new(0.5, 0.0)));
// collinear, intersection is at ray origin
let r2 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(5.0, 0.0));
let l2 = Line::new(Point2::new(-11.0f32, 0.0), Point2::new(1.0, 0.0));
assert_eq!((r2, l2).intersection(), Some(Point2::new(0.0, 0.0)));
// collinear, intersection is line origin
let r3 = Ray::new(Point2::new(0.0f32, 1.0), Vector2::new(0.0, -0.25));
let l3 = Line::new(Point2::new(0.0f32, 0.5), Point2::new(0.0, -0.5));
assert_eq!((r3, l3).intersection(), Some(Point2::new(0.0, 0.5)));
// collinear, no overlap
let r4 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(3.0, 0.0));
let l4 = Line::new(Point2::new(-10.0f32, 0.0), Point2::new(-5.0, 0.0));
assert_eq!((r4, l4).intersection(), None); | identifier_body |
types.rs | //! Various common types.
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io;
use std::result;
use bson::{self, oid};
use itertools::Itertools;
/// The default result type used in this library.
pub type Result<T> = result::Result<T, Error>;
/// A partial save error returned by `Collection::save_all()` method.
#[derive(Debug)]
pub struct PartialSave {
/// The actual cause of the partial save error.
pub cause: Box<Error>,
/// A vector of object ids which have been inserted successfully.
pub successful_ids: Vec<oid::ObjectId>,
}
impl error::Error for PartialSave {
fn description(&self) -> &str {
"save operation completed partially"
}
fn cause(&self) -> Option<&error::Error> {
Some(&*self.cause)
}
}
struct OidHexDisplay(oid::ObjectId);
impl fmt::Display for OidHexDisplay {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
static CHARS: &'static [u8] = b"0123456789abcdef";
for &byte in &self.0.bytes() {
try!(write!(
f,
"{}{}",
CHARS[(byte >> 4) as usize] as char,
CHARS[(byte & 0xf) as usize] as char
));
}
Ok(())
}
}
impl fmt::Display for PartialSave {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.successful_ids.is_empty() {
write!(f, "saved nothing due to an error: {}", self.cause)
} else {
write!(
f,
"only saved objects with ids: [{}] due to an error: {}",
self.successful_ids
.iter()
.cloned()
.map(OidHexDisplay)
.join(", "),
self.cause
)
}
}
}
quick_error! {
/// The main error type used in the library.
#[derive(Debug)]
pub enum Error {
/// I/O error.
Io(err: io::Error) {
from()
description("I/O error")
display("I/O error: {}", err)
cause(err)
}
/// BSON encoding error (when converting Rust BSON representation to the EJDB one).
BsonEncoding(err: bson::EncoderError) {
from()
description("BSON encoding error")
display("BSON encoding error: {}", err)
cause(err)
}
/// BSON decoding error (when converting to Rust BSON representation from the EJDB one).
BsonDecoding(err: bson::DecoderError) {
from()
description("BSON decoding error")
display("BSON decoding error: {}", err)
cause(err)
}
/// Partial save error returned by `Collection::save_all()` method.
PartialSave(err: PartialSave) {
from()
description("partial save")
display("partial save: {}", err)
cause(&*err.cause)
}
/// Some other error. | from(s: &'static str) -> (s.into())
from(s: String) -> (s.into())
}
}
} | Other(msg: Cow<'static, str>) {
description(&*msg)
display("{}", msg) | random_line_split |
types.rs | //! Various common types.
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io;
use std::result;
use bson::{self, oid};
use itertools::Itertools;
/// The default result type used in this library.
pub type Result<T> = result::Result<T, Error>;
/// A partial save error returned by `Collection::save_all()` method.
#[derive(Debug)]
pub struct PartialSave {
/// The actual cause of the partial save error.
pub cause: Box<Error>,
/// A vector of object ids which have been inserted successfully.
pub successful_ids: Vec<oid::ObjectId>,
}
impl error::Error for PartialSave {
fn description(&self) -> &str {
"save operation completed partially"
}
fn cause(&self) -> Option<&error::Error> {
Some(&*self.cause)
}
}
struct | (oid::ObjectId);
impl fmt::Display for OidHexDisplay {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
static CHARS: &'static [u8] = b"0123456789abcdef";
for &byte in &self.0.bytes() {
try!(write!(
f,
"{}{}",
CHARS[(byte >> 4) as usize] as char,
CHARS[(byte & 0xf) as usize] as char
));
}
Ok(())
}
}
impl fmt::Display for PartialSave {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.successful_ids.is_empty() {
write!(f, "saved nothing due to an error: {}", self.cause)
} else {
write!(
f,
"only saved objects with ids: [{}] due to an error: {}",
self.successful_ids
.iter()
.cloned()
.map(OidHexDisplay)
.join(", "),
self.cause
)
}
}
}
quick_error! {
/// The main error type used in the library.
#[derive(Debug)]
pub enum Error {
/// I/O error.
Io(err: io::Error) {
from()
description("I/O error")
display("I/O error: {}", err)
cause(err)
}
/// BSON encoding error (when converting Rust BSON representation to the EJDB one).
BsonEncoding(err: bson::EncoderError) {
from()
description("BSON encoding error")
display("BSON encoding error: {}", err)
cause(err)
}
/// BSON decoding error (when converting to Rust BSON representation from the EJDB one).
BsonDecoding(err: bson::DecoderError) {
from()
description("BSON decoding error")
display("BSON decoding error: {}", err)
cause(err)
}
/// Partial save error returned by `Collection::save_all()` method.
PartialSave(err: PartialSave) {
from()
description("partial save")
display("partial save: {}", err)
cause(&*err.cause)
}
/// Some other error.
Other(msg: Cow<'static, str>) {
description(&*msg)
display("{}", msg)
from(s: &'static str) -> (s.into())
from(s: String) -> (s.into())
}
}
}
| OidHexDisplay | identifier_name |
types.rs | //! Various common types.
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io;
use std::result;
use bson::{self, oid};
use itertools::Itertools;
/// The default result type used in this library.
pub type Result<T> = result::Result<T, Error>;
/// A partial save error returned by `Collection::save_all()` method.
#[derive(Debug)]
pub struct PartialSave {
/// The actual cause of the partial save error.
pub cause: Box<Error>,
/// A vector of object ids which have been inserted successfully.
pub successful_ids: Vec<oid::ObjectId>,
}
impl error::Error for PartialSave {
fn description(&self) -> &str {
"save operation completed partially"
}
fn cause(&self) -> Option<&error::Error> {
Some(&*self.cause)
}
}
struct OidHexDisplay(oid::ObjectId);
impl fmt::Display for OidHexDisplay {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
static CHARS: &'static [u8] = b"0123456789abcdef";
for &byte in &self.0.bytes() {
try!(write!(
f,
"{}{}",
CHARS[(byte >> 4) as usize] as char,
CHARS[(byte & 0xf) as usize] as char
));
}
Ok(())
}
}
impl fmt::Display for PartialSave {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.successful_ids.is_empty() {
write!(f, "saved nothing due to an error: {}", self.cause)
} else |
}
}
quick_error! {
/// The main error type used in the library.
#[derive(Debug)]
pub enum Error {
/// I/O error.
Io(err: io::Error) {
from()
description("I/O error")
display("I/O error: {}", err)
cause(err)
}
/// BSON encoding error (when converting Rust BSON representation to the EJDB one).
BsonEncoding(err: bson::EncoderError) {
from()
description("BSON encoding error")
display("BSON encoding error: {}", err)
cause(err)
}
/// BSON decoding error (when converting to Rust BSON representation from the EJDB one).
BsonDecoding(err: bson::DecoderError) {
from()
description("BSON decoding error")
display("BSON decoding error: {}", err)
cause(err)
}
/// Partial save error returned by `Collection::save_all()` method.
PartialSave(err: PartialSave) {
from()
description("partial save")
display("partial save: {}", err)
cause(&*err.cause)
}
/// Some other error.
Other(msg: Cow<'static, str>) {
description(&*msg)
display("{}", msg)
from(s: &'static str) -> (s.into())
from(s: String) -> (s.into())
}
}
}
| {
write!(
f,
"only saved objects with ids: [{}] due to an error: {}",
self.successful_ids
.iter()
.cloned()
.map(OidHexDisplay)
.join(", "),
self.cause
)
} | conditional_block |
promote.rs | use crate::{api_client,
common::ui::{Status,
UIReader,
UIWriter,
UI},
error::{Error,
Result},
hcore::{package::PackageIdent,
ChannelIdent},
PRODUCT,
VERSION};
use reqwest::StatusCode;
use std::str::FromStr;
fn is_ident(s: &str) -> bool { PackageIdent::from_str(s).is_ok() }
fn in_origin(ident: &str, origin: Option<&str>) -> bool {
origin.map_or(true, |o| PackageIdent::from_str(ident).unwrap().origin == o)
}
pub fn get_ident_list(ui: &mut UI,
group_status: &api_client::SchedulerResponse,
origin: Option<&str>,
interactive: bool)
-> Result<Vec<String>> {
let mut idents: Vec<String> =
group_status.projects
.iter()
.cloned()
.filter(|p| p.state == "Success" && in_origin(&p.ident, origin))
.map(|p| p.ident)
.collect();
if idents.is_empty() ||!interactive {
return Ok(idents);
}
let prelude = "# This is the list of package identifiers that will be processed.\n# You may \
edit this file and remove any packages that you do\n# not want to apply to the \
specified channel.\n"
.to_string();
idents.insert(0, prelude);
idents = idents.iter().map(|s| format!("{}\n", s)).collect();
Ok(ui.edit(&idents)?
.split('\n')
.filter(|s| is_ident(s))
.map(str::to_string)
.collect())
}
async fn get_group_status(bldr_url: &str, group_id: u64) -> Result<api_client::SchedulerResponse> {
let api_client =
api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
let group_status = api_client.get_schedule(group_id as i64, true)
.await
.map_err(Error::ScheduleStatus)?;
Ok(group_status)
}
#[allow(clippy::too_many_arguments)]
pub async fn start(ui: &mut UI,
bldr_url: &str,
group_id: &str,
channel: &ChannelIdent,
origin: Option<&str>,
interactive: bool,
verbose: bool,
token: &str,
promote: bool)
-> Result<()> {
let api_client =
api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
let (promoted_demoted, promoting_demoting, to_from, changing_status, changed_status) =
if promote {
("promoted", "Promoting", "to", Status::Promoting, Status::Promoted)
} else {
("demoted", "Demoting", "from", Status::Demoting, Status::Demoted)
};
let gid = match group_id.parse::<u64>() {
Ok(g) => g,
Err(e) => |
};
let group_status = get_group_status(bldr_url, gid).await?;
let idents = get_ident_list(ui, &group_status, origin, interactive)?;
if idents.is_empty() {
ui.warn("No matching packages found")?;
return Ok(());
}
if verbose {
println!("Packages being {}:", promoted_demoted);
for ident in idents.iter() {
println!(" {}", ident)
}
}
let question = format!("{} {} package(s) {} channel '{}'. Continue?",
promoting_demoting,
idents.len(),
to_from,
channel);
if!ui.prompt_yes_no(&question, Some(true))? {
ui.fatal("Aborted")?;
return Ok(());
}
ui.status(changing_status,
format!("job group {} {} channel '{}'", group_id, to_from, channel))?;
match api_client.job_group_promote_or_demote(gid, &idents, channel, token, promote)
.await
{
Ok(_) => {
ui.status(changed_status,
format!("job group {} {} channel '{}'", group_id, to_from, channel))?;
}
Err(api_client::Error::APIError(StatusCode::UNPROCESSABLE_ENTITY, _)) => {
return Err(Error::JobGroupPromoteOrDemoteUnprocessable(promote));
}
Err(e) => {
return Err(Error::JobGroupPromoteOrDemote(e, promote));
}
};
Ok(())
}
#[cfg(test)]
mod test {
use super::get_ident_list;
use crate::{api_client::{Project,
SchedulerResponse},
common::ui::UI};
fn sample_project_list() -> Vec<Project> {
let project1 = Project { name: "Project1".to_string(),
ident: "core/project1/1.0.0/20180101000000".to_string(),
state: "Success".to_string(),
job_id: "12345678".to_string(),
target: "x86_64-linux".to_string(), };
let project2 = Project { name: "Project2".to_string(),
ident: "core/project2/1.0.0/20180101000000".to_string(),
state: "Success".to_string(),
job_id: "12345678".to_string(),
target: "x86_64-linux".to_string(), };
vec![project1, project2]
}
#[test]
fn test_get_ident_list() {
let mut ui = UI::with_sinks();
let group_status = SchedulerResponse { id: "12345678".to_string(),
state: "Finished".to_string(),
projects: sample_project_list(),
created_at:
"Properly formated timestamp".to_string(),
project_name: "Test Project".to_string(),
target: "x86_64-linux".to_string(), };
let ident_list =
get_ident_list(&mut ui, &group_status, Some("core"), false).expect("Error fetching \
ident list");
assert_eq!(ident_list,
["core/project1/1.0.0/20180101000000",
"core/project2/1.0.0/20180101000000",])
}
}
| {
ui.fatal(format!("Failed to parse group id: {}", e))?;
return Err(Error::ParseIntError(e));
} | conditional_block |
promote.rs | use crate::{api_client,
common::ui::{Status,
UIReader,
UIWriter,
UI},
error::{Error,
Result},
hcore::{package::PackageIdent,
ChannelIdent},
PRODUCT,
VERSION};
use reqwest::StatusCode;
use std::str::FromStr;
fn is_ident(s: &str) -> bool { PackageIdent::from_str(s).is_ok() }
fn in_origin(ident: &str, origin: Option<&str>) -> bool {
origin.map_or(true, |o| PackageIdent::from_str(ident).unwrap().origin == o)
}
pub fn get_ident_list(ui: &mut UI,
group_status: &api_client::SchedulerResponse,
origin: Option<&str>,
interactive: bool)
-> Result<Vec<String>> {
let mut idents: Vec<String> =
group_status.projects
.iter()
.cloned()
.filter(|p| p.state == "Success" && in_origin(&p.ident, origin))
.map(|p| p.ident)
.collect();
if idents.is_empty() ||!interactive {
return Ok(idents);
}
let prelude = "# This is the list of package identifiers that will be processed.\n# You may \
edit this file and remove any packages that you do\n# not want to apply to the \
specified channel.\n"
.to_string();
idents.insert(0, prelude);
idents = idents.iter().map(|s| format!("{}\n", s)).collect();
Ok(ui.edit(&idents)?
.split('\n')
.filter(|s| is_ident(s))
.map(str::to_string)
.collect())
}
async fn get_group_status(bldr_url: &str, group_id: u64) -> Result<api_client::SchedulerResponse> {
let api_client =
api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
let group_status = api_client.get_schedule(group_id as i64, true)
.await
.map_err(Error::ScheduleStatus)?;
Ok(group_status)
}
#[allow(clippy::too_many_arguments)]
pub async fn start(ui: &mut UI,
bldr_url: &str,
group_id: &str,
channel: &ChannelIdent,
origin: Option<&str>,
interactive: bool,
verbose: bool,
token: &str,
promote: bool)
-> Result<()> {
let api_client =
api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
let (promoted_demoted, promoting_demoting, to_from, changing_status, changed_status) =
if promote {
("promoted", "Promoting", "to", Status::Promoting, Status::Promoted)
} else {
("demoted", "Demoting", "from", Status::Demoting, Status::Demoted)
};
let gid = match group_id.parse::<u64>() {
Ok(g) => g,
Err(e) => {
ui.fatal(format!("Failed to parse group id: {}", e))?;
return Err(Error::ParseIntError(e));
}
};
let group_status = get_group_status(bldr_url, gid).await?;
let idents = get_ident_list(ui, &group_status, origin, interactive)?;
if idents.is_empty() {
ui.warn("No matching packages found")?;
return Ok(());
}
if verbose {
println!("Packages being {}:", promoted_demoted);
for ident in idents.iter() {
println!(" {}", ident)
}
}
let question = format!("{} {} package(s) {} channel '{}'. Continue?",
promoting_demoting,
idents.len(),
to_from,
channel);
if!ui.prompt_yes_no(&question, Some(true))? {
ui.fatal("Aborted")?;
return Ok(());
}
ui.status(changing_status,
format!("job group {} {} channel '{}'", group_id, to_from, channel))?;
match api_client.job_group_promote_or_demote(gid, &idents, channel, token, promote)
.await
{
Ok(_) => {
ui.status(changed_status,
format!("job group {} {} channel '{}'", group_id, to_from, channel))?;
}
Err(api_client::Error::APIError(StatusCode::UNPROCESSABLE_ENTITY, _)) => {
return Err(Error::JobGroupPromoteOrDemoteUnprocessable(promote));
}
Err(e) => {
return Err(Error::JobGroupPromoteOrDemote(e, promote));
}
};
Ok(())
}
#[cfg(test)]
mod test {
use super::get_ident_list;
use crate::{api_client::{Project,
SchedulerResponse},
common::ui::UI};
fn sample_project_list() -> Vec<Project> {
let project1 = Project { name: "Project1".to_string(),
ident: "core/project1/1.0.0/20180101000000".to_string(),
state: "Success".to_string(),
job_id: "12345678".to_string(),
target: "x86_64-linux".to_string(), };
let project2 = Project { name: "Project2".to_string(),
ident: "core/project2/1.0.0/20180101000000".to_string(),
state: "Success".to_string(),
job_id: "12345678".to_string(),
target: "x86_64-linux".to_string(), };
vec![project1, project2]
}
#[test]
fn test_get_ident_list() |
}
| {
let mut ui = UI::with_sinks();
let group_status = SchedulerResponse { id: "12345678".to_string(),
state: "Finished".to_string(),
projects: sample_project_list(),
created_at:
"Properly formated timestamp".to_string(),
project_name: "Test Project".to_string(),
target: "x86_64-linux".to_string(), };
let ident_list =
get_ident_list(&mut ui, &group_status, Some("core"), false).expect("Error fetching \
ident list");
assert_eq!(ident_list,
["core/project1/1.0.0/20180101000000",
"core/project2/1.0.0/20180101000000",])
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.